Wednesday, January 28, 2015

Creating SOAP WSDL Web services/ Installing Apache Server/ Installing Apache Axis2

Install 

 1. Axis 2
A) GoTo http://axis.apache.org/axis2/java/core/download.cgi

      B) Goto Eclipse->windows->preferences->web Services-> Axis2 Preferences-> Give downloaded                   Axis2 location

 2. Apache tomcat 6
          a) GoTo http://tomcat.apache.org/download-60.cgi
                   Click Core - > tar.gz
          b) Goto Eclipse->windows->preferences->server->Run time Environment -> Add New Server
Steps:

1.  New->  dynamic web preject ->
                 Select Torget Runtime " Apache tomcat v6"
                  Dynamic web module version "2.5"
                  Configuration -> Check Mark on Axis 2

2.   After creating preject-> create class

3.  Create WSDL
         a) Right click on class->new-> others-> write "web service" and select

           b) Select Apache Server v6.0 and apache axis2 as shown in image
           c) ClassName.wsdl will be created in WebContents/wsdl
           d) In browser wsdl page should be opened.
     

Wednesday, January 14, 2015

Hibernate Sql Java Eclipse Example


This is simple hibernate program to create table and insert records.

Software used
  1. Eclipse
  2. Mysql

Create simple java project in eclipse "com.vishal.hibernate"

Jar's Used:

1. hibernate jars http://hibernate.org/orm/downloads/
             - download latest hibernate and go-to require folder and used all jars
2. mysql-connector-java 

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://127.0.0.1:3306/test</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
        
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Disable the second-level cache  -->

        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop the existing tables and create new one -->

        <property name="hbm2ddl.auto">create</property>
                                        
                                         <!-- create            -> Everytime it will create new table
                                            create-drop   -> deleting existing and creating new table same as above
                                            update           -> To update
  validate        -> To validate existing DB table and new, Will update 
                                                                       or change anything in DB table          -->
    <!-- Mention here all the model classes along with their package name -->
  <mapping class="com.vishal.hibernate.Student_Info"/>
 </session-factory>
</hibernate-configuration>


Student_Info.java
package com.vishal.hibernate;

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

/*This is the Model Class with Annotations 
 - which you would be using for storing or retrieving or performing any other database information
*/
@Entity                  //Tells that class is an entity which hold the data
@Table(name="Student_Information1")  //to store this table in database with different name
public class Student_Info 
{
@Id                 //To specify the primary key @GeneratedValue-To automatically generate ID
@GeneratedValue
private int rollNo;
private String name;
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Main.java
package com.vishal.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class Main 
{
public static void main(String[] args) 
{
Student_Info student=new Student_Info();
student.setName("Raj");
//student.setRollNo(1);
SessionFactory sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory();
Session session=sessionFactory.openSession();
session.beginTransaction();
session.save(student);
                session.getTransaction().commit();
session.close();
//sessionFactory.close();
}
}

Monday, January 12, 2015

Jersey FrameWork Login Page with java Sql Connection


Used Software
  1. Eclipse
  2. SQL
Require Jars
  1. Jersey Jara
  2. MySql Connection jars  

File Structure

 

Code

web.xml
________________________________________________________________________________
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>com.restapi.demo</display-name>
  <welcome-file-list>
              <welcome-file>
V2_EmpLogin.jsp </welcome-file>
  </welcome-file-list>
  <servlet>
             <servlet-name>Jersey REST Service</servlet-name>
             <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
            <init-param>
                          <param-name>com.sun.jersey.config.property.packages</param-name>
                          <param-value>com.restapi.demo</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
          <servlet-name>Jersey REST Service</servlet-name>
          <url-pattern>/api/*</url-pattern>
  </servlet-mapping>
</web-app>


V2_EmpLogin.jsp
_________________________________________________________________________________

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Get User Details</title>
</head>
<body>
<pre>
<form action="V2_EmpLoginServlet" method="post">

    Name    :<input type = "text" name = "username">
    Password:<input type = "text" name = "password">
   
    <input type = "submit" value="Submit">
</form>
</pre>
</body>
</html>


__________________________________________________________________________________

V2_EmpLoginServlet.java

package com.restapi.demo.database;

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

import javax.servlet.RequestDispatcher;
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 javax.ws.rs.core.Cookie;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.representation.Form;

/**
 * Servlet implementation class V2_EmpDatabaseServlet
 */
@WebServlet("/V2_EmpLoginServlet")
public class V2_EmpLoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public V2_EmpLoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        // TODO Auto-generated method stub
        Client client= Client.create();

        String userName=(String)request.getParameter("username");
        String password=(String)request.getParameter("password");
       
        Form form= new Form();
       
        form.add("username", userName);
        //form.add("password", password);
        Cookie cookie= new Cookie("password", password);
        WebResource webResource=client.resource("http://localhost:8080/com.restapi.demo/api/v2/emplogin");
        ClientResponse clientResponse=webResource.accept("text/html").cookie(cookie).post(ClientResponse.class, form);
       
        int output=clientResponse.getStatus();
        if(output==200)
        {
            System.out.println("true");
            response.sendRedirect("V2_LoginSuccess.jsp");
        }
        else
        {
            RequestDispatcher rd = getServletContext().getRequestDispatcher("/V2_EmpLogin.jsp");
            PrintWriter out= response.getWriter();
            out.println("<font color=red>Either user name or password is wrong.</font>");
            rd.include(request, response);
           
        }
    }

}
_________________________________________________________________________________
V2_Database.java

package com.restapi.demo.database;

import java.sql.*;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/v2")

public class V2_Database
{
    @POST
    @Path("/emplogin")
    @Produces(MediaType.TEXT_HTML)
    public Response returnDatabase(@FormParam("username") String username,@CookieParam("password") String password)
    {
        try
        {
            System.out.println("->"+username);
            System.out.println("->"+password);
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root","root");
            PreparedStatement ps = con.prepareStatement("select username,password from users where username = ? and password = ?");
            ps.setString(1, username);
            ps.setString(2, password);
            ResultSet rs = ps.executeQuery();
            int count=0;
            while(rs.next())
            {
                count++;
            }
           
            if(count==1)
            {
                System.out.println("Succussful");
                return Response.status(200).build();
            }
            else
            {
                System.out.println("wrong id and passs");
                return Response.status(201).build();
            }
        }
        catch (Exception e)
        {
            System.out.println("Exception--->"+e);// TODO: handle exception
        }
        return null;
    }

}
 _____________________________________________________________________________

Testing

Test for Wrong Id and Password

Enter Correct ID and Password