Friday, March 23, 2012

Difference Between ClassNotFoundException & NoClassDefFoundError

Assume the following classes

program
  |-------->Test.java
  |--------->Demo.java

Test.java
----------
public class Test{}


Demo.java
-------------

public class Demo
{
public static void main(String s[])throws Exception
{

Class.forName("Test");  //line 1
Test t=new Test();  //line 2
}
}

Observation
ClassNotFoundException
---------------------------------
You keep only line 1(comment line 2),and compile and execute Demo.java,(Donot compile Test.java)it will give you ClassNotFoundException
What ever String you are passing in Class.forName("---") is a class name,and it should be there
solution:  Compile both the java files and then execute Demo class

NoClassDefFoundError
--------------------------------------
Keep Only line 2(comment line 1),and compile and Execute Demo.java.The program successfully compiles &     Executes.It is because,when ur class Demo is using class Test,then No need to compile Test.java,when you compile Demo.java,it auto compiles Test.java

So when will I get Error?  Just remove . from ur classpath & recompile


In classpath generally we add  ;.  at last.
This is because,when the JVM looks for the classes,it looks in classpath and when it sees .  , it  understands that it has to look in the current working directory also.

But if you remove . from classpath,then here auto-compilation will not take place,means you have to compile all the classfiles using javac *.java.

Even after you have compiled both the classes,if u try to execute it,it will still show you NoClassDefFoundError,because u have removed . from classpath variable


Now comment both line1 & line 2,and again recompile only Demo.java
Compilation will be successful,but While execution it will give you same NoClassDefFoundError


Solution:  include ;.  at your classpath









Wednesday, February 29, 2012

use jdk 1.6 to compile the java file as jdk1.3

assert is a keyword introduce at jdk 1.4,You cannot use it as an identifier in jdk1.4 +.
However if you have used it as an identifier,and you want to compile the class,then you need to go back to jdk 1.3.

But you have only jdk 1.6 with you.Still then you can compile your java class,as if you are using jdk 1.3

 Demo.java
 public class Demo
{
public static void main(String[] args) 
{
 boolean assert = true;
if(assert) System.out.println("if is true");
}
}



compile using jdk 1.4+ will give you these error

-------------------------------------------------
>javac Demo.java
Demo.java:5: as of release 1.4, 'assert' is a keyword, and may not be used as an
 identifier
(use -source 1.3 or lower to use 'assert' as an identifier)
                 boolean assert = true;
                         ^
Demo.java:6: as of release 1.4, 'assert' is a keyword, and may not be used as an
 identifier
(use -source 1.3 or lower to use 'assert' as an identifier)
                if(assert) System.out.println("if is true");

To compile as jdk1.3 although you are using jdk 1.4+
--------------------------------------------------------
>javac -source 1.3 Demo.java

Monday, February 27, 2012

Working with Trigger in Oracle

I want to implement autoincrement feature to my employee table.Built in facility is not available but we can write our own trigger concept to do so.

1. Create table in Oracle
------------

 create table Employee1
  (
    empid number primary key,
    empname varchar2(10),
    empsal number(10,2)
   );

2.Create a Sequence which will generate unique empid each time

SQL> CREATE SEQUENCE   EMPID_SEQ  MINVALUE 101 MAXVALUE 1000 INCREMENT BY 1 START WITH 101 NOCACHE   NOCYCLE  NOORDER;

3.Write a Trigger,which will insert the value from empid_seq to empid column of Employee1 table

SQL>
CREATE OR REPLACE TRIGGER EMPID_TRIG
before insert on EMPLOYEE1
for each row
begin
select EMPID_SEQ.nextval into :new.EMPID from dual;
end;
/
ALTER TRIGGER EMPID_TRIG ENABLE;

4.Insert record into table without EmpId.Notice that EmpId is autofilled by sequence value.
SQL>  insert into employee1(empname,empsal) values('suraj',1000);
SQL>   insert into employee1(empname,empsal) values('raj',200);




5>View Record to see the autoIncrement working
SQL> select * from employee1;

     EMPID EMPNAME        EMPSAL
---------- ---------- ----------
       101 suraj            1000
       102 raj               200


Friday, February 17, 2012

Running javaProgram without main() not possible in JDK1.7 latest Version

Running Java Program without main() has become an old story now.
So far we used to write the program like this
StaticDemo.java
public class StaticDemo
{
   static
    { 
        System.out.println("Hello");
        System.out.exit(0); 
     }
}
And then >javac *.java
>java StaticDemo

It compiles and runs successfully,printing Hello

This works well in JDK1.7 old versions(build 1.7.0-ea-b19)

But From jdk 1.7(build1.7.0-ea-b85),It gives run time Exception

Error: Main method not found in class StaticDemo, please define the main method
   public static void main(String[] args)


The latest version while writing this article was build  jdk 1.7(build 1.7.0_03-b05),which also doesnot allow running java program without main();

So the Concept is:
When we say
java StaticDemo
Compiler understands that we are trying to execute the program,so before executing the static block,it first checks whether main() is there or not.If not,throws Exception

Tuesday, February 14, 2012

Email Validation Using RegularExpression

We can validate Email using regularExpression support given by JDK

  EmailValidation.java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmailValidation{
     
    public static void main(String args[])
    {
      Pattern pattern;
      Matcher matcher;
String email="suraj20p@gmail.com";
      String EMAIL_PATTERN = "^[_A-Za-z0-9]+(\\.[_A-Za-z0-9]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

   
     //compile our pattern
     pattern = Pattern.compile(EMAIL_PATTERN);
     //pass our email to matcher,so that it can be checked whether pattern is matching or not
     matcher = pattern.matcher(email);
    
     //check whether string is matched or not
      boolean result= matcher.matches();

      if(result)
           System.out.println("Email Validated Successfully");
      else System.out.println("Invalid Email Address");
    }
}


  Download Source Here

Friday, February 10, 2012

Creating a Formatted XML using Java

Lets Assume we want to create an XML file,
Eg:-

CreatXMLFile.java
----------------------
import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
public class CreatXMLFile
{  
public static void main(String[] args) throws Exception
 {   
    //creating factory
    DocumentBuilderFactory documentBuilderFactory =DocumentBuilderFactory.newInstance();
    //creating a builder
    DocumentBuilder documentBuilder =documentBuilderFactory.newDocumentBuilder(); 
    //creating a document
    Document document = documentBuilder.newDocument();
   
    String root = "SMS";

    //adding root Element
    Element rootElement = document.createElement(root);
    rootElement.setAttribute("area", "hyderabad");

    document.appendChild(rootElement); //adds <SMS> as root element

    String element ="Number";    
    String data = "12345";
   
    Element em = document.createElement(element);
    em.appendChild(document.createTextNode(data));
    rootElement.appendChild(em);  //creates <Number>12345</Number> and adds to root element<SMS>
/*
<SMS>
<Number>12345</Number>
</SMS>
*/
  
    element ="message";   
    data= "hello";
  
    em = document.createElement(element);  
    em.appendChild(document.createTextNode(data));
    rootElement.appendChild(em); //creates <message>hello</message> and adds to root element<SMS>
/*
<SMS>
<Number>12345</Number>
<message>hello</message>
</SMS>
*/
  
  
    em=document.createElement("delivered");
    Element childElement = document.createElement("status");
    childElement.appendChild(document.createTextNode("failed"));
    em.appendChild(childElement);
    rootElement.appendChild(em);//creates <delivered><status> failed</status></delivered> and adds to root element<SMS>

 /*<SMS>
<Number>12345</Number>
<message>hello</message>
<delivered>
      <status> failed</status>
</delivered>
</SMS>
    */
   
    //Used to Write the generated xml structure to  file or system console
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");//arrange the xml in an idented format
    DOMSource source = new DOMSource(document);   
    File f=new File("d:/myfile.xml");
   
    StreamResult result =  new StreamResult(f);  //prints xml into file
    //StreamResult result =  new StreamResult(System.out);   
    transformer.transform(source, result);
 
 }
 }

Thursday, February 9, 2012

Adding column to Existing Table

Syntax
alter table <tableName> add  <New_Column> <datatype_with_size>;



SQL>alter table employee add  empsal number(5);

Wednesday, February 8, 2012

Creating Sequence

A sequence is a variable that can be used to generate unique value everytime


Creating Sequence
CREATE SEQUENCE EMPID_SEQ
 MINVALUE 1
 START WITH 1
 INCREMENT BY 1
 NOCACHE

Calling Sequence
 SELECT EMPID_SEQ.NEXTVAL FROM DUAL;



Dropping Sequence
DROP SEQUENCE EMPID_SEQ

Saturday, January 28, 2012

Reading & Writing Data into XLS Sheet

Sometimes we need to read/Write data from/to Excel sheet.
Here  is the way
1.Create one Excel sheet at any Location(Lets say D:\College.xls)
2.Make sure it is not readOnly(otherwise you cannot write data from Java also)
3.Create/Rename a sheet with name "Student"
4.Create ColumnHeading (Normal way) and write some data into it.

5.Create a ODBC DataSource point to the excel file(College.xls)
Navigate to
Start->Control Panel->Administrative Tools->ODBC->"System Dsn" tab->Click on Add Button-->Select "Driver do MS Excel(*.xls)"-->finish




DataSourceName: xlsdsn
 Click on Option button and uncheck  Read Only
Click on select Workbook button and choose D:\College.xls click OK

click ok-->ok
ExcelTest.java


---------------
// ExcelTest.java  (reads/writes the records from/to Ms-Excel sheet)
import java.sql.*;
public class ExcelTest
{
   public static void main(String args[])throws Exception
   {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection    con = DriverManager.getConnection("jdbc:odbc:xlsdsn");

       Statement st = con.createStatement();

       ResultSet rs = st.executeQuery("select * from [student$]");

         while(rs.next()){
              System.out.println(rs.getInt("sno")+"  "+rs.getString("sname")+"  "+rs.getString("sadd"));
         }
         PreparedStatement ps=con.prepareStatement("insert into [student$] values(?,?,?)");
         ps.setInt(1,10);
         ps.setString(2,"Raja");
         ps.setString(3,"ameerpet");
         ps.executeUpdate();
         ps.close();
         rs.close();
         st.close();
         con.close();
     } // main
 } // class 


Download Code Here








Thursday, January 26, 2012

Configuring Exception page in web.xml

Instead of showing error page for individual action performed in Servlet,JSP,It is always recommended to configure those error page in web.xml

<web-app>

             <servlet>
                       <!-- some servlet cofiguration -->
             </servlet>

             <servlet-mapping>
                       <!-- some servlet mappings-->
             </servlet-mapping>

            <welcome-file-list>
                         <!-- Welcomefile list configurations-->
            </welcome-file-list>

              <error-page>
                        <error-code>404</error-code>
                        <location>/pagenotfound.jsp</location>
               </error-page>
         
                <error-page>
                         <exception-type>java.lang.Exception</exception-type>
                         <location>/error.jsp</location>
               </error-page>
</web-app>

Thursday, January 19, 2012

Knowing the Datatype of a Variable

Given a variable to you,how can u know its type
use typeof operator in javascript

eg:-


alert(typeof "Hello World");
alert(typeof 123);

Converting String to XML in JavaScript

Sometime we need to convert a String in xml form,here is the JavaScript code


<script language=javascript>
//xml data as a string
function fun1()
{
var v="<employee><ename>suraj</ename></employee>";
var xmlForm= StringtoXML(v);
//xmlForm has data in XML format
}

function StringtoXML(text)
{
                if (window.ActiveXObject)
                 {
                  var doc=new ActiveXObject('Microsoft.XMLDOM');
                  doc.async='false';
                  doc.loadXML(text);
                }
              else {
                  var parser=new DOMParser();
                  var doc=parser.parseFromString(text,'text/xml');
                }
                return doc;
            }
 </script>

Thursday, January 12, 2012

live() in Jquery

Once,the dom tree is created and loaded,If u are adding new elements dynamically,u may need to use live() to access those newly created elements.

Eg;  When a page is loaded,You got a select box with list of countries,
You selected a country and clicked on search button,
you got the list of all the state in that country,along with all the districts(in select box), for each starte in a row

When this page was loaded,list of all the country was loaded into select box,In the Dom it is added.
But when you selected country and clicked on search button,another table was loaded containing all the states,
This table is dynamic and it may not be loaded properly in DOM

Support in that table we have 5 rows,representing 5 state of India,each row is having 1 more select box,containing all the list of district in that state,Now you want to alert A msg on selecting any district

Here you need live()
Code Snippet 
-------------------
<script language="JavaScript">
$(document).ready(f1);
function f1()
{
$("#selDistrict").live("change", function() 
                             {
                                alert("I was clicked");
                              }
 }
</script>










  


   




Means this function() will be called when ever value of selDistrict  (id of select component) is changed

Tuesday, January 10, 2012

Working with Jdbc Type5 driver

Yes,JDBC type 5 is out in the market.It has got more good features,and overcome the limitation of type4
This driver is given by vendor called DataDirect,and they have provide driver for
Oracle
MySql
SqlServer
and few more

Steps to work with Type5
----------------------------
1. goto http://www.datadirect.com/products/jdbc/index.html click on Download FreeTrial

,Register your details,and u will get the email attachment,regarding the downloads
Alternatively you can also download the same from my repository here

2.Once you have downloaded you will get  PROGRESS_DATADIRECT_CONNECT_JDBC_4.2.1.jar
Incase you have downloaded from my repository,unzip the rar,inside that u will find the above jar file

3.Extract that jar file and click on Installer.bat
Installer will be activated and this Driver will be installed in your machine.
Let us assume that it is installed in C:\Program Files\Progress\DataDirect\Connect_for_JDBC_42 folder

4.Test your connection
Goto C:\Program Files\Progress\DataDirect\Connect_for_JDBC_42\testforjdbc  and double click testforjdbc.bat

click Press Here to continue.
From the Connection menu,click Connect to DB
In the DataBase:              jdbc:datadirect:oracle://localhost:1521;databaseName=XE
         UserName:             system
         Password:              manager
 click on Connect.you will get "Connection Established" message,If its Successful

5.Writing JavaApplication using TYPE5 Driver
Test.java
----------
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
public class Test
{  
       public static void main(String[] args)throws Exception 
       {
        // Register the driver with the driver manager.
        // If using Java SE 6, you can omit this step.
        // Java SE 6 automatically registers the driver. I am Using JDK 1.6,so Commented this line
        //Class.forName("com.ddtek.jdbc.oracle.OracleDriver");         // Establish the Connection
        String url = "jdbc:datadirect:oracle://localhost:1521;ServiceName=xe";
        Connection  con = DriverManager.getConnection(url, "system", "manager");
        System.out.println("Connection is"+con);
         //We have got connection,play as u wish    // Verify the Connection
        DatabaseMetaData    metaData = con.getMetaData();
        System.out.println("Database Name: " + metaData.getDatabaseProductName());
        System.out.println("Database Version: " +metaData.getDatabaseProductVersion());    
   }
}
 
Note:Add C:\Program Files\Progress\DataDirect\Connect_for_JDBC_42\lib\oracle.jar to  your classpath
Dont want to follow all those installation step,and if you directly need oracle.jar click here
(Directly set oracle.jar in classpath and execute Test.java)


6.Compile and Execute Test.java
>javac Test.java
>java Test

o:p
Connection iscom.ddtek.jdbc.oraclebase.ddah@182f0db
Database Name: Oracle
Database Version: 10.2.0.1.0


Download Src with Oracle.jar   here


Thanks,and happy Programming



Saturday, January 7, 2012

Develop JAX-WS based WebService in GlassFish

Here we are going to learn how to develop a Simple Jax-Ws webservice and deploy it in Glassfish,very manually.
Here I have developed this webservice as webApplication,then created a war file,and deployed it like a normal WebApplication

S/W Used:
jdk 1.6
GlassFish 3.0

Steps
-------


1.Prepare the directory structure











2.Code your resources
  
Calculator.java
----------------
package p1;
import javax.jws.WebService;
import javax.jws.WebMethod;

@WebService
public class Calculator
{
    @WebMethod
    public String sum(int x,int y)
    {
        return ""+(x+y);
    }
}


web.xml
----------
<web-app/>


3.Create your War file,using cmd
calculatorApp\Server> jar cf  MyCalculatorWs.war  .

4.Start your glassfish server
start-->All Program-->Sun Ms-->Application Server v2.1-->start Default Server

5.Deploy the created war file in Glassfish server.

copy MyCalculatorWs.war and paste it to
C:\Sun\AppServer\domains\domain1\autodeploy folder

After you deploy the above war file,you will get MyCalculatorWs.war_deployed file,which  means deployment is successful

6.View the WSDL File
http://localhost:8081/MyCalculatorWs/CalculatorService?WSDL
                        ---- ----------------  ---------   ----------------
                       port  warfile Name   className      fixed word To access WSDL
__________________________________________________________________________
Server part is over,Now we need to write the client
Initially there is no file in client folder








1>Use wsimport tool to generate helper classes using which you can invoke webservice

client> wsimport -p mypack -keep http://localhost:8081/MyCalculatorWs/CalculatorService?WSDL

-p mypack :create a package called mypack,and put all the generated java/class file in it
-keep     :preserve the java file,after .class is created

Note:
wsimport tool is built in tool available in jdk1.6(bin folder)

After the 1st step you will find the following







2.Add your JavaClient which calls the Calculator webservice using the above helperclasses
Add TestClient.java inside client folder(outside mypack folder)

TestClient.java
---------------
import mypack.Calculator;
import mypack.CalculatorService;

public class TestClient
{
public static void main (String [] args)
{
//locate webservice comp
CalculatorService cs=new CalculatorService();

//getAccess to B.obj ref of WebService comp
Calculator bobj=cs.getCalculatorPort();

//call B.methods
String result=bobj.sum(5,10);
System.out.println("The sum is"+result);
}
}

4.Run & Execute TestClient.java
 Client>javac *.java
 Client>java TestClient

Download Source here

Wednesday, January 4, 2012

Sending SMS to your Mobile Through Java Program

Yes,we can send SMs Using our Java Program.These are the steps
Note:Ipipi allows you to send only 5 sms free of cost,After that create one more account
1> create an account in http://www.ipipi.com/
2>I created Account like this:
username:  surajSMS
password: suraj123

3>Prepare the program in this way





-------------------------------------------------------------------------------------------------
SendSMS.java
 ------------------------------------------------------------------------------------------------
import java.io.*;                                                                                   
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendSMS {

    public SendSMS() {
    }
   //create an account on ipipi.com with the given username and password
    public void msgsend() {
        String username = "surajSMS";  //Your Credentials
        String password = "suraj123";
        String smtphost = "ipipi.com";      //Ip/Name of Server
        String compression = "None";       //I dont want any compression
        String from = "surajSMS@ipipi.com";    //ur userid@ipipi.com
        //This mobile number need not be registered with ipipi.com
        String to = "919861098610@sms.ipipi.com";    //mobile number where u want to send sms
        String body = "Hi This Msg is sent through Java Code";
        Transport tr = null;

        try {
         Properties props = System.getProperties();
         props.put("mail.smtp.auth", "true");

         // Get a Session object
         Session mailSession = Session.getDefaultInstance(props, null);

         // construct the message
         Message msg = new MimeMessage(mailSession);

         //Set message attributes
         msg.setFrom(new InternetAddress(from));
         InternetAddress[] address = {new InternetAddress(to)};
         msg.setRecipients(Message.RecipientType.TO, address);
         msg.setSubject(compression);
         msg.setText(body);
         msg.setSentDate(new Date());

         tr = mailSession.getTransport("smtp");
         //try to connect
         tr.connect(smtphost, username, password);
         msg.saveChanges();
         //send msg to all recipients
         tr.sendMessage(msg, msg.getAllRecipients());
         tr.close();
         } catch (Exception e) {
             e.printStackTrace();
         }
    }

      public static void main(String[] argv) {
         SendSMS sms = new SendSMS();
          sms.msgsend();
          System.out.println("Successfull");
      }
}


Download Source Here

Create a File In Client System Using JavaScript

File handling in JavaScript can be done using the FileSystemObject object and its properties and methods. This object is part of Microsoft's Scripting Engine, and thus this is applicable only to Microsoft Windows Operating Systems.

<head>                                                                                     
<script language=javascript>                                                                                                          
var obj = new ActiveXObject("Scripting.FileSystemObject");   
  
varFileObject = obj.OpenTextFile("C:\\Suraj.txt", 2, true,0);      
varFileObject.write("File handling in Javascript");                                       
varFileObject.close();                                                               
</script>                                                                                                     
</head>                                                                                   



Parameter 1: PATH - The file gets created at the path specified on the client machine. If only the file name is mentioned here, the file gets saved on the desktop of the client system.
Parameter 2: I/O mode, indicates the mode of file opening. Possible values are:
  • 1: Opens the file for reading.
  • 2: Opens the file for writing.
  • 8: Opens the file for appending.
Parameter 3: CREATE is a boolean value indicating whether to create the file if it does not exist (true) or to issue an error message if the file does not exist (false).
Parameter 4: FORMAT is optional and indicates the file type. If not specified, the default file type is ASCII. The possible values of format are:
  • TristateUseDefault - 2: Opens the file using the system default
  • TristateTrue -1: Opens the file as Unicode
  • TristateFalse 0: Opens the file as ASCII
The following are some of the methods provided by FileSystemObject for file handling:

MoveFile(source, destination)
MoveFolder(source, destination)
CopyFile(source, destination, overwriteFlag) //overwriteFlag= true/false
CopyFolder(source, destination, overwriteFlag) //overwriteFlag= true/false
CreateFolder(folderName)
CreateTextFile(fileName, overwriteFlag)//overwriteFlag= true/false
DeleteFile(fileName, readPermissionFlag)//readPermissionFlag= true/false
DeleteFolder(folderName, readPermissionFlag)//readPermissionFlag= true/false
DriveExists(letterDrive)
FileExists(fileName)
FolderExists(folderName)
GetSpecialFolder(folderCode) /* The given folderCode is either 0 for a 
windows folder, 1 for a system folder, or 2 for a temporary folder. 
A full path is returned. On a typical installation, "c:\windows" 
is returned as the windows folder, "c:\windows\system" is returned 
as the system folder, and "c:\windows\temp" is returned as the temporary folder. */




Points of Interest

There are a few things to note before implementing FileSystemObject. Since it is an ActiveX object, it will not be created if the security level on the client machine is high. So the website has to be added to the trusted site list so that the ActiveX object can be created.
The user must have write access in the path specified while creating a file. In cases where there is uncertainty, it's better to write the file onto the Temporary Folder of the system. The path for the Temp folder can be found using:
GetSpecialFolder(2)
The above topic is applicable only for IE. The below link gives an idea of how to implement file operations in Mozilla. The below code can be used to check the browser type:
if (navigator.userAgent.indexOf("Opera") >= 0)                                       
{                                                                                    
    alert("This example doesn't work in Opera") ;                                    
    return ;                                                                         
}                                                                                    
if (navigator.userAgent.indexOf("MSIE") >= 0)                                        
{                                                                                    
    alert("This example works in IE") ;                                              
    return ;                                                                         
}                                                                                    
if (navigator.userAgent.indexOf("Mozilla") >= 0)                                     
{                                                                                    
    alert("This example doesn't work in Mozilla") ;                                  
    alert("Check the following link: <a href="http://www.mozilla.org/js/js-file"+    
          "-object.html" title="http://www.mozilla.org/js/js-file-object" +          
          ".html">http://www.mozilla.org/js/js-file-object.html</a>") ;              
    return ;                                                                         
}                                                                                               

Monday, January 2, 2012

Split A String into Array in JavaScript

We have a String containing numbers separated by , or any other delimiters,and we want to get those numbers collected into an array.Here is the steps

<script type="text/javascript">
var str="20,30,40";
var arr=new Array();
arr=str.split(",");
document.write(arr[2]);
</script>

gives 40 //3rd element