September 30, 2011

Service Locator & Business Delegate Design Patterns for an EJB Client

HelloClient.java - This is the EJB Client class

package info.icontraining.ejb.client;

public class HelloClient {
 
   public static void main(String[] args) {  
      System.out.println(MyBusinessDelegate.sayHello("Dinesh"));
   }
}

MyBusinessDelegate.java

package info.icontraining.ejb.client;

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

public class MyBusinessDelegate {

   public static String sayHello(String name) {

      Object obj = MyServiceLocator.getStub("MyEarApp/" 
                  + HelloUserBean.class.getSimpleName() + "/remote");
  
      HelloUser helloUser = (HelloUser) obj;
      return helloUser.sayHello(name);
   }
}

MyServiceLocator.java


package info.icontraining.ejb.client;

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

public class MyServiceLocator {

   public static Object getStub(String jndiName) {
  
      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;
      Object obj = null;
     
      try {
         context = new InitialContext(env);
         obj = context.lookup(jndiName);
      } catch (NamingException e) {
         e.printStackTrace();
      }

      return obj;
   }
}

Adapter Design Pattern code example in Java

Adaptee Concrete

public class Plug {
   private String specification = "5 AMP";
   public String getInput() {
      return specification;
   }
}

Target interface

public interface Socket {
   public String getOutput();
}

Adapter Concrete

public class PlugAdapter implements Socket {

   Plug plug;

   public String getOutput() {
      plug = new Plug();
      String output = plug.getInput();
      return output;
   }
}

Client

public class Client {
   Socket socket;

   public void m1() {
      socket = new PlugAdapter();
      socket.getOutput();
   }
}

Singleton Design Pattern code example in Java

Singleton Class

public class SingletonClass {

   private static SingletonClass uniqueInstance;
   // other variables here

   private SingletonClass() { }

   public static synchronized SingletonClass getInstance() {

      if (uniqueInstance == null)
         uniqueInstance = new SingletonClass();
      return uniqueInstance;
   }

   // other methods here
}

Decorator Design Pattern code example in Java

Abstract Type


public interface IEmail {
   public String getContents();
}

Concrete Type

public class Email implements IEmail {
   private String content;
   public Email(String content) {
      this.content = content;
   }

   @Override
   public String getContents() {
      //general email stuff
      return content;
   }
}

Abstract Type Decorator

public abstract class EmailDecorator implements IEmail {
  
   //wrapped component
   IEmail originalEmail;

   public IEmail getOriginalEmail() {
      return this.originalEmail;
   }

   public void setOriginalEmail(IEmail email) {
      this.originalEmail = email;
   }
}

Concrete Type Decorator

public class SecureEmailDecorator extends EmailDecorator {

   private String content;
   public SecureEmailDecorator(IEmail basicEmail) {
      setOriginalEmail(basicEmail);
   }

   @Override
   public String getContents() {
      //  secure original
      content = encrypt(getOriginalEmail().getContents());
      return content;
   }

   private String encrypt(String message) {
      //encrypt the string
      return  encryptedMessage;
   }
}

Client

public class EmailSender {

   public void sendEmail(IEmail email) {
      // get hold of email contents
      email.getContents();

      // send email code here
   }

   public static void main(String[] args) {
      EmailSender emailSender = new EmailSender();

      IEmail email = new Email();

      // Sending normal email
      emailSender.sendEmail(email);

      // Sending Secure email
      emailSender.sendEmail(new SecureEmailDecorator(email));
   }
}

Observer Design Pattern code example in Java

The Subject Abstract Type

import Observer;

public interface Subject {
   public void addObserver(Observer o);
   public void removeObserver(Observer o);
   public String getState();
   public void setState(String state);
}

The Observer Abstract Type

import Subject;

public interface Observer {
   public void update(Subject s) { ... }
}

Concrete Implementation of Observer Abstract Type (Subscriber)

import Subject;

public class ObserverImpl implements Observer {
   private String state = "";

   public void update(Subject o) {
      state = o.getState();
      System.out.println("Update received from Subject, state changed to : " + state);
   }
}

Concrete Implementation of Subject Abstract Type (Publisher)

import Observer;

public class SubjectImpl implements Subject {
   private List observers = new ArrayList();

   private String state = "";

   public String getState() {
      return state;
   }

   public void setState(String state) {
      this.state = state;
      notifyObservers();
   }

   public void addObserver(Observer o) {
      observers.add(o);
   }

   public void removeObserver(Observer o) {
      observers.remove(o);
   }

   public void notifyObservers() {
      Iterator i = observers.iterator();
      while (i.hasNext()) {
         Observer o = (Observer) i.next();
         o.update(this);
      }
   }
}

The Client

import Subject;
import SubjectImpl;
import Observer;
import ObserverImpl;

public class Client {
   public static void main(String[] args) {
      Observer o = new ObserverImpl();
      Subject s = new SubjectImpl();
      s.addObserver(o);
      s.setState("New State");
   }
}

Strategy Design Pattern code example in Java

The Abstract Type (the dependency)

public interface SortInterface {
   public void sort(List l);
}

The Concrete Implementations of the Abstract Type

public class QuickSort implements SortInterface {
   public void sort(List l) { ... }
}

public class BubbleSort implements SortInterface {
   public void sort(List l) { ... }
}

The Dependent Abstract Type

import SortInterface;

public abstract class Sorter {
   private SortInterface si;

   public void setSorter(SortInterface si) {
      this.si = si; 
   }

   public SortInterface getSorter() {
      return this.si; 
   }

   public void doSort(List listToSort);
}

The Dependent Concrete Type

public class MySorter extends Sorter {

   public void doSort(List listToSort) {
      getSorter().sort(listToSort);
      // other processing here
   }
}

The Client

import MySorter;
import BubbleSort;

public class Client {
   MySorter mysorter = new MySorter();

   mysorter.setSorter(new BubbleSort());
   mysorter.doSort();

   mysorter.setSorter(new QuickSort());
   mysorter.doSort();
}

Accessing request headers in a Struts 2 action

1) Create an action class - HeaderReader.java - in the src folder of the web application

package info.icontraining.struts2;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;

public class HeaderReader extends ActionSupport implements ServletRequestAware {

   private HttpServletRequest request;
 
   public void setServletRequest(HttpServletRequest request) {
      this.request = request;
   }
 
   public String execute() {

      Enumeration e = request.getHeaderNames();
      String headerName = null;

      while(e.hasMoreElements()) {
         headerName = (String) e.nextElement();
         System.out.println(headerName + ": "); 
         System.out.println(request.getHeader(headerName) + "\n");
      }

      return SUCCESS;
   } 
}

2) Add a headers.html file to the WebContent folder of the web application

<html>
<body>
Check Server console log for Header names and values
</body>
</html>

3) Configure the action class in the struts.xml configuration file

<action name="headerReader" class="info.icontraining.struts2.HeaderReader">
   <result>headers.html</result> 
</action>

4) Test the example by accessing the following URL,

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

Setting a cookie in the response in Struts 2

1) Create an action class - CookieWriter.java - in the src folder of the web application

package info.icontraining.struts2;

import javax.servlet.http.Cookie;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class CookieWriter extends ActionSupport {

   public String execute() throws Exception {
      ServletActionContext.getResponse()
                    .addCookie(new Cookie("firstName", "Dinesh"));
      return SUCCESS;
   }
}

2) Create the result JSP - cookieWrite.jsp - in the WebContent folder of the web application. The JSP displays the cookie sent in the response

<html>
<head>
<script type="text/javascript">

function readCookie(name) {
   var nameEQ = name + "=";
   var ca = document.cookie.split(';');
   for(var i=0;i < ca.length;i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') 
         c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) 
         alert("value of " + name + " cookie is " 
                    +  c.substring(nameEQ.length,c.length));
   }
   return null;
}
</script>
</head>
<body>
Setting cookie that came with the response.<br/><br/>
<a href="javascript:readCookie('firstName')" href="#">Read cookie</a>

</body>
</html>

3) Configure the action in the struts.xml configuration file

<action name="cookieWrite" class="info.icontraining.struts2.CookieWriter">
   <result>/cookieWrite.jsp</result>
</action>

4) Test the code by accessing the URL in the browser,

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

Reading a cookie from the request in Struts2

1) Create an action class - CookieReader.java - in the src folder of the Struts 2 enabled Web Application

package info.icontraining.struts2;

public class CookieReader {
 
   private String message;
   private String userName;
   public static final String SUCCESS = "success";

   public String getUserName() {
      return userName;
   }

   public void setUserName(String userName) {
      this.userName = userName;
   }

   public void setMessage(String message) {
      this.message = message;
   }
   
   public String getMessage() {
      return this.message;
   }
   
   public String execute() throws Exception {
      setMessage("Hello " + getUserName());
      return SUCCESS;
   }
}

2) Create the result JSP - cookieRead.jsp - in the WebContent folder of the web application

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Cookie Read Example</title>
</head>
<body>
   <h1><s:property value="message"/></h1>
</body>
</html>

3) Configure the action in the struts.xml, along with the configuration for the cookie interceptor. The <param> element indicates the name of the cookie that to be read from the request,

<action name="cookieRead" class="info.icontraining.struts2.CookieReader">
   <result>/cookieRead.jsp</result>
   <interceptor-ref name="cookie">
      <param name="cookiesName">userName</param>
   </interceptor-ref>
</action>

4) Create an .html file to set the cookie on the browser - cookieTest.html - add the file to the WebCon tent folder of the web application

<html>
<head>
<script type="text/javascript">
   document.cookie="userName=dinipc";
</script>
</head>
<body>
Cookie userName set.
</body>
</html>

5) Test the example by first accessing the cookieTest.html from the browser. This will set the cookie.

http://localhost:8080/WebAppName/cookieTest.html

Next, access the cookieRead.jsp from the browser

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

September 28, 2011

Changing the Struts2 default .action extension

In order to change the default extension, which is .action, in Struts 2 to something else, configure the <constant> element in the struts.xml configuration file as follows,

<struts>
   
   <constant name="struts.action.extension" value="dud"/>

   <package name="myPackage" extends="struts-default">
   
   ...

   </package>
</struts>

Test the Hello World - Struts 2 example with the following URL in the browser,

http://localhost:8080/WebAppName/Name.dud

Session Management Example in Struts2

0|) Implement the Hello World Example for the Struts 2 framework as explained in this example

1) Modify the execute() method within the HelloWorld.java action class to set a session attribute on the SessionMap object as follows,

public String execute()  {

   ActionContext context = ActionContext.getContext();
     
   ((SessionMap) context.getSession()).put("username", getName());
     
   setCustomGreeting( GREETING + getName() );
   return Action.SUCCESS;
}

2) Modify the Hello.jsp result JSP to add an additional link as follows,

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
  <title>HelloWorld</title>
</head>
<body>

  <h1><s:property value="customGreeting"/></h1>
  <br/><br/>

  <s:a action="Linked">Click here</s:a>
</body>
</html>

3) Add a JSP - linkedPage.jsp - in the WebContent folder of the Web application,

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
  <title>Linked Page</title>
</head>
<body>
   <h1>In Linked Page: <s:property value="%{#session.username}"/></h1>
</body>
</html>

4) Configure the new action in the struts.xml file as follows,

<action name="Linked">
   <result>/linkedPage.jsp</result>
</action>

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

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

Upload a text/binary file to the server using a Servlet

1) Create the UploadFile.html file in the WebContent folder of the web application.

<html>
<head>
<title>Upload File</title>
</head>
<body>

<form action="uploadServlet" enctype="multipart/form-data" method="post">
Specify a file to upload <br/>
<input type="file" name="datafile" size="40">
<br/>
<input type="submit" value="Upload">
</form>

</body>
</html>

2) Create the UploadServlet.java servlet class in the src folder of the web application.

package info.icontraining.servlets;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class UploadServlet extends HttpServlet {

   public void doPost(HttpServletRequest request, HttpServletResponse response) 
                     throws ServletException, IOException {
  
      PrintWriter out = response.getWriter();
      String contentType = request.getContentType();
  
      if ((contentType != null) 
               && (contentType.indexOf("multipart/form-data") >= 0)) {

         DataInputStream in = new DataInputStream(request.getInputStream());

         InputStream is = request.getInputStream();
         int formDataLength = request.getContentLength();
   
         // copy incoming bytes into a byte array
         byte dataBytes[] = new byte[formDataLength];
         int byteRead = 0;
         int totalBytesRead = 0;

         while (totalBytesRead < formDataLength) {
            byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
            totalBytesRead += byteRead;
         } 

         // retrieve uploaded filename
         String file = new String(dataBytes);
         String saveFile = file.substring(file.indexOf("filename=\"") + 10);
         saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
         saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,
                                          saveFile.indexOf("\""));
   
         // clip off the file content
         int lastIndex = contentType.lastIndexOf("=");
         String boundary = contentType.substring(lastIndex + 1, 
                                          contentType.length());
         int pos;
         pos = file.indexOf("filename=\"");
         pos = file.indexOf("\n", pos) + 1;
         pos = file.indexOf("\n", pos) + 1;
         pos = file.indexOf("\n", pos) + 1;
         int boundaryLocation = file.indexOf(boundary, pos) - 4;
         int startPos = ((file.substring(0, pos)).getBytes()).length;
         int endPos = ((file.substring(0, 
                              boundaryLocation)).getBytes()).length; 

         String outputfile = this.getServletContext().getRealPath(saveFile);
         FileOutputStream os = new FileOutputStream (outputfile);

         os.write(dataBytes, startPos, (endPos - startPos));
         os.flush();
         os.close();

         out.println("You have successfully uploaded the file");
      }
   }
}

3) Configure the servlet in the web.xml deployment descriptor present in the WebContent/WEB-INF folder of the web application

<servlet>
   <servlet-name>uploadServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>uploadServlet</servlet-name>
   <url-pattern>/uploadServlet</url-pattern>
</servlet-mapping>

4) Test the code with the following URL in the browser. The file will be uploaded to the context root (folder) of the web application.

http://localhost:8080/WebAppName/UploadFile.html

Retrieve Request Headers in a Servlet

1) Create a Java Servlet class - HeaderTest.java - in the src folder of the Web Application

package info.icontraining.servlets;

import java.io.*;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;

public class HeaderTest extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response)
                     throws ServletException, IOException {
  
      PrintWriter out = response.getWriter();

      Enumeration e = request.getHeaderNames();
      String headerName = null;

      while(e.hasMoreElements()) {
         headerName = (String) e.nextElement();
         out.println(headerName + ": "); 
         out.println(request.getHeader(headerName) + "\n");
      }
  
      out.close();
   }
}

2) Configure the servlet in the web.xml deployment descriptor in the WebContent/WEB-INF folder

<servlet>
   <servlet-name>headerTest</servlet-name>
   <servlet-class>info.icontraining.servlets.HeaderTest</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>headerTest</servlet-name>
   <url-pattern>/headerTest</url-pattern>
</servlet-mapping>

3) Test the servlet with the following URL in the browser,

http://localhost:8080/WebAppName/headerTest

Servlet Filter - Hello World Example

1) Create a MyFilter.java filter class in the src folder of the Web Application

package info.icontraining.filters;

import java.io.IOException;
import javax.servlet.*;

public class MyFilter implements Filter {

   private FilterConfig filterConfig;
 
   public void init(FilterConfig filterConfig) throws ServletException {
      this.filterConfig = filterConfig;
   }
 
   public void destroy() {
      System.out.println("Clean-up code in Filter");
   }

   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  
      System.out.println("Filter processing request");
      chain.doFilter(request, response);
      System.out.println("Filter processing response");
   }
}

2) Configure the filter in the web.xml deployment description in the WebContent/WEB-INF folder, as follows,

<filter>
   <filter-name>myFilter</filter-name>
   <filter-class>info.icontraining.filters.MyFilter</filter-class>
</filter>
<filter-mapping>
   <filter-name>myFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

This filter will intercept requests to all URLs (of servlets, JSPs, etc.) in the Web Application

3) Test the filter by accessing any valid URL (servlet URL or JSP) of the Web Application, and check the server console log,

http://localhost:8080/WebAppName/anyValidURL

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.

September 5, 2011

javax.naming.NoInitialContextException: Cannot instantiate class: org.jboss.naming.NamingContextFactory [Root exception is java.lang.ClassNotFoundException

Topic: Java Message Service (JMS)

Application Server: JBoss 4.2.2 GA

Exception:

javax.naming.NoInitialContextException: Cannot instantiate class: org.jboss.naming.NamingContextFactory [Root exception is java.lang.ClassNotFoundException: org.jboss.naming.NamingContextFactory]
at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.init(Unknown Source)
at javax.naming.InitialContext.(Unknown Source)
at info.icontraining.queue.QueueSenderClient.main(QueueSenderClient.java:27)
Caused by: java.lang.ClassNotFoundException: org.jboss.naming.NamingContextFactory
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at com.sun.naming.internal.VersionHelper12.loadClass(Unknown Source)
... 5 more

Resolution:

This exception is thrown with the JMS client code resides outside the JBoss application server. In order to resolve, add the following jar file to the build path / classpath of the application:

%JBOSS_HOME%\client\jbossall-client.jar