Sunday 15 December 2013

JQuery+Ajax+Json+Maven Example with Input Json data and Output also Json data

Explanation:

When we enter name and salary and click on submit,the data which we have entered is converts to json data and send to servlet ,servlet take the data and display same data as json output.

pom.xml

<dependencies>
        <dependency>
              <groupId>org.json</groupId>
              <artifactId>json</artifactId>
              <version>20090211</version>
 </dependency>      
  </dependencies>

HTML PAGE
two.html
<html>
<head>
       <script src="jquery.js"></script>
       <script>
              $(document).ready(function() {
                   
                           $("#SubmitButton").click(function() {
                       
                          var name = $("#name").val();
                          var salary = $("#salary").val();
                         
                          var jsonData = {"name":name,"sal":salary};
                         
                                  $.ajax({
                               
                                 url:'sc2', //servlet url
                                 type:'GET', //servlet request type
                                 contentType: 'application/json', //For input type
                                 data: jsonData, //input data
                                 dataType: 'json', //For output type
                                 success: function(data) {
                                    $("#main").html("<p>JSON Data From Servlet=><br>Name:"+data.name+",<br>Salary:"+data.salary+"</p>");
                                 },
                                 error: function(e) {
                                    alert(e.status); //error status
                                 }
                              });
                           });
              });
       </script>
</head>
<body>
<div id="main">
Name:::<input type="text" name="name" id="name"/>
Salary:<input type="text" name="salary" id="salary"/>

       <button id="SubmitButton">Submit</button>
</div>
</body>
</html>

Servlet:

package com.info.servlet;

import java.io.IOException;
import java.io.PrintWriter;

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

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

public class ServletExample2 extends HttpServlet {
private static final long serialVersionUID = 1L;
     
 
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String name = request.getParameter("name");
String salary = request.getParameter("sal");

PrintWriter out=response.getWriter();
JSONObject json = new JSONObject();

try {
json.put("name",name);
json.put("salary",salary);
} catch (JSONException e) {
e.printStackTrace();
}

out.print(json);
}
}

web.xml:

<web-app>

<servlet>
       <servlet-name>sc2</servlet-name>
       <servlet-class>com.info.servlet.ServletExample2</servlet-class>
</servlet>
<servlet-mapping>
       <servlet-name>sc2</servlet-name>
       <url-pattern>/sc2</url-pattern>
</servlet-mapping>

</web-app>


Friday 8 November 2013

C3PO Connection Pooling

=>We can use C3PO Connection pooling in standalone applications or web based application to connect with database

=>Here i am using mysql db
=>First download c3po related jars or add dependencies for maven
=>Write the code to create connection pooling

pom.xml for maven dependencies:

<dependencies>

  <dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
            
    <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>

  </dependencies>

Program:

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * 
 * @author ramakrishna.v
 *
 */
public class C3POWithMySQLExample {


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

ComboPooledDataSource cpds = new ComboPooledDataSource();
//loads the mysql jdbc driver
try {
cpds.setDriverClass("com.mysql.jdbc.Driver");
} catch (PropertyVetoException e) {
e.printStackTrace();
}             
cpds.setJdbcUrl("jdbc:mysql://localhost:3306/ramakrishna");
cpds.setUser("root");                                  
cpds.setPassword("root");  

Connection con=cpds.getConnection();
//System.out.println(con);

System.out.println("MinPoolSize:::"+cpds.getMinPoolSize());
System.out.println("MaxPoolSize:::"+cpds.getMaxPoolSize());
System.out.println("InitialSize:::"+cpds.getInitialPoolSize());
System.out.println("=================================================");

cpds.setMinPoolSize(5);
cpds.setMaxPoolSize(25);
cpds.setInitialPoolSize(6);
cpds.setAcquireIncrement(5);

System.out.println("MinPoolSize:::"+cpds.getMinPoolSize());
System.out.println("MaxPoolSize:::"+cpds.getMaxPoolSize());
System.out.println("InitialSize:::"+cpds.getInitialPoolSize());

}

}


Output:

MinPoolSize:::3
MaxPoolSize:::15
InitialSize:::3
=================================================
MinPoolSize:::5
MaxPoolSize:::25
InitialSize:::6


DBCP Connection Pooling

=>We can use DBCPConnection pooling in standalone applications or web based application to connect with database
=>Here i am using mysql db
=>First download dbcp related jars/add dependencies for maven
=>Write the code to create connection pooling

pom.xml for Maven Dependencies

 <dependencies>

  <dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
     
     <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
            
  </dependencies>

Program:

import java.sql.*;
import org.apache.commons.dbcp.BasicDataSource;

/**
 * 
 * @author ramakrishna.v
 *
 */
public class DBCPWithMySQLExample {

public static void main(String[] args) {

BasicDataSource bds = new BasicDataSource();
bds.setDriverClassName("com.mysql.jdbc.Driver");
bds.setUrl("jdbc:mysql://localhost:3306/ramakrishna");
bds.setUsername("root");
bds.setPassword("root");

try {
Connection con = bds.getConnection();

System.out.println("MaxActive:::::::::"+bds.getMaxActive());
System.out.println("MaxIdle:::::::::::"+bds.getMaxIdle());
System.out.println("Initial Size:::::::::::"+bds.getInitialSize());
System.out.println("Present no.of Active::::::::"+bds.getNumActive());
System.out.println("Present Idle:::::::::::"+bds.getNumIdle());


bds.setMaxActive(25);
bds.setMaxIdle(10);
bds.setInitialSize(5);

System.out.println("MaxActive:::::::::"+bds.getMaxActive());
System.out.println("MaxIdle:::::::::::"+bds.getMaxIdle());
System.out.println("Initial Size:::::::::::"+bds.getInitialSize());
System.out.println("Present no.of Active::::::::"+bds.getNumActive());
System.out.println("Present Idle:::::::::::"+bds.getNumIdle());

con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

Output:

MaxActive:::::::::8
MaxIdle:::::::::::8
Initial Size:::::::::::0
Present no.of Active::::::::1
Present Idle:::::::::::0
MaxActive:::::::::25
MaxIdle:::::::::::10
Initial Size:::::::::::5
Present no.of Active::::::::1
Present Idle:::::::::::0

Monday 4 November 2013

Get selected table data using JQuery deligate method

=>Just Use jquery.js fiel,And use this code

=>Here no need to maintain tr id.

=>After double click on any row ,data will be display in text boxes.

<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function() {
$("#mytable").delegate("tr",'click',function() {
$(this).find("td").each(function(i){
var value=$(this).text();
$("#"+i).val(value);
});
});

});
</script>
</head>
<body>
<input type="text" id="0"/>
<input type="text" id="1"/></br></br>
<table id="mytable" border="2">
<tr>
<td>1000</td><td>2000</td>
</tr>
<tr>
<td>3000</td><td>4000</td>
</tr>
<tr>
<td>5000</td><td>6000</td>
</tr>
<tr>
<td>7000</td><td>8000</td>
</tr>
</table>
</body>
</html>


Get Selected table data using JQuery

=>Just use jquery.js file,And use this code

=>After double click on any row,Data will be display in text boxes.

<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function() {

$("#mytable tr").dblclick(function() {
var trid=$(this).attr("id");

$("#"+trid+" td").each(function(i) {
var value=$(this).text();
$("#"+i).val(value);
});
});
});
</script>
</head>
<body>
<input type="text" id="0"/>
<input type="text" id="1"/></br></br>
<table id="mytable" border="2">
<tr id="tr1">
<td>1000</td><td>2000</td>
</tr>
<tr id="tr2">
<td>3000</td><td>4000</td>
</tr>
<tr id="tr3">
<td>5000</td><td>6000</td>
</tr>
<tr id="tr4">
<td>7000</td><td>8000</td>
</tr>
</table>
</body>
</html>

Output:



Friday 1 November 2013

Jackrabbit Repository jar,war download

Jackrabbit standalone-2.6.4.jar download.Click below link

http://jackrabbit.apache.org/downloads.html#v2.6

=>Use this command to create Jackrabbit repository and start that 

=>java -jar jackrabbit-standalone-2.6.4.jar -port 2629

=>We can use any port(Without conflicts to other services)

=>When we run the above command jackrabbit repository file will create,so that we can store files,and we can download files from jackrabbit.

=>To see how the files are storing into jackrabbit we can use jackrabbit explorer war file

Jackrabbit war download.Click below link

https://code.google.com/p/jackrabbitexplorer/downloads/list

=>After download this war,just deploy into any server(Tomcat or other) .

=>Access the jackrabbit explorer as follows

=>http://localhost:8080/jackrabbitexplorer/



=>Default user name and passwords are admin,admin

=>Just change port number of jackrabbit,what we assigned (2629) and login,It will open jackrabbit explorer


SOAP WebService Using Apache CXF Example with Service and Client (Bottom To Top Approach)

=>First Develope One interface.Develope your own methods.

=>These methods i want to expose as a FirstService

=>Just Create Normal Java interface with @WebService Annotation only

package com.service;

import javax.jws.WebService;

@WebService
public interface FirstService {

public String methodOne();

public int methodTwo();

}

=>Provide the implementation for Above Interface

=>Just add extra annotation @WebService(endpointInterface="com.service.FirstService")
     End point means interface name with package only

package com.service.impl;

import javax.jws.WebService;

@WebService(endpointInterface="com.service.FirstService")
public class FirstServiceImpl implements FirstService {

public FirstServiceImpl() {
System.out.println("+++++From FirstServiceImpl+++");
}

@Override
public String methodOne() {
System.out.println("+++From FirstServiceImpl methodOne()+++");
return "k fine";
}

@Override
public int methodTwo() {
System.out.println("+++From FirstServiceImpl methodTwo()+++");
return 100;
}
}


=>Add Maven Dependencies for Spring with Apache CFX

        <repositories>

        <repository>
            <id>sourceforge</id>
            <url>http://oss.sonatype.org/content/groups/sourceforge/</url>
            <releases>
                <enabled>true</enabled> 
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>

<properties>
<cxf.version>2.7.2</cxf.version>
    <org.springframework.version>3.0.5.RELEASE</org.springframework.version>
</properties>
<dependencies>

<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>${cxf.version}</version>
</dependency>
<!-- Jetty is needed if you're are not using the CXFServlet -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>${cxf.version}</version>
</dependency>

<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-ws-addr</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-ws-security</artifactId>
<version>${cxf.version}</version>
</dependency>
                <dependency>
  <groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
 
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
             </dependencies>

=>Web.xml

<web-app>
<context-param>
                 <param-name>contextConfigLocation</param-name>
                <param-value>WEB-INF/ApplicationContext.xml</param-value>
        </context-param>
 <listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<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>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>


=>ApplicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:wsa="http://cxf.apache.org/ws/addressing"
xmlns:cxf="http://cxf.apache.org/core"
xsi:schemaLocation="
http://cxf.apache.org/core
http://cxf.apache.org/schemas/core.xsd
http://cxf.apache.org/transports/http/configuration 
http://cxf.apache.org/schemas/configuration/http-conf.xsd 
http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://cxf.apache.org/jaxws
        http://cxf.apache.org/schemas/jaxws.xsd">
<bean id="firstService" class="com.iton.FirstServiceImpl">
</bean>
<jaxws:endpoint implementorClass="com.iton.FirstServiceImpl" implementor="#firstService"                address="/firstService">
</jaxws:endpoint>
</beans>

=>Deploy the Project into the server(Tomcat or any other)

=>After deployment successfull this file will generate automatically.

=>It is the responsibility of apache cxf to identify webservice annotation and convert our java programs into wsdl file as webservice .





=> All Services exposed by us is displayed in this file,This is the WSDL file

=>WSDL : {http://iton.com/}FirstServiceImplService ,click on this link,WSDL of this service will display as follows




=>By using this url only we can generate java files(By using these java files only client can communicate with this service)

=>Copy the url(http://localhost:8090/SoapServiceExample/firstService?wsdl) and go to command prompt
     and use this command to generate java programs(or Stubs).

=>wsimport -keep -s D:\eclipseWorkspace\SOAP\SoapServiceClientExample\src      http://localhost:8090/SoapServiceExample/firstService?wsdl

=>D:\eclipseWorkspace\SOAP\SoapServiceClientExample\src. I am just telling where to copy those generate java files for client program,I am using eclipse so that i put these java files directly into my eclipse work space

=>SoapServiceClientExample is my client project for to access the services.

=>Client Program

package com.iton.client;

import com.service.FirstService;
import com.service.impl.FirstServiceImplService;


public class FirstServiceClient {

public static void main(String args[]) {
//Getting FirstServiceImplService class,In stubs automatically class extension adding with     Service
FirstServiceImplService firstServiceImplService=new FirstServiceImplService();
//From this Service class we are getting our Interface by using getFirstServiceImplPort(),in stubs our class preceeds with get and extension as Port is created automatically
FirstService firstService=firstServiceImplService.getFirstServiceImplPort();
//From interface calling methods
System.out.println("From FirstSrvice methodOne::"+firstService.methodOne());
System.out.println("From FirstSrvice methodTwo::"+firstService.methodTwo());
}
}

Output:

From FirstSrvice methodOne::k fine
From FirstSrvice methodTwo::100





Saturday 19 October 2013

Tomcat connection pooling

->This Tomcat connection pool Depends on Tomcat web server

->First configure database details and connection pool details in the context.xml file in META-INF folder of our web project

->Use ojdbc14.jar

Context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/Client" docBase="ClientModule" crossContext="true" reloadable="false" debug="1">
    <Resource name="jdbcResource" auth="Container" type="javax.sql.DataSource"
       username="dbuser"
       password="dbpassword"
        driverClassName="oracle.jdbc.driver.OracleDriver"
        url="jdbc:oracle:thin:@192.168.0.178:1521:orcl"
        initialSize="25"
        maxActive="25"
        maxIdle="25"
        minIdle="10"
        maxWait="5000"
        removeAbandonedTimeout="50"
        removeAbandoned="true"
        testOnBorrow="true">
   </Resource>
</Context>

username:database username

password:database password

driverClassName:We are using oracle database so 
oracle.jdbc.driver.OracleDriver class

url: database url and database name

initialSize:That means at the time of pool creating it will create 25(we can give any number) connections,after that automatically pool creates new connections based on request.
maxActive:That means at the same time 25(we can give any number) connections only in active mode,so at the same time 26th person can’t get new connection from pool.

maxIdle:Idle means not used objects available in the pool,maximum the pool can have 25(we can give any number) idle objects

minIdle:Any time pool will have minimum of 10 idle objects.

maxWait:We are ready to getting new connection from pool,but pool don’t have connections,so we will wait for 5000 milliseconds(5 seconds),After that time also pool don’t have connections to give us then only displaying error like  org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot get a connection, pool error Timeout waiting for idle object.

removeAbandonedTimeout:50(we can give any number)means when the pool give the connection to us,and we didn’t return back the connection to pool,it will wait for 50 seconds for that connection,After 50 seconds this object is eligible for eviction.

romoveAbondoned: true means After removeAbondonedTime(50 seconds) pool forcefully get that object from us(from java program),If our program execution is not completed also pool will close the connection and get the connection.

testOnBorrow:true means at the time of getting connection from pool it will validate that connection.If validation fails,that connection will remove from the pool and create new connection.

testOnReturn:true means at the time of returning the connection to pool ,it will check that connection,
If validation fails,that connection will not return to pool.

minEvictableIdleTimeMillis:(int) The minimum amount of time an object may sit idle in the pool before it is eligible for eviction. The default value is 60000(60 seconds).This property uses pool internally for idle objects.

timeBetweenEvictionRunsMillis:(int) The number of milliseconds to sleep between runs of the idle connection validation/cleaner thread. This value should not be set under 1 second. It dictates how often we check for idle, abandoned connections, and how often we validate idle connections. The default value is 5000 (5 seconds).

->Create Web based Application

ConnectionPoolClass.java

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.sql.DataSource;


public class ConnectionPoolClass {
      
       public static InitialContext initialContext=null;
       public static DataSource datasource=null;
       Connection con=null;
      
        static {
                try{
                    initialContext = new InitialContext();
                    datasource = (DataSource)initialContext.lookup("java:/comp/env/jdbcResource");
                   
                }catch(Exception e)
                {
                e.printStackTrace();
                }
        }
        
        public boolean getConnection() {
               
                     try {
                           con=(Connection)datasource.getConnection();
                           System.out.println("connection is:"+con);
                     } catch (SQLException e) {
                           e.printStackTrace();
                     }
                      
               return true;
        }
        
        public void closeConnection() {
               try {
                     con.close();
              } catch (SQLException e) {
                     e.printStackTrace();
              }
        }
}

MyServlet.java

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {
      
       public void doGet(HttpServletRequest request,HttpServletResponse response) {
              PrintWriter out=null;
              try {
                     out=response.getWriter();
              } catch (IOException e) {
                     e.printStackTrace();
              }
              ConnectionPoolClass cp=new ConnectionPoolClass();
             
              cp.getConnection();
              cp.closeConnection();
      
       }
}


Web.xml
<servlet>
       <servlet-name>xxx</servlet-name>
       <servlet-class>com.iton.MyServlet</servlet-class>
  </servlet>
 
  <servlet-mapping>
       <servlet-name>xxx</servlet-name>
       <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>


->This program only getting the connection from connection pool,If we get the connection remaining code is normal like perfoming CURD operations to create,update,retrieve,delete with database.