Monday, December 3, 2012

how to use Jquery datataable

1. add jquery.dataTables.js and jquery.dataTables.css in your html. keep these files in proper folder.




2. keep below code in your html code.

AJax call with json response


Set Json response in Controller:

PrintWriter writer = response.getWriter();
JSONArray storeList = new JSONArray();
JSONObject store = null;
List list = new ArrayList();
list.add("RS");
list.add("EUR");
list.add("DOLLER");
for (String string : list) {
    store = new JSONObject();
    store.put("storeName", string);
    storeList.put(store);
}
JSONObject json = new JSONObject();
json.put("storeList", storeList);
sb = json.toString();
writer.write(sb);












ajax call:

Way 1:
$.ajax({
        url : currentPath+'/appName/partnerStoreAddress',
        data : 'store='+selectedValue+'&cbn='+cbnValue,
        dataType : 'json',
        success : function(json) {
            createAdressTable(json);
            $.unblockUI();
        },
        error:function(xhr,errorThrown){
              var r = jQuery.parseJSON(xhr.responseText);
              alert("Message: " + r.Message);
              alert("StackTrace: " + r.StackTrace);
              alert("ExceptionType: " + r.ExceptionType);
              alert(xhr.status);
              alert(errorThrown);
        }
    });

Way 2:

function setupAjaxForm(form_id, form_validations){
    var form = '#' + form_id;
   
    // setup jQuery Plugin 'ajaxForm'    
    var options = {
        target : '#refresh',  //if you want to refresh any div only
        dataType:  'json',
        beforeSubmit: function(){
        $.unblockUI();
         $.blockUI({
                message : ''
            })
            //pageRefresh = 'Y';
        },
        timeout:8000,
        success: function(json){
            $.unblockUI();
            $("#refresh").html($(html).find("#refresh"));
            $('#HPContactEmailList_filter').appendTo($('.themeheader'));
                       
            new setupAjaxForm('dummyForm'); 
           
        },
        error:function(xhr,errorThrown){
            $.unblockUI();
            alert('Selected item was not saved');
           
        }
    };
    $(form).ajaxForm(options);
}


$(document).ready( function () {
   
    $('#HPContactEmailList_filter').appendTo($('.themeheader'));
    new setupAjaxForm('dummyForm'); 
    }
);

Tuesday, October 2, 2012

Common mistake with Date



Use ‘dd/MM/yyyy’ instead of ‘dd/mm/yyyy’ when you are working with SimpleDateFormat to format. otherwise 'mm' will be considered as mints.

Can we access private methods in other class?..yes we can using reflection api


Yes...We can access private methods in other class using reflection API

Example code:

MyClass.java with private method
public class MyClass {

private String myPrivateMethod(String name) {
//Do something private
return "Hello "+;
}
}

Test class:  MainTest.java public class MainTest class{

private MyClass underTest;


public static void main(String []args)throws Exception {

MyClass underTest= new MyClass();

Class[] parameterTypes = new Class[1];
parameterTypes[0] = java.lang.String.class;

Method m = underTest.getClass().getDeclaredMethod("myPrivateMethod", parameterTypes);
m.setAccessible(true);

Object[] parameters = new Object[1];
parameters[0] = "Shekhar Reddy!";

String result = (String) m.invoke(underTest, parameters);
System.out.println(result )//Shekhar Reddy!

}


}
outPut: Hello Shekhar Reddy!

JUnit test case using Mock API

Mock API helps to create dummy object and returns back something to program when we are calling any method on that dummy object instead calling actual object.
Ex:
context.checking(new Expectations() {{
      oneOf (accountDAO).selectAccount(with("1234")); 
      will(returnValue(null));
  }});
 
 
Here we are asking Mock api return "null" value when I Call  
selectAccount method with 1234 value on AccountDAO object.

You can find very good example with maven integration in the below link.

http://onjavahell.blogspot.in/2009/05/good-unit-testing-with-jmock.html

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.