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

Setting up Apache Axis2 in a Web Application

1) Download the required resources for the Apache Axis2 installation from the link here. Unzip the contents of the downloaded zip file.

2) Copy all the jars in the lib folder in the zip file into the WebContent/WEB-INF/lib folder of the web application.

3) Copy the folder axis2-web (and its contents) into the WebContent folder of the web application

4) Copy the conf, modules and services folders into the WebContent/WEB-INF folder of the web application

5) The structure of the Web Application project after the above steps will look like this,

WebAppName
   |
   |--- WebContent
            |
            |--- axis2-web (and all contents of this folder)
            |
            |---WEB-INF
                   |
                   |--- conf (axis2.xml file in this folder)
                   |
                   |--- lib (all jars files in this folder)
                   |
                   |--- modules (*.mar files in this folder)
                   |
                   |--- services (and its contents in this folder)

6) Add the following configuration to the WebContent/WEB-INF/web.xml file of the web application and within its root <web-app> element

<servlet>
   <servlet-name>AxisServlet</servlet-name>
   <servlet-class>org.apache.axis2.transport.http.AxisServlet</servlet-class>
   <load-on-startup>1</load-on-startup>
</servlet>
<servlet>
   <servlet-name>AxisAdminServlet</servlet-name>
   <servlet-class>org.apache.axis2.webapp.AxisAdminServlet</servlet-class>
</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>AxisAdminServlet</servlet-name>
   <url-pattern>/axis2-admin/*</url-pattern>
</servlet-mapping>

<mime-mapping>
   <extension>inc</extension>
   <mime-type>text/plain</mime-type>
</mime-mapping>

<welcome-file-list>
   <welcome-file>index.jsp</welcome-file>
   <welcome-file>index.html</welcome-file>
   <welcome-file>/axis2-web/index.jsp</welcome-file>
</welcome-file-list>

<error-page>
   <error-code>404</error-code>
   <location>/axis2-web/Error/error404.jsp</location>
</error-page>

<error-page>
   <error-code>500</error-code>
   <location>/axis2-web/Error/error500.jsp</location>
</error-page>


7) Deploy the Web Application to the server. Test the installation was successful by accessing the following URL through the browser,

http://localhost:8080/WebAppName/axis2-web/index.jsp

8) Click on the links - Services, Validate and Administration - and check each of the links work.

Note: Use admin/axis2 as username/password to log in as Administrator

Note: If Validate link displays an error message for the Version service, resolve the error from this post here

9) Invoke the Version Web Service with this URL in the browser:

http://localhost:8080/WebAppName/services/Version/getVersionRequest

getVersion Service method error in Apache Axis2 - There was a problem in Axis2 version service , may be the service not available or some thing has gone wrong.

Topic: Apache Axis2

Application Server: JBoss 4.2.2GA

Exception:

Clicking on the Validate link during Apache Axis2 installation shows the following error message:

There was a problem in Axis2 version service , may be the service not available or some thing has gone wrong. But this does not mean system is not working ! Try to upload some other service and check to see whether it is working.

and shows the following stack trace on the server console log:

14:20:11,065 INFO  [STDOUT] 14:20:11,065 ERROR [RPCMessageReceiver] Exception occurred while trying to invoke service method getVersion
org.apache.axis2.AxisFault: namespace mismatch require http://axisversion.sample found http://axisversion.sample/xsd
 at org.apache.axis2.rpc.receivers.RPCUtil.invokeServiceClass(RPCUtil.java:190)
 at org.apache.axis2.rpc.receivers.RPCMessageReceiver.invokeBusinessLogic(RPCMessageReceiver.java:117)
 at org.apache.axis2.receivers.AbstractInOutMessageReceiver.invokeBusinessLogic(AbstractInOutMessageReceiver.java:40)
 at org.apache.axis2.receivers.AbstractMessageReceiver.receive(AbstractMessageReceiver.java:110)
 at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:181)
 at org.apache.axis2.transport.http.HTTPTransportUtils.processHTTPPostRequest(HTTPTransportUtils.java:172)
 at org.apache.axis2.transport.http.AxisServlet.doPost(AxisServlet.java:146)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
 at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:179)
 at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:84)
 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
 at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
 at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:157)
 at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:262)
 at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
 at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
 at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:446)
 at java.lang.Thread.run(Unknown Source)

Resolution:

Open the axis2-web/HappyAxis.jsp and find the following line of code:

OMNamespace omNs = fac.createOMNamespace("http://axisversion.sample/xsd", "ns1");

Modify the above line to the following:

OMNamespace omNs = fac.createOMNamespace("http://axisversion.sample", "ns1");

January 11, 2012

Database Connection Pool Code Example with Apache DBCP and Oracle 10g

1) Download the Apache Commons DBCP and Commons Pool jars from the link here and add them to the classpath / build path of the Java Application / Project.

2) Add the jboss-j2ee.jar file to the class path/build path of the Java Application/Project. The jboss-j2ee.jar file is present in the $JBOSS_HOME/server/default/lib folder of the JBoss Installation folder.

3) Complete the JDBC example at the link here

4) Create a java class - ConnectionPoolExample.java - in the src folder of the Java Application / Project

package info.icontraining.jdbc;

import java.sql.*;
import javax.sql.*;
import org.apache.commons.pool.*;
import org.apache.commons.pool.impl.*;
import org.apache.commons.dbcp.*;

public class ConnectionPoolExample {
 
   private static GenericObjectPool genericPool = new GenericObjectPool();

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

      try {
         Class.forName("oracle.jdbc.OracleDriver");
      } catch (ClassNotFoundException e) {
         e.printStackTrace();
      }

      DataSource dataSource = setupDataSource("jdbc:oracle:thin:system/system@localhost:1521:xe");

      Connection conn = null;
      Statement stmt = null;
      ResultSet rs = null;

      try {
         conn = dataSource.getConnection();
         stmt = conn.createStatement();
         rs = stmt.executeQuery("SELECT * FROM DUAL");
            
         while(rs.next()) {
            for(int i=1; i<=rs.getMetaData().getColumnCount(); i++) {
               System.out.println(rs.getString(i));
            }
         }
            
         System.out.println("Active Connections: " + genericPool.getNumActive() + ", Idle Connections: " + genericPool.getNumIdle());
            
      } catch(SQLException e) {
         e.printStackTrace();
      } finally {
         try { if (rs != null) rs.close(); } catch(Exception e) { }
         try { if (stmt != null) stmt.close(); } catch(Exception e) { }
         try { if (conn != null) conn.close(); } catch(Exception e) { }
      }
        
      System.out.println("Active Connections: " + genericPool.getNumActive() + ", Idle Connections: " + genericPool.getNumIdle());
   }

   public static DataSource setupDataSource(String connectURI) throws Exception {
      ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI,null);
      KeyedObjectPoolFactory kopf =new GenericKeyedObjectPoolFactory(null);

      PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory( connectionFactory, genericPool, kopf, null, false, true);

      for(int i = 0; i < 5; i++) {
         genericPool.addObject();
      }

      System.out.println("Active Connections: " + genericPool.getNumActive() + ", Idle Connections: " + genericPool.getNumIdle());
        
      PoolingDataSource dataSource = new PoolingDataSource(genericPool);
      return dataSource;
   }
}


5) Run the code as a standalone Java Application

January 1, 2012

JDBC Code to read BLOB data type from database table

0) Complete the example to store an image (BLOB data) to a table at the link here

1) Create a Java class - JdbcBlobReader.java - in the src folder of the Java Project / application

package info.icontraining.jdbc;

import java.io.*;
import java.sql.*;

public class JdbcBlobReader {
 
   public static void main(String[] args) throws Exception, IOException, SQLException {
   
      Class.forName("oracle.jdbc.OracleDriver");
      Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","system");

      PreparedStatement pstmt = conn.prepareStatement("Select name, image from MyImages");
      ResultSet rs = pstmt.executeQuery();
      
      while (rs.next()) {
         String name = rs.getString(1);
         String description = rs.getString(2);
         File image = new File("src/icon-training-downloaded.jpg");
         FileOutputStream fos = new FileOutputStream(image);

         byte[] buffer = new byte[1];
         InputStream is = rs.getBinaryStream(2);

         while (is.read(buffer) > 0) {
            fos.write(buffer);
         }

         fos.close();
      }

      conn.close();    
   }
}

2) Run the code as a standalone Java Application

JDBC Code to insert an image in a BLOB column

0) Complete the first 5 steps in the JDBC code example at the link here

1) Create a new table in the database using the following CREATE TABLE command

create table MyImages (
   name VARCHAR(1000),
   image BLOB
);

2) Add the image file to the src folder of the Java Project/Application







3) Create a Java class - JdbcBlobExample.java - to the src folder of the Java Project/Application

package info.icontraining.jdbc;

import java.io.*;
import java.sql.*;

public class JdbcBlobExample {
 
   public static void main(String[] args) throws Exception, IOException, SQLException {
   
      Class.forName("oracle.jdbc.OracleDriver");
      Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","system");

      FileInputStream fis = null;
      PreparedStatement pstmt = null;
    
      try {
         conn.setAutoCommit(false);
      
         File file = new File("src/icon-training.jpg");
         fis = new FileInputStream(file);
      
         pstmt = conn.prepareStatement("insert into MyImages(name, image) values (?, ?)");
      
         pstmt.setString(1, "Icon Training Logo");
         pstmt.setBinaryStream(2, fis, (int) file.length());
      
         pstmt.executeUpdate();
         conn.commit();
      
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         pstmt.close();
         fis.close();
      }
   }
}

4) Run the code as a standalone Java Application

JDBC Transaction Management Code Example

0) Complete the first 6 steps in the JDBC Code example at the link here

1) Create a Java class - JdbcTransactionMgmt.java - in the src folder of the Java Project /Application

package info.icontraining.jdbc;

import java.sql.*;

public class JdbcTransactionMgmt {

   public static void main(String[] args) throws SQLException, ClassNotFoundException {

      Class.forName("oracle.jdbc.OracleDriver");
      Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","system");
      PreparedStatement pstmt = null;
  
      conn.setAutoCommit(false); // start of transaction
  
      try {
         pstmt = conn.prepareStatement("insert into jdbcdemo values (?, ?, ?, ?)");

         pstmt.setString(1, "Ramesh");
         pstmt.setString(2, "PC");
         pstmt.setInt(3, 32);

         Date d = new Date(0);
         pstmt.setDate(4, d.valueOf("1978-9-28"));

         int rowsAffected = pstmt.executeUpdate();
         System.out.println(rowsAffected + " rows affected.");

         // deliberately cause an exception to be thrown
         int i = 3/0;    // comment this line for commit to happen 

         pstmt.setString(1, "Gunjan");
         pstmt.setString(2, "C");
         pstmt.setInt(3, 26);
         pstmt.setDate(4, d.valueOf("1984-10-30"));

         rowsAffected = pstmt.executeUpdate();
         System.out.println(rowsAffected + " rows affected.");

         conn.commit();

         pstmt.close();

      } catch (Exception e) {
         conn.rollback();
         System.err.println("Caught Exception & transaction rollbacked");
      }

      conn.close(); 
   }
}

2) Run the code as a standalone Java application.
Since the code throws an exception, which is caught, and the transaction is rolled-back, no changes reflect in the database table, even though one row was, apparently, successfully inserted.

3) Comment the line that deliberately throws an exception and run the code as a standalone Java application.
Now, both rows are inserted because the transaction gets committed successfully.

JDBC Prepared Statement Code Example

0) Complete the first 6 steps in the JDBC Code Example at the link here

1) Create a java class - JdbcPSExample.java - to the src folder of the Java Project / Application


package info.icontraining.jdbc;

import java.sql.*;

public class JdbcPSExample {

   public static void main(String[] args) throws SQLException, ClassNotFoundException {
  
      Class.forName("oracle.jdbc.OracleDriver");
      Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","system");
      PreparedStatement pstmt = conn.prepareStatement("insert into jdbcdemo values (?, ?, ?, ?)");
  
      pstmt.setString(1, "Dinesh");
      pstmt.setString(2, "PC");
      pstmt.setInt(3, 32);
  
      Date d = new Date(0);
      pstmt.setDate(4, d.valueOf("1978-9-28"));

      int rowsAffected = pstmt.executeUpdate();
      System.out.println(rowsAffected + " rows affected.");

      pstmt.setString(1, "Tanvi");
      pstmt.setString(2, "C");
      pstmt.setInt(3, 26);
      pstmt.setDate(4, d.valueOf("1984-10-30"));
  
      rowsAffected = pstmt.executeUpdate();
      System.out.println(rowsAffected + " rows affected.");

      pstmt.close();
      conn.close(); 
   }
}


3) Run the Example as a standalone Java Application

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

Spring Bean Scope Demo - Prototype & Singleton

1) Create 2 beans - PrototypeBean.java & SingletonBean.java - in the src folder of the web application

package info.icontraining.spring;

public class PrototypeBean {
   private int i;
 
   public PrototypeBean() {
      i = 3;
   }
 
   public void changeValue() {
      i = 5;
   }
 
   public int getValue() {
      return i;
   }
}



package info.icontraining.spring;

public class SingletonBean {

   private int i;
 
   public SingletonBean() {
      i = 3;
   }
 
   public void changeValue() {
      i = 5;
   }
 
   public int getValue() {
      return i;
   } 
}

2) Configure both beans in the WebContent/WEB-INF/applicationContext.xml file - the PrototypeBean bean is configured with the scope attribute set to 'prototype'

<bean id="singleton" class="info.icontraining.spring.SingletonBean" />
 
<bean id="prototype" class="info.icontraining.spring.PrototypeBean" scope="prototype" />

3) Create a client JSP - singletonPrototypeDemo.jsp - in the WebContent folder of the web application

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

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

 SingletonBean s1 = (SingletonBean)factory.getBean("singleton");
 s1.changeValue();
 
 SingletonBean s2 = (SingletonBean)factory.getBean("singleton"); 
 %>
 
 <%= "SingletonBean on Reference-1 after changing value = " + s1.getValue() %><br/>
 <%= "SingletonBean on Reference-2 without changing value = " + s2.getValue() %>

<br/><br/>

<% 
 PrototypeBean p1 = (PrototypeBean)factory.getBean("prototype");
 p1.changeValue();
 
 PrototypeBean p2 = (PrototypeBean)factory.getBean("prototype"); 
 %>

 <%= "PrototypeBean on Reference-1 after changing value = " + p1.getValue() %><br/>
 <%= "PrototypeBean on Reference-2 without changing value = " + p2.getValue() %>

</body>
</html>

4) Test the example with the following URL in the browser

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

Breaking a large applicationContext.xml configuration file into multiple files

0) Complete the Spring Framework Hello World example at this link

1) Create a new configuration file - applicationContext2.xml - in the WebContent/WEB-INF folder of the web application. Make sure that the root <beans> element is the same as in the applicationContext.xml

Move the <bean> configuration for the greetingService bean to the new configuration file and delete it from the applicationContext.xml

2) Modify the configuration in the web.xml by adding the new configuration file name, as follows,

<context-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>/WEB-INF/applicationContext.xml /WEB-INF/applicationContext2.xml</param-value>
  </context-param>

3) Test the Hello World example as in the Hello World example

Initializing, Destroying Spring Beans & instantiating a Spring Bean through a factory method

1) Create an interface - InitDestroyDemo.java - in the src folder of the web application

package info.icontraining.spring;

public interface InitDestroyDemo {
   public void businessMethod();
}


2) Create a Spring Bean that implements the interface - InitDestroyDemoImpl.java - in the src folder of the web application

package info.icontraining.spring;

public class InitDestroyDemoImpl implements InitDestroyDemo {

   private InitDestroyDemoImpl() { }
 
   public void myInitMethod() {
      System.out.println("Inside Init Method of Spring Bean");
   }
 
   public void businessMethod() {
      System.out.println("Inside Business Method of Spring Bean");
   }
 
   public void myDestroyMethod() {
      System.out.println("Inside Destroy Method of Spring Bean");
   }
 
   public static InitDestroyDemo getInstance() {
      return new InitDestroyDemoImpl();
   }
}


3) Configure the Spring Bean in the WebContent/WEB-INF/applicationContext.xml file

The bean is configured with an initializing method using the init-method attribute, with a destroying method using the destroy-method attribute.

The constructor of the bean is made private, and instantiation is instead done through a static factory method, getInstance() - this is configured using the factory-method attribute

<bean id="initDestroyDemo" class="info.icontraining.spring.InitDestroyDemoImpl" init-method="myInitMethod" destroy-method="myDestroyMethod" factory-method="getInstance" />


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

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

View output on Server console

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

 InitDestroyDemo test = (InitDestroyDemo)factory.getBean("initDestroyDemo");
 test.businessMethod();
 
 %>
</body>
</html>


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

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

November 27, 2011

Anonymous Arrays Code Example

Anonymous Arrays in Java are those arrays that are constructed without specifying the size nor assigned a reference. Anonymous arrays are created on-the-fly when needed and cannot be re-accessed (since there is no reference available to the array object), therefore they become eligible for garbage-collection as soon as the code that uses it completes it.

package info.icontraining.core;

public class AnonymousArrays {

   public static void main(String[] args) {
  
      int[] arr1 = {1, 2, 3, 4, 5};
  
      for(int i: arr1) {
         System.out.print(i);
      }
  
      for(int i: new int[]{1, 2, 3, 4, 5} ) {
         System.out.print(i);
      }  
   }
}

November 26, 2011

Writing Unicode characters in Java

Create the following class in the src folder of the Java Project in Eclipse


package info.icontraining.core;

public class CharExample {

   public static void main(String args[]) {
 
      char c='\u0915';
      System.out.println(c);
   } 
}


To enabled Unicode character display in the console of Eclipse, make the following 3 configurations in Eclipse:

1) Open the "Run" menu > Choose "Open Run Dialog ..." > Choose your application and the particular class (in this case, CharExample) > Click on the "Common" tab > Choose "Console Encoding" as "Other" and "UTF-8" from the drop-down list

2) Next, go on the "Arguments" tab > Copy the string "-Dfile.encoding=UTF-8" in the VM arguments text area (without the double quotes). Click "Apply" and then "Close".

3) Finally, go to the "Window" menu > Choose "Preferences ..." > Next, choose "General" > Then "Workspace" > In the "Text File Encoding" select "Other" and "UTF-8" from the drop-down list

October 9, 2011

Access Modifiers for Class members in Java

There are 3 access modifiers for class members: public, private, protected
and 4 access levels: public, private, protected, default (none of the modifiers present)

public access level
A public member (variable or method) can be accessed from another class regardless of the package in which the other class is present.
public members can be inherited by a subclass regardless of the package in which the subclass is present.

package info.icontraining.p1;
public class Test {
   public int i;           // public member variable
}

package info.icontraining.p2;
import info.icontraining.p1.Test;
public class A {
   public void m1() {
      Test t = new Test();
      t.i = 3;       // public members can be accessed 
                     // by code in another class that is
   }                 // present in a different package 
}

package info.icontraining.p2;

import info.icontraining.p1.Test;
public class B extends Test {
   public void m1() {
      i = 3;         // public members can be inherited
   }                 // by another class that is present
}                    // in a different package


private access level
A private member cannot be accessed by code in any class except by code in the class in which the private member is present.
private members cannot be inherited by any subclass.

package info.icontraining.p1;
public class Test {
   private int i;           // private member variable
   public void m1() {
      i = 3;           // private members can be accessed
   }                   // only by code within the class
}                      // in which it is declared

package info.icontraining.p1;
public class A {
   public void method1() {
      Test t = new Test();
      t.i = 3;           // this line will not compile
   }
}

package info.icontraining.p1;
public class B extends Test {
   public void method1() {
      i = 3;            // this line will not compile
   }
}

default access level
A default member can be accessed from another class if both classes are present in the same package.
default members can be inherited by a subclass is both classes are present in the same package.

package info.icontraining.p1;
public class Test {
   int i;              // default member variable
}

package info.icontraining.p1;
public class A {
   public void m1() {
      Test t = new Test();
      t.i = 3;         // can be accessed by a class
   }                   // in same package
}

package info.icontraining.p1;
public class B extends Test {
   public void m2 {
      i = 3;       // can be inherited by a class
   }               // in same package
}

package info.icontraining.p2;
import info.icontraining.p1.Test;
public class C {
   public void m1() {
      Test t = new Test();
      t.i = 3;         // will not compile, cannot be 
   }                   // accessed in another package
}

package info.icontraining.p2;
import info.icontraining.p1.Test;
public class D extends Test {
   public void m2 {
      i = 3;       // will not compile, cannot be
   }               // inherited in another package
}

protected access level
A protected member can be accessed by another class in the same package only.
However, protected members can be inherited by a subclass present in a different package also.


package info.icontraining.p1;
public class Test {
   protected int i;              // protected member variable
}

package info.icontraining.p1;
public class A {
   public void m1() {
      Test t = new Test();
      t.i = 3;         // can be accessed by a class
   }                   // in same package
}

package info.icontraining.p1;
public class B extends Test {
   public void m2 {
      i = 3;       // can be inherited by a class
   }               // in same package
}

package info.icontraining.p2;
import info.icontraining.p1.Test;
public class C {
   public void m1() {
      Test t = new Test();
      t.i = 3;         // will not compile, cannot be
   }                   // accessed in another package
}

package info.icontraining.p2;
import info.icontraining.p1.Test;
public class D extends Test {
   public void m2 {
      i = 3;       // can be inherited by a class
   }               // in another package
}

October 8, 2011

Timer Interval functions in Javascript

Code Example


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

var timerId;

var setAlerts = function() {
   timerId = setInterval("myfunction();",3000);
}

var removeAlerts = function() {
   clearInterval(timerId);
}

function myfunction() {
   alert("Hi");
}

window.onload = function() {
   document.getElementById("setButton").onclick=setAlerts;
   document.getElementById("clearButton").onclick=removeAlerts;
}

</script>
</head>
<body>

<button id="setButton">Set Interval</button><br/>
<button id="clearButton">Clear Interval</button><br/>

</body>
</html>

Javascript to set cookies and get hold of a specific cookie

Write Javascript code to store a cookie and retrieve it - also check if cookies are enabled on the client.

Solution

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

var cookieFunction = function() {
   
if (navigator.cookieEnabled) {
var name = prompt("Enter cookie name");
      var value= prompt("Enter cookie value");
      if ((name) && (value)) {
         var date = new Date("1 Jan 2015 11:30:00");
         document.cookie= name + "="+value+"; expires="+date.toGMTString()+";";
      }
   } else {
      alert("Cookies Not enabled");
   }
}

var getCookie = function() {
   var cookies=document.cookie;
   alert(cookies);
}

var getSpecificCookie = function() {
   var c_name = prompt("Enter cookie name");
   var all_cookies = document.cookie.split( ';' );
   for (i=0;i<all_cookies.length;i++) {
      x = all_cookies[i].substr(0, all_cookies[i].indexOf("="));
      y = all_cookies[i].substr(all_cookies[i].indexOf("=")+1);
      x = x.replace(/^\s+|\s+$/g,"");
      if (x == c_name) {
        alert( unescape(y));
        return;
     }
   }

   alert("Cookie does not exist");
}

window.onload = function() {
   document.getElementById("getCookieButton").onclick=getCookie;
   document.getElementById("getSpecificCookieButton").onclick=getSpecificCookie;
   document.getElementById("diceButton").onclick=rollDice;
}

</script>
</head>
<body>
<button id="cookieButton">Set Cookie</button>
<button id="getCookieButton">Get Cookies</button>
<button id="getSpecificCookieButton">Get Specific Cookie</button>

</body>
</html>

Javascript simulation of rolling of a dice


Write Javascript code to simulate the rolling of a dice. When the user clicks a button, the result should be the simulation of a dice - a value between 1 to 6 is displayed in the String, "Your roll of the dice displayed 3"

Hint: Math.random(), document.getElementById(), innerHTML, onclick event

Solution


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

var rollDice = function() {
   var diceElementNode = document.getElementById("diceValue");
   var diceElementNodeChildren = diceElementNode.childNodes;

   if (diceElementNodeChildren[0] != null) {
      diceElementNodeChildren[0].nodeValue = "The dice value is " + Math.ceil((Math.random() * 6));
   } else {
      var diceTextNode = document.createTextNode("");
      diceTextNode.nodeValue ="The dice value is " + Math.ceil((Math.random() * 6));
      diceElementNode.appendChild(diceTextNode);
   }
}

window.onload = function() {
   document.getElementById("diceButton").onclick=rollDice;
}

</script>
</head>
<body>
<button id="diceButton">Roll Dice</button>
<div id="diceValue"></div>

</body>
</html>

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();
   }
}