Apr 28, 2011

Java Cloning FAQ

Java Cloning FAQ

1) What is Cloning? What importance does it have?
Ans: Creating a copy of object is known as cloning. It has special importance in Java because object cloning is supported by Java itself. Though one can override the behavior of object cloning but there is a default behavior by which copies of objects can be created.



2)How does one create object clones?
Ans: One can create object clones by invoking the clone method on the object to be cloned. The clone() method is defined as protected method in the Object class and is thus inherited by all the classes.

The only requirement for creating object clones is that the class whose objects are being cloned should implement the Cloneable interface. If this is not done that a CloneNotSupported Exception is thrown on calling the clone method.


3) What is the different ways to create object clones?
Ans: Cloning is of two types viz shallow and deep cloning. Shallow cloning is what the default behavior of clone method is and deep cloning is achieved by overriding the clone method in a class.
With shallow cloning the member primitive variables are also cloned but the member reference variables are not cloned. This means that the reference variables referring to objects are shared between the original and cloned objects.


4) Give an example code for both shallow and deep cloning?
Ans:
Shallow Cloning:
public class Test implements Cloneable{
      int a=10;
      StringBuffer str = new StringBuffer("abc");
      public void main (String args[])  throws CloneNotSupportedException{
             Test t1 = new Test();
             Test t2 = (Test)t1.clone();
             t1.a=20;t2.a=30;
             t1.str.append("def");t2.str.append("ghi"); 

             System.out.println("t1.a = " + t1.a + " t2.a = " + t2.a);
             System.out.println("t1.str = " + t1.str + " t2.str = " + t2.str);
      }
}

Output:
t1.a = 20 t2.a = 30
t1.str = abcdefghi t2.str = abcdefghi

Deep Cloning:

public class Test implements Cloneable{
      int a=10;
      StringBuffer str = new StringBuffer("abc"); 
      public void main (String args[])  throws CloneNotSupportedException{
             Test t1 = new Test();
             Test t2 = (Test)t1.clone();
             t1.a=20;t2.a=30;
             t1.str.append("def");t2.str.append("ghi"); 
             System.out.println("t1.a = " + t1.a + " t2.a = " + t2.a);
             System.out.println("t1.str = " + t1.str + " t2.str = " + t2.str);

      }

      @Override
      protected Object clone() throws CloneNotSupoortedException{
             Test t = new Test();
              t.str = new StringBuffer();
              return t;
      }

}

Output:
t1.a = 20 t2.a = 30
t1.str = abcdef t2.str = ghi

Apr 23, 2011

REST Web Service Using CXF - Beginner's Tutorial

REST Web Service Using CXF - Beginner's Tutorial

Here we will demonstrate the creation of a sample REST web service which listens to HTTP GET requests.

You can study the code to get more insight and to expand the functionality.

The packaged war can be downloaded here
Before trying the war deployment, copy all cxf jars from resttest/WEB-INF/lib folder to CATALINA_HOME/lib folder.
  

1) Download CXF, Tomcat, JDK
2) Set CATALINA_HOME to tomcat, JAVA_HOME to Jdk and CXF_HOME to cxf.
3) Add the bin of JAVA_HOME, CATALINA_HOME and CXF_HOME to PATH variable
4) Create a blank project named resttest under webapps folder.
5) Create WEB-INF folder under the resttest folder.
6) Create the package/folder com.example.rest under the WEB-INF folder.
7) Copy the cxf jar fildes from CXF_HOME/lib to CATALINA_HOME/lib
8) Create the following classes:

Order.java
package com.example.rest;

import javax.xml.bind.annotation.XmlRootElement;


@XmlRootElement(name = "Order")
public class Order {

    private int orderId;
    private String itemName;
    private int quantity;
    private String customerName;
    private String shippingAddress;

    public int getOrderId() {
        return orderId;
    }
    public void setOrderId(int orderId) {
        this.orderId = orderId;
    }
    public String getItemName() {
        return itemName;
    }
    public void setItemName(String itemName) {
        this.itemName = itemName;
    }
    public int getQuantity() {
        return quantity;
    }
    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }
    public String getCustomerName() {
        return customerName;
    }
    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }
    public String getShippingAddress() {
        return shippingAddress;
    }
    public void setShippingAddress(String shippingAddress) {
        this.shippingAddress = shippingAddress;
    }

}

OrderList.java

package com.example.rest;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "OrderList")
public class OrderList {

    @XmlElement(name = "order", required = true)
    List <Order> orders;

    public List<Order> getOrder() {
        if (orders == null) {
            orders = new ArrayList<Order>();
        }
        return this.orders;
    }
}

OrderInfo.java
package com.example.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;



@Path("/Order/")
public interface OrderInfo {

@GET
@Produces ("application/xml")
@Path("{orderId}")
public Order getOrder(@PathParam ("orderId") int officeId);

@GET
@Produces ("application/xml")
@Path ("All")
public OrderList getAllOrders();

}

OrderInfoImpl.java
package com.example.rest;

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

public class OrderInfoImpl implements OrderInfo {

    List <Order> list = new ArrayList<Order>();

    OrderInfoImpl(){
        Order order = new Order();
        order.setOrderId(1);
        order.setItemName("Soap");
        order.setQuantity(120);
        order.setCustomerName("Sandeep");
        order.setShippingAddress("Gurgaon");
        list.add(0, order);

        order.setOrderId(2);
        order.setItemName("Shampoo");
        order.setQuantity(50);
        order.setCustomerName("Sandeep");
        order.setShippingAddress("Gurgaon");
        list.add(1, order);
    }

    @Override
    public Order getOrder(int orderId) {
        System.out.println("Inside the GetOrder...");
        if (list.get(0).getOrderId() == orderId) {
            return list.get(0);
        } else if (list.get(1).getOrderId() == orderId) {
            return list.get(1);
        } else {
            return null;
        }
    }

    @Override
    public OrderList getAllOrders() {
        OrderList details = new OrderList();
        for(Order order : list) {
            details.getOrder().add(order);
        }
        return details;
    }
}


cxf.xml
<beans xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="
 http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/util
 http://www.springframework.org/schema/util/spring-util-2.0.xsd
 http://cxf.apache.org/jaxrs
 http://cxf.apache.org/schemas/jaxrs.xsd">

  <import resource="classpath:META-INF/cxf/cxf.xml">
  <import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml">
  <import resource="classpath:META-INF/cxf/cxf-servlet.xml">
  <jaxrs:server address="/" id="connectionService">
   <jaxrs:servicebeans>
              <ref bean="order">
   </ref></jaxrs:servicebeans>
   <jaxrs:extensionmappings>
    <entry key="xml" value="application/xml">
   </entry></jaxrs:extensionmappings>
  </jaxrs:server>
 <bean class="com.javatch.rest.OrderImpl" id="order">
</bean></import></import></import></beans>


web.xml
<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

 <web-app>
  <display-name>RestWithCXF</display-name>

  <context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:com/javatch/rest/cxf.xml</param-value>
  </context-param>
  <listener>

   <listener-class>
    org.springframework.web.context.ContextLoaderListener
   </listener-class>
  </listener>
  <servlet>
   <servlet-name>CXFServlet</servlet-name>

   <servlet-class>
    org.apache.cxf.transport.servlet.CXFServlet
   </servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>CXFServlet</servlet-name>

   <url-pattern>/services/*</url-pattern>
  </servlet-mapping>
 </web-app>



9) Copy web.xml and cxf.xml into WEB-INF folder
10) Copy the compiled classes into WEB-INF/classes folder
11) Start the Tomcat server
12) Browse to the location http://<ipaddress>:<port>/resttest/services/Order/All
or
location http://<ipaddress>:<port>/resttest/services/Order/

Apr 20, 2011

Reasons for Slow Database Performance

Reasons for Slow Database Performance

Usually there are scenarios where the application does not perform as expected. A simple web page which fetches data from database and displays optimizes it for mobiles should be fast and turnaround times should be less than 30 seconds on a good network connection.

But still there are cases where these kinds of applications suffer the most performance issues. This is because the database in these cases is not designed by giving proper attention to the application requirements.

You can change one application design even after delivery but changing the database design once a number of application have been integrated with it is like explosion.

Here I am giving some points which should be kept in mind while designing application and database. Only basic idea is being provided. For details one can search each topic on the web as each point expands well to multiple articles.

1) Bind Variables: When a SQL query is sent to the database engine for processing and sending the result, it is compiled by the database compiler to get the tokens of the query. This involves parsing, optimizing and identifying the query. After a number of steps, the SQL query is passed to the database engine for processing. In a small application with a user base of less than 500, it is usually the same query which is executed more often than others. The use of bind variables helps in storing the compiled query once and executing it with different data at different times. For using bind variables, one needs to use PreparedStatement objects in Java.

2) Query is not well formed: Usually the same SQL query can be written in multiple ways. There are ways by which a query can be optimized to give the best performance. The corresponding SQL construct should be chosen depending upon requirement. I have scenarios where people have used WHERE clause instead of GROUP BY and are complaining of poor response times. Similarly Sub queries and Joins complement each other.

3) Database structure is not well defined/normalized: This is probably known to everybody that the database tables should be properly normalized as this is part of every DBMS course at graduation level. If the tables are not properly designed and normalized, anomalies set in.

4) Proper caching is not in place: Many applications make use of temporary caches on the application server to store the reference data or frequently accessed data as memory is less of an issue than the time with new generation servers.

5) Number of rows in the table too large: If the table itself has too much of data then the queries will take time to execute. Partitioning a table into multiple tables is recommended in these situations. For example: If a table has employee records of 1000000 employees then it could be split into 5 small tables each having 200000 rows. The advantage is we know beforehand in which smaller table to look for a particular employee code as the division of large table can be done on the employee id column.

6) Connections are not being pooled: If connections are not pooled then the each time a new connection is requested for a request to database. Maintaining a connection pool is much better than creating and destroying the connection for executing every SQL query. Of course, there are frameworks like Hibernate which take care of creating the connection pools and also allow the customization of these pools

7) Connections not closed/returned to pool in case of exceptions: When an exception occurs while performing database operations, it ought to be caught. Usually catching the exception is not the issue because SQLException is a checked exception but closing the connection is something that most of the times is left out. If the connection is not released, the same connection cannot be used for any other purpose till the connection is timed out.

8) Stored procedures for complex computations on database: Stored procedures are a good way to perform database intensive operations. This is because they are already compiled and there is less network trips for getting the same results as compared to SQL queries.

15 Interview Questions for JEE Web Application Developer

15 Interview Questions for JEE Web Developer

Here are interview questions targeted more towards a web application developer using web technologies like Java, Struts, Spring, Ajax, HTML, JavaScript etc.

The answers are very brief and are intended to provide the direction towards which one should format his answer. Be more detailed and clear with your answers. All the best.


1) How do you differentiate between Core Java and Enterprise Java?
Expected Ans: Core Java is something that provides the API's like regular expression, String handling, collections. But enterprise java involves writing scalable, secure and per-formant applications which can have large user base.

2) What do you generally do after you have resolved a problem?
Expected Ans: Perform the Root Cause Analysis and make sure the changes done have not effected any other module.

3) What is JSON? Can you represent JSON as Java Object?
Expected Ans: JSON stands for Javascript object notation and is used to initialize Javascript objects. Yes it can be used as Java object also. Provide more info here

4) What kind of HTTP request does the <a href="url">text</a> generate?
Expected Ans: It will generate HTTP GET request

5) What are the common browser issues you will keep in mind while creating a web application?
Expected Ans: 1) User pressing back/refresh button
                            2) Browser crashing
                            3) Session issues
                            4) Compatibility across web browsers

6) What steps will you take for ensuring the proper security of an web application?
Expected Ans: Stuff like Encryption, Authentication and Authorization

7) The Server and Database are working fine at your end but not on customer machine. What will you do?
Expected Ans: 1) Check if the customer has not done any customizations
                             2) Provide a test build same as running at my end (ask customer to take a backup of their  app)
                             3) Check out how the customer is using the application


8) A web application is running but pages are loading slow. How will you figure out what the problem is?
Expected Ans: Look for threading, database, caching issues.

9) What is the difference between frameworks like Jquery/DOJO and AJAX?
Expected Ans: Jquery and DOJO are java script frameworks for writing rich web applications but AJAX is a server communication mechanism which can issue requests without page reload.

10) What are the reasons for a page not found error and how will you sort it out?
Expected Ans: 1) The URL being sent is wrong
                             2) The web.xml mapping is wrong 
                             3) The web server is down 
                             4) The application has not been deployed

11) How will you know whether a Java file is a servlet or not?
Expected Ans: It will extend from HttpServlet class

12) When will you use Servlet and JSP or MVC framework?
Expected Ans: While framework provides a number of components and allows one to concentrate more on the business logic but Servlets and JSP are used for controller and view layer respectively.
13) What are the common issues you have faced in web applications and how did you resolve them?
Expected Ans: 1) Server not starting up. Proper heap size not set
                             2) Migrating from JBoss to Weblogic. Wrote a number of XML configurations
                             Any other generic problems faced during development/support


14) How do you keep yourself updated about the latest web technologies?
Expected Ans: Whatever websites/blogs/forums/authors you follow.

15) What was the last technical book you read?
Expected Ans: Whatever you have read

Apr 19, 2011

How to Send HTTP POST Request in Java

How do I send a POST request using Java?

A POST request can be used for multiple purposes on the web. It can be used for performing the Create or Update operations for various resources. The most common usage of a POST request is in the form of a FORM on an HTML page. 

 

The HTTP protocol doesn’t say anything about the best way to use the POST request but with the web the HTML has become the standard for issuing POST request.
One can also send POST requests from javascript (AJAX), .Net, PHP or Java based programs. Recently I had written a program to issue a POST request in Java. 

If you have server listening for requests then this program code can be handy. In my case, it was a REST web service which was listening for POST requests. One can also issue these HTTP requests for servlets too.
The code follows:

package test;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class Test {
 public static void main(String[] args) throws IOException {
  URL url = new URL("http://localhost:8080/resttest/services/Order/3");
  HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
  httpCon.setDoOutput(true);
  httpCon.setRequestMethod("POST");
  OutputStreamWriter out = new OutputStreamWriter(
      httpCon.getOutputStream());
  System.out.println(httpCon.getResponseCode());
  System.out.println(httpCon.getResponseMessage());
  out.close();
 }
}

Please replace the URL with the actual URL where the server application is listening for POST requests.

One can also use the same code for issuing the other HTTP requests which are GET,PUT and DELETE. To achieve that, change the line:

httpCon.setRequestMethod("POST");
to
httpCon.setRequestMethod("GET");
httpCon.setRequestMethod("PUT");
httpCon.setRequestMethod("DELETE");

Apr 18, 2011

Database SQL Exercises

 Database SQL Exercises

Every developer should have basic knowledge of database and here are some of the exercises that I recently wrote for beginners. 

One can use them to have a hands on experience of the SQL language.
Solutions will be posted later. 

If someone can help me with posting/sending the solutions then it will be great.

1) Create a user with and grant the CONNECT, SESSION and CREATE privileges to him/her.

2) Login using the newly created user and create a table SALARY_STRUCTURE with columns as “EmpId, Basic, LTA, Medical, Special, Food_Coupons”.
          a. The emp id cannot be floating number and should be unique
          b. All salary components can be floating point numbers
          c. LTA Not greater than Rs1000
          d. Medical Not greater than Rs1250
          e. Food_Coupons Not greater than Rs1000

3) Insert random data for 20 employees into the table.

4) Write a SQL query to fetch the total Salary of all the employees.

5) Write a SQL query to list the employee id’s of those employees which have Medical > 500 and Food_Coupons < 300

6) Write a SQL query which displays the HRA component of the salary of each employee. HRA is calculated as 12% of Basic.

7) Write a SQL query to fetch the employee details whose total of all the components is greatest.

8) Write a SQL query which lists only the number of employees (without details) who have Basic greater than sum of LTA and Food_Coupons

9) Alter the table to remove the Special component and add a new component Variable which cannot be greater than Rs10000.

10) Write a query to display the All rows and columns of the table but the columns should have alias as the first character of the column name like B,L,M,V,F

11) Write a SQL query to display all the users which have average of all the salary components equal to any of the salary component. 6,11,20,8,7,14 has average of 11 and is one of the component.

12) Create another t able as EMPLOYEE_DETAILS with columns as “EmpId, Name, Age, Address, PAN No.”
        a. The emp id cannot be floating number and should be unique and should be       consistent  with SALARY_STRUCTURE table (Foreign Key constraint)
         b. Age must be numeric
         c. PAN No can be alpha numeric

13) Add the details of the employees. How will you make sure that there is no employee which has a salary record but no record in EMPLOYEE_DETAILS table?

14) Modify the query created in step 7 to also display the corresponding details from the EMPLOYEE_DETAILS table.

15) Create a SAVEPOINT at this stage

16) DELETE the rows of 5 employees from the EMPLOYEE_DETAILS table who have the lowest salary (using the cascade option). How is DELETE different from TRUNC.

17) DROP the table SALARY_STRUCTURE. You will need to delete the foreign key constraint before doing this.

18) DROP the user from database. You may need ADMIN access for this.

19) Now rollback to the SAVEPOINT created earlier.

20) Commit the changes made in the database so far.

Apr 15, 2011

Specifying VM with Eclipse

Eclipse Closing After Showing Splash Screen

Today we had an issue with the Eclipse IDE showing the splash screen and closing prematurely. A look at a fresh eclipse.ini and the one in the current didn't give any differences. 

The log file created in the .metadata folder of the workspace also didn't point to the exact problem.

Here are the things we tried:
1) Increase heap size in eclipse.ini
2) Removed the plugins specified in the eclipse.ini file
3) Tried a fresh Eclipse

Running eclipse.exe from command line didn't show any error messages. Then we tried eclipsec.exe present in the Eclipse_Home directory and it told that VM could not be located. The exact error message was:

NoClassDefFoundError: Java/Lang/Object

We tried to run eclipse using command line arguments like:
C:/>eclipse.exe -vm /javaw.exe
This resolved the issue and eclipse started fine.

Then we added -vm /javaw.exe to eclipse.ini bout eclipse couldn't start by double clicking eclipse.exe. Then after trying a few things we ended up with:
-vm
/javaw.exe

and it worked with the newline character.

The above information could be helpful to people who get into this situation in future.


Apr 14, 2011

Void Class Java

Why does Void class exist in JDK

I always try to bring some thing new and useful on this blog. This time we will understand the Void.class (which in itself looks something tricky) present in rt.jar.

One can consider the java.lang.Void class as a wrapper for the keyword void.
Some developers draw the analogy with the primitive data types int, long, short and byte etc. which have the wrapper classes as Integer, Long, Short and Byte receptively. But it should be kept in mind that unlike those wrappers Void class doesn't store a value of type void in itself and hence is not a wrapper in true essence.

Purpose:

The Void class according to javadoc exists because of the fact that some time we may need to represent the void keyword as an object. But at the same point we cannot create an instance of the Void class using the new operator.
This is because the constructor in Void has been declared as private. 
Moreover the Void class is a final class which means that there is no way we can inherit this class.

So the only purpose that remains for the existence of the Void class is reflection, where we can get the return type of a method as void. The following piece of code will demonstrate this purpose:



public class Test {
 public static void main(String[] args) throws SecurityException, NoSuchMethodException {
  Class c1 = Test1.class.getMethod("Testt",null).getReturnType();
  System.out.println(c1 == Void.TYPE);
  System.out.println(c1 == Void.class);
 } 
}

class Test1{
 public void Testt(){}
}


One can also use Void class in Generics to specify that you don't care about the specific type of object being used. For example:

List<void> list1;

Apr 5, 2011

Learning from CloneNotSupportedException

Learning from CloneNotSupportedException

CloneNotSupportedException can be taken as an example of custom exception. We can see the source code of this exception class to see how we can create more custom exceptions:

/*
* %W% %E%
*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/

package java.lang;

/**
* Thrown to indicate that the clone method in class 
* Object has been called to clone an object, but that 
* the object's class does not implement the Cloneable 
* interface. 
* 
* Applications that override the clone method can also 
* throw this exception to indicate that an object could not or 
* should not be cloned.
*
* @author  unascribed
* @version %I%, %G%
* @see     java.lang.Cloneable
* @see     java.lang.Object#clone()
* @since   JDK1.0
*/

public
class CloneNotSupportedException extends Exception {
/**
* Constructs a CloneNotSupportedException with no 
* detail message. 
*/
public CloneNotSupportedException() {
super();
}

/**
* Constructs a CloneNotSupportedException with the 
* specified detail message. 
*
* @param   s   the detail message.
*/
public CloneNotSupportedException(String s) {
super(s);
}
}

There we can see that the CloneNotSupportedException extends Exception class which makes this class as a checked exception. Now the question comes as to how to use this exception.

For usage, we go to the clone method of the Object class and we see that the javadoc of this method states that the CloneNotSupportedException is thrown if the Cloneable interface is not implemented by the class on which clone method is invoked.

Similarly, if we want to create our custom exception for scenarios not captured by the exceptions present in the Java API, we need to extend the Exception class or any of its subclass.


Apr 1, 2011

Understanding Front Controller Design Pattern

Understanding Front Controller Design Pattern
 

The front controller design pattern means that all requests that come for a resource in an application will be handled by a single handler and then dispatched to the appropriate handler for that type of request. The front controller may use other helpers to achieve the dispatching mechanism.

While reading the brief overview you may have thought about ActionServlet in Struts 1 or Dispatchers in Struts 2. Yes both of them are implementations of Front controller design pattern. But most of the developers that I have interacted to (specially the beginners) end their thought process of Front Controller at Struts only.

The Front Controller design pattern is applicable and useful for all kind of applications be it web or desktop applications and is not limited to any single programming language or framework. Before the rollout of MVC frameworks in the market, the design pattern was still in use.

The only downside was that not all application could make use of it because of the effort involved. Only the applications which had custom framework in place were using the design pattern.

So for example in case of a Java based web application, which is not using any MVC framework, all the requests would be mapped to a single servlet in web.xml file. This we know can be done by using the servlet mapping (same as we do for ActionServlet in case of Struts 1).


    
         FrontServlet
         com.example.test.FrontServlet
    
    
        FrontServlet
        /*
    

Once the request reached the FrontServlet, it uses some configuration files to decide the appropriate dispatcher for the request and thus forwards the request using forward mechanism.