Thursday, 9 October 2014

SSL+Tomcat 6.0

Required Tools/Softwares:

1. Tomcat 6.0
2. Eclipse
3. JDK 1.7


1. Create Dummy webapplication in eclipse

    Project Name: SSLDemo



2. Go to Java bin directory and use below command to generate keystore.

keytool -genkey -alias sslkey -keyalg RSA -keystore d:\ca\mycer

3. Open server.xml file and enable port:8443 as given below.

keystoreFile: Location of key store file
keystorePass: Password

<Connector SSLEnabled="true" clientAuth="false"
 keystoreFile="D:\ca\mycer" keystorePass="password123" maxThreads="150"
 port="8443" protocol="HTTP/1.1" scheme="https" secure="true"
 sslProtocol="TLS" />

4. Access the application using https protocol with port number:8443

After succeful SSL configuraton below error message should be displayed by browser.


 
After clicking continue we should able to see web page deployed in Tomcat.
 
 
 
 
 
 

Wednesday, 24 September 2014

EJB 3.0 + websphere 8.5

 
EJB:

EJB stands for Enterprise Java Bean. EJB provides an architecure to develop and deploy component based enterprised applications. Bean will run  in EJB container supported by any application server compliant with J2ee 1.3 standard specification.

Advantages of EJB:


1. Componets can be clustered for high availability of the application.
2. Scalability.
3. transaction management.
4. Security.

All life cyce of EJB managed by container and developer has to focus on business logic.

Simple basic application to show how to deploy the EJB application in websphere 8.5.

1. Creat project called MyComponent in eclipse.

POJO bean class to serve simple request. This bean will return the name as a response.
Annotations to define some EJB features.

@Stateless: This bean is stateless. Dont maintain conversation state.
@Local(NameServiceLocal.class). Local view
@Remote(NameServiceRemote.class).Remote View.
@LocalBean

NameService .java
package com.service.com;
import com.service.com.view.NameServiceLocal;
import com.service.com.view.NameServiceRemote;
import javax.ejb.Local;
import javax.ejb.LocalBean;
import javax.ejb.Remote;
import javax.ejb.Stateless;
/**
 * Session Bean implementation class NameService
 */
@Stateless
@Local(NameServiceLocal.class)
@Remote(NameServiceRemote.class)
@LocalBean
public class NameService implements NameServiceRemote, NameServiceLocal
{
    /**
     * Default constructor.
     */
    public NameService()
 {
        // TODO Auto-generated constructor stub
    }
   
public String getName()
{

  return "Prashant Savadi";
 }
}

2.  Create local view for the bean.

package com.service.com.view;
public interface NameServiceLocal
 {
   public String getName();
}
3. Create remote view of the bean

package com.service.com.view;
public interface NameServiceRemote
 {
     public String getName();
}

4. ejb-jar.xml file

<?xml version="1.0" encoding="UTF-8"?><ejb-jar xmlns="http://java.sun.com/xml/ns/javaee" version="3.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd">
  <display-name>MyComponent</display-name>
 </ejb-jar>



5. Export the the project as JAR file and deploy in server as shown below.

 




6. Generating stub class.

Go to server bin directory and run below command to generate stub class.

Stub will be generated and placed into the JAR file. Keep this JAR file in client project classpath and run the client code.



7.Accessing EJB from client code.

Before running client its required to place below jar in class path.

com.ibm.ws.ejb.thinclient_8.5.0

Below is the client code to look up the EJB which is deployed in the server. After running below code EJB should rerurn the name. Here "compremote" is the JNDI name whcih is configured from server admin console and same can be looked up from the client code.

package com.client;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.service.com.view.NameServiceLocal;
import com.service.com.view.NameServiceRemote;
public class Client {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Properties p = new Properties();
  p.put(Context.INITIAL_CONTEXT_FACTORY,"com.ibm.websphere.naming.WsnInitialContextFactory");
  //p.put(Context.URL_PKG_PREFIXES, "jboss.naming:org.jnp.interfaces");
  p.put(Context.PROVIDER_URL, "corbaloc:iiop:localhost:2813");
  //iiop://localhost:2813/
  //p.put(Context.PROVIDER_URL, "iiop://localhost:2809/");
  //String jndi = "ejblocal:enterprise_app_name/ejb_web_project_name.jar/ejb_name#name.of.local.impl.interface";
  NameServiceRemote ejb=null;
  try {
   InitialContext ctx = new InitialContext(p);
    ctx
    .lookup("compremote");
  //java:global/MyComponent/NameService!com.service.com.view.NameServiceRemote
   Object rejb = (Object) ctx
     .lookup("compremote");

   ejb=(NameServiceRemote)javax.rmi.PortableRemoteObject.narrow(rejb,com.service.com.view.NameServiceRemote.class);
//<terminated>com.client.Client at localhost:57599
  } catch (NamingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println(ejb.getName());

 }
}

8. Response

"Prashant Savadi"     :)

 

 

 




Sunday, 7 September 2014

Spring LDAP + Apache DS

Software/tools required:

1. LDAP server : Apache Directory Studio 2.0.0
2. IDE :Eclipse Kepler
3. JDK 1.6
4. Spring LDAP core 2.0.2 release
5. MAVEN 4.0.0


Basics of LDAP:

LDAP stands for Light weight Directory Access protocol for accessing directory servers and LDAP server is mainly used by the most of the organisation to maintain the company information like employee details with proper hierarchy.This is very simple example how basically LDAP can be used.

There are different vendors available in market for LDAP server for example Microsoft Active Directory, Novel ,OpenDS and Apache DS etc.

Apache DS :

Installation & Server configuration:

1. Download Apache directory Studio from link  http://directory.apache.org/studio/
2. Install the server
3. Fallow the link for server configuration: http://directory.apache.org/studio/users- guide/apacheds_configuration/configuration_editor_1.5.0_general.html
4. Now start the server. Server should be up and listening to the port : 10389

Connection Configuration:


Adding/Feeding  Data to the server:

Feed the data using UI or upload the data by upload option. Before uploading prepare the data as given below:
https://directory.apache.org/apacheds/basic-ug/2.1.1-adding-entries.html

File format shall be LDIF. LDIF stands for LDAP Data Interchange format.
Example:

# File prashant_savadi.ldif
dn: ou=people,o=sevenSeas
objectclass: organizationalUnit
objectclass: top
ou: people

dn: cn=Prashant Savadi,ou=people,o=sevenSeas
objectclass: inetOrgPerson
objectclass: organizationalPerson
objectclass: person
objectclass: top
cn: Prashant Savadi
description: A pirate captain and Peter Pan's nemesis
sn: Savadi
mail: gsprashant@xyz.com
userpassword: abcdef

 MAVEN 4.0.0:

Add below maven dependency to the POM.xml file.

<dependency>
 <groupId>org.springframework.ldap</groupId>
 <artifactId>spring-ldap-core</artifactId>
 <version>2.0.2.RELEASE</version>
</dependency>

At a minimum, to use Spring LDAP you need:
  • spring-ldap-core (the Spring LDAP library)
  • spring-core (miscellaneous utility classes used internally by the framework)
  • spring-beans (contains interfaces and classes for manipulating Java beans)
  • spring-data-commons (base infrastructure for repository suppport, etc.)
  • slf4j (a simple logging facade, used internally)
  • spring-context

 Spring LDAP:

Before Spring LDAP API Java Naming and Directory Interfaced (JNDI) was used to interact with LDAP based applications.How Spring JDBC simplified the dabase base access in java similary Spring LDAP made easy interaction with LDAP applications.
Pros:
1. No exception handling.
2. No resource handling (opening/closing resource connection).
3. No plumbing code to even achive simple task.

Spring LDAP is designed to simplify LDAP programming in Java. Some of the features provided by the library are:
  • JdbcTemplate-style template simplifications to LDAP programming(LDAPTemplate).
  • JPA/Hibernate-style annotation-based object/directory mapping.
  • Spring Data repository support, including support for QueryDSL.
  • Utilities to simplify building LDAP queries and distinguished names.
  • Proper LDAP connection pooling.
  • Client-side LDAP compensating transaction support.
Below link shall help you understand the SpringLdap API:

http://docs.spring.io/autorepo/docs/spring-ldap/2.0.2.RELEASE/reference/#introduction








Wednesday, 25 June 2014

DOJO Hello world

DOJO is a javascript framework for developing rich UI based web applications. Dojo built using javascript and html. Best part of dojo is its supports AJAX call and ready made UI components called Widgets.

Dojo comes with below packages:

1. Dojo
2. dijit
3. Dojox
4. Util

DOJO simple application to show how dojo can be used.

1. down load Dojo libray from www.dojotoolkit.org
2. extract the zip and keep in project folder as shown below


3. jsp file

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>

<link rel="stylesheet"
href="../dojo-release-1.0.0/dijit/themes/tundra/tundra.css">
<script type="text/javascript" djConfig="parseOnLoad: true"
src="../dojo-release-1.0.0/dojo/dojo.js"></script>

<script type="text/javascript" src="../dojo-release-1.0.0/dojo/dojo.js">

</script>

<script type="text/javascript">
dojo.require("dijit.form.TextBox");
dojo.require("dijit.form.ComboBox");
dojo.require("dijit.form.CheckBox");
dojo.require("dijit.form.DateTextBox");
</script>
</head>
<body class="tundra">
<p>Enter a date below:</p>
<input dojoType="dijit.form.DateTextBox" />
<p>Enter a Name below:</p>
<input dojoType="dijit.form.TextBox" />
<p>Select a Sate below:</p>


<select dojoType="dijit.form.ComboBox" autocomplete="true"
value="Enter a state">
<option selected="selected">Karnataka</option>
<option>AP</option>
<option>Maharastra</option>
<option>Keral</option>
</select>

<p>Check a Name below:</p>
<input dojoType="dijit.form.CheckBox" />

</body>
</html>


4. Run on server in eclipse

Now we can see the features provided by dojo like combo box, date picker etc.





Monday, 9 June 2014

REST Service


Jars Required:


1.        asm-all-3.3.1.jar
2.        commons-codec.jar
3.        commons-httpclient.jar
4.        commons-logging.jar
5.        jersey-bundle-1.14.jar
6.        json-simple.jar

 

Tools Required:
1.        Eclipse
2.        Any webserver/application server

3.     JDK 1.7

References:

http://rest.elkstein.org/

Restful service:

REST (Representational state Transfer) is an architectural style which is based on WEB standards and the HTTP protocol.

It relies on a
a.        Stateless
b.        client-server
c.        Cacheable communications protocol.
As a programming approach REST is light weight alternative to web service (SOAP) and RPC.

Features:
1.        Data which is retrieved from the server is known as resource.
2.        Resources identified over the network by URI.
3.        Bounded by standard protocol HTTP.
4.        It’s a stateless and simple
5.        Request response represented in JSON/XML/TEXT etc.
 

REST sample:

Server side implementation:

Class: WebServices.java

Using annotation @Path (“/WebServices”) in below code we are just saying this is class needs to looked up for the request http://localhost:8080/Restwebservice/webservice. Annotation @Get used for querying the resource. A method level annotation @Path (“hello”) used to identify the resource and URI for this http://localhost:8080/Restwebservice/webservice/hello. Annotation @Produces("application/json") used for specifying the response type. 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; 
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam; 
@Path("/webservice")
public class WebServices { 
        private static Map<String, Employee> employees = new HashMap<String, Employee>();
        @GET
        @Path("/hello")
        @Produces("application/json")
        public List<Heloo> hello() { 
                Map hellomap = new HashMap();
                Heloo h = new Heloo();
                h.setLname("Savadi");
                h.setName("Prashant");
                hellomap.put("1", h);
                Heloo h1 = new Heloo();
                h1.setLname("Savadi");
                h1.setName("Sushant");
                hellomap.put("2", h1);
                return new ArrayList<Heloo>(hellomap.values());
        }
        @GET
        @Path("/message")
        @Produces("text/plain")
        public String showMsg(@QueryParam("message") String message) {
                return message;
        }
        @GET
        @Path("/employees")
        @Produces("application/xml")
        public List<Employee> listEmployees() {
                return new ArrayList<Employee>(employees.values());
        }
        @GET
        @Path("/employee/{employeeid}")
        @Produces("application/xml")
        public Employee getEmployee(@PathParam("employeeid") String employeeId) {
                return employees.get(employeeId);
        }
        @GET
        @Path("/json/employees/")
        @Produces("application/json")
        public Map listEmployeesJSON() {
                return  employees;
        }
        @GET
        @Path("/json/employee/{employeeid}")
        @Produces("application/json")
        public Employee getEmployeeJSON(@PathParam("employeeid") String employeeId) {
                return employees.get(employeeId);
        } 

}

Class: Heloo.java

This is model class used for returning the data.
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "heloo")
public class Heloo {
        private String name;
        private String lname;
        @XmlElement
        public String getName() {
                return name;
        }
        public void setName(String name) {
                this.name = name;
        }
        @XmlElement
        public String getLname() {
                return lname;
        }    
        public void setLname(String lname) {
                this.lname = lname;
        }
}

WEB.xml file entry for servlet registration:

REST is implemented by jersey API. Need jersey servlet entry in the server wheel.
<servlet>
  <servlet-name>jersey-serlvet</servlet-name>
  <servlet-class>
         com.sun.jersey.spi.container.servlet.ServletContainer
        </servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>jersey-serlvet</servlet-name>
  <url-pattern>/*</url-pattern>
 </servlet-mapping>

 
Client:
 
Using below client we can access the resources from server (cleint/server architecture) using URI :http://localhost:9084/Rest/webservice/hello.

Here response us JSON format and JSON data can be handled by simple-Json API. 

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class RestWebServiceClient { 

       /**

        * @param args

        */

       public static void main(String[] args) {

              RestWebServiceClient restWebServiceClient = new RestWebServiceClient();

              restWebServiceClient.sayHello();

              // restWebServiceClient.getJSONEmployees();

              /*

               * restWebServiceClient.getMessage("Welcome");

               * restWebServiceClient.getXMLEmployees();

               * restWebServiceClient.getXMLEmployee(11111);

               * restWebServiceClient.getJSONEmployees();

               * restWebServiceClient.getJSONEmployee(11111);

               */

       }

       private void sayHello() {

              try {

                     Client client = Client.create();

                     WebResource webResource = client

                                  .resource("http://localhost:9084/Rest/webservice/hello");

                     ClientResponse response = webResource.accept("application/json")

                                  .get(ClientResponse.class);

                     if (response.getStatus() != 200) {

                           throw new RuntimeException("Failed : HTTP error code : "

                                         + response.getStatus());

                     } 

                     String output = response.getEntity(String.class);

                     System.out.println("\n============getResponse============");
                     Object p = new JSONParser().parse(output);

                     JSONObject array = (JSONObject) p;

                     JSONArray jarray = (JSONArray) array.get("heloo");

                     Heloo h=null;

                     List list = new ArrayList();                   

                     Iterator it = jarray.iterator();

                     while (it.hasNext()) {

                           h= new Heloo();
                           JSONObject obj=((JSONObject) it.next());
                           System.out.println(obj.get("name"));
                           System.out.println(obj.get("lname"));
                           h.setName(obj.get("name")+"");
                           h.setLname(obj.get("lname")+"");
                           list.add(h);                   

                          

                     }

                      System.out.println(list.toString());

              } catch (Exception e) {
                     e.printStackTrace();

              }
       }


       private void getMessage(String msg) {

              try {

                     Client client = Client.create();

                     WebResource webResource = client

                                  .resource("http://localhost:8080/Restwebservice/webservice/message/"

                                                + msg);

                     ClientResponse response = webResource.accept("text/plain").get(

                                  ClientResponse.class);

                     if (response.getStatus() != 200) {

                           throw new RuntimeException("Failed : HTTP error code : "

                                         + response.getStatus());

                     }

 

                     String output = response.getEntity(String.class);

                     System.out.println("\n============getCResponse============");

                     System.out.println(output);

 

              } catch (Exception e) {

                     e.printStackTrace();

              }

       }

 

       private void getXMLEmployees() {

              try {

                     Client client = Client.create();

                     WebResource webResource = client

                                  .resource("http://localhost:8080/Restwebservice/webservice/employees");

                     ClientResponse response = webResource.accept("application/xml")

                                  .get(ClientResponse.class);

                     if (response.getStatus() != 200) {

                           throw new RuntimeException("Failed : HTTP error code : "

                                         + response.getStatus());

                     }

 

                     String output = response.getEntity(String.class);

                     System.out.println("\n============getCResponse============");

                     System.out.println(output);

 

              } catch (Exception e) {

                     e.printStackTrace();

              }

       }

 

       private void getXMLEmployee(int empid) {

              try {

                     Client client = Client.create();

                     WebResource webResource = client

                                  .resource("http://localhost:8080/Restwebservice/webservice/employee/"

                                                + empid);

                     ClientResponse response = webResource.accept("application/xml")

                                  .get(ClientResponse.class);

                     if (response.getStatus() != 200) {

                           throw new RuntimeException("Failed : HTTP error code : "

                                         + response.getStatus());

                     }

 

                     String output = response.getEntity(String.class);

                     System.out.println("\n============getCResponse============");

                     System.out.println(output);

 

              } catch (Exception e) {

                     e.printStackTrace();

              }

       }

 

       private void getJSONEmployees() {

              try {

                     Client client = Client.create();

                     WebResource webResource = client

                                  .resource("http://localhost:8080/Restwebservice/webservice/json/employees/");

                     ClientResponse response = webResource.accept("application/json")

                                  .get(ClientResponse.class);

                     if (response.getStatus() != 200) {

                           throw new RuntimeException("Failed : HTTP error code : "

                                         + response.getStatus());

                     }

 

                     String output = response.getEntity(String.class);

                     System.out.println("\n============getCResponse============");

                     System.out.println(output);

 

              } catch (Exception e) {

                     e.printStackTrace();

              }

       }

 

       private void getJSONEmployee(int empid) {

              try {

                     Client client = Client.create();

                     WebResource webResource = client

                                  .resource("http://localhost:8080/Restwebservice/webservice/json/employee/"

                                                + empid);

                     ClientResponse response = webResource.accept("application/json")

                                  .get(ClientResponse.class);

                     if (response.getStatus() != 200) {

                           throw new RuntimeException("Failed : HTTP error code : "

                                         + response.getStatus());

                     }

 

                     String output = response.getEntity(String.class);

                     System.out.println("\n============getCResponse============");

                     System.out.println(output);

 

              } catch (Exception e) {

                     e.printStackTrace();

              }

       }

}