Drop Down

Monday, January 28, 2019

Struts_App1

--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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Struts1_HelloWorld</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
  <servlet-name>action</servlet-name>
       <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
         <init-param>
  <param-name>config</param-name>
  <param-value>/WEB-INF/struts-config.xml</param-value> 
  </init-param>
  <load-on-startup>1</load-on-startup>  
  </servlet>
  <servlet-mapping>
        <servlet-name>action</servlet-name>
  <url-pattern>*.do</url-pattern>
  </servlet-mapping>

</web-app>
----------------------
--Index.jsp
---------------------
<%@taglib uri="http://struts.apache.org/tags-html" prefix ="html"%>
<html:errors/>
<h1>Welcome to World</h1>
<html:form action ="hello">
Name: <html:text property="name"/>
Roll: <html:text property="roll"/>
<html:submit value ="Say Hello"/>
</html:form>
---------------------
--FormBankUp.java
---------------------
package bean;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;
//This is bean class which extends ActionForm, //
public class FormBackUp extends ActionForm
{
private int roll;
private String name;

public int getRoll() {
return roll;
}
public void setRoll(int roll) {
this.roll = roll;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

@Override
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request)
{
ActionErrors ae = new ActionErrors();
if(name.equals(""))
{
ae.add("name", new ActionMessage("nameError"));
//return ae;
}
/*if("".equals(getRoll() ) )
{
ae.add("roll", new ActionMessage("rollError"));
//return ae;
}*/
return ae;
}
}

-----------------------
--HelloController.java
-----------------------
package bean;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.struts.action.*;
public class HelloController extends Action
{//This similar to controller classes ie. Servlets service()
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, ServletRequest request, ServletResponse response)
throws Exception 
{
String name = request.getParameter("name");
int roll = Integer.parseInt(request.getParameter("roll"));
System.out.println("Name: "+name);
System.out.println("Roll: "+roll);
request.setAttribute("res","Hello......"+name);
return mapping.findForward("success");
}
}

---------------------
--Success.jsp
---------------------

<%=request.getAttribute("res") %>>

--------------------
--struts-config.xml
--------------------
<?xml version="1.0" encoding="UTF-8"?>
<struts-config>
<form-bean>
<form-bean name="HF" type ="bean.FormBackUp"/> <!-- HF if ref. to FormBackUP -->
</form-bean>
<action-mapping>
<action path="/hello" name="HF" index="/index.jsp" type="bean.HelloController">
<forward name="success" path="/Success.jsp"/>
</action>
</action-mapping>
<message-resources parameter="bean/messages"/>


</struts-config>
--------------------------
--messages.properties
--------------------------
nameError = <font color='red'> Please Enter Name</font>
rollError = <font color='red'> Please fill Roll No.</font>

========================================================================

Tuesday, January 22, 2019

Google Drive Link: Core Codes

Multithreading:: InterProcess Communication

package multithreading;

public class ThreadA
{
public static void main(String[] args) throws InterruptedException
{
ThreadB b = new ThreadB();
b.start();
synchronized (b)
{
  b.wait();
}
System.out.println("Total: "+ b.sum);
}
}

class ThreadB extends Thread
{
int sum =0;
public void run()
{
for(int i=1;i<100;i++)
{
sum = sum+i;
}
synchronized(this)
{
this.notify();
}
}

}

MultiThreading - Main Thread Wait until Child Thread completes

package multithreading;
//Main Thread Wait until Child Thread completes
public class MyThread5
{


public static void main(String[] args) throws InterruptedException
{
MyThreadJoin mj = new MyThreadJoin();
mj.start();
mj.join(); //-------------------Wait until Child Thread completes

  char[] ch = {'e','t','y','r','w','d','g','h','t','s','e','b','n','l','k'};
  for(char c : ch)
  {
  System.out.println(c);
  try
  {
Thread.sleep(200);
  }
  catch(Exception e)
  {
  System.out.println(e);
  }
  }

}

}

class MyThreadJoin extends Thread
{
public void run()
{
int[] arr = {5,7,8,9,2,3,4,11,33,55,77,55,33,99,100};
for(int a : arr)
{
System.out.println(a);
try
{
Thread.sleep(200);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}

MultiThreading - Child Thread Wait until Main Thread completes

package multithreading;
//Child Thread Wait until Main Thread completes
public class MyThread6_Join
{

public static void main(String[] args) throws InterruptedException
{
ThreadJoin.mt = Thread.currentThread();
ThreadJoin tj = new ThreadJoin();
tj.start();

  char[] ch = {'e','t','y','r','w','d','g','h','t','s','e','b','n','l','k'};
  for(char c : ch)
  {
  System.out.println(c);
  try
  {
Thread.sleep(200);
  }
  catch(Exception e)
  {
  System.out.println(e);
  }
  }

}

}
//************************************CHILD*********************************
class ThreadJoin extends Thread
{
static Thread mt;
public void run()
{

try
{
mt.join();
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}

int[] arr = {5,7,8,9,2,3,4,11,33,55,77,55,33,99,100};
for(int a : arr)
{
System.out.println(a);
try
{
Thread.sleep(200);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}

Thursday, January 17, 2019

Ways to Iterate HashMap

package collection_Codes;

import java.util.HashMap;

public class Hashmap_Iterate2 {

public static void main(String[] args)
{
HashMap<String,String> m = new HashMap<String,String>();
m.put("name", "Amit");
m.put("college","NIT");
m.put("profession","SE");

for(String s : m.keySet())
{
String val = m.get(s);
System.out.println(s +" "+val);
}

}

}
========================================================================

package collection_Codes;
//Interface Entry is present inside MAP Interface. Entry has 3 methods:
// 1) Object getKey();
// 2) Object getValue();
// 3) Object setValue(Object );
//**********************************
import java.util.HashMap;
import java.util.Map;

public class HashMap_Iterate1 {

public static void main(String[] args) 
{
HashMap<String,String> m = new HashMap<String,String>();
m.put("name", "Amit");
m.put("college","NIT");
m.put("profession","SE");
for(Map.Entry<String,String> entry : m.entrySet())
{
System.out.println(entry.getKey()+" = "+entry.getValue());
}

}

}
===================================================================
package ERRORS;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class Test {

public static void main(String[] args)
{
   Map<String,String> m  = new HashMap<>();
   m.put("game", "FOOTBALL");
   m.put("food", "Haldiram Full Thali");
   m.put("hobby", "WINNING");
   m.put("place", "America");
   m.put("bd", "7 AUGUST");
   // Now Iterate
 
   //********************************* Method 1
   for(String s1 : m.keySet())
   {
  System.out.println(s1 +" "+m.get(s1));
   }
 
   //********************************* Method 2
 
   Set <Entry<String , String>> entry = m.entrySet();  
   for(Entry<String, String> s1 : entry)
   {
   System.out.println(s1.getKey()+"  ~  "+s1.getValue());
   }  

}

}
========================================================================

PICS





Top 10 Methods for Java Arrays

0. Decalre an array
String[] aArray = new String[5];
String[] bArray = {"a","b","c", "d", "e"};
String[] cArray = new String[]{"a","b","c","d","e"};

1. Print an array in Java
int[] intArray = { 1, 2, 3, 4, 5 };
String intArrayString = Arrays.toString(intArray);
 
// print directly will print reference value
System.out.println(intArray);
// [I@7150bd4d
 
System.out.println(intArrayString);
// [1, 2, 3, 4, 5]
2. Create ArrayList from array
String[] stringArray = { "a", "b", "c", "d", "e" };
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray));
System.out.println(arrayList);
// [a, b, c, d, e]
3. Check if an array contains a certain value
String[] stringArray = { "a", "b", "c", "d", "e" };
boolean b = Arrays.asList(stringArray).contains("a");
System.out.println(b);
// true
4. Concatenate two arrays
int[] intArray = { 1, 2, 3, 4, 5 };
int[] intArray2 = { 6, 7, 8, 9, 10 };
// Apache Commons Lang library
int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);
5. Declare array inline
method(new String[]{"a", "b", "c", "d", "e"});
6. Joins the elements of the provided array into a single String
// containing the provided list of elements
// Apache common lang
String j = StringUtils.join(new String[] { "a", "b", "c" }, ", ");
System.out.println(j);
// a, b, c
7. Covnert ArrayList to Array
     Arrays.asList
String[] stringArray = { "a", "b", "c", "d", "e" };
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray));
String[] stringArr = new String[arrayList.size()];
arrayList.toArray(stringArr);
for (String s : stringArr)
System.out.println(s);
8. Convert Array to Set
Set<String> set = new HashSet<String>(Arrays.asList(stringArray));
System.out.println(set);
//[d, e, b, c, a]
9. Reverse an array
int[] intArray = { 1, 2, 3, 4, 5 };
ArrayUtils.reverse(intArray);
System.out.println(Arrays.toString(intArray));
//[5, 4, 3, 2, 1]
10. Remove element of an array
int[] intArray = { 1, 2, 3, 4, 5 };
int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array
System.out.println(Arrays.toString(removed));
One more – convert int to byte array
byte[] bytes = ByteBuffer.allocate(4).putInt(8).array();
 
for (byte t : bytes) {
System.out.format("0x%x ", t);
}
===================================================

Converting List to Array

-----------------------------------------------------
1)The list interface comes with the toArray() method that returns an array containing all of the elements in this list in proper sequence (from the first to last element). 


Converting List to Array

COMPARATOR::: Sort Employee Object using employee id

package comparator.Emp;
//When we are not allowed to change Class Employee code (i.e we can't implement Comparable)
//We use comparator Interface.
public class Employee
{
int empid;
String name;
int deptid;
public Employee(int empid, String name, int deptid)
{
super();
this.empid = empid;
this.name = name;
this.deptid = deptid;
}
/*@Override
public String toString() {
return "Empid=" + empid + ", Name=" + name + ", Deptid=" + deptid;
}*/


}
==========================================
package comparator.Emp;
import java.util.*;
//Sort the Employeee Class using empid -- Use Comparator
public class Emp_Runner {

public static void main(String[] args) 
{
Employee emp1  = new Employee(111,"Amit",549);
Employee emp2  = new Employee(674,"Dinesh",549);
Employee emp3  = new Employee(352,"Manohar",667);
Employee emp4  = new Employee(642,"Dilip",889);
Employee emp5  = new Employee(133,"Govind",667);
 
List list = new ArrayList();
list.add(emp1);
list.add(emp2);
list.add(emp3);
list.add(emp4);
list.add(emp5);
 
Comparator comp = new Emp_Comp(); //Comparator is Interface so we can't instanciate it.
Collections.sort(list,new Emp_Comp());  //call to compare() .... from here
 
Iterator itr = list.iterator();
while(itr.hasNext())
{
Employee emp = (Employee) itr.next();
System.out.println("Empid=" + emp.empid + ", Name=" + emp.name + ", Deptid=" + emp.deptid);
 
}
 
 
}


}
==========================================
package comparator.Emp;

import java.util.Comparator;

public class Emp_Comp implements Comparator<Employee>
{

@Override
public int compare(Employee e1, Employee e2) 
{
if(e1.empid > e2.empid)
{
return 1;
}
else return 
-1;
}

}
============================================
============================================

COMPARATOR:: Sort simple ArrayList of STRING & INTEGER

package ERRORS;
// Use of Comparator
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Test
{

public static void main(String[] args)
{
//*********List of Integers*************
  ArrayList list = new ArrayList();
  list.add(98);
  list.add(89);
  list.add(108);
  list.add(897);
  list.add(55);

  Comparator<Integer> comp_int = new Test2_Comp();
  Collections.sort(list,new Test2_Comp());
  System.out.println(list);
  System.out.println("********************************");

//*********List of Strings*************
  ArrayList list2 = new ArrayList();
  list2.add("Tiger");
  list2.add("Elephant");
  list2.add("Aeroplane");
  list2.add("ink");
  list2.add("apricote");

  //To Sort list >> equalsEgnoreCase().....Aa Bb Cc...
  Comparator<String> comp = new Test_Comp();
  Collections.sort(list2,new Test_Comp());
  System.out.println(list2);
}

}

=========================================

package ERRORS;

import java.util.Comparator;
import java.util.List;

public class Test_Comp implements  Comparator<String>
{

@Override
public int compare(String s1, String s2)
{
//System.out.println(s2);
return s1.compareToIgnoreCase(s2);
//return 0;
}

}
==========================================
package ERRORS;

import java.util.Comparator;

public class Test2_Comp implements Comparator <Integer>
{
public int compare(Integer integer1, Integer integer2)
{
if(integer1 > integer2)
return 1;
else
return -1;
}

}
===========================================
===========================================
NOTE:
--------
To sort integers according to last digit use the below code.
----------------------------------------------------------------------
public int compare(Integer integer1, Integer integer2)
{
if(integer1%10 > integer2%10)
return 1;
else
return -1;
}
----------------------------------------------------------------------




Comparable:::::Sorting Book Object according to Book ID

package Coparable_Std;
//Sorting Book Object according to Book ID
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class Book_main {

public static void main(String[] args)
{
  Book_comp book1 = new Book_comp(183,"Book1",456);
  Book_comp book2 = new Book_comp(675,"Book2",799);
  Book_comp book3 = new Book_comp(335,"Book3",5454);
  Book_comp book4 = new Book_comp(832,"Book4",454);
  Book_comp book5 = new Book_comp(331,"Book5",778);
  Book_comp book6 = new Book_comp(113,"Book6",234);
  Book_comp book7 = new Book_comp(674,"Book7",788);

  ArrayList list = new ArrayList();
  list.add(book1);
  list.add(book2);
  list.add(book3);
  list.add(book4);
  list.add(book5);
  list.add(book6);
  list.add(book7);

  Collections.sort(list);
  //System.out.println(list); // works when we overrides toString() in Book_comp & no need for below codes for iterate
  Iterator itr = list.iterator();
  while(itr.hasNext())
  {
  Book_comp book = (Book_comp) itr.next();
      System.out.println("Book ID: "+book.book_Id+" ~ Book Name: "+book.book_Name+" ~ Book Price: "+book.book_Price);
   }

}

}
------------------------
-----------------------
package Coparable_Std;

public class Book_comp implements Comparable<Book_comp>
{
int book_Id;
String book_Name;
double book_Price;
public Book_comp(int book_Id, String book_Name, double book_Price) 
{
super();
this.book_Id = book_Id;
this.book_Name = book_Name;
this.book_Price = book_Price;
}
public int getBook_Id() {
return book_Id;
}
public void setBook_Id(int book_Id) {
this.book_Id = book_Id;
}
public String getBook_Name() {
return book_Name;
}
public void setBook_Name(String book_Name) {
this.book_Name = book_Name;
}
public double getBook_Price() {
return book_Price;
}
public void setBook_Price(double book_Price) {
this.book_Price = book_Price;
}
/*@Override
public String toString() {
return "Book_comp [book_Id=" + book_Id + ", book_Name=" + book_Name + ", book_Price=" + book_Price + "]";
}*/

@Override
public int compareTo(Book_comp o) 
{
  if(this.book_Id > o.book_Id)
return 1;
  else
  return -1;
}

}
========================================================================

Wednesday, January 16, 2019

Important Methods

copyOf()
--------
Syntax:

 copyOf(int[] original, int newLength) 
----eg.
public static void main(String args[]) 
    { 
        // initializing an array original 
        int[] org = new int[] {1, 2 ,3}; 
  
        System.out.println("Original Array"); 
        for (int i = 0; i < org.length; i++) 
            System.out.print(org[i] + " "); 
  
        // copying array org to copy 
        int[] copy = Arrays.copyOf(org, 5); 
  
        // Changing some elements of copy 
        copy[3] = 11; 
        copy[4] = 55; 
  
        System.out.println("\nNew array copy after modifications:"); 
        for (int i = 0; i < copy.length; i++) 
            System.out.print(copy[i] + " "); 
    } 
-----------------------------------------------------------------------------------------
--System.arraycopy()
--
Syntax :

public static void 
arraycopy(Object source_arr, int sourcePos,Object dest_arr, int destPos, int len)
---eg.
 public static void main(String[] args) 
    { 
        int s[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; 
        int d[] = { 15, 25, 35, 45, 55, 65, 75, 85, 95, 105}; 
  
        int source_arr[], sourcePos, dest_arr[], destPos, len; 
        source_arr = s; 
        sourcePos = 3; 
        dest_arr = d; 
        destPos = 5; 
        len = 4; 
  
        // Print elements of source 
        System.out.print("source_array : "); 
        for (int i = 0; i < s.length; i++) 
            System.out.print(s[i] + " "); 
        System.out.println(""); 
  
        System.out.println("sourcePos : " + sourcePos); 
         
        // Print elements of source 
        System.out.print("dest_array : "); 
        for (int i = 0; i < d.length; i++) 
            System.out.print(d[i] + " "); 
        System.out.println(""); 
         
        System.out.println("destPos : " + destPos); 
         
        System.out.println("len : " + len); 
         
        // Use of arraycopy() method 
        System.arraycopy(source_arr, sourcePos, dest_arr,  
                                            destPos, len); 
         
        // Print elements of destination after 
        System.out.print("final dest_array : "); 
        for (int i = 0; i < d.length; i++) 
            System.out.print(d[i] + " "); 
    } 
-----------------------------------------------------------------------------------------
Object[] obj = list.toArray();//ArrayList to Array 
for copying arraylist to array
---------------------------
---------------------------
1.List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia));  //copy
2.List<Integer> list2 = Arrays.asList(ia);

import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) 
        throws Exception 
    { 
  
        try { 
  
            // creating Arrays of String type 
            String a[] = new String[] { "A", "B", "C", "D" }; 
  
            // getting the list view of Array 
            List<String> list = Arrays.asList(a); 
  
            // printing the list 
            System.out.println("The list is: " + list); 
        } 
  
        catch (NullPointerException e) { 
            System.out.println("Exception thrown : " + e); 
        } 
    } 
Output:
The list is: [A, B, C, D]
----------------------------------

Comparable:::::Sort an object using comparable

package Coparable_Std;
//Sort an object using comparable

import java.util.ArrayList;
import java.util.*;

public class Runner_Student_Comparable
{

public static void main(String[] args)
{

Student_Comparable sc1 = new Student_Comparable(12,"maths","Michle");
Student_Comparable sc2 = new Student_Comparable(100,"Science","Hitler");
Student_Comparable sc3 = new Student_Comparable(67,"hindi","Dicosta");
Student_Comparable sc4 = new Student_Comparable(99,"Urdu","Hillary");
Student_Comparable sc5 = new Student_Comparable(10,"Marathi","Donald");

ArrayList al = new ArrayList();
al.add(sc1);
al.add(sc2);
al.add(sc3);
al.add(sc4);
al.add(sc5);
Collections.sort(al); // Yaha se internally compareTo() call hota hai..[Comparable (I)]

Iterator itr = al.iterator();
while(itr.hasNext())
{
Student_Comparable sc = (Student_Comparable)itr.next();
System.out.println(sc.name +" ~ " +sc.roll+" ~ "+sc.subject);
}


}

}
-----------------------
-----------------------
package Coparable_Std;

import java.util.ArrayList;

public class Student_Comparable implements Comparable<Student_Comparable>
{
int roll;
String subject;
String name;
Student_Comparable(int a, String b, String c)
{
this.roll = a;
this.subject = b;
this.name = c;
}

public int compareTo(Student_Comparable sc) 
{
//System.out.println("Inside compareTo()");
if(roll == sc.roll)
{
return 0;
}
if(roll > sc.roll)
{
return -1;
}
else
return 1;
}

}

Comparable :::::Sort Employee OBJECT according to Names

package Coparable_Std;
//Sort Employee OBJECT according to Names.......
public class Employee implements Comparable<Employee>
{
int e_id;
int dept_id;
String name;

Employee(int eid,int dept,String name)
{
this.e_id = eid;
this.dept_id = dept;
this.name = name;
}

@Override
public int compareTo(Employee emp)
{
return this.name.compareTo(emp.name); //** For Strings we don't need to do anything
}   //coz String has it own implemented compareTo() for sorting

}
--------
--------
package Coparable_Std;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class Employee_Runner {

public static void main(String[] args) 
{
  
  Employee e1 = new Employee(104,072,"Giridhar");
  Employee e2 = new Employee(145,911,"Amit");
  Employee e3 = new Employee(167,053,"Mallik");
  Employee e4 = new Employee(134,884,"Pranav");
  Employee e5 = new Employee(101,445,"Ginny");
  ArrayList list = new ArrayList();
  list.add(e1);
  list.add(e2);
  list.add(e3);
  list.add(e4);
  list.add(e5);   
  Collections.sort(list);
  Iterator itr = list.iterator();
  while(itr.hasNext())
  {
  Employee emp = (Employee)itr.next();
  System.out.println(emp.e_id+"  "+emp.dept_id+"   "+emp.name);
  }  

}

}

Thursday, January 10, 2019

JS_Validation_Email

<html>
<body>
<script src="validation.js"></script>
<center><br><br><br><br>

<form action="registration.java" onsubmit="return validateEmail()">
Name: <input type="text" name="name"><br><br>
Email: <input type ="text" name="email"><br><br>
<input type ="submit" value="submit" >
</form>

</center>
</body>
</html>
====================



function validate()
{ alert("inside 1");
var result = true;
var i = document.getElementsByTagName("input");
if(i[0].value.length==0)
result = false;
return (result);
}

function validateEmail()
{
var result = true;
var e = document.getElementsByName("email")[0].value; // [0] means first email (if there are multiple emails)
//alert(e);
var atindex = e.indexOf('@');
//alert(atindex);
var dotindex = e.lastIndexOf('.');
//alert(dotindex);
if(atindex<1 || dotindex >= e.length-2 || dotindex - atindex <3)
result = false;


return (result);
}

PL SQL Basic Part 1

begin
dbms_output.put_line('welcome Amit to PL/SQL');
dbms_output.put_line(sysdate);
dbms_output.put_line(1234);
dbms_output.put_line(1+2+3+4);
dbms_output.put_line(user);
dbms_output.put_line(systimestamp);
end;

show serveroutput;
set serveroutput on;
----------------------------------------------
declare
v1 number;
v2 varchar2(10);
begin
v1:= 25;
v2:= 'AMIT';
dbms_output.put_line(v1);
dbms_output.put_line(v2);
end;
/
--------------------------------Addition
declare
a number;
b number;
c number;
begin
a := 10;
b:= 20;
c := a+b;
dbms_output.put_line(c);
end;
/
---------------------------------
---------------------------------
declare
a number default 10;
b number default 20;
c number :=30;
d number :=40;
begin
dbms_output.put_line(a+b);
dbms_output.put_line(c+d);
end;
--=============================
declare
c number :=30;
d number :=40;
e constant number :=500; --'e' is constant and it's value can't be changed
begin
c:= 110; ---previous value is overridden
d:=190;
dbms_output.put_line(c+d+e);
end;
----------------------------------------------------------------------
--DECLARATION- Cursor,Exception,Type,Local Subprogram,Pragma
----------------------------------------------------------------------
Declare
--
CURSOR c1 is select * from dept; --Cursor declaration
--
e1 Exception; -- this is exception , user defined
--
PRAGMA exception_init(e1,-2001); -- Pragma ie. procedure call
--
Type t1 is table of number; ----TYPE (Collections)
Type t2 is table of varchar2(100);
Type t2 is table of emp%ROWTYPE;
--
Produre P1 is ---- Local sub program(must be the last on in declaration)
Begin
dbms_output.put_line(P1);
END;
---------------------------
---- Exception Predefined
---------------------------
declare
v1 number;
begin
v1:= 'character to number assignment'; -- we can't assign char to number
dbms_output.put_line('v1 : '||v1);
exception
when value_error then
    dbms_output.put_line('Eception  - Value error');
end;
------------------------
---- Exception Default
------------------------
declare
v1 number;
begin
v1:= 'character to number assignment'; -- we can't assign char to number
dbms_output.put_line('v1 : '||v1);
exception
when others then
    dbms_output.put_line('Eception  - others');
end;
------------------------
---- Local Variables /Gloabal variable
--Local var. are declared in pl blocks and globle variable comes from
--outside applications (java,dotNet application etc.)
------------------------
var v1 number;
var v2 date;
var; ---to see all the globle variables

begin
:x := 25; --globle var starts with colon (:)
end;
---------------------------------------------
--SQL in plsql
---------------------------------------------
-- DML -- select,Insert,Update,Delete,Merge
-- TCL -- Commit,Rollback,Savepoint,Set Transaction
--
desc RES_BOOK_LIST;
--
declare
v_id varchar2(10);
v_name varchar2(30);
v_author varchar2(30);
begin
select book_id,book_name,author
into v_id ,v_name,v_author
from RES_BOOK_LIST
where book_id ='109';
dbms_output.put_line('ID: '||v_id||' :: '||'Name: '||v_name||' :: '||'Author: '||v_author);
end;
/
set serveroutput on ;
--------------------------
desc RES_BOOK_LIST;
--
begin
insert into RES_BOOK_LIST(book_id,book_name,author)
values('9876','My Time','Manjhi');
end;
/
-------------------------------------------------
-------------------------------------------------

declare
v_id VARCHAR2(10);
v_name VARCHAR2(30);
v_author  VARCHAR2(30);
begin
select BOOK_ID,BOOK_NAME,AUTHOR
into v_id,v_name,v_author
from RES_BOOK_LIST
where BOOK_ID= '100';
dbms_output.put_line('Original Values:-');
dbms_output.put_line('ID: '||v_id||' :: '||'Name: '||v_name||' :: '||'Author: '||v_author);

update RES_BOOK_LIST
set BOOK_NAME='Wings of Fire' where BOOK_ID= '100';

select BOOK_ID,BOOK_NAME,AUTHOR
into v_id,v_name,v_author
from RES_BOOK_LIST
where BOOK_ID= '100';
dbms_output.put_line('After Update:-');
dbms_output.put_line('ID: '||v_id||' :: '||'Name: '||v_name||' :: '||'Author: '||v_author);

rollback;

select BOOK_ID,BOOK_NAME,AUTHOR
into v_id,v_name,v_author
from RES_BOOK_LIST
where BOOK_ID= '100';
dbms_output.put_line('After Rollback:-');
dbms_output.put_line('ID: '||v_id||' :: '||'Name: '||v_name||' :: '||'Author: '||v_author);
commit;
end;

-----------------------------------------------
--Rollback
declare
savepoint s1;
rollback to s1;
end;
------------------------------------------------
---SET Transaction
declare
begin
set transaction read only;  --must be first statement
end;
commit;
--
declare
begin
set transaction read write;  --must be first statement
end;

update RES_BOOK_LIST
set BOOK_NAME='Wings of Fire' where BOOK_ID= '100';

rollback;
-------------------------------------------------------------------
--PL/SQL Attributes
-------------------------------------------------------------------
-- In above pl blocks we used fixed size and fixed data types which is not
-- good practice as any change in db causes error , Hence use Attributes.
-- Two Types
--1)%type
--2)%row type
--------------------Examples..
--
declare
--v_bname varchar2(14)  ---- No attributes i.e fixed type
v_bname master_book_list.BOOK_NAME %TYPE; --- With attributes
Begin
select book_name
into v_bname
from master_book_list
where BOOK_ID = '100';
dbms_output.put_line('Book Name:'||v_bname);
end;
/
set serveroutput on;
---
declare
v_id   RES_BOOK_LIST.book_id %type;
v_name RES_BOOK_LIST.book_name %type;
v_author RES_BOOK_LIST.author %type;
begin
select book_id,book_name,author
into v_id ,v_name,v_author
from RES_BOOK_LIST
where book_id ='109';
dbms_output.put_line('ID: '||v_id||' :: '||'Name: '||v_name||' :: '||'Author: '||v_author);
end;
/
------------------------
-- % ROW TYPE
------------------------
-- In % ROW Type we don't specify column name , we specify only table and on
--runtime the corrosponding datatype and size is taken dynamically.
--Example
declare
v_emp EMPLOYEES %rowtype;
begin
select EMPLOYEE_ID,FIRST_NAME,LAST_NAME,EMAIL
into v_emp.EMPLOYEE_ID ,v_emp.FIRST_NAME,v_emp.LAST_NAME,v_emp.EMAIL
from EMPLOYEES
where EMPLOYEE_ID='100';
dbms_output.put_line('E_ID:'||v_emp.EMPLOYEE_ID||' :: '||'F_Name:'||v_emp.FIRST_NAME||' :: '||'L_Name:'||v_emp.LAST_NAME||' :: '||'Email:'||v_emp.EMAIL);
end;
/
--------------------------------------------------------------------------
--Named Block
-------------
--<<ABC>>  this is lebel
--this level can be used for complete block starting with Declare  or Begin
--can be used any where in Begin or Exception part
--cannot be used in Declaration part
----we can call globle variables from local/sub blocks.
--------------------------------------------------------------------------
<<ABC>>
Declare
v1 number;
v2 number;
Begin
v1:= 10;
v2:= 11;
dbms_output.put_line('Globle v1: '||v1);
dbms_output.put_line('Globle v2: '||v2);
  <<XYZ>>
  Declare
  V3 number;
  v4 number;
  Begin
  v3:= 20;
  v4:= 21;
  dbms_output.put_line('Local V3 '||v3);
  dbms_output.put_line('Local V4 '||v4);
  dbms_output.put_line('Globle var from local area v1: '||v1);
  dbms_output.put_line('Globle from local area v2: '||v2);
  -----
  dbms_output.put_line('Local XYZ: '||XYZ.v4);
  dbms_output.put_line('Globle ABC: '||ABC.v1);
 
  end;
end;
/
--------------------------------------------------------------------------------
--IDENTIFIERS
---------------
--Identifiers are names of Procedures,Functions,Variables,Constants,Cursors,Exceptions etc.
--Max Length = 30 characters
--
---------------------------------------------------------------------------------

--------------------------------------------------------------------------------
--Control Structures
--------------------
--if/if-else/nested If/
--Loop/While/For
--Goto/Null
---------------------------------------------------------------------------------
--IF Else
---------
Declare
v1 number := 1;
v2 number;
v3 number;
begin
v2:= 10;
v3:= 20;
if v1>=1 then
dbms_output.put_line(v2+v3);
end if;
exception
when others then
    dbms_output.put_line('Eception  - others');
end;
/
-----------------------------
declare
v1 varchar(10) := 'AMIT';
v2 varchar(10) := 'MANJHI';
begin
if v1 = 'AMIT' then
  if v2 ='MANJHI' then
   dbms_output.put_line('Eligible');
   end if;
end if;
end;
/
------------------------------------------------
--Loop
--..
--End Loop;
------------------------------------------------
declare
v1 number := 1;
begin
loop
dbms_output.put_line(v1);
exit when v1>=10;
v1 := v1 + 1;
end loop;
end;
/

------------------------------------------------
--For Loop
-----------
-- for i in 1 ..10 Loop
-- End loop;
-- for i in reverse 1 .. 10 loop
-- End loop;
-------------------------------------------------
declare
--v1 number := 10;
begin
for i in 1 .. 10 loop
dbms_output.put_line(i);
--i := i+2;  ----------------------> Not allowed to assign to loop variable
end loop;
end;
/
----------------------
declare
v1 number := 10;
begin
for i in reverse 1 .. v1 loop
dbms_output.put_line(i);
end loop;
end;
/
-------------------------------------------------------------------
-- While Loop
-------------------------------------------------------------------
DECLARE
   a number(2) := 10;
BEGIN
   WHILE a < 20 LOOP
      dbms_output.put_line('value of a: ' || a);
      a := a + 1;
   END LOOP; 
END;
/


----------------------------
--Goto & Null
----------------------------
Declare
v1 number := 1;
begin
    <<abc>>
     begin
     dbms_output.put_line(v1);
     end;
     if v1>=5 then
     return;
     end if;   
     v1:= v1+1;
     goto abc;   
end;
/
----
begin
if 1=1 then
null;  --->does noting
end if;
end;
------------------------------------------------------------------------------
-- OPERATORS
-- :=    assignment
-- ..    for loop
--  != , <> , ~=   Inequality/Not Equal to
--  =>   Association  (4 passing value to parameters(function, procedure,cursor))
--  **   Exponential (used for power ^2)
--Examples
--var1 number := 10;
--for in 1 .. 10 loop;
-- if v1 ~= V2
-- v1:= 2**3;
--
------------------------------------------------------------------------------
-- SUB PROGRAMS
----Procedures (Used for Actions)
----Function (Used for Calculations mainly)
------------------------------------------------------------------------------
--Procedure
--It has its Name/Parameters/DB Object/stored in db/reusable
--/seperate Compilation+Execution
--Errors not displayed directly .. use showErrors(Functions)
--or query User_Errors(data dictionary)
--cannot be called in DML
-----------
--Example
Create or replace procedure proc_p1 is
begin
dbms_output.put_line('Welcome to my First Proc.');
dbms_output.put_line('Proc Created');
end;
/
set serveroutput on;
execute proc_p1;
show error;

-----Procedure with Error
create or replace procedure proc_p2 is
--declare
num1 number;
begin
num1  : 10;   ----Error :=
dbms_output.put_line(10/2);
exception
when others then
dbms_output.put_line('OOPs! something went wrong!');
end;
/
--------------
exec PROC_P2;
show errors; ---shows most resent compiled pl sql objects.
--------------
-- user_errors
-- user_source
-- user_objects
--user_procedures
--------------
select * from user_errors; --predefined table for errors
select * from user_source; --Data Dictionary to stored all PL-SQL Objects(proc,trigger,functions,etc.)
select text from user_source where name ='ADD_JOB_HISTORY'; -- to check Procedure coding
select * from  user_objects; --Data dictionary  to get all DB objects (Both sql +plsql)
select * from user_procedures;--Data dictionary to get all PLSQL Objects. (Procedures, Fuctions, Triggers,...)

--------------------------------------------------------------
---Extra
---Merging query (dept to dept1)
Merge into dept1 A
using dep B
on (A.deptno = B.deptno)
when matched then update set loc = B.loc
when not matched then insert(deptno,dname,loc,loc_id)
                      values(B.deptno,B.dname,B.loc,B.loc_id);
---------------------------------------------------------------                   
alter user hr identified by hr account unlock;
grant debug connect session to hr;
grant debug any procedure to hr
------------------------------------------------------------------------------------------------------------------
                                                      continued.....
------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- SUB PROGRAMS
----Procedures (Used for Actions)
----Function (Used for Calculations mainly)
------------------------------------------------------------------------------
--Procedure
--It has its Name/Parameters/DB Object/stored in db/reusable
--/seperate Compilation+Execution
--Errors not displayed directly .. use showErrors(Functions)
--or query User_Errors(data dictionary)
--cannot be called in DML
-----------
--Example
Create or replace procedure proc_p1 is
begin
dbms_output.put_line('Welcome to my First Proc.');
dbms_output.put_line('Proc Created');
end;
/
set serveroutput on;
execute proc_p1;
show error;

-----Procedure with Error
create or replace procedure proc_p2 is
--declare
num1 number;
begin
num1  : 10;   ----Error :=
dbms_output.put_line(10/2);
exception
when others then
dbms_output.put_line('OOPs! something went wrong!');
end;
/
--------------
exec PROC_P2;
show errors; ---shows most resent compiled pl sql objects.
--------------
-- user_errors
-- user_source
-- user_objects
--user_procedures
--------------
select * from user_errors; --predefined table for errors
select * from user_source; --Data Dictionary to stored all PL-SQL Objects(proc,trigger,functions,etc.)
select text from user_source where name ='ADD_JOB_HISTORY'; -- to check Procedure coding
select * from  user_objects; --Data dictionary  to get all DB objects (Both sql +plsql)
select * from user_procedures;--Data dictionary to get all PLAQL Objects.
------------------------------------------------------------
-----------------------------------------------
select * from EMP_SAL;
create procedure proc_sum (a IN number , b IN number, c OUT number)
AS
begin
c := a+b;
end;
/
---
var k number;  --
execute proc_sum(100,5000,:k);
print :k;
-----------------
-----------------
create  or replace procedure proc_p2
AS
v_id     EMPLOYEES.EMPLOYEE_ID  %type;
v_fname  EMPLOYEES.FIRST_NAME %type;
v_lname  EMPLOYEES.LAST_NAME %type;
v_email  EMPLOYEES.EMAIL %type;
BEGIN
select EMPLOYEE_ID,FIRST_NAME,LAST_NAME,EMAIL
into v_id ,v_Fname,v_Lname,v_Email
from Employees
where EMPLOYEE_ID = 100;
dbms_output.put_line('EMPLOYEE_ID: '||v_id||'  FIRST_NAME: '||v_fname||'  LAST_NAME: '||v_lname||'  EMAIL: '||v_email);
end;

execute  proc_p2;
---------------------
---------------------
create  or replace procedure proc_p3
AS
v_id   RES_BOOK_LIST.book_id %type;
v_name RES_BOOK_LIST.book_name %type;
v_author RES_BOOK_LIST.author %type;
begin
select book_id,book_name,author
into v_id ,v_name,v_author
from RES_BOOK_LIST
where book_id ='109';
dbms_output.put_line('ID: '||v_id||' :: '||'Name: '||v_name||' :: '||'Author: '||v_author);
end;
-----------------------
-----------------------
-- Procedures with IN OUT Parameter
------------------------------
create or replace procedure increase_salary(Eid IN number,Amt IN Number,S out Number) IS
begin
update emp_sal set salary = salary+Amt
where e_id= Eid;
commit;
select salary into S from Emp_sal where e_id = Eid;
end;
/
--------
var k number;  --
execute increase_salary(100,5000,:k);
print :k;
--------
----------------------------------------------------------------
--Function
----------------------------------------------------------------
----------Example 1 ---
create or replace function f1 return number Is
begin
 return 123; --Number type
end;
/
---
var x number;
execute :x := f1;---calling function (f1) and storing returned value to x variable
print x;
--or--
declare
v number;
begin
v := f1;
dbms_output.put_line(v);
end;
--or--
select f1 from dual;
--or--
begin
dbms_output.put_line(f1);
end;
------------------------------------------------------------------------------
------------------------------------------------------------------------------
create function f2 (id IN Number) return varchar IS
v_id  emp_sal.e_id %Type;
F_name  emp_sal.f_name %Type;
L_name  emp_sal.l_name %Type;
v_salary  emp_sal.salary %Type;
begin
select e_id,f_name,l_name,salary
into v_id,f_name,l_name,v_salary
from Emp_sal where e_id = id;
return 'EID:'||v_id||' F_NAME:'||f_name||' L_NAME:'||l_name||' Salary:'||v_salary;
end;
/
---
select f2(100) from dual;
---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--Cursors
--3 types
--1)Static - select statement is fixed
--    2 types - 1)Implecit 2)Expicit
--2)Dynamic - select statement is not fixed
--3)Ref Cursors - Provide storage + return result set
--    2 types - 1) Strong 2) weak  (Strong has return type but weak does not)
--sys_refcursor is data type for ref Cursor
-----------------------------------
---Example weak ref cursor
create or replace procedure proc_ref_cursor (v_id IN Number, vref_cursor OUT sys_refcursor)
IS
Begin
open vref_cursor for select * from emp_sal where e_id = v_id;
end;
/
--
var vref refcursor; --globle variable
execute proc_ref_cursor(100,:vref);
print vref;
------------------------------------------------------------------------
------------------------------------------------------------------------
create or replace procedure pc (vref_cursor OUT sys_refcursor)
IS
Begin
open vref_cursor for select * from emp_sal;
end;
/
--
var vref refcursor; --globle variable
execute pc(:vref);
print vref;

------------------------------------------------------------------------------



Java 8 Notes Pics