Saturday, 7 January 2017

Exception Handling interview questions

1. Create custom exception

class MyOwnException extends Exception {
   public MyOwnException(String msg){
      super(msg);
   }
}

class CustomExceptionTest {
   static void  employeeAge(int age) throws MyOwnException{
      if(age < 0)
         throw new MyOwnException("Age can't be less than zero");
      else
         System.out.println("Input is valid!!");
   }
   public static void main(String[] args) {
       try {
            employeeAge(-2);
       }
       catch (MyOwnException e) {
            e.printStackTrace();
       }
   }
}
--------------------------------------------------------------------------------
MyOwnException: Age can't be less than zero
at EmployeeTest.employeeAge(EmployeeTest.java:10)
at EmployeeTest.main(EmployeeTest.java:16)
--------------------------------------------------------------------------------
2. Return statement
//Finally block overrides the value returned by try and catch blocks.

public class returnStatement {

public static String returnMethod(){
try {
return "try";
} catch (Exception e) {
return "catch";
}finally{
return "finally";
}
}
public static void main(String[] args) {
System.out.println(returnStatement.returnMethod());
}

}
-------------------------------------------------------------------------
finally
-------------------------------------------------------------------------
3. When the finally block doesn't execute, following are the circumstances 
1.When we place System.exit() in our code for stopping the jvm.
2.Abnormal situations like H/w problems.
3. finally block raises exception.

Sunday, 22 May 2016

Spring MVC Application



HelloYogiController.java

package com.yug.test;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
//import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

@Controller

public class HelloYogiController{

@InitBinder
public void initBinder(WebDataBinder  binder){
//binder.setDisallowedFields(new String[]{"password"});
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy****mm**dd");
binder.registerCustomEditor(Date.class, "dob",new CustomDateEditor(dateFormat, false));
binder.registerCustomEditor(String.class, "username", new nameEditor());
}

@RequestMapping(value="/admissionfrom.html", method= RequestMethod.GET)
public ModelAndView getFormPage() {
ModelAndView mav=new ModelAndView("Admissionfrom");

return mav;
}

@ModelAttribute
public void addingCommonObjects(Model m){
m.addAttribute("msg", "Welcome to Spring MVC Applications using @ModelAttribute");
}

@RequestMapping(value="/submitformpage.html", method= RequestMethod.POST)
public ModelAndView getFormResult(@Valid @ModelAttribute("emp") Employee e, BindingResult result) {

if(result.hasErrors()){
ModelAndView mav=new ModelAndView("Admissionfrom");
return mav;
}
ModelAndView mav=new ModelAndView("HelloPage");

return mav;
}

}

Employee.java

package com.yug.test;

import java.util.ArrayList;
import java.util.Date;

import javax.validation.constraints.Max;
import javax.validation.constraints.Past;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

public class Employee {


private String username;

@Size(min=3, max=11, message="Password size must be between {min} and {max}")
@isYogiFieldValidator(listOfValidPasswords="java|.net|sql")
private String password;

@Max(2222)
private long mobile;
@Past
private Date dob;

private ArrayList<String> skills;
private Address empaddr;
public Address getEmpaddr() {
return empaddr;
}
public void setEmpaddr(Address empaddr) {
this.empaddr = empaddr;
}
public long getMobile() {
return mobile;
}
public void setMobile(long mobile) {
this.mobile = mobile;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public ArrayList<String> getSkills() {
return skills;
}
public void setSkills(ArrayList<String> skills) {
this.skills = skills;
}



public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}


}

Address.java

package com.yug.test;

public class Address {
private String country;
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getPincode() {
return pincode;
}
public void setPincode(int pincode) {
this.pincode = pincode;
}
private String city;
private int pincode;

}

FieldValidator.java

package com.yug.test;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class FieldValidator implements ConstraintValidator<isYogiFieldValidator, String>{
String islistOfValidpwd;
@Override
public void initialize(isYogiFieldValidator isFieldValidator){
this.islistOfValidpwd = isFieldValidator.listOfValidPasswords();
}
public boolean isValid(String skills, ConstraintValidatorContext ctx) {
if(skills == null){
return false;
}
if(skills.matches(islistOfValidpwd)){
return true;
}else{
return false;
}
}

}


isYogiFieldValidator.java

package com.yug.test;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Documented
@Constraint(validatedBy= FieldValidator.class)
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)

public @interface isYogiFieldValidator {

//String listOfValidPasswords() default "java|.net|sql"; 
String listOfValidPasswords();  
String message() default "Please, provide skills which you have, Accepted passwords are java, .net, and sql";
Class<?>[] groups() default{};
Class<? extends Payload>[] payload() default{};
}


nameEditor.java

package com.yug.test;

import java.beans.PropertyEditorSupport;

public class nameEditor extends PropertyEditorSupport {

@Override
public void setAsText(String username)throws IllegalArgumentException{
if(username.contains("Mr.") || username.contains("Mrs.")){
setValue(username);
}else{
username="Ms."+username;
setValue(username);
}
}
}


AdmissionForm.java

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1><b>${msg}</b></h1>
 <form:errors path="emp.*"/>  
<form action="/firstSpringMVCEx/submitformpage.html" method="post">
<table>
<td><tr>Enter User Name :</tr>
</td><td><tr><input type="text" name="username"></tr></td><br><br>
<td><tr>Enter User - Pwd :</tr>
</td><td><tr><input type="password" name="password"></tr></td><br><br>
<td align="right"><tr> </tr>

<td><tr>Enter ur mobile # :</tr>
</td><td><tr><input type="text" name="mobile"></tr></td><br><br>

<td><tr>Enter User DOB :</tr>
</td><td><tr><input type="text" name="dob"></tr></td><br><br>
<td><tr>Enter Skills set :</tr>
</td><td><tr><select name="skills" multiple="multiple">
<option value="java">Java</option>
<option value=".net">.Net</option>
<option value="sql">SQL</option>

</tr></td><br><br>

</td><td align="center">
</table>
<table>
<tr>
<td>Country :</td><td><input type="text" name="empaddr.country"/></td></tr>
<tr>
<td>City :</td><td><input type="text" name="empaddr.city"/></td></tr>
<tr>
<td>Pincode :</td><td><input type="text" name="empaddr.pincode"/></td></tr>
</table>
<tr><input type="submit" value="submit"></tr></td>
</form>
</body>
</html>

empMassages.properties

Size = please, Enter a value for {0} field between {2} and {1} and dynamically that is cacheSeconds property.
#Size = please, Enter a value for password field between min and max and only size annotation is using.
#Size.java.lang.String = please, Enter a value for password field between 2 and 10 and type added.
#Size.password = please, Enter a value for password field between 2 and 10 and reference removed.
#Size.emp.password = please, Enter a value for password field between 2 and 10.

HelloPage.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 
<h1><b>${msg}</b></h1>


<table>
<tr>
<td>user name is : </td>
<td>${emp.username}</td>
</tr>
<tr>
<td>user pwd is : </td>
<td>${emp.password}</td>
</tr>
<tr>
<td>user mobile is : </td>
<td>${emp.mobile}</td>
</tr>
<tr>
<td>user DOB is : </td>
<td>${emp.dob}</td>
</tr>
<tr>
<td>user skills is : </td>
<td>${emp.skills}</td>
</tr>

<tr>
<td>Employee Address :</td>
<td>
County :${emp.empaddr.country}
City :${emp.empaddr.city}
Pincode :${emp.empaddr.pincode}
</td></tr>
</table>
</body>
</html>

spring-dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd ">

  <context:component-scan base-package="com.yug.test"></context:component-scan> 
 <mvc:annotation-driven></mvc:annotation-driven>
 
 
 <bean id="viewResolver"  class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
    <property name="prefix">  
      <value>/WEB-INF/</value>  
    </property>  
    <property name="suffix">  
      <value>.jsp</value>  
    </property>  
  </bean> 
  
  <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
  <property name="basename" value="/WEB-INF/empMessages"></property>
  <property name="cacheSeconds" value="1"></property>
  </bean> 
</beans>  

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>firstSpringMVCEx</display-name>
   
  <servlet>
  <servlet-name>spring-dispatcher</servlet-name>
        <servlet-class>
             org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
  <servlet-name>spring-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
  </servlet-mapping>
<welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
</web-app>


SQL Practise

create table std_table(stno number ,stname varchar2(20),stcity varchar2(20),pincode number ,address varchar2(30), fee varchar2(10),company varchar2(20) )

select * from student_table

desc student_table

--=========DDL================Dr.CAT============

alter table student_table modify pincode number(6)

alter table student_table add fee number;

alter table student_table drop column company

alter table student_table rename column stcity to city

alter table student_table rename to std_table

alter table std_table rename to student_table

--==========================================

insert into student_table values(100,'yug','pune',503183,'addr3',25000)

truncate table student_table

drop table student_table

flashback table test to before drop

create table emp_tab(eid number,ename varchar2(20),)

select * from emp_tab

drop table emp_tab purge

--================DML========SUDI======

insert into student_table values(100,'yug','pune',507183,'addr1')

insert into student_table values(&stno,'&stname','&city',&pincode,'&address')

insert into student_table(stno,pincode) values(&stno,&pincode)

update student_table set fee=22000 where stno='104'

--update student_table set stname='yugandhar' where address=null  can not update

select * from student_table

select stno A,stname B,city C,pincode D,address E from student_table

select stno student_number, stno+100 test_no from student_table where stno>102

select * from student_table order by stno [desc];

select rowid, rownum from student_table

select sum(fee) from student_table

select avg(fee) from student_table

select min(fee) from student_table

select max(fee) from student_table

select 2+3+5/2 from dual;

select trunc(sysdate) from dual;

select count(*) from student_table

select count(stname) from student_table

select count(distinct stname) from student_table

select * from user_tab_columns where table_name='student_table'

desc user_tab_columns

select student_table.* from STUDENT_TABLE;

select student_table.*,nvl(address,'myaddr') from student_table;

select student_table.*,nvl2(address,'myaddr','nullAddr') from student_table;

select student_table.*,nvl2(city,'pune','hyd') from student_table;

select student_table.*,nvl2(stname,'fist','second') from student_table;

select stno , length(stno), city, length(city), nullif(length(stno),length(city)) from student_table;

select stname , length(stname), city, length(city), nullif(length(stname),length(city)) from student_table;

select stno, count(*) from student_table group by stno;

select stno, count(*) from student_table group by stno having count(*)>1;

select stno, count(*),sum(fee) from student_table group by stno;

select stno, count(*),sum(fee),max(fee),min(fee),avg(fee) from student_table group by stno;

create sequence s2 minvalue 100 maxvalue 110 increment by 3;

create table seq_test1(id number , name varchar2(10));

insert into  seq_test values(s2.nextval, 'yog6')

select * from seq_test

alter sequence s2 maxvalue 115;

select * from user_sequences

select * from student_table

create table std as select * from student_table

select * from std

create table std1 as select * from student_table where 1=2

select * from std1

insert into std1 select * from student_table

update std1 set fee=17000 where stno='addr2'


Wednesday, 16 March 2016

Cursors in PL/SQL

1. Cursor in Procedure

CREATE OR REPLACE PROCEDURE SCOTT.proc_cur1 IS
v_ename emp.ename%type;
v_sal EMP.SAL%type;
cursor mycsr is select ename,sal from emp;
 BEGIN
  open mycsr;
  fetch mycsr into v_ename,v_sal;
  dbms_output.put_line(v_ename||', '||v_sal);
  close mycsr;
     EXCEPTION
     WHEN NO_DATA_FOUND THEN
       NULL;
     WHEN OTHERS THEN
       -- Consider logging the error and then re-raise
       RAISE;
END proc_cur1;
/

2. Cursor in Procedure

CREATE OR REPLACE PROCEDURE SCOTT.cur_in_proc(a emp.deptno%type) IS
 cursor mycsr is select * from emp where deptno=a;
 b emp%rowtype;
 BEGIN
 open mycsr;
 loop
 fetch mycsr into b;
 if mycsr%FOUND then
 dbms_output.put_line(b.empno||', '||b.deptno||', '||b.ename);
 else exit;
 end if;
 end loop;
 close mycsr;
    EXCEPTION
     WHEN NO_DATA_FOUND THEN
       NULL;
     WHEN OTHERS THEN
       -- Consider logging the error and then re-raise
       RAISE;
END cur_in_proc;
/

3. Cursor in Procedure

CREATE OR REPLACE PROCEDURE SCOTT.proc_cur2 IS
 v_ename EMP.ENAME%type;
 v_sal EMP.SAL%type;
 cursor mycsr is select ename,sal from emp;
 BEGIN
  open mycsr;
  loop
  fetch mycsr into v_ename, v_sal;
  dbms_output.put_line(v_ename||''||v_sal);
  end loop;
  close mycsr;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       NULL;
     WHEN OTHERS THEN
       -- Consider logging the error and then re-raise
       RAISE;
END proc_cur2;
/

4.Cursor in Procedure

CREATE OR REPLACE PROCEDURE SCOTT.proc_cur3 IS
cursor mycsr is select * from emp;
v_mycsr_data mycsr%rowtype;
begin
open mycsr;
loop
fetch mycsr into v_mycsr_data;
dbms_output.put_line('Record Number is '||mycsr%ROWCOUNT||' '||v_mycsr_data.ename);
exit when mycsr%NOTFOUND;
end loop;
close mycsr;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       NULL;
     WHEN OTHERS THEN
       -- Consider logging the error and then re-raise
       RAISE;
END proc_cur3;
/

5. Cursor in Procedure

CREATE OR REPLACE PROCEDURE SCOTT.proc_cur4 IS
cursor mycsr is select * from emp;
v_mycsr mycsr%ROWTYPE;
begin
open mycsr;
dbms_output.put_line('The details of an employee in our organization as follows');
dbms_output.put_line('----------------------------------------');
 dbms_output.put_line('Name  '||'     Designation  '||'         Basic Salaray'||'            Annual Salary');
 dbms_output.put_line('---------------------------------------');
 loop
 fetch mycsr into v_mycsr;
 exit when mycsr%NOTFOUND;
 dbms_output.put_line(v_mycsr.ename||'      '||v_mycsr.job||'                     '||v_mycsr.sal||'                   '||v_mycsr.sal*12);
 end loop;
 close mycsr;
    EXCEPTION
     WHEN NO_DATA_FOUND THEN
       NULL;
     WHEN OTHERS THEN
       -- Consider logging the error and then re-raise
       RAISE;
END proc_cur4;
/

6. Cursor in Procedure

CREATE OR REPLACE PROCEDURE SCOTT.proc_cur5 IS
mycsr_cnt number ;
cursor mycsr is select * from emp;
v_mycsr_data mycsr%ROWTYPE;
begin
open mycsr;
loop
fetch mycsr into  v_mycsr_data;
exit when mycsr%NOTFOUND;
mycsr_cnt:= mycsr%ROWCOUNT;
if v_mycsr_data.job='SALESMAN' then
dbms_output.put_line(v_mycsr_data.ename||'     '||v_mycsr_data.job||'    Eligible for commission.');
else
dbms_output.put_line('Not Eligible for commission.');
end if;
end loop;
close mycsr;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       NULL;
     WHEN OTHERS THEN
       -- Consider logging the error and then re-raise
       RAISE;
END proc_cur5;
/

7. Cursor in Procedure

CREATE OR REPLACE PROCEDURE SCOTT.proc_cursor_use2 IS
cursor deptcsr is select deptno,dname from dept order by deptno;
cursor empcsr(v_deptno emp.deptno%type) is select ename,job,hiredate,sal from emp where deptno=v_deptno;
v_curdeptno DEPT.DEPTNO%type;
v_curdname DEPT.DNAME%type;
v_ename EMP.ENAME%type;
v_job EMP.JOB%type;
v_mgr EMP.MGR%type;
v_hiredate EMP.HIREDATE%type;
v_sal EMP.SAL%type;
begin
open deptcsr;
loop
fetch deptcsr into v_curdeptno,v_curdname;
exit when deptcsr%NOTFOUND;
dbms_output.put_line('Department number '||v_curdeptno||' department name '||v_curdname);
if empcsr%ISOPEN then
close empcsr;
end if;
open empcsr(v_curdeptno);
loop
fetch empcsr into v_ename,v_job,v_hiredate,v_sal;
if empcsr%FOUND then
dbms_output.put_line(v_ename||' '||v_job||' '||v_hiredate||' '||v_sal);
else
dbms_output.put_line('End of Employees in department '||v_curdeptno);
end if;
exit when empcsr%NOTFOUND;
end loop;
if empcsr%ISOPEN then
close empcsr;
end if;
end loop;
if empcsr%ISOPEN then
close empcsr;
end if;
close deptcsr;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       NULL;
     WHEN OTHERS THEN
       -- Consider logging the error and then re-raise
       RAISE;
END proc_cursor_use2;
/

8. Cursor in Procedure

CREATE OR REPLACE PROCEDURE SCOTT.proc_cur_for1 IS
cursor mycsr is select * from emp;
v_mycsr mycsr%ROWTYPE;
begin
for v_mycsr in mycsr
loop
dbms_output.put_line('=========='||v_mycsr.ename);
end loop;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       NULL;
     WHEN OTHERS THEN
       -- Consider logging the error and then re-raise
       RAISE;
END proc_cur_for1;
/

9. Cursor in Procedure

CREATE OR REPLACE PROCEDURE SCOTT.proc_cur_for2 IS
cursor mycsr is select * from emp;
begin
for cur_index in mycsr
loop
dbms_output.put_line('Record number is '||mycsr%ROWCOUNT||' '||cur_index.ename);
end loop;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       NULL;
     WHEN OTHERS THEN
       -- Consider logging the error and then re-raise
       RAISE;
END proc_cur_for2;
/

10. Cursor in Procedure

CREATE OR REPLACE PROCEDURE SCOTT.proc_cur_for3 IS
cursor mycsr is select * from emp order by sal desc;
begin
for v_cur_ind in mycsr
loop
dbms_output.put_line('Records number is '||RPAD(mycsr%ROWCOUNT,10)||' '||RPAD(v_cur_ind.ename,10)||' with salary is '||RPAD(v_cur_ind.sal,10));
exit when mycsr%ROWCOUNT=5;
end loop;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       NULL;
     WHEN OTHERS THEN
       -- Consider logging the error and then re-raise
       RAISE;
END proc_cur_for3;
/

11. Cursor in Procedure

CREATE OR REPLACE PROCEDURE SCOTT.proc_cur_for_subqry1 IS
v_dname dept.dname%type;
v_loc dept.loc%type;
begin
for emp_ind in (select dname, deptno from dept order by deptno)
loop
select dname, loc into v_dname, v_loc from dept where deptno=emp_ind.deptno;
dbms_output.put_line(emp_ind.deptno||'  '||emp_ind.dname||'  '||v_dname||'  '||v_loc);
end loop;
   EXCEPTION
   when TOO_MANY_ROWS then
   dbms_output.put_line('Retrieving too many rows');
     WHEN NO_DATA_FOUND THEN
       NULL;
     WHEN OTHERS THEN
       -- Consider logging the error and then re-raise
       RAISE;
END proc_cur_for_subqry1;
/

12. Cursor in Procedure

CREATE OR REPLACE PROCEDURE SCOTT.proc_cur_for_subqry2 IS
begin
for v_ind in (select * from dept)
loop
dbms_output.put_line('Department '||v_ind.dname||' and number '||v_ind.deptno||' located at '||v_ind.loc);
end loop;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       NULL;
     WHEN OTHERS THEN
       -- Consider logging the error and then re-raise
       RAISE;
END proc_cur_for_subqry2;
/

13. Cursor in Procedure

CREATE OR REPLACE PROCEDURE SCOTT.proc_cur_updt_of_and_curent_of IS
cursor mycsr is select sal from emp where deptno=30 for UPDATE OF sal NOWAIT;
begin
for mycsr_ind in mycsr
loop
 update emp set sal=sal+(mycsr_ind.sal*1.10) where CURRENT OF mycsr;
end loop;
commit;
    EXCEPTION
     WHEN NO_DATA_FOUND THEN
       NULL;
     WHEN OTHERS THEN
       -- Consider logging the error and then re-raise
       RAISE;
END proc_cur_updt_of_and_curent_of;
/

14. Cursor in Procedure

CREATE OR REPLACE PROCEDURE SCOTT.proc_cur_while1 IS
cursor mycsr is select * from emp;
v_mycsr mycsr%ROWTYPE;
begin
open mycsr;
fetch mycsr into v_mycsr;
while mycsr%FOUND
loop
dbms_output.put_line('=============='||v_mycsr.ename);
fetch mycsr into v_mycsr;
end loop;
close mycsr;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       NULL;
     WHEN OTHERS THEN
       -- Consider logging the error and then re-raise
       RAISE;
END proc_cur_while1;
/

15. Cursor in Procedure

CREATE OR REPLACE PROCEDURE SCOTT.proc_cur_while2 IS
cursor mycsr is select * from emp;
v_mycsr mycsr%rowtype;
begin
open mycsr;
fetch mycsr into v_mycsr;
while mycsr%FOUND
loop
dbms_output.put_line('Record number is '||mycsr%ROWCOUNT||' '||v_mycsr.ename);
fetch mycsr into v_mycsr;
end loop;
close mycsr;
    EXCEPTION
     WHEN NO_DATA_FOUND THEN
       NULL;
     WHEN OTHERS THEN
       -- Consider logging the error and then re-raise
       RAISE;
END proc_cur_while2;
/

16. Cursor in Procedure

CREATE OR REPLACE PROCEDURE SCOTT.Real_cursor_use1 IS
v_number number(2):=3;
v_ename emp.ename%type;
v_sal EMP.SAL%type;
cursor mycsr is select ename,sal from emp;
begin
 delete bigheads;
 commit;
 open mycsr;
 fetch mycsr into v_ename,v_sal;
 while mycsr%ROWCOUNT<=v_number and mycsr%FOUND
 loop
 insert into bigheads(ename, salary) values(v_ename, v_sal);
 fetch mycsr into v_ename,v_sal;
 end loop;
 close mycsr;
 commit;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       NULL;
     WHEN OTHERS THEN
       -- Consider logging the error and then re-raise
       RAISE;
END Real_cursor_use1;
/

Monday, 25 January 2016

Hibernate first Application

TestClient.java(For insert/update/delete operations)
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class TestClient {
public static void main(String[] args) {

Configuration cfg=new org.hibernate.cfg.Configuration();
   cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file
   
   //creating seession factory object
   SessionFactory factory=cfg.buildSessionFactory();
   
   //creating session object
   Session session=factory.openSession();
   
   //creating transaction object
   Transaction t=session.beginTransaction();
       
   Employee e1=new Employee();
   e1.setId(3888);
   e1.setFirstName("ravi");
   e1.setLastName("kumar");
   
   session.persist(e1);//persisting the object
   
   t.commit();//transaction is committed
   session.close();
   
   System.out.println("successfully saved");

}
}

TestClient.java (For selecting the records from DB)

import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class TestClient {
public static void main(String[] args) {

Configuration cfg=new org.hibernate.cfg.Configuration();
   cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file
   
   //creating seession factory object
   SessionFactory factory=cfg.buildSessionFactory();
   
   //creating session object
   Session session=factory.openSession();
   
   Query qry = session.createQuery("from Employee");

List l =qry.list();
System.out.println("Total Number Of Records : "+l.size());
Iterator it = l.iterator();

while(it.hasNext())
{
Object o = (Object)it.next();
Employee p = (Employee)o;
System.out.println("Employee id : "+p.getId());
System.out.println("Employee first Name : "+p.getFirstName());
System.out.println("Employee last Name : "+p.getLastName());
System.out.println("----------------------");
}
     session.close();
}

}

Employee.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

 <hibernate-mapping>
  <class name="Employee" table="emp123">
    <id name="id">
     <generator class="assigned"></generator>
    </id>
         
    <property name="firstName"></property>
    <property name="lastName"></property>
         
  </class>
         
 </hibernate-mapping>

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-configuration PUBLIC  
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  
<hibernate-configuration>  
    <session-factory>  
        <property name="hbm2ddl.auto">update</property>  
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:sysdba</property>  
        <property name="connection.username">scott</property>  
        <property name="connection.password">yogi</property>  
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>  
    <mapping resource="employee.hbm.xml"/>  
    </session-factory>  
</hibernate-configuration>   

Employee.java


public class Employee {
private int id;  
private String firstName,lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

Class path jars: Right-click on HB app --> properties --> java build path --> libraries -->add external jars. Download path(http://hibernate.org/orm/downloads/)


Wednesday, 11 November 2015

HTML/jsp + servlets + csv file storing the values

index.jsp
=======
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Datepicker - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script>
  $(function() {
    $( "#datepicker" ).datepicker();
  });
  </script>
</head>
<body>
<form action="register">
 id :<input type="text" id="i" name="id"><br>
 name :<input type="text" id="n" name="name"><br>
 Location :<input type="text" id="l" name="location"><br>
<p>Date : <input type="text" id="datepicker" name="dob"></p>
 <input type="submit"   value="submit">
 </form>

</body>
</html>

web.xml
=======
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>JavascriptEx</display-name>
 
  <servlet>
  <servlet-name>firstsrv</servlet-name>
  <servlet-class>com.test.firstservlet.welcomeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  <servlet-name>firstsrv</servlet-name>
  <url-pattern>/register</url-pattern>
  </servlet-mapping>
 
 
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

welcomeServlet.java
===============
package com.test.firstservlet;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class welcomeServlet extends HttpServlet{

public void init()
 {
     System.out.println("init method call");
 }
public void doGet(HttpServletRequest req, HttpServletResponse response)throws ServletException{

try{
ServletContext servletContext = getServletContext();
       String filepath = servletContext.getRealPath("logs");
       PrintWriter out = response.getWriter();
       String file;
       /*String actionname = request.getParameter("actiontype");
       String status = request.getParameter("status");
       String dateandtime = request.getParameter("dateandtime");
       String user = request.getParameter("username");
       String space = request.getParameter("space");*/
       System.out.println("logpath >>>>>>>>>>"+filepath);
       String id=req.getParameter("id");
String name=req.getParameter("name");
String location=req.getParameter("location");
String dob=req.getParameter("dob");
System.out.println(id+" == "+name+" == "+location+" == "+dob);
     
SimpleDateFormat formatter;
       Date date = new Date();
       formatter = new SimpleDateFormat("MM/dd/yyyy");
       date = formatter.parse(dob);
       file = formatter.format(date);
       System.out.println(file);
     
       String filename = "abcdfile.csv";
       File f;
       f = new File(filepath,filename);
       if(!f.exists()){
           f.createNewFile();
           System.out.println("New file "+filename+" has been created in the following directory"+filepath);
           try {
             
               FileWriter fw = new FileWriter(f);
             
               fw.append("User ID");
               fw.append(',');
               fw.append("Name");
               fw.append(',');
               fw.append("Location");
               fw.append(',');
                fw.append("Date of Birth");
               fw.append('\n');
             
               fw.append(id);
               fw.append(',');
               fw.append(name);
               fw.append(',');
               fw.append(location);
               fw.append(',');
                fw.append(file);
               fw.append('\n');
             
               fw.flush();
               fw.close();
               out.println("<b>Csv file Successfully created.</b>");
             
           } catch (Exception ex) {
               ex.printStackTrace();
           }
       }else{
           System.out.println("File name already exists...");
           FileWriter fw = new FileWriter(f, true);
           fw.append(id);
           fw.append(',');
           fw.append(name);
           fw.append(',');
           fw.append(location);
           fw.append(',');
            fw.append(file);
           fw.append('\n');
            fw.flush();
           fw.close();
           out.println("<b>Csv file Successfully created.</b>");
       }
   
}catch(Exception e){

}
}
}