Wednesday, 10 September 2014

List Interface Examples

package com.ram;

import java.util.Collection;
import java.util.Iterator;

import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Stack;
import java.util.Vector;

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

    public static void main(String[] args) {
       
        List<String> arayList = new ArrayList<String>();
        arayList.add("R");
        arayList.add("A");
        arayList.add("M");
        retrieveValues("List","ArrayList",arayList);
       
        List<String> linkedList = new LinkedList<String>();
        linkedList.add("R");
        linkedList.add("A");
        linkedList.add("M");
        retrieveValues("List","LinkedList",linkedList);
       
        List<String> stack = new Stack<String>();
        stack.add("R");
        stack.add("A");
        stack.add("M");
        retrieveValues("List","Stack",stack);
       
        List<String> vector = new Vector<String>();
        vector.add("R");
        vector.add("A");
        vector.add("M");
        retrieveValues("List","Vector",vector);
       
       }
   
     @SuppressWarnings({ "rawtypes"})
     static void retrieveValues(String var1,String var2,Collection collection) {
         System.out.println(var1+" interface using "+var2+" class");
          Iterator iterator = collection.iterator();
          while (iterator.hasNext()) {
             String string = (String) iterator.next();
             System.out.println(string);
          }
          System.out.println("===========================");
       }
    }

Wednesday, 3 September 2014

SOAP WebService Example Service using spring and apache cxf (Top To Bottom Approach)

=>Procedure
1)Add maven Dependencies for spring and apache cxf
2)Write wsdl and xsd 
3)Generate stubs(Generated java classes,use wsimport command)
4)Develope implementation class
5)Configue implementation class as spring bean in spring configuration file
6)Configure CXFServlet in web.xml file
7)Deploy the project into any web server

1)=>First add maven dependencies to your project

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>SoapBasicExampleTopToBottom</groupId>
    <artifactId>SoapBasicExampleTopToBottom</artifactId>
    <version>1</version>
    <packaging>war</packaging>
    <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>

        <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>
  </project>


2)=> Write wsdl,xsd ,Here service name is DemoService,method name is Addition.

DemoService.wsdl

<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:demoService="http://com.ram/services/demo"
targetNamespace="http://com.ram/services/demo">

    <wsdl:types>
        <xsd:schema>
            <xsd:import namespace="http://com.ram/services/demo" schemaLocation="DemoService.xsd"/>
        </xsd:schema>
    </wsdl:types>

    <wsdl:message name="AdditionInputMessage">
        <wsdl:part name="AdditionInputPart" element="demoService:AdditionRequest"/>
    </wsdl:message>
    <wsdl:message name="AdditionOutputMessage">
        <wsdl:part name="AdditionOutputPart" element="demoService:AdditionResponse"/>
    </wsdl:message>
    <wsdl:message name="AdditionFaultMessage">
        <wsdl:part name="AdditionFaultPart" element="demoService:AdditionFault"/>
    </wsdl:message>
   
    <wsdl:portType name="DemoServicePortType">
        <wsdl:operation name="Addition">
            <wsdl:input name="AdditionInput" message="demoService:AdditionInputMessage"/>
            <wsdl:output name="AdditionOutput" message="demoService:AdditionOutputMessage"/>
            <wsdl:fault name="AdditionFault" message="demoService:AdditionFaultMessage"/>
        </wsdl:operation>
    </wsdl:portType>

    <wsdl:binding name="DemoServiceBinding" type="demoService:DemoServicePortType">
        <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
        <wsdl:operation name="Addition">
            <soap:operation soapAction="Addition"/>
            <wsdl:input name="AdditionInput">
                <soap:body use="literal"/>
            </wsdl:input>
            <wsdl:output name="AdditionOutput">
                <soap:body use="literal"/>
            </wsdl:output>
            <wsdl:fault name="AdditionFault">
                <soap:fault name="AdditionFault" use="literal"/>
            </wsdl:fault>
        </wsdl:operation>
    </wsdl:binding>

    <wsdl:service name="DemoService">
        <wsdl:port name="demoServicePort" binding="demoService:DemoServiceBinding">
            <soap:address location="No Target Adress"/>
        </wsdl:port>
    </wsdl:service>
</wsdl:definitions>


DemoService.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:tns="http://com.ram/services/demo" targetNamespace="http://com.ram/services/demo"
    elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xs:element name="AdditionRequest">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="value1" type="xs:integer"/>
                <xs:element name="value2" type="xs:integer"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    <xs:element name="AdditionResponse">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="result" type="xs:integer"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    <xs:element name="AdditionFault">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="Fault" type="xs:string">
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>


3)=> Generate stubs based on your wsdl

wsimport -keep -s yourProjectsrcLocation yourProjectWsdlUrl

4)=> Provide Implementation 

package com.iton.serviceimpl;

import java.math.BigInteger;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;

import ram.com.services.demo.AdditionFaultMessage;
import ram.com.services.demo.AdditionRequest;
import ram.com.services.demo.AdditionResponse;
import ram.com.services.demo.DemoServicePortType;

/**
 *
 * @author ramakrishna.v
 *
 */
public class ArithmeticServiceImpl implements DemoServicePortType {

    @Override
    @WebResult(name = "AdditionResponse", targetNamespace = "http://com.ram/services/demo", partName = "AdditionOutputPart")
    @WebMethod(operationName = "Addition", action = "Addition")
    public AdditionResponse addition(
            @WebParam(partName = "AdditionInputPart", name = "AdditionRequest", targetNamespace = "http://com.ram/services/demo") AdditionRequest additionInputPart)
            throws AdditionFaultMessage {
       
        BigInteger value1 = additionInputPart.getValue1();
        BigInteger value2 = additionInputPart.getValue2();
        BigInteger result =  value1.add(value2);
        System.out.println(result);
        AdditionResponse obj = new AdditionResponse();
        obj.setResult(result);
       
        return obj;
    }
}


 5)=>Configure this implementation class in spring configuration file

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:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:jaxws="http://cxf.apache.org/jaxws"
    xmlns:wsa="http://cxf.apache.org/ws/addressing"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
      http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://cxf.apache.org/jaxws
    http://cxf.apache.org/schemas/jaxws.xsd">

    <context:annotation-config />
   
    <bean id="demoService" class="com.iton.serviceimpl.ArithmeticServiceImpl"/>
   
    <jaxws:endpoint id="Demo" implementor="#demoService"
        address="/DemoService" xmlns:tns="http://com.ram/services/demo"
        serviceName="tns:DemoService" endpointName="tns:demoServicePort"
        wsdlLocation="wsdl/DemoService.wsdl">
    </jaxws:endpoint> 
</beans>


6)Configure CXFServlet in web.xml file

<web-app>
<display-name>SoapTopToBottomExample</display-name>
  <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>



7)Deploy the project into web server.For example It will display the web service wsdl url as follows.

=>http://localhost:7777/SoapBasicExampleTopToBottom






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: