Monday 21 March 2016

Spring+Apache CXF+Hibernate Integration java

 Create a Dynamic Web  project in eclipse . Project structure looks like below

Web.xml
  

  ApacheCXF-Up-Down-Text-File
  
    CXFServlet
    org.apache.cxf.transport.servlet.CXFServlet
    1
  
  
    CXFServlet
    /services/*
  
  
    contextConfigLocation
    WEB-INF/apache-cxf-services.xml,WEB-INF/ApplicationContext.xml
  
  
    org.springframework.web.context.ContextLoaderListener
  
  
    index.html
  

ApplicationContext.xml


 

    
 
   
    
 
   
    
 
 
    
        
    
 
 
    
        
        
              
                 com.helloworld.model.HelloWorldDTO    
            
        
        
            
                org.hibernate.dialect.MySQLDialect
                update
                true
            
        
    
 
    
    
        
        
        
        
    

apache-cxf-services.xml


 
 
    
 
   
    
     
   
    
        
            
         
        
            
        
        
            
        
       
   
  
    


HelloWorldDTO.java

package com.helloworld.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.springframework.cglib.beans.BeanCopier.Generator;

@Entity
@Table(name="helloworld")
public class HelloWorldDTO {
 @Id
 @GeneratedValue
 @Column(name="id")
    private int id;
 
 @Column(name="name")
 private String name;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

}
IHelloWorldService.java

package com.helloworld.service;

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

import com.helloworld.model.HelloWorldDTO;

@Path("/helloservice")
public interface IHelloWorldService {
 
 @GET
 @Path("sayhello/{name}")
 @Produces(MediaType.APPLICATION_JSON)
 public HelloWorldDTO sayHello(@PathParam("name") String name);

}
HelloWorldServiceImpl.java

package com.helloworld.service;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.helloworld.model.HelloWorldDTO;

@Transactional
@Service("helloService")
public class HelloWorldServiceImpl implements IHelloWorldService{
 @Autowired
 private SessionFactory sessionFactory;

 public SessionFactory getSessionFactory() {
  return sessionFactory;
 }

 public void setSessionFactory(SessionFactory sessionFactory) {
  this.sessionFactory = sessionFactory;
 }

 @Override
 public HelloWorldDTO sayHello(String name) {
  HelloWorldDTO hdto=new HelloWorldDTO();
  hdto.setName(name);
  sessionFactory.getCurrentSession().save(hdto);
  
  return hdto;
 }

}

Please enter the below URL in broswer. The Out put json looks like
You can see the records inserted in database as below

Tuesday 10 November 2015

org.hibernate.HibernateException: Javassist Enhancement failed

I was practicing a sample of hibernate to fetch data .I was encountered with an exception

INFO: HHH000327: Error performing load command : org.hibernate.HibernateException: Javassist Enhancement failed: com.practice.hibernate.Customer
Exception in thread "main" org.hibernate.HibernateException: Javassist Enhancement failed: com.practice.hibernate.Customer
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.getProxy(JavassistLazyInitializer.java:142)


Solution :

Please make sure that if you're overloading constructor in a class make a presence of actual empty argument constructor in it

in my case

Customer.java looks like



package com.practice.hibernate;

public class Customer {
 private int cid;
 private String name;
 private String city;
 private long phone;
 private double balance;
 
 public Customer(String name,String city,long phone,double balance) {
  
  
  this.name=name;
  this.city=city;
  this.phone=phone;
  this.balance=balance;
 }
 public int getCid() {
  return cid;
 }
 public void setCid(int cid) {
  this.cid = cid;
 }
 public double getBalance() {
  return balance;
 }
 public void setBalance(double balance) {
  this.balance = balance;
 }
 public long getPhone() {
  return phone;
 }
 public void setPhone(long phone) {
  this.phone = phone;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
}
To avoid the Exception i have modified the class a below
package com.practice.hibernate;

public class Customer {
 private int cid;
 private String name;
 private String city;
 private long phone;
 private double balance;
 public Customer() {
  // TODO Auto-generated constructor stub
 }
 public Customer(String name,String city,long phone,double balance) {
  // TODO Auto-generated constructor stub
  
  this.name=name;
  this.city=city;
  this.phone=phone;
  this.balance=balance;
 }
 public int getCid() {
  return cid;
 }
 public void setCid(int cid) {
  this.cid = cid;
 }
 public double getBalance() {
  return balance;
 }
 public void setBalance(double balance) {
  this.balance = balance;
 }
 public long getPhone() {
  return phone;
 }
 public void setPhone(long phone) {
  this.phone = phone;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
}

Thursday 18 December 2014

JQuery Autocomplete Box in java Dynamic web application using MySQL

          This post is going to demonstrate how to implement auto complete box in a dynamic web project in java .To implement auto complete text box  in this web application i have used Java,Servlets,MySQl database,JSON and last but very important Jquery.At first have a glance at the directory structure in your Dynamic web application of eclipse.

1)Directory Structure.


























2)Download project from this link Download.And import the project into your Eclipse
3)Now lets start with Database here.Create a java class under com.DataSource.mysql package in your project.The code looks like this.
package com.DataSource.mysql;

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

import com.mysql.jdbc.Connection;

public class DataSource {
 private static DataSource ds=null;
 private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
         //Change the database name,username,password as per your database design 
 private static final String DB_URL = "jdbc:mysql://localhost/naveen";
 private static final String USER = "root";
 private static final String PASS = "root";
 private DataSource(){
  
 }
    public static DataSource getInstace(){
     if(ds==null){
      ds=new DataSource();
     }
     return ds;
    }
    public static Connection getConnection(){
     Connection conn = null;
        try{
           Class.forName("com.mysql.jdbc.Driver");
           System.out.println("Connecting to database...");
           conn = (Connection) DriverManager.getConnection(DB_URL,USER,PASS);
        }catch(Exception e){
         try {
    conn.close();
   } catch (SQLException e1) {
    e1.printStackTrace();
   }
         e.printStackTrace();
        }
    return conn;
    }
}
4)Now create a Servlet AutoComplete.java
package com.autocomplete.sample;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;

import com.DataSource.mysql.DataSource;

/**
 * Servlet implementation class AutoComplete
 */

public class AutoComplete extends HttpServlet {
 private static final long serialVersionUID = 1L;

    public AutoComplete() {
        super();

    }
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  ArrayList al=new ArrayList();
  try{
  DataSource ds=DataSource.getInstace();
      Connection conn=ds.getConnection();
      Statement stmt=conn.createStatement();
      String sql="select name from customers";
      ResultSet rs = stmt.executeQuery(sql);
      while(rs.next()){
       al.add(rs.getString("name"));
      }
      rs.close();
      stmt.close();
      conn.close();
  }catch(Exception e){
   e.printStackTrace();
  }
   JSONArray json=new JSONArray(al);
   response.setContentType("application/json");
         response.getWriter().print(json);
 }   
}
5)Now configure your web.xml file as below.

  AutoCompleteBox
  
    home.jsp
  
  
    Auto
    com.autocomplete.sample.AutoComplete
  
  
     Auto
     /Auto
  

6)Now create a home.jsp page under WebContent folder


  
  Autocomplete Example
  
  
  
  


 
7)Drop the dependency jars under WEB-INF/lib folder .Here I have created a tables customers under my schema and retrieving all the names and sending it to jsp as Json object.So you can design your own tables and databases and change the query in the statement in above mentioned class and use it .If you had anny issues in executing this or any exceptions that are interrupting you please let me know here in comment box below.
8)And the output of the application looks like this
Thank you Have a nice day

Monday 21 July 2014

how to run a dynamic web project in eclipse using weblogic

Hello Viewers


This post is regarding how to configure web logic server for dynamic web project in your eclipse I D E .Below Given are the steps to configure Web logic server for dynamic web project..

Steps:
1)In eclipse go to windows->show view->Other and type servers and click on it you should be able to find servers tab in the eclipse show view.


2)Click on new server wizard link .You will find list of servers available for configuration,Check for web-logic

3)If web logic was not foundClick "download additional server adapters" hyperlinkand downloadWeb Logic adapters from Oracle(Oracle cloud tools and oracle web-logic tools).

4) Now your eclipse is ready with web-logic server adapters.

Configuring Web-logic to dynamic web project:
1)Go to start menu go to web logic server configuration wizard.Follow the steps click on Next ->
button and create a domain with some desired name say some DummyDomain give Web-logic credentials and port number in the web-logic wizard

2) Now configure web-logic server .Follow the steps like click on new server wizard in servers tab as shown in Image 3.
select the web-logic adapter that matches your server version.Browse web logic home and web-logic domain that which you had created before




and click finish to finish the server configuration

3) Create a dynamic web project now


4)And create a index.jsp file under the dynamic project and click run as ->Run on server
Web logic starts fine and opens index.jsp as welcome file in browser

Some Issues that may interrupt:
An internal error occurred during: "Publishing to Oracle WebLogic Server
              Could not initialize class oracle.eclipse.tools.weblogic.facets.WlsGarFacet          
If this interrupts your execution Go to Eclipse->Market place-> and search for Oracle Coherence Tools and install it and re run the dynamic web project .This helps in solving the above mentioned issue

Tuesday 24 June 2014

JAX-RS Jersey Hello World beginner example -Java web services

A Simple Hello World example to know the basic jersey -RS web service

Steps:

1)Open eclipse and create a Dynamic web project with some project
name of your  choice


2) Download jersey -RS 2.0 jars from this link https://jersey.java.net/download.html
3) Go to WebContent/WEB-INF/lib folder under your project and drop all jars present under jersey folder into lib directory
4)Add the jars to the build path and add java-json.jar along with other jars to buildpath
5) Now configure web.xml (deployment descriptor) under WEB-INF as follows

  JerseyBeginner
  

    index.jsp

  
  
    HelloWorld
    org.glassfish.jersey.servlet.ServletContainer
    
      jersey.config.server.provider.packages
      com.practice.jersey
    
  
  
    HelloWorld
    /rest/*
  

Now create a package under src folder as com.practice.jersey(As given in <param-value> tags in web.xml
Create a class HelloWorld under package com.practice.jersey
Place code below in HelloWorld.java
   package com.practice.jersey;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.json.JSONException;
import org.json.JSONObject;

@Path("/hello")
public class HelloWorld {
 @GET
 @Produces(MediaType.TEXT_PLAIN)
 public String sayHello(){
  return "hello World";
 }
   
 @Path("/{name}")
 @GET
 @Produces(MediaType.TEXT_XML)
 public String toXmlHello(@PathParam("name") String name){
  return "Hello "+name+"";
 }
 
 @Path("/{name}/json")
 @GET
 @Produces(MediaType.APPLICATION_JSON)

 public Response toJsonHello(@PathParam("name") String name) throws JSONException{
  JSONObject sample=new JSONObject();  
   sample.accumulate("name", "Hello"+name);  
  return Response.status(Response.Status.ACCEPTED).entity(sample.toString()).build();
 }
}

Now run the project on server open the browser and type the Ur L's as below
1)http://localhost:8080/JerseyBeginner/rest/hello
2)http://localhost:8080/JerseyHelloWorld/rest/hello/javasimplestuff
3)http://localhost:8080/JerseyHelloWorld/rest/hello/javasimplestuff/json

output 1:   First URL calls sayHello() in HelloWorld
output2:  Second URL calls toXmlHello() in HelloWorld @Pathparam  takes the value passed from URL @Path indicates the URL pattern to call for that particular rest resouce
           
output3: Third URL calls toJsonHello()  in HelloWorld it takes path param and construct Json and returns the response
               

Wednesday 7 May 2014

Sort Integer array without using sort() method -Java

Hi Viewers


        This post is regarding a small code snippet which helps us to sort an integer array of elements   without using any of the sort() method present in Arrays or Collections in Java API.We used bubble       sort  technique to sort the integer array.This is being asked frequently in written exams of interviewing process.Hope this code snippet helps you 


Code Begins here:


public class SortIntArray {

 public static void main(String[] args) {
  int[] a={12,4,1,7,10,21,21,18,17,15,5,34,30};
  SortIntArray sia=new SortIntArray();
  int[] des=sia.toDescendingOrder(a);
  int[] asc=sia.toAsscendingOrder(a);
  System.out.println(">>>>>>>>>>>descending order>>>");
  for(int i=0;i<des.length;i++){
   System.out.print(des[i]+"\t");
  }
  System.out.println("");
  System.out.println(">>>>>>>asscending order>>>>>>");
  for(int i=0;i<asc.length;i++){
   System.out.print(asc[i]+"\t");
  }
 }
  public int[] toDescendingOrder(int[] a){
   int[] b=toAsscendingOrder(a);
   int c[]=new int[b.length];
   int j=0;
   for(int i=b.length-1;i>=0;i--){
    c[j]=b[i];
    j++;
   }
 return c;
  }
  public int[] toAsscendingOrder(int[] a){
  int swap;
  for(int i=0;i<a.length-1;i++){
   for(int j=0;j<a.length-1-i;j++){
    if(a[j]>a[j+1]){
     swap=a[j];
     a[j]=a[j+1];
     a[j+1]=swap;
    }
   } 
  }
   return a;
  }
}
output: >>>>>>>>>>>descending order>>>
        34 30 21 21 18 17 15 12 10 7 5 4 1 
        >>>>>>>asscending order>>>>>>
        1 4 5 7 10 12 15 17 18 21 21 30 34

Wednesday 9 April 2014

Mongodb Import and Export database -MONGODB


This post is regarding how to import and export mongodb data dump. 
To export the database we need to run  mongodump.exe.
To import the database dump we need to run mongorestore.exe.
Consider and example Customer database need to be exported and imported


WINDOWS:

Export Dump:
step 1: Make sure that mongodb is running in your machine if its not running
go to mongodb\bin folder in your mongodb installation and run mongod.exe file
step 2: Run mongodump.exe file which will export all schema present in db to data folder
inside bin directory of mongodb installation

Step 3: If you want to export a particular schema of your db to a desired location in your machine
then press windows+r type cmd and thenEnter button your command prompt will be opened Go to mongo installation bin directory

Command : mongodump.exe -d customer --out C:\

This will export database customer to C:\ in your machine

    Restore Dump:
command:mongorestore.exe -d customer C:\\customer
This will import database customer to mongodb

UBUNTU :
Export Dump:
step 1: Make sure that mongodb is running in your machine if its not running
run command sudo service mongodb startand the run the below command to
export the dump
Command :mongodump -d customer --out /home

This will export database customer to /home in your machine

Restore Dump:
command:mongorestore -d customer /home/customer
This will import database customer to mongodb




Thanks and regards

javasimplestuff