Friday, 28 August 2015

How to create a DataSource in WebLogic Server 11g console.



In this post you will learn how to create a Datasource in the Weblogic server 11g console.

To achieve this follow below steps:

1.  Login to Weblogic server console using http://<hostname>:<port>/console
2. Expand Services and click on Data Sources
3. Click on New and select Generic Data Source
 












4 Enter below entries and click Next











 
5. Keep default value and click Next


 









 6. Click Next












  7. Enter below entries according to your DB details and click Next












8. Click on Test Configuration, if below entries are correct then Connection would get succeeded and click Next











9. Select Server on which you want to deploy datasource. In this case we have only DefaultServer, click DefaultServer and click Finish.












10. testDS will get created and same can be used to get database connection.
 



Thursday, 27 August 2015

Configure Oracle DataSource in Tomcat

Here is the procedure, how to configure Oracle datasource in Tomcat and lookup the same.

     1. Get Oracle driver

Download Oracle driver from here and copy it to $TOMCAT\lib folder

     2. Create META-INF/context.xml and add following entry.

 <?xml version="1.0" encoding="windows-1252" ?>
<Context override="true">

    <Resource name="jdbc/hr" auth="Container"
        type="javax.sql.DataSource" maxActive="100" maxIdle="30"
        maxWait="10000" username="hr" password="welcome1"
        driverClassName="oracle.jdbc.driver.OracleDriver"
        url="jdbc:oracle:thin:@localhost:1521:orcl" />   
    </Context>



    3. web.xml configuration

<?xml version = '1.0' encoding = 'windows-1252'?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5" xmlns="http://java.sun.com/xml/ns/javaee">
   
  <resource-ref>
    <description>Oracle Datasource</description>
    <res-ref-name>jdbc/hr</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>
</web-app>



  4. Lookup datasource via context lookup service

Below class lookup datasource and established connection with Oracle DB

import javax.naming.Context;
import javax.naming.InitialContext;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class GetConnection {

    private static DataSource ds;

    public static DataSource getDS() {
        try {
            Context ctx = new InitialContext();
            ds = (DataSource)ctx.lookup("java:comp/env/jdbc/hr");
        } catch (NamingException e) {
            e.printStackTrace();
        }
        return ds;
    }

    public static void main(String[] args) {
        try {

            DataSource ds = GetConnection.getDS();

            Connection connection = ds.getConnection();
        } catch (SQLException sqle) {
            sqle.printStackTrace();
        }
    }

}




Get Current Date using Java

Below code give current date in String.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;


public class CurrentDate {
    public CurrentDate() {
        super();
    }

    public static void main(String[] args) {
        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
                Calendar cal = Calendar.getInstance();             
                System.out.println(dateFormat.format(cal.getTime()));
    }
}

Current Date in GregorianCalendar using java

Code snippet that will give Current date in GregorianCalendar format:


import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

public class CurrentDate {
    public CurrentDate() {
        super();
    }

    public static void main(String[] args) {
            XMLGregorianCalendar xgcal = null;
                try {
                    GregorianCalendar gcal =
                        (GregorianCalendar)GregorianCalendar.getInstance();
                     xgcal =
                        DatatypeFactory.newInstance().newXMLGregorianCalendar(gcal);
                    System.out.println("xgcal "+xgcal.toString());
                } catch (DatatypeConfigurationException dce) {
                   System.out.println("Exception occurred while getting XMLGregorianCalendar "+dce);
                 }
    }
}

Wednesday, 26 August 2015

Java Jndi datasource lookup

JNDI style is typical when using an application server(Weblogic, JBOSS) or a web container(Apache Tomcat).

Here's a example of the lookup Datasource created in Server.

import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DatabaseConnection {
    public DatabaseConnection() {
        super();
    }
    // JNDI name created in Server

    final static String DATA_SOURCE="jdbc/PortalDS";
    public static void main(String[] args) {

        Connection connection = DatabaseConnection.init(DATA_SOURCE);
       
        System.out.println("Connection "+connection);

    }
   
    private static Connection init(String dsName) {
              Connection con = null;
              DataSource datasource = null;
      
              Context initialContext = null;
              try{
                initialContext = new InitialContext();
                if (initialContext == null) {
                }
                datasource = (DataSource)initialContext.lookup(dsName);
                if (datasource != null) {
                     con = datasource.getConnection();
                } else {
                    System.out.println("Failed to lookup datasource.");

                }
              }catch (SQLException sqle) {
                     System.out.println("SQL Exception occurred while getting DataSource : " +
                               sqle);
                    
                 } catch (NamingException ne) {
                     System.out.println("Naming Exception occurred while getting DataSource : " +
                               ne);
               

                 }
            
              return con;
          }
}
 

Get Oracle DB connection using Oracle driver

Here is an example to connect Oracle DB using Oracle driver.

1) Download Oracle JDBC Driver

Download Oracle JDBC Driver from  here

2) Set classpath of above jar

3) Use below code to connect Oracle DB

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ObtainDBConnection {
    public ObtainDBConnection() {
        super();
    }

    private static Connection getConnnection() {

        try {
            // Load oracle driver
            Class.forName("oracle.jdbc.driver.OracleDriver");
           
        } catch (ClassNotFoundException e) {

            System.out.println("Oracle JDBC Driver not found");
            e.printStackTrace();
            return null;

        }

        Connection connection = null;

        try {
           
            String connectionString = "jdbc:oracle:thin:@localhost:1521:orcl";
            String userName = "hr";
            String password = "welcome1";

            connection =
                    DriverManager.getConnection(connectionString,userName, password);

        } catch (SQLException e) {

            System.out.println("Oracle database connection couldn't be established. Please check DB details!!");
            e.printStackTrace();
            return null;

        }

        if (connection != null) {
            System.out.println("DB connection established successfully");
            return connection;
        } else {
            System.out.println("Failed to connect DB.");
            return null;
        }
    }
   
    public static void main(String args[]){
        Connection connection = ObtainDBConnection.getConnnection();
       
        System.out.println("Connection "+connection);
       
    }
}

Difference between Sun JDK And Oracle JRockit

This is very important to know, which jdk is better than and which one to use.

Below are some basic difference between Sun JDK and Oracle JRockit.

As we know, JVM is responsible to convert  java byte code into machine code.

Sun jdk and Oracle JRockit do the same thing using different mechanism.

Sun JDK uses interpreter  – In this mechanism, the byte code is read and the translated into machine language, but these results are not saved in the memory. So every time even if the same method is run again and again, the JVM has to translate the code into machine language. This means machine code will not be reusable as it is not saved anywhere in the memory.  

Oracle JRockit uses only JIT compiler (Just In Time) – JIT mechanism means, once a method is run, the byte code is translated to machine language and this is saved in the memory. This means if the method is run again, there is no need for translation and the machine code is reused.

In the long run processes, JRockit gives a slightly better performance as compared to sun jdk.

Memory spaces in jdks:
 
Sun JDK has the following memory spaces:
  1.  Eden space
  2.  Survivior space
  3.  Tenured generation 
  4.  Permanent generation

 The objects move from one space to another according to its age and survival from garbage collection.

JRockit has 2 spaces
  1. Young generation 
  2.  Old generation
It uses the same mechanism of garbage collection. There is nothing called as permanent generation in JRockit.



Memory and other JVM tunings:

JRockit gives advanced JVM tunings. From the release R26 and above, JRockit takes care of few tunings by itself. For example if there is an outofmemory occuring on the native TLA in previous releases due to insufficient TLA size which is 2k by default, in later releases the JRockit tunes these settings as per the requirement of the application. This has to be done and taken care of by the user in case of sun jdk. But then it is always better to be in a safer side it is recommended to have the tunings done by self.

Which one should we use?

It definitely depends on the application you want to run. Here is a summary of when to use them:

Sun JDK

  • Desktop application
  • UI (swing) based application
  • Desktop daemon
  • Fast starting JVM

JRockit

  • Java application server
  • High performance application
  • Need of a full monitoring environment