Showing posts with label J2EE. Show all posts
Showing posts with label J2EE. Show all posts

First RESTful Webservice

To create RESTful webservice using plain JDK, tomcat and Jersey (JAX-RS sample implementation)

Pre Requisite:
  1. JDK
  2. Tomcat ( any other servlet container)
  3. Jersey - Its sample JAX-RS implementation. It uses servlet controller that handle REST URLS.
Steps :
1. Create eclipse project with following structure
WEB-INF
--classes
--lib
--web.xml

2. Download latest Jersey jars from http://download.java.net/maven/2/com/sun/jersey/jersey-archive/ and extract it under lib folder.

3. Create following java class under src and make sure to set output folder in eclipse to WEB-INF/classes.

package com.rahul.ws;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("helloworld")
public class HelloWorldResource {
    @GET
    @Produces("text/plain")
    public String getMessage() {
        return "This is sample REST service";
    }
}

4. Add entry into web.xml for Jersey controller


    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/web-app_3_0.xsd">
   
        RestfulContainer
        com.sun.jersey.spi.container.servlet.ServletContainer
       
            com.sun.jersey.config.property.packages
            com.rahul.ws
       

        1
   

   
        RestfulContainer
        /resources/*
   


5. Create war file using "%JAVA_HOME%\bin\jar" cvf restful.war WEB-INF

6. Deploy this war under tomcat and access the service using
    http://localhost:9090/restful/resources/helloworld
7. That's it !!


Weblogic: Changing context root and redirection

Sometime you might have to change the context root(CR) of the application deployed on weblogic from CR1 to CR2. This can be easily done by updating the context root in the application.xml file in your ear file.

But then if you might also want to redirect all the old URL references to this new context root. So if somebody access http://yourhost/CR1 it should redirect to http://yourhost/CR2. It’s easy to do in Apache server using mod_rewrite module. But weblogic as such don’t provide this functionality.

 

So here is quick handy way to achieve this:

1.    Create a dummy web module under CR1.

2.    Update application.xml as follows:

   

<module > 

       <web>

         <web-uri>newAppDir</web-uri>

         <context-root>/CR2</context-root>

      </web>

   </module>

    <module> 

       <web>

         <web-uri>oldAppDir</web-uri>

         <context-root>/CR1</context-root>

      </web>

   </module>

     

3.    Configure web.xml for this dummy web application such that all the requests will be handled by a single JSP, redirector.jsp

a.    Set the welcome file as redirector.jsp

b.    Add Following servlet mapping to catch all the URLs and let it handle by redirector.jsp

 

<servlet-name>wlRedirector</servlet-name>

<jsp-file>/redirector.jsp</jsp-file>

</servlet>

<servlet-mapping>

     <servlet-name>wlRedirector</servlet-name>

     <url-pattern>/*</url-pattern>

 </servlet-mapping>

 

4.    In the redirector.jsp add code to change the CR1 to CR2 and sendRedirect to CR2

                                String recvUrl = request.getRequestURI();

          recvUrl = "/CR2" + recvUrl;

         if (request.getQueryString() != null) {

          recvUrl += '?' + request.getQueryString();

         }

URL reconstructedURL = new URL(request.getScheme(),

                               request.getServerName(),

                               request.getServerPort(),

                               recvUrl);

response.sendRedirect (reconstructedURL.toString());

 

 

Rahul Ner

 

Analyzing thread dump for your Java application

Is your J2EE application responding slowly ? Is it getting hanged every now and then ?

The best way to start is take thread dump whenever you think performance is not to up to the mark and then analyze it.

Taking Thread Dump:

On unix system , you just have to first find out PID of your java process. You can use PS –alf | grep –in ‘java’ to find out the same.

Once you have PID, simply execute Following command:

 kill -3 PID

This will inform JVM to take current snapshot. It will be then copy to your standard log file/stdout file.

On windows, you have to execute ctr-break on the command prompt.


Analyzing Thread Dump:

If you don’t have right to tool for this, then it’s very hard to grasp what’s going on. I have used TDA http://www.ohloh.net/p/tda . This one is very nice, simple, easy and free tool. Once you open your log file (containing dump) in this tool, it will show all threads in tree structure, along with details of each thread. Most important of it is the thread state which could be like runnable, wait, wait on monitor, wait on conditions etc. Also it will show sleeping and locking threads separately. This will help you to identify the object on which threads are waiting and thereby identifying bottleneck in the system.

It has one feature to compare multiple thread dumps. It helps in finding out long running threads instantly.

If you have set -XX:+PrintClassHistogram JVM option while starting it, in thread dump it will also provide information of number of instance create for each classes along with the total bytes required for those objects. This should give you a fair idea of what classes and which modules are the one to look first for the optimization.


Rahul Ner

(RNer)

Creating web service from java class using Axis

Axis provides excellent platform for web service creation and deployment. Let's say you have a plain java class that you would like to expose as a web service. You can achieve this in few minutes. I assume here axis.war is already deployed on to your app server.

1. Create your java class with the method that you want to expose. (Its not web service aware.. so you don’t need to implement any interface etc.)

2. Now, register your web service with Axis. Simply add entry following entry to axis.war\WEB-INF\server-config.wsdd.

 <service name="WebServiceDemo" provider="java:RPC">

                       <parameter name="className" value="test.wbservice.Demo"/>

  <parameter name="allowedMethods" value="*"/>

                                           <parameter name="wsdlTargetNamespace" value="http://test.wbservice"/>

                                                                                </service>

 

 Class Name is fully qualified name of the class created in step 1. Now copy demo.class file to axis.war\WEB-INF\lib. If you prefer, You can create jar file containing this class and copy that to lib directory.


3. Restart your app server

4. Now you have deployed web successfully. You can check that using http://appsever_url/axis/services/webserviceDemo

    You can generate WSDL file containing all information of your web service using  http://appsever_url/axis/services/webserviceDemo?wsdl

5. Now You can generate client side stubs and classes required using WSDL2Java tool provided by axis.

   You have to execute this class passing wsdl to it.

java -cp axis.jar;commons-discovery.jar;commons-logging.jar;jaxrpc.jar;saaj.jar;log4j-1.2.8.jar;xml-apis.jar;xerces.jar;wsdl4j.jar org.apache.axis.wsdl.WSDL2Java   http://appsever_url/axis/services/webserviceDemo?wsdl


This will create all required file at the client side.


6.Generate client

        DemoServiceLocator demoLocator  = new DemoServiceLocator ();

       Demo demo = demoLocator .getWebServiceDemo();

        Demo.call_your_method()


Rahul Ner

IE : Security Warning Message

When you browse to a page through HTTPS, sometimes you might get a popup similar to this :

The main reason for this is your page refers to some link which is HTTP and not HTTPS i.e. not using a secured protocol.

To resolve this:
1. Make sure every external link you are using is HTTPS
2. All your internal links should be relative


Change
div#header {
background-image: url(http://www.example.com/images/header.png) no-repeat;
}

To:

div#header {
background-image: url(/images/header.png) no-repeat;
}

3. Make sure all the IFRAME have src attribute set and points to some HTTPS or relative url. If you can't specify any url, add a blank html page in your application and specify the src to point to that page.

i.e. <IFRAME src="/../blank.html"/>

Sun Buys MySQL.

Sun MicroSystems has decided to put around a billion dollars behind the M in LAMP. It plans to recover the money by providing service, infrastructure and customization of this most used free database. It has more than 10 million installations,used mostly by educational institutions, small scales web apps and social networking sites.
Read the full story at the blog of Jonathan Schwartz, CEO of Sun

Java Interview Question

Hi People,


JGuide  contains a nice collections of Java Inteview questions along with the answers. You can also find revision notes for the interview.
A nice thing is some of the live intreview  samples are also available.
Hope this will help for the people who are looking for the Java/J2ee Jobs. 
Java interview, Java  Jobs  in Singapore , Singapore j2ee jobs
 

Enjoy.
RNer.

Service-Oriented Architecture

SOA or Service-oriented architecture is the
new buzzword now a day in the enterprise IT department. What is SOA? In the
very simplistic way it is a web service having heavy top ups. It is gaining
the popularity because it promises to bring down the cost of IT solutions by
reusing the complete software solution rather that just part of it. It goes
one step beyond the Object oriented languages by reusing complete software
and not just libraries.All of the basic object oriented concept such as
encapsulation, abstraction, loose coupling, contract implementation etc. all
holds but in more stringent way. It allows finding the already developed
services, distributing it and using it to develop the custom services that
again can be shared.


The wikipedia definition says "Service Oriented Architecture (SOA) is an
architectural style that guides all aspects of creating and using business
processes, packaged as services, throughout their lifecycle, as well as
defining and provisioning the IT infrastructure that allows different
applications to exchange data and participate in business processes loosely
coupled from the operating systems and programming languages underlying those
applications"



Many vendors are coming with the SOA products, Some of them are



  • Actional Corporation: SOA Management Software

  • Adobe Systems: LiveCycle Enterprise Suite w/Flex, AIR and PDF
    clients

  • AmberPoint: SOA Governance, Management & Security Software

  • Apache: ServiceMix

  • Apple Computer: WebObjects

  • BEA Systems: WebLogic, AquaLogic, and Tuxedo product families

  • Business Objects: Business Intelligence Platform

  • Cognos: Business Intelligence Platform

  • ContentMaster: Unstructured, semi structured and structured data
    transformation

  • Contivo: Contivo metadata design solutions

  • Cordys: Business Process Management (BPM) centric SOA

  • E2E: MDI - Model Driven Integration

  • elemenope: Open-source SOA framework.

  • Fujitsu: The SynfiniWay SOA framework

  • GigaSpaces: SBA - Write Once, Scale Anywhere

  • IBM : Service-Oriented Architecture Solutions

  • Infravio: SOA Registry and Governance Solutions

  • IONA Technologies: Artix ESB Enterprise Service Bus

  • iWay Software: iWay Foundation for SOA

  • Kantega: Kantega Secure Identity

  • Layer 7 Technologies: Security, Performance, Operational Management
    (Governance)

  • MEGA International: Business-Driven SOA

  • MetaMatrix: MetaMatrix Dimension

  • Microsoft: BizTalk and WCF

  • MuleSource: Mule

  • Nexaweb: Platform 4.0

  • Onyx Software Corporation: Onyx Web Services and the Onyx Process
    Manager

  • Oracle Corporation: Oracle Application Server, Oracle SOA Suite

  • PNMsoft: Business Process Management (BPM) centric SOA

  • Progress Software: Sonic ESB, Actional Web Services Management and SOA
    Management, DataXtend Data Integration Software

  • Rogue Wave Software: Rogue Wave Hydra Suite - High Performance SOA

  • SeeWhy: Event driven Business Intelligence Platform for SOA

  • SAP: NetWeaver

  • SOAMatrix Software: SOALayers product suite, SOAIntegrator platform;
    SOA Integration, Governance, Management and Security solutions

  • SOA Software: SOA, XML, and Web services management and security

  • Software AG: crossvision is an SOA suite

  • Solstice Software: Solstice Integra Suite is a SOA testing suite

  • Torry Harris Business Solutions: Vendor neutral Service Oriented
    Architecture implementation

  • OutSystems Agile SOA Platform

  • Ultimus: Business Process Management (BPM) Suite with integrated
    SOA

  • Xcalia: Intermediation Core (metadata driven business model and unified
    Data Access for databases and services (Web Services, Mainframe computer,
    Message Oriented Middleware) from Java, .Net and Data Access Services



I think the Semantic web (more on that in other post) along with the SOA,
is going to change the fundamental way we use the Internet in last decade.
The collaborating and sharing of IT solution will provide us the services
that we hardly though of and that too at very cheap price. You can book a
flight ticket, which will show you the available hotel in your destination
that fits your budget and also that matched your schedule. You don't have to
do any thing! Just be on the net! And for the software developers its going
to be highly challenging and back paining evolution!



This article is licensed under the GNU Free Documentation License. It uses
material from the Wikipedia article. Service-oriented architecture