Tuesday, October 2, 2012

Singleton object using Enum type

Since Java 1.5, there is a new approach to implement Singletons. Simply make it an enum type :
public enum MySingleton {

  INSTANCE;

  //Singleton method
  public void someMethod( ) {...}
}
Accessing the enum singleton :
MySingleton.INSTANCE.someMethod( );

New in spring 2.5 and Dependencies injection with Spring annotations (@Repository, @Service, @Autowired)

Click on below link to know what is new in spring 2.5

http://www.infoq.com/articles/spring-2.5-part-1
 Click below link to find simple example code with old and new bean configuration Dependencies injection with Spring annotations (@Repository, @Service, @Autowired). 
http://onjavahell.blogspot.in/2009/04/dependencies-injection-with-spring.html

Wednesday, July 18, 2012

How to test Restlet webservice using JUnit without deploying webservice in webserver

How to test Restlet web service using JUnit without deploying web service in web server


1. create a class to load all bean xml files extending Application

public class WebServiceServer extends Application {

    /**
     * Creates a root Restlet that will receive all incoming calls.
     */
    @Override
    public synchronized Restlet createInboundRoot() {
        // Create a router Restlet that routes each call to a
        // new instance of HelloWorldResource.

        File contextDir = new File(System.getProperty("user.dir"));
        if (!contextDir.getName().equals("context")) {
            contextDir = new File(contextDir, "context");
        }

        if (!contextDir.isDirectory()) {
            throw new IllegalStateException("Could not find context directory");
        }
        FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(
                new String[] {contextDir + "\\WEB-INF\\beans\\WebService-servlet.xml" });
        SpringRouter router = context.getBean("root", SpringRouter.class);

        // Defines only one route
        router.attach("/webservice", ActualRestletClass.class);

        return router;
    }
}


2. WebService-servlet.xml file config


       
           
               
               
                   
                       
                   

               

           

       

   


   
     


3. Actual restlet webservice

public class ServiceResource extends ServerResource {
@Override
    protected Representation get(Variant variant) throws ResourceException {


Representation resource = new StringRepresentation(content, mediaType);
    return resource;
    }}

}

4. Now test your restlet

 public class TestWebService {
    public static void main(String[] args) throws Exception {
        // Create a new Component.
        Component component = new Component();
        // Add a new HTTP server listening on port 8182.
        component.getServers().add(Protocol.HTTP, 8182);
    
        // Attach the sample application.
        component.getDefaultHost().attach("/WebService",
                new WebServiceServer());
        // Start the component.
        component.start();
    }
}




Wednesday, July 11, 2012

How to use ENUM in Hibernate

Using ENUM in Hibernate
1. create enum type
public enum LoginStatus {

ACTIVE,
INACTIVE
}

2. add property with Enum type
private LoginStatus status;

public LoginStatus getStatus() {
return status;
}

public void setStatus(LoginStatus status) {
this.status = status;
}

3. if we use the above code this will insert the entries as index of ENUM values (0,1) in DB insteade of ACTIVE,INACTIVE values

if we want to insert as values then we need to create new table with ENUM values.

How to generate hbm POJO and DAO files from table using Eclipse

How to generate hbm POJO and DAO files from table using Eclipse

First we need to install "Hibernate prespectives" if you don't have already

1. go to 'help'  in eclipse
2. install new software and click on add button
3. provide this site in pop-up
for Galileo 3.5 :http://download.jboss.org/jbosstools/updates/JBossTools-3.1.1.GA

for Ganymede 3.4: http://download.jboss.org/jbosstools/updates/JBossTools-3.0.3.GA

for indigo: http://download.jboss.org/jbosstools/updates/stable/indigo/

4. install all software starting with 'Hibernate' name.

5. after installation you should be able to see Hibernate prespectives.


Then create new java project. file --> New --> java project
1. Right on project select New --> others --> Hibernate Configuration file --> next -->
2. Provide all required URL, driver class, uname and password etc..after these steps you should be able to see hibernate.cfg.xml file in your project
3.   a. Then right click on project New --> other --> select "Hibernate Reverse Engineering" then click on "NEXT" --> "NEXT" .

     b. Then right click on project New --> other --> select "Hibernate Console configuration" then click on "NEXT" --> "Finish" 

4. select "console configuration" and click on "Refresh" button it will take some time to your data scheme.
5. Once the schema available then include required tables to  generate hbm, POJO, DAO etc..
6. click on "finish" button
7. got to "Run" and select "Hibernate Code Generation"  then select "Hibernate Code Generation configuration"
8. Right click on "Hibernate Code Generation" and  "new" then fill required info(out put dir) in "Main" and "Exporter" tab
9. Then Click on "apply" and "Run" buttons

You should be able to see .hbm.xml, Pojo, Dao etc.. in out put directory.



You can find related info in below link
http://download.jboss.org/jbosstools/updates/











Cheers,
Shekhar reddy



Tuesday, July 10, 2012

Volatile keyword in Java

Volatile keyword in Java is used as an indicator to Thread that do not cache value of this variable and always read it from main memory.
Example using Singleton:
public class Singleton{
private static volatile Singleton _instance;

public static Singleton getInstance(){

   if(_instance == null){
            synchronized(Singleton.class){
              if(_instance == null)
              _instance = new Singleton();
            }

   }
   return _instance;

}

If you look at the code carefully you will be able to figure out:
1) We are only creating instance one time
2) We are creating instance lazily at the time of first request comes.

If we do not make _instance variable volatile then Thread which is creating instance of Singleton is not able to communicate other thread, that instance has been

created until it comes out of the Singleton block, so if Thread A is creating Singleton instance and just after creation lost the CPU, all other thread will not be

able to see value of _instance as not null and they will believe its still null.

Notes:
1. Volatile keyword in Java is only application to variable and using volatile keyword with class and method is illegal.
2. Volatile keyword in Java guarantees that value of volatile variable will always be read from main memory and not from Thread's local cache.

Monday, June 25, 2012

Future Date Validation in JavaScript

Future Date Validation:            

                       var months = {
                                        Jan : 1,
                                        Feb : 2,
                                        Mar : 3,
                                        Apr : 4,
                                        May : 5,
                                        Jun : 6,
                                        Jul : 7,
                                        Aug : 8,
                                        Sep : 9,
                                        Oct : 10,
                                        Nov : 11,
                                        Dec : 12
                                    };
                                    function futureDateValidation(id) {

                                        var dateStr = '27 Jun 2012';

                                        var dateArr = dateStr.split(' ');// not a perfect solution, but meh

                                        var dateObj = new Date();
                                        var day = parseInt(dateArr[0]);
                                        alert(day);

                                        var month = months[dateArr[1]];
                                        alert(month);

                                        var year = parseInt(dateArr[2]);
                                        alert(year);

                                        if (year < 1970)
                                            year += 100;

                                        dateObj.setFullYear(year, month, day);

                                        if (dateObj > new Date()) {
                                            alert('Too late.');
                                        }
                                    }

Tuesday, June 19, 2012

Basic Log4j info

The rootLogger is the one that resides on the top of the logger hierarchy. Here we set its level to DEBUG and added the console appender (CA) to it. The console

appender can have arbitrary name, here its name is CA.

log4j.rootLogger=DEBUG, CA
log4j.appender.CA=org.apache.log4j.ConsoleAppender
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n


Since the rootLogger level is set to DEBUG all the messages are displayed.

The log4j levels follow the following order.


DEBUG
INFO
WARN
ERROR
FATAL

If you set the rootLogger level to WARN then only the WARN, ERROR and FATAL level log messages will be displayed and the rest will be dropped



How can we write our own arraylist without using collections?

You have to use array of Object to store the element and then provide the functionality of adding,seraching and removing the element.This is the way you can create



your own arrayList without using Collections.



1. Make an array of Object holding some predefined number of objects.

2. Take a double variable indicating loadFactor.

3. if the length of the occupied array elements becomes three fourth(or the value of the loadFactor)

3.1 Create an array of Object with size double of the original array.

3.2 copy content of original array to this new array.

3.3 return the new array and delete old array

Wednesday, June 13, 2012

Database Isolation levels

Isolation levels :


TRANSACTION_SERIALIZABLE: Strongest level of isolation. Places a range lock on the data set, preventing other

users from updating or inserting rows into the data set until the transaction is

complete. Can produce deadlocks.

TRANSACTION_REPEATABLE_READ: Locks are placed on all data that is used in a query, preventing other users from

updating the data, but new phantom records can be inserted into the data set

by another user and are included in later reads in the current transaction.

TRANSACTION_READ_COMMITTED: Can't read uncommitted data by another transaction. Shared locks are held while

the data is being read to avoid dirty reads, but the data can be changed before

the end of the transaction resulting in non-repeatable reads and phantom

records.

TRANSACTION_READ_UNCOMMITTED:

Can read uncommitted data (dirty read) by another transaction, and nonrepeatable

reads and phantom records are possible. Least restrictive of all

isolation levels. No shared locks are issued and no exclusive locks are

honoured.

Saturday, June 2, 2012

Uploadify code to send parameters to server with Uploaded file

JSP code :
























Comment :





Reference :















 
 
Servlet code to get request parameter:
 
 
package com.hp;




import java.io.File;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.List;



import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;



import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileUploadException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;



public class UploadServlet extends HttpServlet {

private static final long serialVersionUID = 1L;



/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

*

*/

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

PrintWriter writer = response.getWriter();

writer.write("call POST with multipart form data");

}



/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

*

*/

@SuppressWarnings("unchecked")

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

boolean exit = false;

if (!ServletFileUpload.isMultipartContent(request)) {

throw new IllegalArgumentException("Request is not multipart, please 'multipart/form-data' enctype for your form.");

}



ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());

PrintWriter writer = response.getWriter();

response.setContentType("text/plain");

String comments=request.getParameter("comment");

try {

List items = uploadHandler.parseRequest(request);

for (FileItem item : items) {

if (!item.isFormField()) {

System.out.println("Name: " + item.getName());

System.out.println("Size: " + item.getSize());

System.out.println("Type: " + item.getContentType());

File file = File.createTempFile(item.getName(), "");

item.write(file);

writer.write("{\"name\":\""+ item.getName() + "\",\"type\":\"" + item.getContentType() + "\",\"size\":\"" + item.getSize() + "\"}");

break; // assume we only get one file at a time

}

else{

if(item.getFieldName().equalsIgnoreCase("comment")){

String comment = item.getString();

System.out.println("comment "+comment);

if(comment == null

comment.trim().isEmpty()){

writer.write("{\"error\":\""+"yes"+"\",\"errorType\":\""+"NullComment"+"\"}");

exit = true;

}



}

else if(item.getFieldName().equalsIgnoreCase("reference")){

String ref = item.getString();

System.out.println("reference "+ref);

if(ref == null

ref.trim().isEmpty()){

writer.write("{\"error\":\""+"yes"+"\",\"errorType\":\""+"NullReference"+"\"}");

exit = true;

}

}



if(exit == true){

break;

}



}

}

} catch (FileUploadException e) {

throw new RuntimeException(e);

} catch (Exception e) {

throw new RuntimeException(e);

} finally {

writer.close();

}



}



}