Codebusters

Sample Programs For Various Features

Making A Servlet Application For Weblogic 10

This post produces a sample program for servlet and run it on Weblogic 10 server. The basic purpose of this post is to present the deploying of webapps for weblogic.

Prerequisits of this sample requires weblogic 10 setup and WL_HOME environment variable set. Next is ANT installed along with classpaths. We are using ant so that the dependencies are clear and implementation settings need not be altered.

Say the SAMPLE.DIR is the directory where we are carrying the sample implementation. All paths will be in reference to this directory. 

1. First we will make a src folder which will contain the source folder. I am making myservlet.HelloWorld servlet. This will be kept in SAMPLE.DIR/src/myservlet directory.

Here is the code for the source

 HelloWorld.java

————————————————————————–

package myservlet;

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class HelloWorld extends HttpServlet {

 

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

response.setContentType(“text/html”);

PrintWriter out = response.getWriter();

out.println(“<html>” +

“\n<head>” +

“\n<title>My servlet</title>”+

“</head>” +

“<body>” +

“<center> <h1> Hello world </h1> </center>” +

“</body>” +

“\n</html>”);

System.out.println(“hi”);

}

}

—————————————————————————–

2. We make an etc folder that contains the deployment descriptors for the application. We need two files for the structure. web.xml and application.xml

web.xml

—————————————————–

<?xml version=”1.0″ encoding=”ISO-8859-1″?>
<!DOCTYPE web-app
    PUBLIC “-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN”
    “http://java.sun.com/j2ee/dtds/web-app_2_2.dtd“>

<web-app>
  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>myservlet.HelloWorld</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/helloworld</url-pattern>
    </servlet-mapping>
</web-app>

———————————————————

application.xml

———————————————————

<?xml version=”1.0″ encoding=”UTF-8″?>
<application xmlns=”http://java.sun.com/xml/ns/j2ee” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” version=”1.4″>
  <description>Hello world service</description>
  <display-name>HelloWorld</display-name>
  <module>
    <web>
      <web-uri>Hello-world.war</web-uri>
      <context-root>servlet</context-root>
    </web>
  </module>
 </application>

—————————————————————-

3. Finally all tasks are written to the build.xml file for ant targeting. This does all the required tasks for the purpose. We will keep this build.xml in the SAMPLE.DIR

I will explain the code later for and the ant targets involved..

build.xml

———————————————————————-

<project name=”hello_world” default=”all” basedir=”.”>

 <property environment=”env”/>
 <property name=”src.dir” location=”./src”/>
 <property name=”bld.dir” location=”./build”/>
 <property name=”ear.dir” location=”./ear”/>
 <property name=”web.class.dir” location=”${ear.dir}/WEB-INF/classes”/>
 <property name=”server.host” value=”localhost”/>
 <property name=”server.port” value=”7001″/>
 <property name=”server.url” value=”${server.host}:${server.port}”/>
 <property name=”server.username” value=”weblogic”/>
 <property name=”server.password” value=”weblogic”/>
 <property name=”weblogic.jar.loc” location=”${env.WL_HOME}\server\lib\weblogic.jar”/>
 <property name=”etc.dir” location=”./etc”/>
 <property name=”war.dir” location=”./war”/>
 <property name=”app.name” value=”hello-world”/>

 <path id=”weblogic”>
  <pathelement path=”${weblogic.jar.loc}”/>
 </path>

 <taskdef name=”wldeploy” classname=”weblogic.ant.taskdefs.management.WLDeploy”>
  <classpath refid=”weblogic”/>
 </taskdef>

 
 <target name=”clean” depends=”build-clean, clean-ear, clean-war-setup”/>
 
 <target name=”build-setup”>
  <mkdir dir=”${bld.dir}”/>
 </target>

 <target name=”build-clean”>
  <delete dir=”${bld.dir}”/>
 </target>

 <target name=”build” depends=”build-setup” description=”Compiles the source files”>
  <echo message=”Compiling the source files”/>
  <javac srcdir=”${src.dir}” destdir=”${bld.dir}”>
   <classpath refid=”weblogic”/>
  </javac>
 </target>

 <target name=”ear-setup”>
  <mkdir dir=”${ear.dir}/META-INF”/>
 </target>

 <target name=”clean-ear”>
  <delete dir=”${ear.dir}”/>
 </target>
  
 <target name=”create-war-setup”>
  <mkdir dir=”${war.dir}/WEB-INF/classes”/>
  <copy todir=”${war.dir}/WEB-INF” file=”${etc.dir}/web.xml”/>
  <copy todir=”${war.dir}/WEB-INF/classes”>
   <fileset dir=”${bld.dir}”/>
  </copy>
 </target>

 <target name=”clean-war-setup”>
  <delete dir=”${war.dir}”/>
  <delete file=”${app.name}.war”/>
 </target>
 
 <target name=”create-war” depends=”create-war-setup” description=”creates the ${app.name}.war”>
  <jar destfile=”${app.name}.war” basedir=”${war.dir}”/>
 </target>

 <target name=”create-ear” depends=”ear-setup, create-war” description=”creates ear for the application”>
  <copy todir=”${ear.dir}/META-INF” file=”${etc.dir}/application.xml”/>
  <copy todir=”${ear.dir}” file=”${app.name}.war”/>
 </target> 

 <target name=”deploy” description=”–> Deploys the file to the WLS”>
  <echo message=”Deploying the file to weblogic server”/>
  <wldeploy action=”deploy”  
    source=”${ear.dir}”
        name=”${app.name}”
    user=”${server.username}”
    password=”weblogic”
    verbose=”true”
    adminurl=”t3://localhost:7001″
    debug=”true”>
  </wldeploy>
 </target>
 <target name=”undeploy” description=”–> Undeploys the file to the WLS”>
  <echo message=”undeploying the file to weblogic server”/>
  <wldeploy action=”undeploy”  
    name=”${app.name}”
    user=”${server.username}”
    password=”weblogic”
    verbose=”true”
    adminurl=”t3://localhost:7001″
    debug=”true”>
  </wldeploy>
 </target>

  
 <target name=”all” depends=”clean, build, create-ear, deploy”/>
</project>

——————————————————————–

Explaination

We need weblogic.jar from server/lib of WL_HOME for dependencies. We make a classpath weblogic pointing to that.

Server host, port, username, password can be changed accordingly.

a. Target build compiles the files to the SAMPLE.DIR/build directory. For including the servlet package we need weblogic.jar hence it is included in the classpath

b.  Target create-war makes the war file using those class files. The structure of war is made in SAMPLE.DIR and then packaged using jar utility. The structure contains WEB-INF folder with web.xml in it along with classes subfolder. This classes will contain the compiled classes from SAMPLE.DIR/build

c. Target create-ear makes the ear and things ready for deployment. Ear structure is as follows

Eardirectory/ META-INF / application.xml

                  / hello-world.war

This hello-world.war was generated at the time we are running create-war. The same one is copied to this.

d. Deploy the servlet. Deploying needs wldeploy task for its purpose which is defined in weblogic.jar We specify the ear location as source fo rthe deployment. This step needs servers up and running and server settings accurate.

e. After the ear is deployed servlet can be checked at http://localhost:7001/servlet/helloworld

The pattern is http://<hostname&gt;:<portname>/<contextname>/<mapping-urlname>

where context name is specified in application.xml and mapping-urlname is specified in web.xml

Note: The version of Weblogic JDK and the one used for compilation should be same. Generally jdk comes with bea server and is present at <bea installation directory>/jdk<version> For safe use, this jdk can be included in path for compilation

Note: There can be many wars and according context roots. All these need to be specified in application.xml

Note: In case server is at some other host, upload=true should be added to the wldeploy task

Hope this all works fine for you.. 🙂

 

June 19, 2008 Posted by | Uncategorized | 1 Comment

Making JAX-WS Web service using WebLogic 10

Web services are a mechanism to invoke services over web application. The best part of web-services is the transfer mechanism. XML SOAP messages are used for transmission of messages which makes it highly optimized and speedy.

Following example creates and implements a simple web-service which can be deployed to WebLogic 10. Following are the pre requisites of the sample. All of these are freely available on net.

1. Apache Ant ( ant downloads page) We will use ant for all compilation and deployment purposes. This makes us comfortable on repeated use in future. Set the ANT_HOME path in exvironment

2. JDK (java downloads page) add the bin to the classpath

3. WebLogic 10 application server (bea download) set WL_HOME to the installation directory.

4. xalan api. (xalan) some jars are needed for running the client on webservices.

Procedure
Choose a directory to work upon and create src and lib folders. Make sure ANT_HOME is set and ant is working.
Open a command prompt and set weblogic environment by running setWLSEnv.cmd from %WL_HOME%\server\bin directory

Create a service program in the src folder. I am creating webservice.Greet class. The folder structure should be according to the packages. Eg. Greet.java will be kept in src\webservice\ folder.

//Greet.java
package webservice;

import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService(serviceName=”Greeting_Service”, targetNamespace=”http://harsh.oracle&#8221;)
public class Greet {

@WebMethod(operationName = “sayHi”)
public String sayHi(RequestDetail detail)
{
StringBuffer buffer = new StringBuffer(“Message is \n”);
buffer.append(“\nName – ” + detail.getName());
buffer.append(“\nAddress – ” + detail.getAddress());
buffer.append(“\nMail – “+detail.getMail());
buffer.append(“\nPhone – “+ detail.getPhone());

System.out.println(buffer.toString());
return buffer.toString();
}
}

———————————————————————————————-
Annotations specify the name with which service will be exposed to the clients. We can specify the service name and operation name along with name space. Else compiler takes the default argument which constructs a name according to the method names.

Constructors of exposed service should not contain any arguments. Default constructors are used. They may or may not be defined.

I am using RequestDetail.java so that example also constitutes complex type arguments.
————————————————————————————————–
//RequestDetail.java
package webservice;

public class RequestDetail {
private String Name;
private String Address;
private String mail;
private String phone;

public RequestDetail(String Name, String Address, String mail, String phone) {
this.Name= Name;
this.Address= Address;
this.mail= mail;
this.phone= phone;
}

public RequestDetail() {}

public void setName(String Name) {
this.Name = Name;
}

public void setAddress(String Address) {
this.Address = Address;
}

public void setMail(String mail) {
this.mail = mail;
}

public void setPhone(String phone) {
this.phone = phone;
}

public String getName() {
return this.Name;
}

public String getAddress() {
return this.Address;
}

public String getMail() {
return this.mail;
}

public String getPhone() {
return this.phone;
}
}

——————————————————————————————-
This creates a source for our web service. Applications can be extended to heavy projects as per requirements.

Now its time to start with build.xml This file is read by ant for firing of the targets.
Place this build.xml along with src and lib directory.

I will explain each segment in following part.

build.xml

The starting tag specifies the project name, base directory of execution and default target.
If we want to run a desired target we add the name of the target along with the ant clause
———————————————————————————-
eg ant build

The init target sets the property names of variables used throughout the build. This is useful as in case of changing the directory names only init target needs to be updated.

Target build-setup creates the build directory if it is not created so far. Depends argument specifies that init target is fired first so the property variables are initialized.

Make sure you have executed setWLSEnv from %WL_HOME%\server\bin directory.

Target ws-compile compiles the webservice in the specified format. JWSC needs to defined before use. For this we need %WL_HOME%\server\lib\weblogic.jar This will compile and keep the deployment dependent files to the build directory. Deployment descriptors are automatically created.

Start weblogic server and be prepared to deploy the file.
wldeploy again needs to be defined as it is weblogic specific.

For this example. Server stands up on localhost port 7001 and username and password are unchanged. weblogic is default case.
Deployment name will be same as application name
Source can be given as ${bld.dir} also. By giving the war name is like making it specific.

If the service is deployed properly, a WSDL is generated automatically and will be placed at http://localhost:7001/Greet/Greeting_Service?WSDL

This WSDL file contains the service description and names by which it is exposed. If you watch carefully, portname tag contains the service name, operation name contains method names, and message elements represents the argument types.

Now it is time to make a client and test the service. We will create a proxy for this service and use a java client to invoke it.

build-client target builds the client for the service. It uses a clientgen task which is defined manually. We can specify package name of the proxy. I kept it as client.proxy

Now will make a testClient which will invoke the method in client proxy
I am keeping testclient.java in Client-prog directory. Every client build target copies the java file to the client directory and compiles the integration.

Here is the file..

//testClient.java
package client;

import client.proxy.*;

public class testClient {
public static void main(String args[]) throws Exception {

RequestDetail detail = new RequestDetail();
detail.setName(“harsh”);
detail.setAddress(“btm”);
detail.setMail(“hm@oracle.com”);
detail.setPhone(“246275”);

GreetingService gs =new GreetingService();
String ret = gs.getGreetPort().sayHi(detail);

System.out.println(“Message from web service – “+ret);
}
}

————————————————————————————————-

run-client target executes the client. Copy xalan.jar , serializer.jar , xercesImpl.jar , xml-apis.jar from xalan download to the lib directory as there are dependencies on them.

Message will be prompted. to the client side as well as the server log (prompt on which server is running) as we have given a print statement in the Greet.java for the details.

🙂

Note:

Here are the special cases which could be a point while making webservices.

1. Making single war for multiple applications

Above example works fine for a single file. But if there are more then one java classes exposed as web application, every jws in ant target makes a different war. If we want to put all the stuff in a single war, following snippet gives the example.

<module name=”wsgen” contextPath=”wsgen”>
<jwsfileset srcdir=”${ws.src.dir}”>
<include name=”**/*WS.java”/>
</jwsfileset>
</module>

Every module is taken in a different jar. Hence, creates simplicity of use.

2. Referred libraries

In case exposed services has dependencies other than specified src folder, They can be kept in APP-INF/lib directory of the ear build (build directory of webservice ws-bld in this example). Dependencies should be bundled up in jar. No other reference is needed for exposing the libraries.

3. Setting Context Root

Context Root can be set by adding an element at the time of compilation of service.

It can be done by adding WLHttpTransport element to jws where we specify the file containing web service definition to be exposed. Here is a sample usage

<WLHttpTransport

contextPath=”TestService” serviceUri=”TestService”

portName=”TestServicePort1″/>

May 17, 2008 Posted by | J2EE, JAVA, Uncategorized, Web Services | 6 Comments