Thursday, March 1, 2012

Top 20 Java Websites


Here’s the best 20 Java websites in my collections, which provides latest Java news, articles and tutorials. If you have other great Java websites, please leave a comment to share with others.
P.S The order doesn’t means any priority.

1. O’Reilly Java

onjava.com
URL : http://www.onjava.com
Since : 10-feb-2000
Rss : http://www.oreillynet.com/pub/feed/7?format=rss2
Description : O’Reilly’s, contains latest Java technology news, quality code snippets, full example and detail explanation.

2. Sun Developer Network (SDN)

java.sun.com
URL : http://java.sun.com
Since : 19-mar-1986
Rss : http://developers.sun.com/rss/java.xml
Description : The official Java developer website, always get the latest Java related news here.

3. Developer.com

developer.com
URL : http://www.developer.com/java/
Since : 21-dec-1995
Rss : http://www.developer.com/icom_includes/feeds/developer/dev-25.xml
Description : Java news and articles in developer.com

4. Java.net

java.net
URL : http://www.java.net
Since : 18-jun-1997
Rss : None
Description : The Java community website hosted by Oracle.

5. IBM’s Developerworks

ibm.com
URL : https://www.ibm.com/developerworks/java/
Since : 19-mar-1986
Rss : http://www.ibm.com/developerworks/views/java/rss/libraryview.jsp
Description : Java news and articles in IBM’s Developerworks.

6. Java World

javaworld.com
URL : http://www.javaworld.com
Since : 22-nov-1995
Rss : http://www.javaworld.com/rss/index.html
Description : Well-known Java websites, you just can’t miss this one.

7. Devx

devx.com
URL : http://www.devx.com/Java/Door/6972
Since : 26-sep-1997
Rss : http://feeds.feedburner.com/DevxLatestJavaArticles
Description : Java news and articles in Devx.com.

8. TheServerSide.com

theserverside.com
URL : http://www.theserverside.com
Since : 05-jan-2000
Rss : http://www.theserverside.com/rss
Description : Java community to discuss the server side development.

9. Big Moose Saloon

coderanch.com
URL : http://www.coderanch.com
Since : 27-aug-2004
Rss : Vary in topic, visit http://www.coderanch.com/forums
Description : Friendly and popular Java forum.

10. Stack Overflow

stackoverflow.com
URL : http://stackoverflow.com
Since : 26-dec-2003
Rss : http://stackoverflow.com/feeds
Description : Well-known generic programming Q & A site organized by tags. Java topics included.

11. jGuru

jguru.com
URL : http://www.jguru.com
Since : 16-sep-1997
Rss : None
Description : Java articles and Q&A style forum.

12. Official Java Tutorials

official java tutorials
URL : http://download-llnw.oracle.com/docs/cd/E17409_01/javase/tutorial/
Since : Unknown
Rss : None
Description : The Official Java tutorials from Oracle.

13. Java Blogs Aggregator

javablogs.com
URL : http://www.javablogs.com
Since : 25-nov-2002
Rss : http://javablogs.com/ViewDaysBlogs.action?view=rss
Description : Blogs aggregator for many active Java-based blogs.

14. Java-Source.Net

java-source.com
URL : http://www.java-source.net
Since : 25-feb-2004
Rss : None
Description : Java frameworks collection site. Well organized.

15. Java Lobby

javalobby
URL : http://java.dzone.com
Since : 17-may-1998
Rss : http://www.dzone.com/feed/frontpage/rss.xml
Description : The heart of the Java developer community.

16. Jdocs

jdocs.com
URL : http://www.jdocs.com
Since : 01-jul-2004
Rss : None
Description : Search engine for Java API documentation.

17. Java2s.com

java2s.com
URL : http://www.java2s.com
Since : 07-nov-2004
Rss : None
Description : Many Java programming tutorials and source code example, well organized by categories.

18. Java Tips

java-tips.org
URL : http://www.java-tips.org
Since : 22-Apr-2005
Rss : None
Description : Many quick and Java source code example.

19. RoseIndia

roseindia.net
URL : http://www.roseindia.net
Since : 23-may-2000
Rss : None
Description : Collection of Java tutorials, cover wide range of Java topics.

20. Mkyong

mkyong.com
URL : http://www.mkyong.com
Since : 30-oct-2007
Rss : http://feeds.feedburner.com/FeedForMkyong
Description : Cover wide range of the Java tutorials : Spring, Hibernate, Struts, Struts 2…

What is the need to Override Hashcode() and equals() method



Although there are lots of materials are available on internet and API document about the necessity of the overriding the hashcode() and equals() method in Java but lots of new developers still not able to understand the necessity of hashcode() method.
In this article, I will try to explain step by step the need of overriding hashcode() method in Java.
Few Thump rules:
If two objects are same then they must return same value in hashcode() and equals() method whenever invoked.
It is not necessary that two different object must have different hashcode values. it might be possible that they share common hash bucket.
JVM assigns unique hashcode value to each object when they are created in memory and if developers don’t override the hashcode method then there is no way the two object returns same hashcode value.
As the question comes in your mind that equals() method is used to compare objects that they are having same value or not but why should we override the hashcode method ?
The answer to the question is for the hash technique based data structures like HashMap and HashTable.

How Hashcode works in java
As you can see in above diagram that every object is placed in Hash bucket depending on the hashcode they have. It is not necessary that every different object must have different hashcode. hashcode is used to narrow the search result. When we try to insert any key in HashMap first it checks whether any other object present with same hashcode and if yes then it checks for the equals() method. If two objects are same then HashMap will not add that key instead it will replace the old value by new one.
What will happen if I don’t override the hashcode method?
Ans : If the object does not implement hashcode() method and used as key then we will not get the object back as shown in below code.
Code without implementation of equals() and hashcode()

class Movie {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getReleaseYr() {
        return releaseYr;
    }
    public void setReleaseYr(int releaseYr) {
        this.releaseYr = releaseYr;
    }
    private int releaseYr;
}
public class HashMapDemo {
    public static void main(String[] args) {
        Movie m = new Movie();
        m.setName("Thank You");
        m.setReleaseYr(2011);

        Movie m1 = new Movie();      
        m1.setName("Khiladi");
        m1.setReleaseYr(1993);

        Movie m2 = new Movie();      
        m2.setName("Taskvir");
        m2.setReleaseYr(2010);

        Movie m3 = new Movie();
        m3.setName("Taskvir");
        m3.setReleaseYr(2010);

        HashMap<Movie, String> map = new HashMap<Movie, String>();
        map.put(m, "ThankYou");
        map.put(m1, "Khiladi");
        map.put(m2, "Tasvir");
        map.put(m3, "Duplicate Tasvir");
        //Iterate over HashMap
        for (Movie mm : map.keySet()) {
            System.out.println(map.get(mm).toString());
        }

        Movie m4 = new Movie();
        m4.setActor("Akshay");
        m4.setName("Taskvir");
        m4.setReleaseYr(2010);
        if(map.get(m4) == null ){
            System.out.println("----------------");
            System.out.println("Object not found");
            System.out.println("----------------");
        }else{
            System.out.println(map.get(m4).toString());
        }
    }
}
Output:
Khiladi
Tasvir
ThankYou
Duplicate Tasvir
—————-
Object not found
—————-
As you can see in above program :
Duplicate objects are added in Hashmap as a key (Because we have not overided the hashcode and equals method)
We are not able to get back object from map (Because hashcode is not implemented)
Same program with equals and hashcode implementation:

class Movie {
    private String name, actor;
    public boolean equals(Object o) {
        Movie m = (Movie) o;
        return  m.name.equals(this.name) && m.releaseYr == this.releaseYr;
    }
    public int hashCode() {
       return name.hashCode() + releaseYr;
    }
    public String getName() {
        return name;
   }
    public void setName(String name) {
        this.name = name;
    }
    public int getReleaseYr() {
        return releaseYr;
    }
    public void setReleaseYr(int releaseYr) {
        this.releaseYr = releaseYr;
    }
   private int releaseYr;
}
public class HashMapDemo {
    public static void main(String[] args) {
        Movie m = new Movie();
        m.setName("Thank You");
        m.setReleaseYr(2011);

        Movie m1 = new Movie();
        m1.setName("Khiladi");
        m1.setReleaseYr(1993);

        Movie m2 = new Movie();
        m2.setName("Taskvir");
        m2.setReleaseYr(2010);

        Movie m3 = new Movie();
        m3.setName("Taskvir");
        m3.setReleaseYr(2010);

        HashMap<Movie, String> map = new HashMap<Movie, String>();
        map.put(m, "ThankYou");
        map.put(m1, "Khiladi");
        map.put(m2, "Tasvir");
        map.put(m3, "Duplicate Tasvir");
        // Iterate over HashMap
        for (Movie mm : map.keySet()) {
            System.out.println(map.get(mm).toString());
        }
        Movie m4 = new Movie();
        m4.setActor("Akshay");
        m4.setName("Taskvir");
        m4.setReleaseYr(2010);
        if (map.get(m4) == null) {
           System.out.println("----------------");
            System.out.println("Object not found");
            System.out.println("----------------");
        } else {
            System.out.println("----------------");
            System.out.println(map.get(m4).toString());
            System.out.println("----------------");
        }
    }
}
Output:
Khiladi
Duplicate Tasvir
ThankYou
—————-
Duplicate Tasvir
—————-
As you can see :
Duplicate Keys are not added instead there values are replaced.
Now the object is retrieved from the Map.
Ques : How to iterate over keyset of HashMap in JDK 4 and 5?
Ans : This is the common question asked in interview.
In JAVA 5 : we can use advance for loop as shown in above code, use map.keySet(). This will return theSet (As Keys must be unique)
In JAVA 4 : use map.keySet() and get the Iterator object using map.iterate() . then using while loop , get the value for each key.

Sunday, February 19, 2012

sending sms code


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
//import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.*;
/**
 *
 * @author sreenath (https://github.com/tacticiankerala/Unofficial-Way2Sms-API-using-JAVA/blob/master/Way2SMS.java) modified by Abhimanyu singh rathore (http://ibm-tgmc.blogspot.com)
 */
public class Way2Sms {
   // private URLConnection sendSMSConnection;
    private String sessionCookie;
    private Proxy proxy;
    private String baseurl;
    private static Random svcRand = new Random();
    private int a;
    //Function to support connection through an HTTP Proxy
    public void setProxy(String proxyHost,int proxyPort)
    {
        proxy=new Proxy(Proxy.Type.HTTP,java.net.InetSocketAddress.createUnresolved(proxyHost, proxyPort));
    }
    //Logging in to Way2sms and returning the authentication cookie
    //No need to Give the cookie back to sendSMS() but cookie is returned for expanding the flexibility of the code
    public String loginWay2SMS(String userName,String password)
    {
        String cookie=null;
        URL urlLogin;
        String loginContent;
        HttpURLConnection loginConnection;
        if(userName==null || userName.isEmpty())
        {
            System.err.println("A Valid User Name must be present!");
            System.exit(0);
        }
        if(password==null || password.isEmpty())
        {
            System.err.println("A Valid Password must be present!");
            System.exit(0);
        }
        try {
            //UTF-8 encoding is the web standard so data must be encoded to UTF-8
            userName=URLEncoder.encode(userName, "UTF-8");
            password=URLEncoder.encode(password, "UTF-8");
            String   tologinurl=baseurl+"Login1.action";

         //   urlLogin=new URL("http://site5.way2sms.com/Login1.action");
            urlLogin=new URL(tologinurl);
            if(proxy==null)
            {
                loginConnection = (HttpURLConnection) urlLogin.openConnection();
            }
            else
            {
                loginConnection = (HttpURLConnection) urlLogin.openConnection(proxy);
            }
         
            loginContent="username=" + userName + "&password=" + password+"&button=Login";
            //Faking that we are from a valid client
            loginConnection.setDoOutput(true);
            loginConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
            loginConnection.setRequestProperty("Content-Length", String.valueOf(loginContent.length()));
            loginConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            loginConnection.setRequestProperty("Accept", "*/*");
            loginConnection.setRequestProperty("Referer", "http://site5.way2sms.com//entry.jsp");
            loginConnection.setRequestMethod("POST");
            loginConnection.setInstanceFollowRedirects(false);
            //Writing the Content to the site
            PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(loginConnection.getOutputStream()), true);
            printWriter.print(loginContent);
            printWriter.flush();
            printWriter.close();
            //Reading the cookie
            cookie = loginConnection.getHeaderField("Set-Cookie");
         
         
        } catch (MalformedURLException ex) {
           System.err.println("Login URL Error");
           System.exit(0);
        } catch (UnsupportedEncodingException ex) {
            System.err.println("Error in encoding Username or Password");
            System.exit(0);
        }catch (IOException ex) {
            System.err.println("Can not connect to Login URL");
            //retrying
       
          if(a==6)a=0;
            a++;
            baseurl="http://site"+a+".way2sms.com/";
            System.out.println(baseurl);
            loginWay2SMS(userName,password);
            // System.exit(0);
        }
        if(cookie==null || cookie.isEmpty())
        {
            System.err.println("Some error occured...Try again in a few seconds..If still problem exists check your username and password");
        }
        sessionCookie=cookie;
        return cookie;
             
     
     
    }
    public void sendSMS(String phoneNumber,String message,String action,String username,String password)
    {
     
            if(phoneNumber==null || phoneNumber.isEmpty())
            {
                System.err.println("Enter A Valid Phone Number");
                System.exit(0);
            }
            else
            {
                try
                {
                 
                //    long testLong=Long.valueOf(phoneNumber);
                }catch(NumberFormatException ex)
                {
                    System.err.println("Invalid Phone Number");
                    System.exit(0);
                }
                 
             
            }
         
            if(message==null|| message.length()==1|| message.isEmpty())
            {
                System.err.println("Enter A Valid Phone Number");
                System.exit(0);
            }
            else if(message.length()>140)
            {
                System.err.println("Message should be less than 140 characters");
            }
            if(action==null || action.isEmpty())
            {
                System.err.println("Enter Valid Action to send Message");
                System.exit(0);
            }
         
            URL sendURL;
            HttpURLConnection sendConnection;
            String sendContent;
            try {
                 message=URLEncoder.encode(message, "UTF-8");
                //sendURL=new URL("http://site5.way2sms.com/FirstServletsms?custid=");
                 String   tosendurl=baseurl+"quicksms.action?";
                //sendURL=new URL("http://site5.way2sms.com/quicksms.action?");
                 sendURL=new URL(tosendurl);
                 if(proxy==null)
                {
                    sendConnection = (HttpURLConnection) sendURL.openConnection();
                }
                else
                {
                    //sendConnection = (HttpURLConnection) sendURL.openConnection(proxy);
                sendConnection = (HttpURLConnection) sendURL.openConnection();
                }
               // sendContent="custid=undefined&HiddenAction=instantsms&Action="+action+"&login=&pass=&MobNo="+ phoneNumber+ "&textArea="+message;
              //  sendContent="custid=undefined&HiddenAction=instantsms&Action=sa65sdf656fdfd&login=&pass=&MobNo=9543246247&textArea=hello";
           
                // working url  for me   sendContent="HiddenAction=instantsms&catnamedis=Birthday&textfield2=+91&MobNo="+phoneNumber+"&txtLen=5&textArea="+message+"&Action=sa65sdf656fdfd&login=9543246247&pass=*********";
                sendContent="HiddenAction=instantsms&catnamedis=Birthday&textfield2=+91&MobNo="+phoneNumber+"&txtLen=5&textArea="+message+"&Action="+action+"&login="+username+"&pass="+password+"";
                sendConnection.setDoOutput(true);
                sendConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
                sendConnection.setRequestProperty("Content-Length", String.valueOf(sendContent.getBytes().length));
                sendConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                sendConnection.setRequestProperty("Accept", "*/*");
                sendConnection.setRequestProperty("Cookie", sessionCookie);
                sendConnection.setRequestMethod("POST");
                sendConnection.setInstanceFollowRedirects(false);
             
                PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(sendConnection.getOutputStream()),true);
                printWriter.print(sendContent);
                printWriter.flush();
                printWriter.close();
                //Reading the returned web page to analyse whether the operation was sucessfull
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(sendConnection.getInputStream()));
                StringBuilder SendResult=new StringBuilder();
                String line;
                while ((line=bufferedReader.readLine()) != null)
                {
                    SendResult.append(line);
                    SendResult.append('\n');
                    //Message has been submitted successfully
                }
                if(SendResult.toString().contains("Message has been submitted successfully"))
                {
                    System.out.println("Message sent to "+phoneNumber+" successfully.");
                }
                else
                {
                    System.err.println("Message could not send to "+phoneNumber+". Also check login credentials");
                    System.out.print(SendResult.toString());
                }
                bufferedReader.close();
             
            }catch (UnsupportedEncodingException ex) {
                System.err.println("Message content encoding error");
                System.exit(0);
            }catch (MalformedURLException ex) {
                System.err.println("Sending URL Error");
              //retrying
                if(a==6)a=0;
                a++;
                baseurl="http://site"+a+".way2sms.com/";
                System.out.println(baseurl);
                loginWay2SMS(username,password);
       sendSMS(phoneNumber,message,action,username,password);

                // System.exit(0);
            }catch (IOException ex) {
               System.err.println("Sending URL Connection Error");
               System.exit(0);
            }
     
     
    }
    public void logoutWay2SMS()
    {
        try {
            HttpURLConnection logoutConnection;
            URL logoutURL;
            String logouturlmy=baseurl+"jsp/logout.jsp";
           // logoutURL = new URL("http://site3.way2sms.com/jsp/logout.jsp");
            logoutURL = new URL(logouturlmy);
            if(proxy==null)
            {
               logoutConnection = (HttpURLConnection) logoutURL.openConnection();
            }
            else
            {
               logoutConnection = (HttpURLConnection) logoutURL.openConnection(proxy);
            }
         
            logoutConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
            logoutConnection.setRequestProperty("Accept", "*/*");
            logoutConnection.setRequestProperty("Cookie", sessionCookie);
            logoutConnection.setRequestMethod("GET");
            logoutConnection.setInstanceFollowRedirects(true);
           BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(logoutConnection.getInputStream()));
            while ((bufferedReader.readLine()) != null);
            bufferedReader.close();
        } catch (MalformedURLException ex) {
            System.err.println("Logout URL Error");
            System.exit(0);
        }catch (IOException ex) {
            System.err.println("Logout URL Connection Error");
            System.exit(0);
        }
    }
    Way2Sms()
    {
        proxy=null;
        //sendSMSConnection=null;
        a=svcRand.nextInt(6);
        while(a==0)
        a=svcRand.nextInt(6);
        baseurl="http://site"+a+".way2sms.com/";
     
        System.out.print(baseurl);
    }
    public static void main(String args[])
    {
        final String USERNAME="";//REQUIRED
        final String PASSWORD="";//REQUIRED
        final String ACTION="sa65sdf656fdfd";//REQUIRED :e.g sa65sdf656fdfd  In order to understand ACTION value please read the blog
        Way2Sms sms=new Way2Sms();
        //HTTP PROXY
        //sms.setProxy("10.1.1.1",8080); //REQUIRED ONLY IF CONNECTING THROUGH A PROXY
     
        StringBuilder phoneNumber= new StringBuilder();
        StringBuilder message=new StringBuilder();
     /*   if(args.length>0)
        {
          if(args[0].toLowerCase().compareTo("phone")==0)
          {
            int i=1;
            while(args[i].toLowerCase().compareTo("message")!=0)
            {
                phoneNumber.append(args[i]);
                 phoneNumber.append(';');
                i++;
            }
            for(i=i+1;i<args.length;i++)
            {
                message.append(args[i]);
                message.append(' ');
            }
          }
          else
          {
          System.out.println("USAGE : Way2SMS phone <phonenumber1> <phonenumber2> ... message <message>");
            System.exit(0);
          }
        }
        else
        { */
        String msg2=" hi hru"; //msg to be sent
            phoneNumber.append("0124354555555"); /*want to use as bean ??? pass the parametrs for phone,message to send multiple number just insert ';' between them and pass as  a string */
            phoneNumber.append(';');
         
            if(msg2==null||msg2==""||msg2==" ")
           {System.out.print("please enter msg of length >0");
           System.exit(0);
           }
            message.append(msg2);
            message.append(' ');
         
        // System.out.println("USAGE : Way2SMS phone <phonenumber1> <phonenumber2> ... message <message>");
           // System.exit(0);
     
   /* }
 */        //baseurl 1:http://site4.way2sms.com/ 2:http://site4.way2sms.com/ 3.http://site1.way2sms.com/
     
     
        String cookie=sms.loginWay2SMS(USERNAME,PASSWORD);
        System.out.println(cookie);
        String textMessage=message.toString();
        String strPhoneNumber=phoneNumber.toString();
        String arrPhoneNUmber[]=strPhoneNumber.split(";");
        for(int i=0;i<arrPhoneNUmber.length;i++)
        {
       
         sms.sendSMS(arrPhoneNUmber[i], textMessage, ACTION,USERNAME,PASSWORD);
        }
     
        sms.logoutWay2SMS();
    }
}


Reference Links:

http://ibm-tgmc.blogspot.in/2011/12/sending-sms-via-way2sms-using-java.html
http://jtechbits.blogspot.in/2011/06/sending-sms-through-way2sms-in-java.html

Thursday, October 20, 2011

Change global_name of oracle

SQL> SELECT * FROM GLOBAL_NAME;

GLOBAL_NAME
--------------------------------------------------------------------------------
ORATEMP.REGRESS.RDBMS.DEV.US.ORACLE.COM

SQL> ALTER DATABASE RENAME GLOBAL_NAME TO oratemp ;

SQL> SELECT * FROM GLOBAL_NAME;

Sunday, October 16, 2011

configure glassfish in myeclipse

http://glassfishplugins.java.net/eclipse34/index.html

Tuesday, October 11, 2011

Java Database Connectivity (JDBC Tutorial)

Java Database Connectivity:
JDBC (Java Database Connectivity) is designed to allow users to use SQL(Structured Query Language) to query databases. It makes the tasks of the developers easy as it handles all low-level concerns about particular database types.

JDBC is similar to Microsoft’s ODBC with the plus point “Platform Independence”. To use JDBC, you need to have database driver to communicate with the database. Normally drivers are installed while installing the database. Like if you install MS SQL Server, Oracle or DB2, database drivers will be installed. If you are working with MySQL, PostgreSQL or some third party database, you need to put its driver (Jar fileI into the class path.

JDBC Drivers
            JDBC drivers can be broadly divided into four categories depending upon the driver implementation. The four categories/types are:

            1: JDBC-ODBC Bridge
            2:  Native-API/partly Java driver
            3: Net-protocol/all-Java driver
            4: Native-protocol/all-Java driver

I will briefly talk about each type:
            JDBC-OBC bridge driver is pure Java and is include in java.sql.*. The client needs ODBC driver manager and ODBC driver for data source. It is ideal in situations, when ODBC driver is available for the database and is already installed on the client machine.

            Type-2 is Native code driver. It implements native JDBC interfaces using language functions in the DBMS product’s API. Type 2 drivers need platform specific library, so client and server both may run on same host. Type 2 drivers offer better performance than Type 1 drivers.

Type 3 drivers are pure Java drivers and they use middleware network protocol. They need DBMS server to implement the standard protocol to be middleware specific. The advantage is that there is no nee for any vendor database library to be present on client machines. Interesting thing is, there is no JDBC standard network protocol yet.

Type 4 drivers are pure Java drivers and they use vendor specific network protocol. These use DBMS specific network protocol (Oracle SQL Net, etc).
For the beginners, Type 1 drivers are suitable. Users simply have to make a DSN and start interacting with the database.

Using JDBC-ODBC Bridge

The beginners should start with JDBC-ODBC Bridge since it is simple and easy to work with. Consider that you have a database with tables and data and you want to connect to it in order to carry out operations.
            First step is to create an ODBC dsn. It is done from Control panel > Data Sources (ODBC).
            Now you have to load the JDBC driver. This is done using static method forName(…) of class called Class. Static method forName(…) takes name of the driver as parameter.

Code:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

DriverManager.getConnection() is used to connect to the database. Its signature is as follows:

Code:
static Connection getConnection(String url, String user, String password)



Continue... 
31/01/2011


Connection time:

            Sometimes, it is interesting to know how much time it takes to connect to the database. The code sample below calculates the time it takes to connect to a database referred by dsn.

Code:
long connection_time;
Date start = new Date();  //get start time
String stUrl_= "jdbc:odbc:myDSN";
connection_ = DriverManager.getConnection(stUrl,"sa","sa");
Date end = new java.util.Date();  //get end time
connection_time = end.getTime()-start.getTime();
 
 
Getting the Warnings:

            Sometimes it is a wise decision to retrieve the first warning reported by calls on this Connection object. This can be done using getWarnings() method. The code sample below shows how to print all the warnings with their sates and messages.

Code:
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" ) ;
Connection conn = DriverManager.getConnection( "jdbc:odbc:Database" ) ;

// Print all warnings
for( SQLWarning warn = conn.getWarnings(); warn != null; warn = warn.getNextWarning() )
{
System.out.println( "SQL Warning:" ) ;
System.out.println( "State  : " + warn.getSQLState()  ) ;
System.out.println( "Message: " + warn.getMessage()   ) ;
System.out.println( "Error  : " + warn.getErrorCode() ) ;
}

Adding records in the database tables:

            Statement object is used to add enteries into the tables. The method used is executeUpdate(…).


Code:
Statement st = conn.createStatement();
st.executeUpdate("INSERT INTO customers VALUES (100, 'Laiq', 'Mr.', 'Paris', 2008)");


Using Resultset:
            ResultSet is an interface found in java.sql package. It actually represents a table in the memory containing all the records fetched from the database in result of a query.

Code:
String name, brand ;
float price;

ResultSet rs = stmt.executeQuery("SELECT * FROM customers");
while ( rs.next() ) {
name = rs.getString("name");
brand = rs.getString("brand");
price = rs.getFloat("price");
}

Getting number of rows updated
            Statement’s executeUpdate(…) method return no of row modified. So you can easily know how many rows were modified by your update query.

Code:
int rows = stmt.executeUpdate( "UPDATE customer SET
cust_name = ‘Laiq’ WHERE cust_id = 100" ) ;
System.out.println( rows + " Rows modified" ) ;

Change( Screen) Windows display resolution.

'Using this code to change Screen Resolution......... or your computer
' this code is use for VB 6.0

'********************** Module*****************
Declarations
Public Const EWX_LOGOFF = 0
Public Const EWX_SHUTDOWN = 1
Public Const EWX_REBOOT = 2
Public Const EWX_FORCE = 4
Public Const CCDEVICENAME = 32
Public Const CCFORMNAME = 32
Public Const DM_BITSPERPEL = &H40000
Public Const DM_PELSWIDTH = &H80000
Public Const DM_PELSHEIGHT = &H100000
Public Const CDS_UPDATEREGISTRY = &H1
Public Const CDS_TEST = &H4
Public Const DISP_CHANGE_SUCCESSFUL = 0
Public Const DISP_CHANGE_RESTART = 1

Type typDevMODE
    dmDeviceName       As String * CCDEVICENAME
    dmSpecVersion      As Integer
    dmDriverVersion    As Integer
    dmSize             As Integer
    dmDriverExtra      As Integer
    dmFields           As Long
    dmOrientation      As Integer
    dmPaperSize        As Integer
    dmPaperLength      As Integer
    dmPaperWidth       As Integer
    dmScale            As Integer
    dmCopies           As Integer
    dmDefaultSource    As Integer
    dmPrintQuality     As Integer
    dmColor            As Integer
    dmDuplex           As Integer
    dmYResolution      As Integer
    dmTTOption         As Integer
    dmCollate          As Integer
    dmFormName         As String * CCFORMNAME
    dmUnusedPadding    As Integer
    dmBitsPerPel       As Integer
    dmPelsWidth        As Long
    dmPelsHeight       As Long
    dmDisplayFlags     As Long
    dmDisplayFrequency As Long
End Type

Declare Function EnumDisplaySettings Lib "user32" Alias "EnumDisplaySettingsA" (ByVal lpszDeviceName As Long, ByVal iModeNum As Long, lptypDevMode As Any) As Boolean
Declare Function ChangeDisplaySettings Lib "user32" Alias "ChangeDisplaySettingsA" (lptypDevMode As Any, ByVal dwFlags As Long) As Long
Declare Function ExitWindowsEx Lib "user32" (ByVal uFlags As Long, ByVal dwReserved As Long) As Long

'********************************************************************************************************************************************************************
'**************************Form******************************

Dim ScreenWidth As Integer
Dim ScreenHeight As Integer



Private Sub Command1_Click()
'Code:
'Following Text Boxes is the parameters for the screen resulution
'eg. 800*600
Dim typDevM As typDevMODE
Dim lngResult As Long
Dim intAns    As Integer
ScreenWidth = Val(Text1.Text) '800
ScreenHeight = Val(Text2.Text) '600

' Retrieve info about the current graphics mode
' on the current display device.
lngResult = EnumDisplaySettings(0, 0, typDevM)

' Set the new resolution. Don't change the color
' depth so a restart is not necessary.
With typDevM
    .dmFields = DM_PELSWIDTH Or DM_PELSHEIGHT
    .dmPelsWidth = ScreenWidth  'ScreenWidth (640,800,1024, etc)
    .dmPelsHeight = ScreenHeight 'ScreenHeight (480,600,768, etc)
End With

' Change the display settings to the specified graphics mode.
lngResult = ChangeDisplaySettings(typDevM, CDS_TEST)
Select Case lngResult
    Case DISP_CHANGE_RESTART
        intAns = MsgBox("You must restart your computer to apply these changes." & _
            vbCrLf & vbCrLf & "Do you want to restart now?", _
            vbYesNo + vbSystemModal, "Screen Resolution")
        If intAns = vbYes Then Call ExitWindowsEx(EWX_REBOOT, 0)
    Case DISP_CHANGE_SUCCESSFUL
        Call ChangeDisplaySettings(typDevM, CDS_UPDATEREGISTRY)
        Message = MsgBox("Screen resolution changed", vbInformation, "Resolution Changed ")
    Case Else
        Message = MsgBox("Mode not supported", vbSystemModal, "Error")
End Select

End Sub

Digital clock by using timer (swing) in Java

Here is a piece of code to build a Java clock, using swing,


        Timer t = new Timer(1000, updateClockAction);
        t.start();



ActionListener updateClockAction = new ActionListener() {
  public void actionPerformed(ActionEvent e) {
      // Assumes clock is a custom component
     lblTime.setText(System.currentTimeMillis()+"");
      // OR
    
      // Assumes clock is a JLabel
      lblTime.setText(new Date().toString());
    }
};