Wednesday, September 11, 2013

Java method to pass n number of arguments or default arguments

I was writing a Java code for Fibonacci numbers using recursion in java.

There might be n number of ways to achieve this.

I was used the below way, where there can be n number of arguments provided to a java method.

To brief about Fibonacci series
0, 1, 1, 2, 3, 5, 8, ...

First and next value in series is 0 & 1, first value in the sequence is 0, second is 1, third value is (first + second value in the series), goes on...
F0 = 0 & F1= 1

Below is the java method which will be recursively called.
private static long calculateFibo(long start, long next, long numberofiter, int... i)
while calling this method it is not necessary that the last parameter in the method signature should be provided.
Below is how it is called, there is no fourth parameter passed.
long result = calculateFibo(start,next,numberofiter);

Also note in the implementation of the method,
the int... i is validated, this is a integer array variable. where the first in the the array is the count used to validate the iteration.
This validation is done here
                   int leng = i.length;

                   if(leng > 0 && leng == 1)
          {
                     cnt = i[0]; //This i[0] has the first value of the string.
//When iterating recursively we are passing this value refer the next code snippet
                cnt++;
           }


Calling the "calculateFibo" method recursive passing the default parameter. Below is the code snippet.
                calculateFibo(start, next, numberofiter,cnt);
cnt is the last parameter passed.

As here i need int variable passed is as int ... i. This can be Object also.

Code:
--------------------------------------------------------------------------------------------------------
public class FiboStart {


public static void main(String args[])
{
long start =0;
long next =1;
//Just the number of iteration.
long numberofiter = 37;

long result = calculateFibo(start,next,numberofiter);
System.out.println(numberofiter + " Fibonacci is "+ result);
}

private static long calculateFibo(long start, long next, long numberofiter, int... i) {
int leng = i.length;
int cnt = 0;
if(leng > 0 && leng == 1)
{
cnt = i[0];
cnt++;
}

if( cnt < numberofiter)
{
System.out.println("start := "+start+ " , next "+next +" === cnt "+cnt);
next = start+next;
start =next - start;
return calculateFibo(start, next, numberofiter,cnt);
}
return start;

}
}

Output in this case will be 
            37 Fibonacci is 24157817

=======================================================================
Below is the code where one can pass more than one int value when calling the method.
Highlighted code is changed for understanding.

Code:
----------------------------------------------------------------------------------------------------------



public class FiboStart {

public static void main(String args[])
{
long start =0;
long next =1;

long numberofiter = 10;

long result = calculateFibo(start,next,numberofiter);
System.out.println(numberofiter + " Fibonacci is "+ result);
}

private static long calculateFibo(long start, long next, long numberofiter, int... i) {
int leng = i.length;
int cnt = 0;
int cnt1 = 0;
if(leng > 0 && leng == 2)
{
cnt = i[0];
cnt1 = i[1];
System.out.println("first default param "+i[0]+" AND  "+"second default param "+i[1]);
cnt1 = cnt1+10;
cnt++;
}

if( cnt < numberofiter)
{
//System.out.println("start := "+start+ " , next "+next +" === cnt "+cnt);
next = start+next;
start =next - start;
return calculateFibo(start, next, numberofiter,cnt,cnt1);
}
return start;
}
}



Output:




first default param 0 AND  second default param 0
first default param 1 AND  second default param 10
first default param 2 AND  second default param 20
first default param 3 AND  second default param 30
first default param 4 AND  second default param 40
first default param 5 AND  second default param 50
first default param 6 AND  second default param 60
first default param 7 AND  second default param 70
first default param 8 AND  second default param 80
first default param 9 AND  second default param 90
10 Fibonacci is 55




Wednesday, August 21, 2013

Eclipse message Error occurred during initialization of VM Incompatible initial and maximum heap sizes specified

When do we get 

Error occurred during initialization of VM 
Incompatible initial and maximum heap sizes specified 

During the Java application development using eclipse which uses huge memory i provided the -X JVM arguments in the eclipse.

When providing the -X option i gave the order wrongly like

-Xmx512m -Xms2048m


On executing the application i got the error message, the easiest way to fix is change the order as below

-Xms512m -Xmx2048m


Tuesday, August 6, 2013

Oracle BULK COLLECT and FORALL statements



Oracle BULK COLLECT and FORALL :

BULK COLLECT:
SELECT statements that retrieve multiple rows with a single fetch, improving the speed of data retrieval.

1. Oracle BULK COLLECT INTO with queries:

In software development when dealing with database we may use to write functions, procedure or executable blocks in oracle pl/sql in certain circumstance where we need an alternate to cursors we can use bulk collect for selecting values from the table.

Below is a example for BULK COLLECT INTO FROM QUERY

Create a table temp_test using the below query.

create table temp_test (emp_name varchar2(50), emp_id number(10) primary key, emp_dept varchar2(25), emp_gender varchar2(1));

Assume below are the data in the table.
EMP_NAME
EMP_ID
EMP_DEPT
EMP_GENDER
test1
1
dept1
M
test2
2
dept2
M
test3
3
dept1
F
test4
4
dept2
F
test5
5
dept2
M
test5
6
dept2
F
test7
7
dept2
M
test8
8
dept2
M
test9
9
dept9
M





Code Example#1 
For BULK COLLECT INTO to select the data from the table 

DECLARE
   --Below is the variable that can hold the filed values of the table.
   TYPE insrt_temp IS TABLE OF temp_test%ROWTYPE;
   v_temp   insrt_temp;
BEGIN
   --query to select the values from temp_test table and store it in the type variable
   SELECT *
     BULK COLLECT INTO v_temp
     FROM temp_test;
   --below code will loop thru the selected values and prints the information
   FOR i IN 1 .. v_temp.COUNT
   LOOP
      DBMS_OUTPUT.put_line ('inside loop : ' || v_temp (i).emp_name);
   END LOOP;
END;
/ 
Output: (enable dbms_output if you are using tools like toad)

inside loop : test1
inside loop : test2
inside loop : test3
inside loop : test4
inside loop : test5
inside loop : test5
inside loop : test7
inside loop : test8
inside loop : test9

2. Oracle BULK COLLECT INTO with Cursors:

Below is the code sample with the same table information.
we try to fetch the data from the table via cursor and bulk collect


Code Example #2:


DECLARE
   --Below is the variable that can hold the filed values of the table.
   TYPE insrt_temp IS TABLE OF temp_test%ROWTYPE;

   v_temp   insrt_temp;
   --Cursor declaration
   CURSOR cur_temptest
   IS
      SELECT *
        FROM temp_test
       WHERE emp_id BETWEEN 1 AND 9;
BEGIN
   --query to select the values from temp_test table and store it in the type variable
   OPEN cur_temptest;

   FETCH cur_temptest BULK COLLECT INTO v_temp;

   CLOSE cur_temptest;

   --below code will loop thru the selected values and prints the information
   FOR i IN 1 .. v_temp.COUNT
   LOOP
      DBMS_OUTPUT.put_line ('employ loop : ' || v_temp (i).emp_name);
   END LOOP;
END;
/

Output of code example #2: 

employ loop : test1
employ loop : test2
employ loop : test3
employ loop : test4
employ loop : test5
employ loop : test5
employ loop : test7
employ loop : test8
employ loop : test9


3. Oracle FORALL :
FORALL: INSERTs, UPDATEs, and DELETEs that use collections to change multiple rows of data very quickly

Code Example #3: 
The below code sample will insert the values into temp_test table. after executing this pl/sql block. use the above BULK COLLECT INTO code to view the value.


DECLARE
   TYPE num_list_type IS TABLE OF NUMBER
      INDEX BY BINARY_INTEGER;
   v_num   num_list_type;
BEGIN
   v_num (1) := 13;
   v_num (2) := 14;
   v_num (3) := 15;
   v_num (4) := 16;

   FORALL i IN v_num.FIRST .. v_num.LAST
      INSERT INTO temp_test
           VALUES ('test' || v_num (i),
                   v_num (i),
                   'dept' || v_num (i),
                   'M');

END;
/
Output:
The code will get executed successfully.

On executing the Code Example #1 you get the below output after executing the code example #3:

Output after executing the example #3 and using the code example #1 or #2: 

nside loop : test1
inside loop : test2
inside loop : test3
inside loop : test4
inside loop : test5
inside loop : test5
inside loop : test7
inside loop : test8
inside loop : test9
inside loop : test13
inside loop : test14
inside loop : test15
inside loop : test16

4. Oracle FORALL with SQL%BULK_ROWCOUNT:

The %BULK_ROWCOUNT cursor attribute is a composite structure designed to use with FORALL statement.
The %BULK_ROWCOUNT acts like an associative array (index-by-table). Its ith element stores the number of rows processed by the ith execution of the INSERT statement. If the ith execution affects no rows, then %BULK_ROWCOUNT(i) returns zero.


Code Example #4:


DECLARE
   TYPE num_list_type IS TABLE OF NUMBER
      INDEX BY BINARY_INTEGER;

   v_num   num_list_type;
BEGIN
   v_num (1) := 13;
   v_num (2) := 14;
   v_num (3) := 15;
   v_num (4) := 16;

   FORALL i IN v_num.FIRST .. v_num.LAST
      INSERT INTO temp_test
           VALUES ('test' || v_num (i),
                   v_num (i),
                   'dept' || v_num (i),
                   'M');

   FOR i IN v_num.FIRST .. v_num.LAST
   LOOP
      DBMS_OUTPUT.put_line (
            'Value inserted '
         || SQL%BULK_ROWCOUNT (i)
         || ' row (s)'
         || ' within for loop '
         || i);
   END LOOP;
END;
/
Output:
Value inserted 1 row (s) within for loop 1
Value inserted 1 row (s) within for loop 2
Value inserted 1 row (s) within for loop 3
Value inserted 1 row (s) within for loop 4


The performance as always is a factor of data volume. For bulk collect and forall statements there is a detailed information related to performance in the below link
http://www.oracle.com/technetwork/issue-archive/2012/12-sep/o52plsql-1709862.html





Thursday, July 25, 2013

Dynamically generating a properties file and Reading a properties file in Java using Properties java class


To generate a properties file setting the key-value attributes:

The code is self explanatory 

Code snippet example #1: 

 Below is the code which will generate the properties file named, dbdetail.properties.

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
 
public class GenerateProperties
{
    public static void main( String[] args )
    {
     Properties prop = new Properties();
 
     try {
      //set the properties value
      prop.setProperty("databasename", "dbname");
      prop.setProperty("dbuserid", "userId");
      prop.setProperty("dbpassword", "passwrd");
 
      //save properties to project root folder
      prop.store(new FileOutputStream("dbdetail.properties"), null);
 
     } catch (IOException ex) {
      ex.printStackTrace();
        }
    }
}
Output:
a file dbdetail.properties will be created with below content

#Thu Jul 25 10:09:07 PDT 2013
dbuserid=userId
databasename=dbname
dbpassword=passwrd


To read the properties file using Properties object of java

Code snippet example #2:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
 
public class ReadProperties
{
    public static void main( String[] args )
    {
     Properties prop = new Properties();
 
     try {
               //load a properties file
      prop.load(new FileInputStream("dbdetails.properties"));
 
               //get the property value and print it out
                System.out.println(prop.getProperty("databasename"));
      System.out.println(prop.getProperty("dbuserid"));
      System.out.println(prop.getProperty("dbpassword"));
 
     } catch (IOException ex) {
      ex.printStackTrace();
        }
 
    }
}
Note: be sure that the location of the properties file is within the classpath.
Output will be :

dbname
userId
passwrd

There are other scenarios to load the properties file:
Instead of specifying the location of the properties file, if we include the properties file in class path we can directly read the file. 
refer to the  (Code snippet example #2), we are using FileInputStream instead we can use getClassLoader() to locate the properties file if its included in the classpath. 

Below is the code to load the properties file when the properties file is within the class path

1. to access the properties file - static way
2. to access the propertied file within non-static way

Below is representation of 1. accessing within a static block
Code snippet example #3

import java.io.FileInputStream;
import java.io.IOException;
import java.utilutil.Properties;
 
public class ReadPropFrmClasspath
{
    public static void main( String[] args )
    {
     Properties prop = new Properties();
 
     try {
               //load a properties file from class path, inside static method
      prop.load(ReadPropFrmClasspath.class.getClassLoader().getResourceAsStream("dbdetail.properties");));
 
               //get the property value and print it out
                System.out.println(prop.getProperty("databasename"));
      System.out.println(prop.getProperty("dbuserid"));
      System.out.println(prop.getProperty("dbpassword"));
 
     } catch (IOException ex) {
      ex.printStackTrace();
        }
 
    }
}
Note: 
prop.load(ReadPropFrmClasspath.class.getClassLoader().getResourceAsStream("dbdetail.properties");));
Output:
dbname
userId
passwrd


Below is representation of 2. accessing within a non-static block:

import java.io.FileInputStream;
import java.io.IOException;
import java.utilutil.Properties;
 
public class ReadPoprFrmClassPath2
{
    public static void main( String[] args )
    {
     Properties prop = new Properties();
 
     try {
               //load a properties file from class path, non-static method
      prop.load(getClass().getClassLoader().getResourceAsStream("dbdetail.properties");));

 
               //get the property value and print it out
                System.out.println(prop.getProperty("database"));
      System.out.println(prop.getProperty("dbuser"));
      System.out.println(prop.getProperty("dbpassword"));
 
     } catch (IOException ex) {
      ex.printStackTrace();
        }
 
    }
}
Note: 
prop.load(getClass().getClassLoader().getResourceAsStream("dbdetail.properties");));
Output:

dbname
userId
passwrd


To read the properties file we can also use the ResourceBundle objects of java.

It all depends on the situation in the development to use.











Tuesday, July 23, 2013

Spring 3.1+ Profile - using profile in web application development.

SPRING Profiles:

Definition: This is spring framework newest feature (available in spring 3.1 and above versions)
During the development of web application we undergo different environments through out the software development life cycle (SDLC) like development environment, testing environment, production environment, etc.
Assume the database for each environment is different, then it is overhead for the developer to change the information in the configuration file or properties file for database credentials for every environment. If the web-application is developed using spring (3.1 +) profiles comes into picture to rescue us.

Its easy to configure. Let us see how to configure it in spring application.

The spring context file has provision to define profile in beans tag. (i assume you have knowledge about the spring context files).

Example (code snippet of spring-context.xml):

Note: i am using Spring 3.2.

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

 <beans profile= "development">
     <bean id = "datasoure" class="org.apache.commons.dbcp.BasicDataSource"  destroy-method="close">
                          <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@host:port:dbname" />
<property name="username" value="usrid" />
<property name="password" value="passwrd" />
     </bean>
</beans>
 <beans profile= "test">
     <bean id = "datasoure" class="org.apache.commons.dbcp.BasicDataSource"  destroy-method="close">
                          <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@host:port:dbname" />
<property name="username" value="usrid" />
<property name="password" value="passwrd" />
     </bean>
  </beans>
</beans>

The nexted <beans> tag is used here for defining the profile information.

Now we need to tell Spring to take the appropriate database information from this context file, so we will use "spring.profiles.active"
I am using the web.xml servlet.Dispatcher to tell spring to use spring-context.xml file.and we can use the profile value (development or test) as init parameter to fetch the appropriate database information.

Example Code snippet of  web.xml to invoke the specific profile information:

<?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_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>profilesample</display-name>
        
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/spring-context.xml</param-value>
</init-param>
<init-param>
<param-name>spring.profiles.active</param-name>
<param-value>development</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
  <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
         </servlet-mapping>
...
...
..
 </web-app>

The init-pram for the "spring.profile.active" is development which tells spring to use the "development" bean information of spring-context.xml to get the database connection. If you need the test database information to be used in the init-param tag param-value used test.

Info:
The profiles can also be configured using annotation. 



Monday, June 10, 2013

Linux/Unix mail - view and delete all mail for an user

Linux Command to view, delete mail:

After sudo as the user, to check the mail information for the user below command needs to be used:

Command 1: (view the unread mails)
$ mail
Output:
Mail version 8.1 6/6/93.  Type ? for help.

"/var/spool/mail/user1": 1 message 1 unread
>U  1 root@user1 Mon Jun 10 10:40  25/1044 ......

&

Note: In this case the "$" prompt is changed to "&" indicates inside mail process.

Command 2: (display unread mail content)
& <hit_return_or_enter_key>
Output:
Message 1:

From username@user1.com  Mon Jun 10 10:40:11 2013
Date: Mon, 10 Jun 2013 10:40:01 -0700
From: root@user1.com (Cron Daemon)
To: username@user1.com
Subject: Cron <username@user1> /startApp.ksh >> /logTest.log
Content-Type: text/plain; charset=UTF-8
.......
.......
&

Note: the above is the content of the unread mail in Linux. 
If there is no mail to read when you hit enter, in "&" prompt (in mail process), the output will be 
"At EOF"

Command 2 .1: (when there is no mail to read in mail process on hitting enter)
&
Output:
At EOF



Command 3: (delete mail options)
& d <hit_enter_or_return_key>
Output:

Note: Nothing will be displayed as output, back to & prompt. This command will delete the mail one at a time.

& d * <hit_enter_or_return_key>

Output:

Note: Nothing will be displayed as output, back to & prompt. This command will delete all the mail for that user.


Command 4: (display mail options)
& ? <hit_enter_or_return_key>

Output:

    Mail   Commands
t <message list>                type messages
n                               goto and type next message
e <message list>                edit messages
f <message list>                give head lines of messages
d <message list>                delete messages
s <message list> file           append messages to file
u <message list>                undelete messages
R <message list>                reply to message senders
r <message list>                reply to message senders and all recipients
pre <message list>              make messages go back to /usr/spool/mail
m <user list>                   mail to specific users
q                               quit, saving unresolved messages in mbox
x                               quit, do not remove system mailbox
h                               print out active message headers
!                               shell escape
cd [directory]                  chdir to directory or home if none given

A <message list> consists of integers, ranges of same, or user names separated
by spaces.  If omitted, Mail uses the last message typed.

A <user list> consists of user names or aliases separated by spaces.
Aliases are defined in .mailrc in your home directory.
&

Command 4: (to quit from the  mail process shell)
& q <hit_enter_or_return_key>

Output:

Note: Nothing will be displayed as output, back to "$" prompt.

After deleting all the mails or when there is not mails to read for the user:
Command 4:
$ mail
Output:
No mail for username

Wednesday, May 29, 2013

Invalid chunk'=true' ignored warning message in Spring application.


Issue:

WARNING: Parameters: Invalid chunk '=true' ignored. is getting logged in the web application.

We have a web application developed using Spring, Struts2 & hibernate framework.

When we navigate from one tab to another tab within the application we get the below message logged in the log file. 
We have used the log4j for logging information within the application.


The warning message in the log file is mentioned below.

May 29, 2013 9:18:34 AM org.apache.tomcat.util.http.Parameters processParameters
WARNING: Parameters: Invalid chunk '=true' ignored.



Resolution:

This message was logged in our application because we didn't have the name attribute for a hidden field.

code snippet that cased the warning message:

 <s:hidden id = "testid" value="true"></s:hidden>

to fix, we added the name attribute to this tag as

<s:hidden id="testid" name="testid" value="true"></s:hidden>


Though this is a warning message, sometime we don't want this warning message to be logged. The above solution can be applied.

refer the below link also for more explanation.

Friday, May 24, 2013

command to view the running process in Linux/Unix

In most of the web application deployed in linux/unix machine.

we may some time need to know, whether the process is running or not.

For example:
our application is deployed in Linux system and runs in tomcat server.
we use tomcat scripts to deploy the application (start/stop shell script).

it would always be good to verify whether the application is deployed and running in the server.

command to use

$ ps -ef

Note: ps - provide the snapshot of process status running in Linux/ unix os

- e and -f are generally known as switch for the command or options or selection.
            -e will select all the process running
            -f  will provide full format listing of the process.

there are more number of options for "ps" command use the below command to explore it

$ man ps

or

$ ps -help

On executing the command

Command #1
$ ps -ef

sample out put:

UID      PID     PPID C   STIME     TTY     TIME      CMD
root      1170  1139   0     09:42       pts/0    00:00:00   su - user1

user1     6021  1171  0    13:35        pts/0    00:00:00    ps -ef
user2     6022  1171  0    13:35        pts/0    00:00:00  -ksh

The Command #1 can output can be piped to grep to filter specific line to be displayed.

Example
Command #2
$ ps -ef | gerp user2

sample out put

user2     6022  1171  0    13:35        pts/0    00:00:00  -ksh

only returns the line that contains user2 (as we are greping for it in linux).

additionally use the below command combination to get the header also

Command #3
$ ps -ef | grep -e user2 -e PID

sample out put 
UID      PID     PPID C   STIME     TTY     TIME      CMD
user2     6022  1171  0    13:35        pts/0    00:00:00  -ksh

If the process needs to be killed we should use the PID number of the process. PID stands for process-id, every process in Linux has an process-id. For more information, we need to understand the Linux OS structure.

to kill the running process use the below command 

$ kill -9 6022

kill - command to kill the process
-9 is the option which force kills
PID process id which should be killed, in this case its 6022.

Note: always be cautious on using the kill command when killing a process. 


Tuesday, May 21, 2013

oracle query to return null when query returns no rows to return

Assume there is employee table (oracle 11g)

employee
empolyee_num   employeeName  department

10001                 ABC1                Sales
10002                ABC2                Accounts
10003                ABC3                Sales


employee_salary (employee# is foreign key)

employee_sal_id   employee_num  employee_salary
           1                   10001              1000
           2                  10002                1200

the below query

Query #1:
select es.employee_sal from employee emp, employee_salary es where emp.employee_num = es.employee_num
and emp.employee_num = 10003;

the above query will return no rows returned.

If the above query needs to return a null we can wrap the above query as below

Query #2:
select (select es.employee_sal from employee emp, employee_salary es where emp.employee_num = es.employee_num and emp.employee_num = 1000) as salary from dual;

this query will return a null instead of no row found.

If needed we can return a 0 instead of null using the nvl () function.

Query #3:
select nvl((select es.employee_salary from employee emp, employee_salary es where emp.employee_num = es.employee_num and emp.employee_num = 1000),0) as salary from dual;

Note:
There might be scenarios while working with procedures or function, if the WHERE clause condition didn't match the query possibly returns NO ROW FOUND and if i use the if clause to check for NULL the PL/SQL block would throw an error.

In my case,  i wanted to find the salary for the employee writing a procedure.
 in cursor i fetched the employee_num, then used this empolyee_num to a select query to get the salary and print in DBMS_OUT.

Create table using the below queries in ORACLE 11g


CREATE TABLE employee
(
   employee_num    NUMBER (10) CONSTRAINT pk_emp_num PRIMARY KEY,
   employee_name   VARCHAR2 (25),
   department      VARCHAR2 (20)
);




CREATE TABLE employee_salary
(
   employee_sal_id   NUMBER (10) CONSTRAINT pk_emp_sal_id PRIMARY KEY,
   employee_num      NUMBER (10),
   employee_sal      NUMBER (6, 2),
   CONSTRAINT fk_supplier FOREIGN KEY
      (employee_num)
       REFERENCES employee (employee_num)
);

Insert the values into the tables using below query:

insert into employee values(10001,'ABC1','Sales');
insert into employee values(10002,'ABC2','Accounts');
insert into employee values(10003,'ABC3','Sales');

insert into employee_salary values (1, 10001, 1000.00);
insert into employee_salary values (2, 10002, 1200.00);

Try executing the below PL/SQL block code:


DECLARE
   CURSOR cur_employee_num
   IS
      SELECT *
        FROM employee emp;

   curval1   cur_employee_num%ROWTYPE;
   salval    NUMBER (6, 2) := 0;
BEGIN
   OPEN cur_employee_num;

   LOOP
      FETCH cur_employee_num INTO curval1;

      EXIT WHEN cur_employee_num%NOTFOUND;

      IF curval1.employee_num IS NOT NULL AND curval1.employee_num > 0
      THEN
         SELECT employee_sal
           INTO salval
           FROM employee_salary
          WHERE employee_num = curval1.employee_num;

         IF salval > 0
         THEN
            DBMS_OUTPUT.put_line (
                  'Salary of employee '
               || curval1.employee_num
               || ' is = '
               || salval);
         END IF;
      END IF;
   END LOOP;

   CLOSE cur_employee_num;
END;
/


OUTPUT:
Error or exception:
ORA-01403: no data found

ORA-06512: at line 19

Salary of employee 10001 is = 1000
Salary of employee 10002 is = 1200



If i change the above PL/SQL block as below (refer the highlighted code below)

DECLARE
   CURSOR cur_employee_num
   IS
      SELECT *
        FROM employee emp;

   curval1   cur_employee_num%ROWTYPE;
   salval    NUMBER (6, 2) := 0;
BEGIN
   OPEN cur_employee_num;

   LOOP
      FETCH cur_employee_num INTO curval1;

      EXIT WHEN cur_employee_num%NOTFOUND;

      IF curval1.employee_num IS NOT NULL AND curval1.employee_num > 0
      THEN
         SELECT (SELECT employee_sal
                   FROM employee_salary
                  WHERE employee_num = curval1.employee_num)
           INTO salval
           FROM DUAL;

         IF salval > 0
         THEN
            DBMS_OUTPUT.put_line (
                  'Salary of employee '
               || curval1.employee_num
               || ' is = '
               || salval);
         END IF;
      END IF;
   END LOOP;

   CLOSE cur_employee_num;
END;
/

OUTPUT:

Salary of employee 10001 is = 1000
Salary of employee 10002 is = 1200
(there is no exception)

Query #3 can be used if a 0 to be returned instead of NULL in the highlighted query.




Tuesday, May 14, 2013

Java ResourceBundle to read properties file.

Java provide an class named ResuorceBundle to read the properties file.


Generally properties file is a simple key value file, which will be useful in software coding to extract the common code from the class files, like database connection attributes, queries, constants, etc. This will make the code easy for maintenance.

Below is a sample code piece on how to read the values from properties file using resourcebundle.


create a file named prop.properties, with the below contents

Filename  >>prop.properties<< (below are the contents in the file)

propkey1=propvalue1
propkey2=propvalue2


if using eclipse create a java project and use the below code in a class file.

File/java class name >>PropertyResourcebundEx<<

import java.util.ResourceBundle;

public class PropertyResourcebundEx {

public static void main(String args[])
{
//Below is the declaration to get the instance of the property file.
//the prop.properties file should be within the class path, as the resourcebundle can read the properties file.

//prop is the properties file name
// there is no necessity to provide the extension of the properties file as this file is within the class path.

ResourceBundle rsbundle = ResourceBundle.getBundle("prop");

//below is the code which will get the information of the prop file
//getSring() method of the resourcebundle will get the value of the key propkey1 from the property file
String PROP_VAL1 = rsbundle .getString("propkey1");
String PROP_VAL2 = rsbundle .getString("propkey2");

System.out.println("Propval1 & propval2 = " + PROP_VAL1+ " && "+ PROP_VAL2);
}
}

Output:
>> Propvalue1 & propval2 = propvalue1 && propvalue2

Note: if the prop.properties file is not within the class path, then we get the below exception:

Exception in thread "main" java.util.MissingResourceException: Can't find bundle for base name prop, locale en_US
at java.util.ResourceBundle.throwMissingResourceException(Unknown Source)
at java.util.ResourceBundle.getBundleImpl(Unknown Source)
at java.util.ResourceBundle.getBundle(Unknown Source)
at com.test.mail.PropertyResourcebundEx.main(PropertyResourcebundEx.java:12)

Thursday, May 9, 2013

favicon or custome icon display in web application

To display a favicon or custom icon or company logo icon on a web application.


We had an tomcat web application to include the favicon to it.

To display the icon we should use the

<link rel="icon" href="/favicon.ico">

the above should go within the html head. even if its a jsp file.

you can also use "type" attribute in the "link" tag, like below

<link rel="icon" href="/favicon.ico" type="image/x-icon">
also
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">

shortcut and icon in rel attribute of the link tag identifies two relations icon and shortcut.
shortcut doesn't have a meaning.

the imgae favicon.ico : should be a 16x16 or 32x32 image. to design an icon you can use the http://www.xiconeditor.com/ 

put this the corresponding image locations in the application, provide the reference in the "href" attribute of "link" tag.

start the tomcat application after making the link reference.

clear the IE temporary files, histories, cookies. even from the favorite links.

provide the link of the application and the favicon will be displayed.