Showing posts with label Hello World Example. Show all posts
Showing posts with label Hello World Example. Show all posts

January 15, 2012

Deploying an Apache Axis2 Web Service - Hello World Example

1) Setup Apache Axis2 in the web application - follow the steps here

2) Create a POJO - HelloWorldService.java - in the src folder of the web application

package info.icontraining.ws.axis2;

public class HelloWorld {
   public String sayHello(String name) {
      return "Hello " + name;
   }
}

3) In the WebContent/WEB-INF/services folder, create a new folder and name it 'HelloWorld'.
In this folder create a sub-folder and name it 'META-INF'.
In the META-INF folder create a new XML file - name it 'services.xml'.

4) Add the following configuration to the services.xml file created in the step above,

<service>
   <parameter name="ServiceClass" locked="false">info.icontraining.ws.axis2.HelloWorld</parameter>
   <operation name="sayHello">
      <messageReceiver class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
   </operation> 
</service>

5) Now go to the build/classes folder of the web application. Copy the folder named 'info' and paste it into the services/HelloWorld folder created in step 3.

So, now in the services/HelloWorld folder, there are 2 folders - META-INF and info
The META-INF folder contains the services.xml file.
The info folder contains the following hierarchy of sub-folders - icontraining/ws/axis2/HelloWorldService.class

6) Deploy the Web Application to the server, and access the following URL in the browser,

http://localhost:8080/WebAppName/services/listServices

The HelloWorld service will be present in the list of services.

7) Invoke the Web Service with the following URL in the browser,

http://localhost:8080/WebAppName/services/HelloWorld/sayHello?name=dinesh

December 31, 2011

Spring - Hibernate framework Integration - Hello World Example

0) To proceed with this example, complete the Spring Hello World Example and the Hibernate Hello World Example

1) Put 2 jar files from the Apache Commons collection in the WebContent/WEB-INF/lib folder of the web application - download the jars from this link

2) Add the following elements to the Spring configuration file, applicationContext.xml
Integrating Spring with Hibernate results in the hibernate.cfg.xml becoming obsolete - the configuration in hibernate.cfg.xml is now put in the applicationContext.xml

Configuration for DataSource (Database Connection properties)

<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
   <property name="driverClassName" value="oracle.jdbc.OracleDriver" />
   <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
   <property name="username" value="system" />
   <property name="password" value="system" />
</bean>

Configuration for Hibernate (of hibernate.cfg.xml)


<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
   <property name="dataSource" ref="dataSource"/>
   <property name="mappingResources">
      <list>
         <value>info/icontraining/hibernate/Message.hbm.xml</value>
      </list>
   </property>
   <property name="hibernateProperties">
      <props>
         <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
      </props>
   </property>
</bean>

Configuration for HibernateTemplate, DAOs, etc.

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
   <property name="sessionFactory" ref="sessionFactory" />
</bean>
 
<bean id="myDao" class="info.icontraining.dao.MyDAO">
   <property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>


3) Create a MyDAO.java class in the src folder of the web application - this class does the actual persistence

package info.icontraining.dao;

import java.util.List;
import info.icontraining.hibernate.Message;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class MyDAO {

   private HibernateTemplate hibernateTemplate;
 
   public void setHibernateTemplate(HibernateTemplate template) {
      this.hibernateTemplate = template;
   }
 
   public void saveData(String str) {
      Message message1 = new Message(str);
      hibernateTemplate.save(message1);
   }

   public int retrieveData() {
      List<Message> messages = hibernateTemplate.find("from Message as m order by m.text asc");
      return messages.size();
   } 
}


4) Create a client JSP - springHibernate.jsp - in the WebContent folder of the web application


<%@ page  import="org.springframework.context.*,org.springframework.web.context.*,info.icontraining.spring.*,info.icontraining.dao.*"%>
<html>
<body>

<% 
 ApplicationContext factory = 
  (ApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

 MyDAO mydao = (MyDAO)factory.getBean("myDao");
 mydao.saveData("Spring Hibernate");
 
 int numMessages = mydao.retrieveData();
%>
 
<%= numMessages + " messages found." %>

</body>
</html>

5) Test the example with the following URL in the browser,

http://localhost:8080/WebAppName/springHibernate.jsp

Log into Oracle Database and check the contents of the appropriate table

September 7, 2011

Java Message Service (JMS) Topic- Hello World Example with MessageListener

1) Configure the JMS Topic in the JBoss 4.2.2GA Server, in the file ${JBOSS_SERVER}/server/default/deploy/jms/jbossmq-destinations-service.xml

<mbean code="org.jboss.mq.server.jmx.Topic"
  name="jboss.mq.destination:service=Topic,name=myTopic1">
  <depends optional-attribute-
  name="DestinationManager">jboss.mq:service=DestinationManager</depends>
</mbean>

Ensure that the name myTopic1 is unique within the XML file

2) The ConnectionFactory administered object is pre-configured with the default JNDI name 'ConnectionFactory' in JBoss

Note: Add the following jar file to the classpath / build path of the Java Project / Application:

%JBOSS_HOME%\client\jbossall-client.jar

3) Create the TopicPublisherClient.java

package info.icontraining.topic;

import javax.jms.*;
import javax.naming.*;
import java.util.*;

public class TopicPublisherClient {

   public static void main(String[] args) {

      TopicConnection conn = null;
      TopicSession session = null;
      Topic topic = null;
   
      try {
         Properties props = new Properties();
         props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.NamingContextFactory");
         props.put(Context.URL_PKG_PREFIXES, "jboss.naming:org.jnp.interfaces");
         props.put(Context.PROVIDER_URL, "localhost:1099");
         props.put("java.naming.rmi.security.manager", "yes");

         InitialContext iniCtx = new InitialContext(props);

         Object cf = iniCtx.lookup("ConnectionFactory");
         TopicConnectionFactory tcf = (TopicConnectionFactory) cf;
    
         conn = tcf.createTopicConnection();

         topic = (Topic) iniCtx.lookup("topic/myTopic1");
    
         session = conn.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
         conn.start();

         TopicPublisher topicPublisher = session.createPublisher(topic);

         TextMessage message = session.createTextMessage();
         message.setText("this is a test message");
         topicPublisher.publish(message);
         System.out.println("Message published.");

         topicPublisher.close();

      } catch (NamingException e) {   
         System.out.println(e.toString());
      } catch (JMSException e) {
         System.out.println("JMS Exception");
      } finally {
         if (conn != null) {
            try {
               conn.close();
            } catch (JMSException e) {}
         }
      }
   }
}

4) Create the TopicSubscriberClient.java

package info.icontraining.topic;

import javax.jms.*;
import javax.naming.*;
import java.util.*;

public class TopicSubscriberClient
{
   public static void main(String[] args) {
      TopicConnection topicConnection = null;
      char answer = '\0';
  
      try 
      {
         Properties props = new Properties();

          props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.NamingContextFactory");
          props.put(Context.URL_PKG_PREFIXES, "jboss.naming:org.jnp.interfaces");
          props.put(Context.PROVIDER_URL, "localhost:1099");
          props.put("java.naming.rmi.security.manager", "yes");

          Context context = new InitialContext(props);
          TopicConnectionFactory tcf= (TopicConnectionFactory) context.lookup("ConnectionFactory");
          topicConnection = tcf.createTopicConnection();

          String topicName = "topic/myTopic1";
          Topic topic = (Topic) context.lookup(topicName);
   
          TopicSession topicSession = topicConnection.createTopicSession(false,  TopicSession.AUTO_ACKNOWLEDGE);
          topicConnection.start();

          TopicSubscriber topicSubscriber = topicSession.createSubscriber(topic);
   
          topicSubscriber.setMessageListener(new MyMessageListener());

          for(;;) {}
      }
      catch (JMSException e) {
         System.out.println("JMS Exception");
      } catch (Exception e) {
         System.out.println(e.toString());
      } finally {
         if (topicConnection != null) {
            try {
               topicConnection.close();
            } catch (JMSException e) {}
         }
      }
   }

   static class MyMessageListener implements MessageListener { 

      public void onMessage(Message message) {

         TextMessage tm = (TextMessage) message;

         try {
            System.out.println("onMessage==>"+ tm.getText());
         } catch(Throwable t) {
            t.printStackTrace();
         }
      }
   }
}

5) Run multiple instances of TopicSubscriberClient in multiple heaps. Next, run TopicPublisherClient to send the message to the JMS Topic.

July 16, 2011

Struts 2 - Spring framework Integration - Hello World Example

0) Ensure that both Struts 2 and Spring are setup in the web application. For Struts 2-enable the web application, refer this link and to Spring-enable the web application refer this link.

1) Download the Struts-Spring plugin jar from the link here and copy it in the WebContent/WEB-INF/lib folder of the web application

2) Modify the Struts 2 filter configuration in the web.xml file as follows,

<filter>
   <filter-name>struts2</filter-name>
   <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>

3) Copy the following configuration for the action element in the struts.xml file. The class attribute of the action element is assigned to the bean id from the applicationContext.xml rather than the actual class name

<action name="hello" class="greetingService">
   <result>/successSpring.jsp</result>
</action>

4) Modify the GreetingServiceImpl.java class to enter the following execute() and getGreeting() methods,

public String execute() { 
   return "success";
}

public String getGreeting() {
   return this.greeting;
}

5) Create a JSP - successSpring.jsp - in the WebContent folder of the web application

<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<body>   <s:property value="greeting" />
</body>
</html>

6) Test the example with the following URL in the browser,

http://localhost:8080/WebAppName/hello.action

July 5, 2011

Struts 2 - Hello World Example (with Annotations)

1) Create a new Web Application Project in Eclipse. Download the Struts 2 jars and other dependent jars from the link here and copy them into the WebContent/WEB-INF/lib folder of the web application.

2) Copy the following configuration for the Struts2 FilterDispatcher in the web.xml file of the web application

<filter>
   <filter-name>struts2</filter-name>
   <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
   <init-param>
      <param-name>actionPackages</param-name>
      <param-value>info.icontraining.struts2</param-value>   
   </init-param>
</filter>
<filter-mapping>
   <filter-name>struts2</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

The actionPackages parameter is used to specify the location (in terms of package names) of the action classes. Multiple packages can be specified by a comma-separated list.

3) Add the AnnotatedNameCollector.java class to the src folder of the web application. This class is an action class. Action classes in Struts2 with annotation-based configuration should either implement the Action interface or extend from the ActionSupport class or use a naming convention where the action class names end in the word 'Action'.

package info.icontraining.struts2;

import org.apache.struts2.config.Result;
import com.opensymphony.xwork2.ActionSupport;

@Result( value="/AnnotatedNameCollector.jsp" )
public class AnnotatedNameCollector extends ActionSupport {

}

The URL to access this action from the browser is derived by making the first character of the action class name smaller and appending the '.action' extension after the rest of the class name. So,

AnnotatedNameCollector.java can be accessed with the URL annotatedNameCollector.action

4) Add the AnnotatedHelloWorldAction class also to the src folder of the web application. In this case, the action class name ends with the word 'Action' and therefore does not need to extend the ActionSupport class or implement the Action interface

package info.icontraining.struts2;

import org.apache.struts2.config.Result;

@Result(name="SUCCESS", value="/HelloWorld.jsp" )
public class AnnotatedHelloWorldAction {

   private static final String GREETING = "Hello ";
     public String execute()  {
      setCustomGreeting( GREETING + getName() );
      return "SUCCESS";
   }

   private String name;
   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
    
   private String customGreeting;
  
   public String getCustomGreeting() {
      return customGreeting;
   }
  
   public void setCustomGreeting( String customGreeting ){
      this.customGreeting = customGreeting;
   }
}

The URL to access this action from the browser is derived by making the first character of the action class  name smaller, dropping the 'Action' at the end of the class name and appending the '.action' extension after the rest of the class name. So,

AnnotatedHelloWorldAction.java can be accessed with the URL annotatedHelloWorld.action

5) Create the AnnotatedNameCollector.jsp and HelloWorld.jsp as below and add them to the WebContent folder of the web application

AnnotatedNameCollector.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
  <head>
      <title>Name Collector</title>
  </head>
  <body>       <s:form action="annotatedHelloWorld">
        <s:textfield name="name" label="Your name"/>
        <s:submit/>
      </s:form>
  </body>
</html>

HelloWorld.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
  <head>
     <title>HelloWorld</title>
  </head>
  <body>       
     <h1><s:property value="customGreeting"/></h1>
  </body>
</html>

6) Test the application by typing the following URL in the browser,

http://localhost:8080/WebAppName/annotatedNameCollector.action

June 18, 2011

EJB3 Message-Driven Bean (MDB) - Hello World Example

0) Create an EJB Project and an EAR project according to instructions specified in the following example

1) Create a new Message-Driven Bean class in the ejbModule folder of the EJB Project created in the previous example.


package info.icontraining.mdb;


import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;


@MessageDriven
(activationConfig = {
@ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/MDBQueue2"),
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "AUTO_ACKNOWLEDGE")  })


public class MyMDB implements MessageListener {

   public void onMessage(Message message) {

      System.out.println("onMessage");
      TextMessage textMessage = (TextMessage) message;
      try {
         System.out.println("Received in an EJB3 MDB: " + 
                             textMessage.getText());
      
      } catch(Throwable t) {
         t.printStackTrace();
      }
   }
}


2) The EJB3 Message-Driven Bean (MDB) acts as a JMS consumer only. It cannot be directly accessed from a client. It is given messages delivered to a particular JMS destination such as a queue or topic.

We next create a JMS Client to write messages to a JMS Queue. The JMS provider will asynchronously deliver messages to the MDB by invoking its onMessage() method. This method like a business method of an MDB. The JMS client created below is a standalone Java program.


package info.icontraining.jms.client;


import javax.jms.*;
import javax.jms.Queue;
import javax.naming.*;
import java.util.*;


public class MyMDBSenderClient {


   public static void main(String[] args) {


      QueueConnection conn = null;
      QueueSession session = null;
      Queue que;

      try {
         Hashtable props = new Hashtable();


         props.put(Context.INITIAL_CONTEXT_FACTORY, 
                   "org.jboss.naming.NamingContextFactory");
         props.put(Context.URL_PKG_PREFIXES, 
                   "jboss.naming:org.jnp.interfaces");
         props.put(Context.PROVIDER_URL, "localhost:1099");
         props.put("java.naming.rmi.security.manager", "yes");


         InitialContext iniCtx = new InitialContext(props);


         Object tmp = iniCtx.lookup("ConnectionFactory");
         QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;

         conn = qcf.createQueueConnection();
         que = (Queue) iniCtx.lookup("queue/MDBQueue2");
         session = conn.createQueueSession(false,
                                      QueueSession.AUTO_ACKNOWLEDGE);
         conn.start();


         QueueSender queueSender = session.createSender(que);
         TextMessage message = session.createTextMessage();
         message.setText("Sent from MyMDBSenderClient");
         queueSender.send(message);


         System.out.println("Message sent.");



         queueSender.close();


      } catch (NamingException e) {
         System.out.println(e.toString());
      } catch (JMSException e) {
         System.out.println("JMS Exception");
      } finally {
         if (conn != null) {
            try {
               conn.close();
            } catch (JMSException e) {
               System.out.println("JMS Exception");
            }
         }
      }
   }
}


3) Test the MDB by executing the JMS Client code created in Step-2. Check the output in the server console printed by code in the MDB's onMessage() method.

EJB3 Stateless Session Bean with Remote access - Hello World Example

0) Refer to the EJB3 Stateless Session Bean with Local access at this link

1) In the HelloUser.java interface of the above example, replace the @Local annotation with the @Remote annotation


package info.icontraining.session;


import javax.ejb.Remote;
@Remote
public interface HelloUser {
   public String sayHello(String name);
}


2) The client in this case will not a Servlet (since the servlet object in the above example, exists in the same JVM heap as the EJB3 Session bean object, so it is not a remote object). We shall instead create a standalone Java application that executes outside the Application Server in a differente JVM Heap, effectively making the EJB Client a remote client.

Also, ensure that the EJB Project is present in the Build Path of the HelloClient Java Project. Right-click on the HelloClient Java project and select the "Java Build Path" option. Select the "Projects" tab and select add the EJB Project by clicking on the "Add..." button.

HelloClient.java


package com.yesm.client;



import java.util.Hashtable;
import javax.naming.*;
import info.icontraining.session.*;



public class HelloClient {
   public static void main(String[] args) {

      Hashtable env = new Hashtable();
      env.put("java.naming.factory.initial",
              "org.jnp.interfaces.NamingContextFactory");
      env.put("java.naming.factory.url.pkgs",
              "org.jboss.naming:org.jnp.interfaces");
      env.put("java.naming.provider.url","localhost:1099");

      Context context = null;

      try {
         context = new InitialContext(env);

         HelloUser helloUser = (HelloUser) context.lookup("MyEarApp/" +
                        HelloUserBean.class.getSimpleName() + "/remote");
         System.out.println(helloUser.sayHello("Dinesh"));
      } catch (NamingException e) {
         e.printStackTrace();
      }
   }
}


3) Deploy the EAR (Enterprise Application) according to instructions specified in the above example. Once the EAR is deployed, execute the EJB Client code to test remote accessibility of the EJB3 Stateless Session Bean.

June 1, 2011

EJB3 Entity Beans - Hello World Example

0) Download the Oracle Database 10g Express Edition and setup according to instructions on this link

1) Create a new Java Project named JPAdemo, in Eclipse. Click Finish.

Add the Oracle JDBC driver jar(ojdbc14.jar) to the build path of the project. This jar file is present at the following path of the Oracle installation - %ORACLE_HOME%\app\oracle\product\10.2.0\server\jdbc\lib

Also, add all the jars files present in the JBoss-4.2.2GA application server at the following paths:
- %JBOSS_HOME%\lib
- %JBOSS_HOME%\server\default\lib

2) Create a new class, Message.java in the src folder of the project. This class is the Entity Bean or the persistent class / entity according to the Java Persistence API (JPA) terminology.
The annotations in this class are equivalent to the configurations in the hibernate mapping files of the Hibernate persistence framework.


package info.icontraining.entity;


import javax.persistence.*;


@Entity
@Table(name="MESSAGES_TABLE_JPA")
public class Message {


    @Id
    @GeneratedValue
    @Column(name="MESSAGE_ID")
    private Long id;

    @Column(name="MESSAGE_TEXT")
    private String text;

    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="NEXT_MESSAGE_ID")
    private Message nextMessage;

    private Message() { }

    public Message(String text) {
        this.text = text;
    }


    public Long getId() {
        return id;
    }


    public void setId(Long id) {
        this.id = id;
    }


    public String getText() {
        return text;
    }


    public void setText(String text) {
        this.text = text;
    }


    public Message getNextMessage() {
        return nextMessage;
    }


    public void setNextMessage(Message nextMessage) {
        this.nextMessage = nextMessage;
    }
}


3) Create another class - Client.java - within the src folder. This class contains code to persist entities (or persistent objects) to the database table and retrieve data into persistent objects from the database table.


package info.icontraining.client;


import java.util.List;
import info.icontraining.entity.*;


import javax.persistence.*;


public class Client {


    public static void main(String[] args) {

        EntityManagerFactory emf = 
               Persistence.createEntityManagerFactory("JPAdemo");
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        tx.begin();

        Message msg = new Message("Hello World");
        em.persist(msg);

        tx.commit();
        em.close();

        EntityManager newEm = emf.createEntityManager();
        EntityTransaction newTx = newEm.getTransaction();

        newTx.begin();

        List msgs = newEm.createQuery
           ("select m from Message m order by m.text asc").getResultList();

        System.out.println(msgs.size() + " messages found.");

        for(Object m: msgs) {
            Message loadedMsg = (Message)m;
            System.out.println(loadedMsg.getText());
        }

        newTx.commit();
        newEm.close();

        emf.close();
    }
}


4) Add the following XML configuration file, named persistence.xml within the src\META-INF folder


<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
   <persistence-unit name="JPAdemo">
      <properties>
        <property name="hibernate.archive.autodetection" value="class,hbm" />
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.format_sql" value="true" />
        <property name="hibernate.connection.driver_class" 
                          value="oracle.jdbc.OracleDriver" />
        <property name="hibernate.connection.url" 
                          value="jdbc:oracle:thin:@localhost:1521:xe" />
        <property name="hibernate.connection.username" value="xxxxx" />
        <property name="hibernate.connection.password" value="xxxxx" />
        <property name="hibernate.dialect" 
                          value="org.hibernate.dialect.Oracle9Dialect" />
        <property name="hibernate.hbm2ddl.auto" value="update" />
        <property name="hibernate.generate_statistics" value="true" />
        <property name="cache.provider_class" 
                          value="org.hibernate.cache.NoCacheProvider" />
      </properties>
   </persistence-unit>
</persistence>


5) Run the Client.java class as a standalone Java program to test the Entity Bean

May 31, 2011

EJB3 Stateful Session Bean - Hello World Example

0) To setup an EJB3 project within an Enterprise Application (EAR) and deploy it to the JBoss Application Server, visit this link

1) In the MyEJBProject, create two classes - Account.java and AccountBean.java - within the ejbModule folder

Account.java


package info.icontraining.session;


import javax.ejb.*;


@Remote
public interface Account {


  public float deposit(float amount);
  public float withdraw(float amount);
  
  @Remove 
  public void remove();


}


AccountBean.java


package info.icontraining.session;


import javax.ejb.*;


@Stateful(name="AccountBean")
@Remote(Account.class)  
public class AccountBean implements Account {
   
    float balance = 0;


    public float deposit(float amount){
        balance += amount;
        return balance;
    }
 
    public float withdraw(float amount){
        balance -= amount;
        return balance;
    }

    @Remove  
    public void remove() {
        balance = 0;
    }
}


2) Within the web application, create two JSPs - accountForm.jsp and accountDetails.jsp - within the WebContent folder

accountForm.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1" %>


<html>
<body>


<h1><p align="center">Bank Transaction Form</p></h1>
<hr/><br/>

<form action="accountDetails.jsp" method="post">
  <table align="center"> 
   <tr><td>Enter the amount: <input type="text" name="amt" size="10"></td></tr>
   <tr><td><b>Select your choice:</b></td></tr>
   <tr><td><input type="radio" name="operation" value ="dep">Deposit</td></tr>
   <tr><td><input type="radio" name="operation" value ="with">Withdraw<br/></td></tr>
   <tr><td><input type="radio" name="operation" value ="balance">Check Balance<br/></td></tr>
   <tr><td><input type="submit" value="Submit"><input type="reset" value="Reset"></td></tr>
  </table>
</form>


</body>
</html>



accountDetails.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1" %>
<%@ page import="info.icontraining.session.*, javax.naming.*"%>


 <%!
     public Account account = null;
     float bal=0;


     public void jspInit() {
         try {
            InitialContext ic = new InitialContext();
            account = (Account) ic.lookup("MyEarApp/AccountBean/remote");
            System.out.println("Loaded Account Bean");
         } catch (Exception ex) {
            System.out.println("Error: "+ ex.getMessage());
         }
     }
    
     public void jspDestroy() {
        account = null;
     }
%>


   <%
    try {
       String s1 = request.getParameter("amt");
       String s2 = request.getParameter("operation");


       if (s1.equals("")) s1=null;
       
       if ( s1 != null) {
           Float amt  = new Float(s1);
                
           if(s2.equals("dep")) {
               bal=account.deposit(amt.floatValue());
               out.println("Balance is: " + bal);
               out.println("<br/><a href=accountForm.jsp>Go back</a>");


           } else if(s2.equals("with")) {
               bal=account.withdraw(amt.floatValue());
               out.println("Balance is: " + bal);
               out.println("<br/><a href=accountForm.jsp>Go back</a>");
           
           } else {        
   %>
             <p>Please select your choice</p>
                
   <%
           }
    } else {
   
           if (account != null) {  
   %>
           <p><b>Your Current Balance is:</b> <%= bal%><br/>
           <% out.println("<br/><a href=accountForm.jsp>Go back</a>"); %>
           <p>
   <%     
           }
     }
  } catch (Exception e) {
       e.printStackTrace();
  }
%>


3) Deploy the Enterprise Application comprising of the EJB Project and the Web Application.
Type the following URL in the browser and test the stateful session bean:

http://localhost:8080/MyEarApp/accountForm.jsp

EJB3 Stateless Session Bean - Hello World Example

1) Open Eclipse. Go to File > New > Project ...
Select EJB > EJB Project
Name the Project as MyEJBProject. Click Next.
Ensure that "EJB Module" with "3.0" as the version & "Java" with "5.0" as the version, checkboxes are ticked. Click Next. Click Finish.

2) In the MyEJBProject, create the following pieces of code within the ejbModule folder

HelloUser.java interface


package info.icontraining.session;


import javax.ejb.Local;


@Local  
public interface HelloUser {
      public String sayHello(String name);
}


HelloUserBean.java class



package info.icontraining.session;


import javax.ejb.Stateless;


@Stateless
public class HelloUserBean implements HelloUser {

      public String sayHello(String name) {
           return "Hello " + name + "! Welcome to EJB 3!";
      }
}


3) In your web application project (this is a different project compared to the EJB project just created above), add the following servlet code and configure it in the web.xml file

HelloUserClient.java servlet class


package info.icontraining.ejb.client;


import javax.naming.*;
import info.icontraining.session.*;
import java.io.*;
import java.util.Hashtable;
import javax.servlet.ServletException;
import javax.servlet.http.*;


public class HelloUserClient extends HttpServlet {


   public void doGet(HttpServletRequest req, HttpServletResponse res) 
                   throws ServletException, IOException {

       Hashtable env = new Hashtable(); 
       env.put("java.naming.factory.initial", 
                       "org.jnp.interfaces.NamingContextFactory");
       env.put("java.naming.factory.url.pkgs", 
                       "org.jboss.naming:org.jnp.interfaces"); 
       env.put("java.naming.provider.url","localhost:1099"); 


       PrintWriter out = res.getWriter();

       Context context;
       try {
           context = new InitialContext(env);

           HelloUser helloUser = (HelloUser) context.lookup("MyEarApp/" 
+ HelloUserBean.class.getSimpleName() + "/local");

           out.println(helloUser.sayHello("Dinesh"));

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


web.xml configuration


<servlet>
    <servlet-name>HelloUserClient</servlet-name>
    <servlet-class>info.icontraining.ejb.client.HelloUserClient</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>HelloUserClient</servlet-name>
    <url-pattern>/helloUserClient</url-pattern>
</servlet-mapping>


4) Right-click on the Web Application Project and select the "Properties" menu item.
Select "Java Build Path" from the options on the left.
Click on the "Projects" Tab.
Click the "Add..." button; Tick the "MyEJBProject" checkbox. Click OK. Again, click OK.
Any build errors in the Web Application project / servlet class will get removed.

5) Click on the "File" menu item at the top.
Select New > Project ...
Choose "J2EE" and then "Enterprise Application Project". Click Next.
Name the project as "MyEarApp". Click Next.
Check the "MyEJBProject" and the Web Application Project as the 2 modules to be added within the Enterprise Application Project. Also, check the "Generate Deployment Descriptor" option.
Click Finish.

Note: In Eclipse Helios, after creating the Enterprise Application Project, right click on the project, select Properties. In the pop-up window, select "Deployment Assembly" on the left. Then click on the "Add..." button and select choose Project and click Next. Select the 2 projects - the EJB Project (MyEJBProject) and the web application project together (by pressing down the CTRL key). Click Finish.

6) Open the application.xml file within the new created EAR project - MyEarApp - within the EarContent/META-INF folder.
Modify the <context-root> element of the web application to /MyEarApp

7) Deploy the MyEarApp project to the JBoss Application Server and test the EJB by typing the following URL in the browser:

http://localhost:8080/MyEarApp/helloUserClient

April 14, 2011

Deploying WSDD Web Services with Apache Axis 1.4 - Hello World Example

1) Create a HelloWorld.java service class in the src folder of the web application. The public methods of this class will be exposed as a web service.


package info.icontraining.ws;


public class HelloWorld 

     public String sayHello() 
     { 
         return "Hello World"; 
     } 



2) Create a HelloWorld.wsdd file in a local folder (not inside the application but anywhere on your hard disk, for example, C:\my-wsdd-files) to configure the web service and register with with the Apache Axis deployment


<deployment xmlns="http://xml.apache.org/axis/wsdd/" xmlns:java="http://xml.apache.org/axis/wsdd/providers/java"> 
   <service name="HelloWorld" provider="java:RPC"> 
      <parameter name="className" value="info.icontraining.ws.HelloWorld"/> 
      <parameter name="allowedMethods" value="*"/> 
   </service> 
</deployment> 


Note: Deploy the application to the Application Server at this time.

3) Register this web service by following the below steps,

a) Go to the "Run" menu in Eclipse and select the "Open Run Dialog..." option

b) In the Project, add the WebAppName; In the Main Class add: org.apache.axis.client.AdminClient

c) Click on the "Arguments" tab and in the Program Arguments, add the following:
-lhttp://localhost:8080/WebAppName/services/AdminService C:\path-to-wsdd-folder\HelloWorld.wsdd

Replace WebAppName and the path-to-wsdd-folder appropriately.

- The web service is registered if you see the output message:
<Admin>Done Processing</Admin>

Note: Re-starting of the JBoss Server will undo the registration of the web service.

4) To access the web service WSDL, invoke the following URL in the browser,
http://localhost:8080/WebAppName/services/HelloWorld?wsdl

Hibernate 3.0 - Hello World Example

0) Download Oracle Express 10g Express Edition and setup according to instructions on this link.
Copy the Oracle JDBC jar into the lib folder of the web application.

1) Download the hibernate_jars.zip from this link, unzip and paste the jar files into the WebContent/WEB-INF/lib folder of the web application

2) Create the persistent class, Message.java in the src folder of the web application

package info.icontraining.hibernate;
public class Message { 
  
   private Long id; 
   private String text; 
   private Message nextMessage; 
  
   private Message() {} 
     
   public Message(String text) { 
      this.text = text; 
   } 
   public Long getId() { 
      return id; 
   } 
   private void setId(Long id) { 
      this.id = id; 
   } 
   public String getText() { 
      return text; 
   } 
   public void setText(String text) { 
      this.text = text; 
   } 
   public Message getNextMessage() { 
      return nextMessage; 
   } 
   public void setNextMessage(Message nextMessage) { 
      this.nextMessage = nextMessage; 
   }   
} 


3) Create the Message.hbm.xml file in the same folder (package) as the Message.java class - this is the hibernate mapping file for the persistent class Message.java.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping> 
   <class name="info.icontraining.hibernate.Message" table="MESSAGES"> 
      <id name="id" column="MESSAGE_ID"> 
         <generator class="native"/> 
      </id> 
      <property name="text" column="MESSAGE_TEXT"/> 
      <many-to-one name="nextMessage" cascade="all" column="NEXT_MESSAGE_ID"/> 
   </class> 
</hibernate-mapping>


4) Create the hibernate.cfg.xml file in the WebContent/WEB-INF folder - this file holds the Hibernate configuration. Make sure that the username, password, the database connection string and the JDBC driver class name in this file are appropriate for your database installation.

<?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>  
<property name="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</property> 
<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property> 
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> 
<property name="hibernate.connection.username">system</property> 
<property name="hibernate.connection.password">system</property> 
<property name="show_sql">true</property> 
<property name="hibernate.use_sql_comments">true</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> 
<property name="hibernate.hbm2ddl.auto">create</property> 
<property name="hibernate.current_session_context_class">thread</property> 
<property name="hibernate.generate_statistics">true</property> 
<property name="hibernate.format_sql">true</property> 

<!-- Mapping files --> 
<mapping resource="info/icontraining/hibernate/Message.hbm.xml" /> 

</session-factory>
  
</hibernate-configuration>  


5) Create a HibernateUtil.java utility class in the src folder of the web application. This class abstracts the loading of the Hibernate configuration and procuring the SessionFactory object

package info.icontraining.hibernate;

import org.hibernate.*; 
import org.hibernate.cfg.*; 

public class HibernateUtil { 

   private static SessionFactory sessionFactory; 

   static { 
      try { 
         sessionFactory = new Configuration().configure("/WEB-INF/hibernate.cfg.xml").buildSessionFactory(); 
      } catch (Throwable ex) { 
         ex.printStackTrace(); 
      } 
   } 

   public static SessionFactory getSessionFactory() { 
      return sessionFactory; 
   } 
   public static void shutdown() { 
      getSessionFactory().close(); 
   } 
} 


6) Create the MessageServlet.java servlet class in the src folder of the web application. This class contains code to persist/retrieve the persistent objects.

package info.icontraining.servlets;

import java.io.*; 
import java.util.*; 
import javax.servlet.*; 
import javax.servlet.http.* ; 
import org.hibernate.*; 
import info.icontraining.hibernate.*;

public class MessageServlet extends HttpServlet { 
  
   public void doGet(HttpServletRequest req, HttpServletResponse res) 
                        throws IOException, ServletException{ 
  
      PrintWriter out = res.getWriter(); 

      Session session = HibernateUtil.getSessionFactory().openSession(); 
      Transaction tx = session.beginTransaction(); 
      Message message1 = new Message("Hello World"); 
      session.save(message1); 
      tx.commit(); 
      session.close(); 

      Session newSession = HibernateUtil.getSessionFactory().openSession(); 
      Transaction newTransaction = newSession.beginTransaction(); 
      List messages = newSession.createQuery("from Message as m order by m.text asc").list(); 
      out.println( messages.size() + " message(s) found:" ); 

      for (Iterator iter = messages.iterator(); iter.hasNext(); ) { 
         Message message2 = iter.next(); 
         out.println( message2.getText() ); 
      }

      newTransaction.commit(); 
      newSession.close();  
   } 
}


7) Configure the servlet class in the web.xml file

<servlet>
   <servlet-name>MessageServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.MessageServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>MessageServlet</servlet-name>
   <url-pattern>/messageServlet.hibernate</url-pattern>
</servlet-mapping>


8) Test the code by typing the following URL in the browser,

http://localhost:8080/WebAppName/messageServlet.hibernate

April 12, 2011

Apache Axis 1.4 - Hello World JWS Web Service Client

In this post, we will create the Web Service Client for the Apache Axis JWS Web Service at this link

1) Create a class HelloWorldClient.java in the src folder of the web application. This class will be a standalone class with a main method and will run in its own JVM


package info.icontraining.ws.client;


import org.apache.axis.client.*;
import org.apache.axis.encoding.XMLType;
import javax.xml.rpc.ParameterMode;


public class HelloWorldClient {


  public static void main(String[] args) throws Exception{
String endpoint = "http://localhost:8080/WebAppName/HelloWorld.jws";


Service  service = new Service();
Call call = (Call) service.createCall();


call.setTargetEndpointAddress( new java.net.URL(endpoint) );
call.setOperationName( "sayHello" );
call.setReturnType( XMLType.XSD_STRING );


String ret = (String) call.invoke( new Object [] { });
System.out.println("Got result : " + ret);
  }
}


2) Run this class as a 'Java Application' (and will not execute on the server)

Apache Axis 1.4 - Hello World Example JWS web service

1) Download the following resources:
Apache Axis Jar Files - Click here
WebContent Files - Click here
Resources Files - Click here

2) Unzip the Axis_jars.zip file and copy the Axis jars to the WebContent/WEB-INF/lib folder of the Web Application.
Unzip the web_content_files.zip file and copy the contents to the WebContent folder of the Web Application.
In the src folder create a new package named 'resources'. Unzip the resources_files.zip file and copy the contents to the src folder within the package 'resources'.

3) Add the following configuration to the WebContent/WEB-INF/web.xml file of the Web Application


<listener>
   <listener-class>org.apache.axis.transport.http.AxisHTTPSessionListener</listener-class>
</listener>



<servlet>
    <servlet-name>AxisServlet</servlet-name>
    <servlet-class>org.apache.axis.transport.http.AxisServlet</servlet-class>
</servlet>


<servlet>
    <servlet-name>AdminServlet</servlet-name>
    <servlet-class>org.apache.axis.transport.http.AdminServlet</servlet-class>
    <load-on-startup>100</load-on-startup>
</servlet>


<servlet>
    <servlet-name>SOAPMonitorService</servlet-name>
    <servlet-class>org.apache.axis.monitor.SOAPMonitorService</servlet-class>
    <init-param>
      <param-name>SOAPMonitorPort</param-name>
      <param-value>5001</param-value>
    </init-param>
    <load-on-startup>100</load-on-startup>
</servlet>



<servlet-mapping>
    <servlet-name>AxisServlet</servlet-name>
    <url-pattern>/servlet/AxisServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>AxisServlet</servlet-name>
    <url-pattern>*.jws</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>AxisServlet</servlet-name>
    <url-pattern>/services/*</url-pattern>
</servlet-mapping>


<servlet-mapping>
    <servlet-name>AdminServlet</servlet-name>
    <url-pattern>/servlet/AdminServlet</url-pattern>
</servlet-mapping>


<servlet-mapping>
    <servlet-name>SOAPMonitorService</servlet-name>
    <url-pattern>/SOAPMonitor</url-pattern>
</servlet-mapping>


<mime-mapping>
    <extension>wsdl</extension>
    <mime-type>text/xml</mime-type>
</mime-mapping>


<mime-mapping>
    <extension>xsd</extension>
    <mime-type>text/xml</mime-type>
</mime-mapping>

4) Test the Axis setup by typing the following URL in the browser:

http://localhost:8080/WebAppName/happyaxis.jsp

5) To deploy a JWS Web Service, create a file, HelloWorld.jws, in the WebContent folder of the web application with the following code

public class HelloWorld { 
  
  public String sayHello() { 
     return "Hello World"; 
  } 


6) Deploy the Web Application and access the following URL in the browser:

http://localhost:8080/WebAppName/HelloWorld.jws

To access the WSDL for the web service, type the following URL in the browser:

http://localhost:8080/WebAppName/HelloWorld.jws?wsdl


Resolution to the Error:




java.lang.RuntimeException: No compiler found in your classpath! (you may need to add 'tools.jar')

Copy the tools.jar file from the JDK/lib folder into the %JBOSS HOME%\server\default\lib folder.