Wednesday, 16 March 2016

Tricky Java Interview Questions

Question 1:
Which of two below overridden method will get called when we call method(null)?
public class Demo1 {
public void method(Object obj){
System.out.println("Object");
}

public void method(String str){
System.out.println("String");
}

public static void main(String[] args) {
Demo1 demo1 = new Demo1();
demo1.method(null);
}
}

Answer 1 :  method(String str) will get called as the child class get preference in case of ambibuity.

Question 2:
Which of two below overridden method will get called when we call demo1.test(collection), demo1.test(list), demo1.test(arrayList)?
public class Demo1 {
public void test(Collection<String> c) {
System.out.println("Collections");
}

public void test(ArrayList<String> al) {
System.out.println("ArrayList");
}

public static void main(String[] args) {
Collection<String> collection = new ArrayList<String>();
List<String> list = new ArrayList<String>();
ArrayList<String> arrayList = new ArrayList<String>();
demo1.test(collection);
demo1.test(list);
demo1.test(arrayList);
}
}

Answer 2: test(Collection<String> c) will get calledin case of demo1.test(collection), and demo1.test(list) and test(ArrayList<String> al) will get called in case of demo1.test(arrayList). So the final output would be ...
Collections
Collections
ArrayList

Question 3 : What will be the result 
hashmap.put(new Employee(), "A")
hashmap.put(new Employee(), "B") 
hashmap.get(new Employee());

Answer 3 : It will return null;

Question 4: What is the core difference between Object Oriented and Object based languages
Answer 4: 
Object-based : Any language that offers the built-in ability to easily create and use objects. There is one major criterion: Encapsulation: 
As far as object-based-but-not-object-oriented languages go, a good example would be Visual Basic (not the .net stuff; i'm talking about VB6 and VBA). Classes exist, but can't inherit from each other.
Object-oriented languages are object-based languages that take things a step further. They have built-in support for the two other pillars of OOP:
Inheritance. 
Polymorphism.  
Question 5: What is Upcasting and downcasting
Answer 5: Upcasting and downcasting are NOT like casting primitives from one to other, and i believe that's what causes a lot of confusion, when programmer starts to learn casting objects

Object ---> Animal ---> Mammal ---> Dog
Object ---> Animal ---> Mammal ---> Cat
Upcasting <-------------------> Downcasting

When we cast Dog to Animal, Mammal or Object it is upcasting
When we cast Animal to Dog or Mammal it is downcasting

Casting does not actually change the object itself, but its just label it differently. 
For example, if you create a Cat and upcast it to Animal, then the object doesn't stop from being a Cat. It's still a Cat, but it's just treated as any other Animal and it's Cat properties are hidden until it's downcasted to a Cat again. 

Although there's no need to for programmer to upcast manually, it's allowed to do.Consider the following example:
Code: Mammal m = (Mammal)new Cat(); is equal to 
Code: Mammal m = new Cat(); 

But downcasting must always be done manually:
Code: Cat c1 = new Cat();  
  Animal a = c1; //automatic upcasting to Animal

  Cat c2 = (Cat) a;    //manual downcasting back to a Cat

Question 6: What is Just in Time JIT Compiler?
Answer:
In the Java programming language and environment, a just-in-time(JITcompiler is a program that turns Java bytecode (a program that contains instructions that must be interpreted) into instructions that can be sent directly to the processor. 
After you've written a Java program, the source language statements are compiled by the Java compiler into bytecode rather than into code that contains instructions that match a particular hardware platform's processor. The bytecode is platform-independent code that can be sent to any platform and run on that platform with the help of JIT.

Question 7: How many types of Memory area's are allocated by JVM?
Answer: 
The JVM performs four main tasks: 
· Loads code
· Verifies code
· Executes code
· Provides runtime environment

JVM provides definitions for the:
· Memory area
· Class file format
· Register set
· Garbage-collected heap
· Fatal error reporting etc.

Types of memory allocated by JVM:
· Class (Method) Area
· Heap
· Stack
· Program Counter Register
· Native Method Stack
1) Classloader:
Classloader is a subsystem of JVM that is used to load class files.
2) Class (Method) Area:
Class (Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods.
3) Heap:
It is the runtime data area in which objects are allocated.
4) Stack:
Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.
5) Program Counter Register:
PC (program counter) register. It contains the address of the Java virtual machine instruction currently being executed.
6) Native Method Stack:
It contains all the native methods used in the application.

Execution Engine:
It contains:
1) A virtual processor
2) Interpreter: Read bytecode stream then execute the instructions.

3) Just-In-Time(JIT) compiler: It is used to improve the performance.JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here the term compiler refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU

Wednesday, 10 June 2015

Core Java Interview Question : 
1 : How to create a immutable object in Java? 
An immutable class is one whose state can not be changed once created. Here, state of object essentially means the values stored in instance variable in class whether they are primitive types or reference types.

To make a class immutable, below steps needs to be followed:

Don’t provide “setter” methods or methods that modify fields or objects referred to by fields. Setter methods are meant to change the state of object and this is what we want to prevent here.

Make all fields final and private. Fields declared private will not be accessible outside the class and making them final will ensure the even accidentally you can not change them.

Don’t allow subclasses to override methods. The simplest way to do this is to declare the class as final. Final classes in java can not be overridden.

Always remember that your instance variables will be either mutable or immutable. Identify them and return new objects with copied content for all mutable objects (object references). Immutable variables (primitive types) can be returned safely without extra effort.

2 : Difference between Runnable and Callable interface in Java?

Runnable and Callable interface both are designed to represent task, which can be executed by any thread. Both does same task for the programmer with few difference between each other. In this tutorial we will see about difference between Runnable and Callable interface difference and when we need to use Runnable and Callable interface in our application.

Runnable interface introduced in JDK 1.0, whereas Callable interface introduced in Java 5 release along with other major changes e.g. Generics, Enum, Static imports and variable argument method.
Since both are interface when we implement these interface we need to implement run() method from Runnable interface and call() method from Callable interface.
run() method didn't not return any value, whereas call() method returns Object where Callable interface is a generic parameterized interface and Type of value is provided at implementation.
Callable interface can throw checked exception because it's call method throws Exception where as run() method has its limitation.

Basically if our application needs to return any value from executor method then we need to for Callable interface than Runnable interface.

Bu keeping all these differences and usage between Runnalbe and Callable interface programmer need to be in a position to decide which interface he needs to choose for his application.

As this is one of the important interview question asked in most of the interviews followed by multi-threading question and mostly asked in Banking domain Java interviews.

3 : What is thread synchronization. Difference between object level locking and class level locking. ?

Synchronization refers to multi-threading. A synchronized block of code can only be executed by one thread at a time.
Java supports multiple threads to be executed. This may cause two or more threads to access the same fields or objects. Synchronization is a process which keeps all concurrent threads in execution to be in synch. Synchronization avoids memory consistence errors caused due to inconsistent view of shared memory. When a method is declared as synchronized; the thread holds the monitor for that method’s object If another thread is executing the synchronized method, your thread is blocked until that thread releases the monitor.
Synchronization in java is achieved using synchronized keyword. You can use synchronized keyword in your class on defined methods or blocks. Keyword can not be used with variables or attributes in class definition.

Object level locking

Object level locking is mechanism when you want to synchronize a non-static method or non-static code block such that only one thread will be able to execute the code block on given instance of the class. This should always be done to make instance level data thread safe.

Class level locking

Class level locking prevents multiple threads to enter in synchronized block in any of all available instances on runtime. This means if in runtime there are 100 instances of  DemoClass, then only one thread will be able to execute demoMethod() in any one of instance at a time, and all other instances will be locked for other threads. This should always be done to make static data thread safe.

Some Important notes about threading

  1. Synchronization in java guarantees that no two threads can execute a synchronized method which requires same lock simultaneously or concurrently.
  2. synchronized keyword can be used only with methods and code blocks. These methods or blocks can be static or non-static both.
  3. When ever a thread enters into java synchronized method or block it acquires a lock and whenever it leaves java synchronized method or block it releases the lock. Lock is released even if thread leaves synchronized method after completion or due to any Error or Exception.
  4. java synchronized keyword is re-entrant in nature it means if a java synchronized method calls another synchronized method which requires same lock then current thread which is holding lock can enter into that method without acquiring lock.
  5. Java Synchronization will throw NullPointerException if object used in java synchronized block is null. For example, in above code sample if lock is initialized as null, the synchronized (lock) will throw NullPointerException.
  6. Synchronized methods in Java put a performance cost on your application. So use synchronization when it is absolutely required. Also, consider using synchronized code blocks for synchronizing only critical section of your code.
  7. It’s possible that both static synchronized and non static synchronized method can run simultaneously or concurrently because they lock on different object.
  8. According to the Java language specification you can not use java synchronized keyword with constructor it’s illegal and result in compilation error.
  9. Do not synchronize on non final field on synchronized block in Java. because reference of non final field may change any time and then different thread might synchronizing on different objects i.e. no synchronization at all. Best is to use String class, which is already immutable and declared final.
4: What is Fail fast Iterator?
Fail fast iterator while iterating through the collection , instantly throws Concurrent Modification Exception if there is structural modification  of the collection . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. 
Fail-fast iterator can throw ConcurrentModificationException in two scenarios :

Single Threaded Environment
After the creation of the iterator , structure is modified at any time by any method other than iterator's own remove method. 
  
Multiple Threaded Environment 
If one thread is modifying the structure of the collection while other thread is iterating over it .

How  Fail  Fast Iterator  come to know that the internal structure is modified ?
Iterator read internal data structure (object array) directly . The internal data structure(i.e object array) should not be modified while iterating through the collection. To ensure this it maintains an internal  flag "mods" .Iterator checks the "mods" flag whenever it gets the next value (using hasNext() method and next() method). Value of mods flag changes whenever there is an structural modification. Thus indicating iterator to throw ConcurrentModificationException.


5: What is Fail Safe Iterator ?
Fail Safe Iterator makes copy of the internal data structure (object array) and iterates over the copied data structure.Any structural modification done to the iterator affects the copied data structure.  So , original data structure remains  structurally unchanged .Hence , no ConcurrentModificationException throws by the fail safe iterator.
Two  issues associated with Fail Safe Iterator are :
1. Overhead of maintaining the copied data structure i.e memory.
2.  Fail safe iterator does not guarantee that the data being read is the data currently in the original data structure. 
According to Oracle docs , fail safe iterator is ordinarily too costly, but may be more efficient than alternatives when traversal operations vastly outnumber mutations, and is useful when you cannot or don’t want to synchronize traversals, yet need to preclude interference among concurrent threads. The "snapshot" style iterator method uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException.The iterator will not reflect additions, removals, or changes to the list since the iterator was created. Element-changing operations on iterators themselves (remove(), set(), and add()) are not supported. These methods throw UnsupportedOperationException.
 

Friday, 5 September 2014

Log4j Configuration for web application in JBOSS and Tomcat

Step 1: Download commons-io.jar, commons-lang-2.6.jar and log4j-1.2.15.jar.

Step2: Put jar files in WEB-INF/lib.

Step3: Create a web application with servlet.

Step 4. Complete Servlet Code for reference:

log4j.xml :  (for JBoss -- uncomment "<!--<param name="File" value="${jboss.server.log.dir}/loggers.log"/>-->" and comment "<param name="File" value="../logs/loggers.log" />")

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//log4j/log4j Configuration//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="abc-date-rollout" class="org.apache.log4j.DailyRollingFileAppender">
       <param name="File" value="../logs/loggers.log" />
       <!--<param name="File" value="${jboss.server.log.dir}/loggers.log"/>-->
       <param name="DatePattern" value="'.'yyyy-MM-dd" />
       <layout class="org.apache.log4j.PatternLayout">
          <param name="ConversionPattern" value="%d{dd MMM yyyy HH:mm:ss,SSS} %-5p: %c - %m%n"/>        
       </layout>
    </appender>
 
    <appender name="ASYNC" class="org.apache.log4j.AsyncAppender">
    <param name="BufferSize" value="500"/>
    <appender-ref ref="abc-date-rollout"/>
    </appender>

    <root>
        <priority value="INFO"/>
        <appender-ref ref="abc-date-rollout" />
    </root>
</log4j:configuration>


Complete web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" 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>DBConnServlet</display-name>
  <context-param>
    <param-name>log4j-properties-location</param-name>
    <param-value>WEB-INF/classes/log4j.xml</param-value>
  </context-param>
  <resource-ref>
    <description>COS Database Connection</description>
    <res-ref-name>jdbc/DSName</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
    <mapped-name>jdbc/DSName</mapped-name>
  </resource-ref>
  <listener>
    <listener-class>com.test.listener.AppContextListener</listener-class>
  </listener>
  <servlet>
    <description>Proxy servlet for all Technical workflows</description>
    <display-name>DBConnServlet</display-name>
    <servlet-name>DBConnServlet</servlet-name>
    <servlet-class>com.test.servlet.DBConnServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>DBConnServlet</servlet-name>
    <url-pattern>/Connection/*</url-pattern>
  </servlet-mapping>
  <session-config>
    <session-timeout>1440</session-timeout>
  </session-config>
</web-app>

Listener Class

package com.test.listener;

import java.io.File;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

public class AppContextListener implements ServletContextListener {

/**
 * @see ServletContextListener#contextInitialized(ServletContextEvent)
 */
public void contextInitialized(ServletContextEvent objServletContextEvent) {
final ServletContext servletContext = objServletContextEvent.getServletContext();

        // Logger initialization starts
Logger log = null;
System.out.println("AppContextListener is initializing log4j");
String log4jLocation = servletContext.getInitParameter("log4j-properties-location");
if (log4jLocation == null) {
System.err
.println("*** No log4j-properties-location init param, so initializing log4j with BasicConfigurator");
BasicConfigurator.configure();
} else {
String webAppPath = servletContext.getRealPath("/");
String log4jProp = webAppPath + log4jLocation;
File log4j = new File(log4jProp);
if (log4j.exists()) {
System.out.println("Initializing log4j with: " + log4jProp);
DOMConfigurator.configure(log4jProp);
} else {
System.err
.println("*** " + log4jProp + " file not found, so initializing log4j with BasicConfigurator");
BasicConfigurator.configure();
}
}
//Get logger to log events
log = Logger.getLogger(AppContextListener.class.getName());
// Logger initialization Ends
log.info("contextInitialized(): ServletContextListener started : " + new Date());
}

/**
 * @see ServletContextListener#contextDestroyed(ServletContextEvent)
 */
public void contextDestroyed(ServletContextEvent objServletContextEvent) {
Logger log = Logger.getLogger(AppContextListener.class.getName());
// get our timer from the Context
log.info("run(): ServletContextListener destroyed : ");
}


}

Servlet Class for Connection: 

package com.test.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

/**
 * Servlet implementation class DBConnectionServlet
 */
public class DBConnServlet extends HttpServlet {

private static final long serialVersionUID = 1L;
static Logger log = Logger.getLogger(DBConnServlet.class.getName());

/*
 * (non-Javadoc)
 * 
 * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
 */
public void init(ServletConfig config) {
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
con = getConnection();
// Execute SQL query
stmt = con.createStatement();
String sql;
sql = "SELECT FirstName, LastName FROM [Config].[UserMaster]";
rs = stmt.executeQuery(sql);
while (rs.next()) {
// Retrieve by column name
String first = rs.getString("FirstName");
String last = rs.getString("LastName");
System.out.println("Name : " + first + " " + last);
}
rs.close();
stmt.close();
con.close();

} catch (Exception e){
try{
rs.close();
stmt.close();
con.close();
}catch(SQLException sqle){
}
}
}

/**
 * Get connection from data source.
 * @return
 * @throws SQLException
 */
public Connection getConnection() throws SQLException {
Connection conDB = null;
try {
// sqljdbc4.jar - support JDBC 4.0, it works only JRE 6.0 or later
// Get value from web.xml
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource sqlDS = (DataSource) envCtx.lookup("jdbc/DSName");
conDB = sqlDS.getConnection();
} catch (Exception e) {
System.out.println(" ***** DbConnection.GetConnection ERROR ***** " + e);
}
return conDB;
}
}

Complete context.xml: 

<?xml version='1.0' encoding='utf-8'?>
<Context path="/DBConnApp/Connection" docBase="DBTest"
        debug="5" reloadable="true" crossContext="true" sessionCookiePathUsesTrailingSlash='false'>

    <Resource
    name="jdbc/DSName"
    auth="Container"
    type="javax.sql.DataSource"
    removeAbandoned="true" removeAbandonedTimeout="30" maxActive="100" maxIdle="30" maxWait="10000"
    username="aj83793" password="Mahavir9" testOnBorrow="true" validationQuery="select 1"
    driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
    url="jdbc:sqlserver://10.173.56.215:1433;DatabaseName=CobaltDEV"/>

</Context>

Complete jboss-web.xml: 

<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
<class-loading java2ClassLoadingCompliance="false">
<loader-repository>
org.myapp:loader=MyClassLoader
<loader-repository-config>java2ParentDelegation=false</loader-repository-config>
</loader-repository>
</class-loading>

<resource-ref>
   <res-ref-name>java:jdbc/DSName</res-ref-name>
   <jndi-name>java:jdbc/DSName</jndi-name>
   <res-type>javax.sql.DataSource</res-type>
</resource-ref>

</jboss-web>

Thursday, 4 September 2014

JDBC Connection configuration to MicroSoft SQL server database in Tomcat 6.0 and JBoss 5.1.0.GA

Step 1: Download the Jar file for JDBC 4.

Step2: Put sqljdbc4.jar in /TomcatHome/Tomcat6.0/lib for tomcat and Jboss-5.1.0.-jdk\server\default\lib for JBoss.

Step3: Create a web application with servlet which will be used to test the database connection through JBoss and Tomcat.

Application Details:
1.WEB-INF/web.xml of web application will contain (This is required for both Tomcat and JBoss).
<resource-ref>
   <description>COS Database Connection</description>
   <res-ref-name>jdbc/DSName</res-ref-name>
   <res-type>javax.sql.DataSource</res-type>
   <res-auth>Container</res-auth>
   <res-sharing-scope>Shareable</res-sharing-scope>
   <mapped-name>jdbc/DSName</mapped-name>
</resource-ref>

2. META-INF/context.xml will contain an entry for resource (Required for Tomcat)
<?xml version='1.0' encoding='utf-8'?>
<Context path="/DBConnectionServlet/Connection" docBase="DBTest"
        debug="5" reloadable="true" crossContext="true" sessionCookiePathUsesTrailingSlash='false'>
<Resource
   name="jdbc/DSName"
   auth="Container"
   type="javax.sql.DataSource"
   removeAbandoned="true" removeAbandonedTimeout="30" maxActive="100" maxIdle="30" maxWait="10000"
   username="username" password="password" testOnBorrow="true" validationQuery="select 1"
   driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
   url="jdbc:sqlserver://XXX.XXX.XXX.XXX:1433;DatabaseName=DatabaseName"/>

</Context>

3. WEB-INF/jboss-web.xml will contain resource-ref for database. (Required for JBoss)
<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
<resource-ref> <description>COS Database Connection</description> <res-ref-name>jdbc/DSName</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> <res-sharing-scope>Shareable</res-sharing-scope> <mapped-name>jdbc/DSName</mapped-name> </resource-ref>

</jboss-web>

4. Create mssql-ds.xml and put it at \Jboss-5.1.0.-jdk\server\default\deploy (Required for JBoss)

<?xml version="1.0" encoding="UTF-8"?>

<!-- ===================================================================== -->
<!--                                                                       -->
<!--  JBoss Server Configuration                                           -->
<!--                                                                       -->
<!-- ===================================================================== -->

<!-- See http://www.jboss.org/community/wiki/Multiple1PC for information about local-tx-datasource -->
<!-- $Id: mssql-ds.xml 88948 2009-05-15 14:09:08Z jesper.pedersen $ -->

  <!-- ======================================================================-->
  <!-- New ConnectionManager setup for Microsoft SQL Server 2005  driver     -->
  <!-- Further information about the Microsoft JDBC Driver version 1.1      -->
  <!-- can be found here:                                                   -->
  <!-- http://msdn2.microsoft.com/en-us/library/aa496082.aspx               -->
  <!-- ===================================================================== -->

<datasources>
  <local-tx-datasource>
    <jndi-name>jdbc/DSName</jndi-name>
<use-java-context>false</use-java-context>
    <connection-url>jdbc:sqlserver://XXX.XXX.XXX.XXX:1433; DatabaseName=DatabaseName</connection-url>
    <driver-class>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver-class>
    <user-name>username</user-name>
    <password>password</password>
        <!-- sql to call when connection is created
        <new-connection-sql>some arbitrary sql</new-connection-sql>
        -->

        <!-- sql to call on an existing pooled connection when it is obtained from pool
        <check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
        -->

      <!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->
      <metadata>
         <type-mapping>MS SQLSERVER2000</type-mapping>
      </metadata>
  </local-tx-datasource>

</datasources>

5. Complete Servlet Code for reference:

Complete web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" 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>DBConnServlet</display-name>
  <context-param>
    <param-name>log4j-properties-location</param-name>
    <param-value>WEB-INF/classes/log4j.xml</param-value>
  </context-param>
  <resource-ref>
    <description>COS Database Connection</description>
    <res-ref-name>jdbc/DSName</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
    <mapped-name>jdbc/DSName</mapped-name>
  </resource-ref>
  <listener>
    <listener-class>com.test.listener.AppContextListener</listener-class>
  </listener>
  <servlet>
    <description>Proxy servlet for all Technical workflows</description>
    <display-name>DBConnServlet</display-name>
    <servlet-name>DBConnServlet</servlet-name>
    <servlet-class>com.test.servlet.DBConnServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>DBConnServlet</servlet-name>
    <url-pattern>/Connection/*</url-pattern>
  </servlet-mapping>
  <session-config>
    <session-timeout>1440</session-timeout>
  </session-config>
</web-app>

Listener Class

package com.test.listener;

import java.io.File;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

public class AppContextListener implements ServletContextListener {

/**
* @see ServletContextListener#contextInitialized(ServletContextEvent)
*/
public void contextInitialized(ServletContextEvent objServletContextEvent) {
final ServletContext servletContext = objServletContextEvent.getServletContext();

        // Logger initialization starts
Logger log = null;
System.out.println("AppContextListener is initializing log4j");
String log4jLocation = servletContext.getInitParameter("log4j-properties-location");
if (log4jLocation == null) {
System.err
.println("*** No log4j-properties-location init param, so initializing log4j with BasicConfigurator");
BasicConfigurator.configure();
} else {
String webAppPath = servletContext.getRealPath("/");
String log4jProp = webAppPath + log4jLocation;
File log4j = new File(log4jProp);
if (log4j.exists()) {
System.out.println("Initializing log4j with: " + log4jProp);
DOMConfigurator.configure(log4jProp);
} else {
System.err
.println("*** " + log4jProp + " file not found, so initializing log4j with BasicConfigurator");
BasicConfigurator.configure();
}
}
//Get logger to log events
log = Logger.getLogger(AppContextListener.class.getName());
// Logger initialization Ends
log.info("contextInitialized(): ServletContextListener started : " + new Date());
}

/**
* @see ServletContextListener#contextDestroyed(ServletContextEvent)
*/
public void contextDestroyed(ServletContextEvent objServletContextEvent) {
Logger log = Logger.getLogger(AppContextListener.class.getName());
// get our timer from the Context
log.info("run(): ServletContextListener destroyed : ");
}


}

Servlet Class for Connection: 

package com.test.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

/**
 * Servlet implementation class DBConnectionServlet
 */
public class DBConnServlet extends HttpServlet {

private static final long serialVersionUID = 1L;
static Logger log = Logger.getLogger(DBConnServlet.class.getName());

/*
* (non-Javadoc)
* @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
*/
public void init(ServletConfig config) {
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
con = getConnection();
// Execute SQL query
stmt = con.createStatement();
String sql;
sql = "SELECT FirstName, LastName FROM [Config].[UserMaster]";
rs = stmt.executeQuery(sql);
while (rs.next()) {
// Retrieve by column name
String first = rs.getString("FirstName");
String last = rs.getString("LastName");
System.out.println("Name : " + first + " " + last);
}
rs.close();
stmt.close();
con.close();

} catch (Exception e){
try{
rs.close();
stmt.close();
con.close();
}catch(SQLException sqle){
}
}
}

/**
* Get connection from data source.
* @return
* @throws SQLException
*/
public Connection getConnection() throws SQLException {
Connection conDB = null;
try {
// sqljdbc4.jar - support JDBC 4.0, it works only JRE 6.0 or later
// Get value from web.xml
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource sqlDS = (DataSource) envCtx.lookup("jdbc/DSName");
conDB = sqlDS.getConnection();
} catch (Exception e) {
System.out.println(" ***** DbConnection.GetConnection ERROR ***** " + e);
}
return conDB;
}
}

Complete context.xml: 

<?xml version='1.0' encoding='utf-8'?>
<Context path="/DBConnApp/Connection" docBase="DBTest"
        debug="5" reloadable="true" crossContext="true" sessionCookiePathUsesTrailingSlash='false'>

    <Resource
   name="jdbc/DSName"
   auth="Container"
   type="javax.sql.DataSource"
   removeAbandoned="true" removeAbandonedTimeout="30" maxActive="100" maxIdle="30" maxWait="10000"
   username="aj83793" password="Mahavir9" testOnBorrow="true" validationQuery="select 1"
   driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
   url="jdbc:sqlserver://10.173.56.215:1433;DatabaseName=CobaltDEV"/>

</Context>

Complete jboss-web.xml: 

<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
<class-loading java2ClassLoadingCompliance="false">
<loader-repository>
org.myapp:loader=MyClassLoader
<loader-repository-config>java2ParentDelegation=false</loader-repository-config>
</loader-repository>
</class-loading>

<resource-ref> <description>COS Database Connection</description> <res-ref-name>jdbc/DSName</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> <res-sharing-scope>Shareable</res-sharing-scope> <mapped-name>jdbc/DSName</mapped-name> </resource-ref>

</jboss-web>

log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//log4j/log4j Configuration//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="cblt-date-rollout" class="org.apache.log4j.DailyRollingFileAppender">
       <param name="File" value="../logs/loggers.log" />
       <!--<param name="File" value="${jboss.server.log.dir}/loggers.log"/>-->
       <param name="DatePattern" value="'.'yyyy-MM-dd" />
       <layout class="org.apache.log4j.PatternLayout">
          <param name="ConversionPattern" value="%d{dd MMM yyyy HH:mm:ss,SSS} %-5p: %c - %m%n"/>        
       </layout>
    </appender>
 
    <appender name="ASYNC" class="org.apache.log4j.AsyncAppender">
   <param name="BufferSize" value="500"/>
   <appender-ref ref="cblt-date-rollout"/>
    </appender>

    <root>
        <priority value="INFO"/>
        <appender-ref ref="cblt-date-rollout" />
    </root>
</log4j:configuration>

Friday, 21 February 2014

Here I am providing code with JAXB for converting java object to xml and xml to java objects.

Java Class to convert to xml

package com.bj.file.test.jaxb;

import java.util.ArrayList;
import java.util.List;

public class Customer {
private String firstName;
    private String lastName;
    private List<PhoneNumber> phoneNumbers = new ArrayList<PhoneNumber>();

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public List<PhoneNumber> getPhoneNumbers() {
        return phoneNumbers;
    }

    public void setPhoneNumbers(List<PhoneNumber> phoneNumbers) {
        this.phoneNumbers = phoneNumbers;
    }
}

package com.bj.file.test.jaxb;

public class PhoneNumber {
private String type;
    private String number;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }
}


Now a demo class which shows how can you convert xml to Java object and Java object to XML. 

Here I have provided a method genericReadingInput() which convert all the objects to corrosponding XML without knowing the objects name. It will take the root tag as the object class name and other parameters as element of xml.

package com.bj.file.test.jaxb;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.namespace.QName;
import javax.xml.transform.stream.StreamSource;

public class Demo {

// This will allow only specific objects.
private void readingInput() throws Exception {
JAXBContext jc = JAXBContext.newInstance(Customer.class);

StreamSource xml = new StreamSource("src/com/bj/file/test/jaxb/input.xml");

Unmarshaller unmarshaller = jc.createUnmarshaller();
JAXBElement<Customer> je1 = unmarshaller.unmarshal(xml, Customer.class);
Customer customer = je1.getValue();

JAXBElement<Customer> je2 = new JAXBElement<Customer>(new QName("Customer"), Customer.class, customer);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(je2, System.out);
}

// This will allow generic objects in place of specific objects.
private void genericReadingInput() throws Exception {

JAXBContext jc = JAXBContext.newInstance(Customer.class);
StreamSource xml = new StreamSource("src/com/bj/file/test/jaxb/input.xml");

Unmarshaller unmarshaller = jc.createUnmarshaller();
JAXBElement<Customer> je1 = unmarshaller.unmarshal(xml, Customer.class);
                // Now convert this to a plain java object
Object obj = je1.getValue();
                
                // Here you do not need to know the name of java objects class name So you can use this code for any object.
JAXBElement<? extends Object> je2 = new JAXBElement<Object>(new QName(getClassName(obj)), Object.class, obj);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(je2, System.out);

}

//This will allow to write xml from java object without annotation.
private void convertJavaObj2Xml() throws Exception {
JAXBContext jc = JAXBContext.newInstance(Customer.class);

Customer customer = new Customer();
customer.setFirstName("Lyoubomir");
customer.setLastName("Veltchev");

PhoneNumber workPhone = new PhoneNumber();
workPhone.setType("work");
workPhone.setNumber("555-1111");
customer.getPhoneNumbers().add(workPhone);

Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
JAXBElement<Customer> rootElement = new JAXBElement<Customer>(new QName("customer"), Customer.class, customer);
marshaller.marshal(rootElement, System.out);
}

private String getClassName(Object obj) {
return obj.getClass().getSimpleName();
}
public static void main(String[] args) throws Exception {
Demo demo = new Demo();
demo.convertJavaObj2Xml();
System.out.println("\n\n\n\n");
demo.readingInput();
demo.genericReadingInput();
}
}