Monday, April 30, 2012

Java: File searching program

To search a particular file recursively

Let’s see a Java program which will search a particular file recursively. In this example we will provide a root path from where it will search a particular file recursively. Either you can search a file by its name or you can provide a valid regular expression.

Using this logic you can implement a file searcher program.

About the example:

Logic behind this program is very simple; it searches a root folder recursively. If the current path is a directory then it will call the same function searchFile(String path, String search) again and again till the particular node file is reached. Now if it is a node file then it will search for the String or the given regular expression.

Let’s see a simple self explanatory java code. No need to add any jar file, directly you can run below the below program and see the output. Just provide a root path and String or valid regular expression to search.

/* SearchFile.java */

import java.io.File;

public class SearchFile {

 /* path : provide root directory from where it will search recursively.
  * search : String or valid regular expression. 
  */ 
 public void searchFile(String path,String search) {
  
  File file = new File(path);
  
  //System.out.println("Searching.."+file.getAbsolutePath());
  
  if(file.isDirectory()) {
   File[] allFilesInDirectory = file.listFiles();
   
   for (File eachFile : allFilesInDirectory) {  
    searchFile(eachFile.getAbsolutePath(),search);
   }
  }
  else {
   if(file.getName().matches(search)) {
    System.out.println("File Found >> "+file.getAbsolutePath());
   }
  }
 }
 public static void main(String[] args) {
  
  SearchFile serchObj = new SearchFile();
  //It will search for a jar file in C drive
  serchObj.searchFile("C:/",".*jar");
 }

}

Java : Read / Write excel (.xls) file

Lets see how we can create excel (.xls) file in Java. Below example show how to write a xls file.

Java Excel API is a mature, open source java API enabling developers to read, write, and modifiy Excel spreadsheets dynamically.

Lets look at a Simple Example, which can be used for reading, writing Excel (.xls) file, Even it's cell can be formatted according to our requirement.

To know more about Java Excel API Click here

In this example we will first create Excel file (Sample.xls) using writeXLSFile() method and then we will read same Excel file (Sample.xls) using readXLSFile() method

For Java Excel API Click here

To run below example you will need to Download jxl.jar file, Click here to download.

Assuming you have set jxl.jar in classpath, Lets see a simple self explanatory example.


Friday, April 27, 2012

Liferay : Target "depoly" does not exist in the project "my-greeting-portlet"

After creating a portlet, as mentioned in liferay documentation.While deploying it to tomcat, below mentioned error was seen.

Target "depoly" does not exist in the project "my-greeting-portlet"

Please see the commands below.

C:\liferay-plugins-sdk-6.0.5\portlets>create.bat my-greeting "My Greeting"
Buildfile: C:\liferay-plugins-sdk-6.0.5\portlets\build.xml

create:
    [unzip] Expanding: C:\liferay-plugins-sdk-6.0.5\portlets\portlet.zip into C:
\liferay-plugins-sdk-6.0.5\portlets\my-greeting-portlet
    [mkdir] Created dir: C:\liferay-plugins-sdk-6.0.5\portlets\my-greeting-portl
et\docroot\WEB-INF\tld
     [copy] Copying 6 files to C:\liferay-plugins-sdk-6.0.5\portlets\my-greeting
-portlet\docroot\WEB-INF\tld

BUILD SUCCESSFUL
Total time: 4 seconds

C:\liferay-plugins-sdk-6.0.5\portlets>

While deploying using ant deploy command, below mentioned error was seen.

C:\liferay-plugins-sdk-6.0.5\portlets>cd my-greeting-portlet

C:\liferay-plugins-sdk-6.0.5\portlets\my-greeting-portlet>ant deploy
Buildfile: C:\liferay-plugins-sdk-6.0.5\portlets\my-greeting-portlet\build.xml

BUILD FAILED
Target "depoly" does not exist in the project "my-greeting-portlet".

C:\liferay-plugins-sdk-6.0.5\portlets\my-greeting-portlet>

Java : Simple AES Cryptography example

Advanced Encryption Standard (AES) is a specification for the encryption of electronic data. It has been adopted by the U.S. government and is now used worldwide. It supersedes DES.[3] The algorithm described by AES is a symmetric-key algorithm, meaning the same key is used for both encrypting and decrypting the data. (To know more click here).

To run this example you will need below mentioned JAR files in classpath.
  • jce.jar
  • rt.jar

If you are using JDK 6 or higher version, These JAR files are implicitly present. You can cross verify in JRE folder. Probably in "C:\Program Files\Java\jre6\lib"

Hence C:\Program Files\Java\jre6\lib\jce.jar and C:\Program Files\Java\jre6\lib\rt.jar are implicitly set in your classpath. Below is the sample self explanatory Java program using AES Cipher. Directly you can run the program and see output.

Simple AES Cipher Example in java

/* SimpleCryptography.java */

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class SimpleCryptography {
    
    private String AlgoName = "AES";
    
    private String keyString = "Desire_SecretKey";
    
    public String encrypt(String sValue) throws Exception {
        
        SecretKeySpec skeySpec = new SecretKeySpec(keyString.getBytes(), AlgoName);
        Cipher cipher = Cipher.getInstance(AlgoName);
        
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        
        byte[] encrypted = cipher.doFinal(sValue.getBytes());
        
        BASE64Encoder bASE64Encoder = new BASE64Encoder();
        String enStr = bASE64Encoder.encodeBuffer(encrypted);    
        
        return enStr;
    }
    
    public String decrypt(String sValue) throws Exception {
        
        SecretKeySpec skeySpec = new SecretKeySpec(keyString.getBytes(), AlgoName);
        Cipher cipher = Cipher.getInstance(AlgoName);
        
        BASE64Decoder bASE64Decoder = new BASE64Decoder();
        byte decrytByt[] = bASE64Decoder.decodeBuffer(sValue);
        
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        
        byte decrypted[] = cipher.doFinal(decrytByt);
        
        String deStr = new String(decrypted).trim();
        
        return deStr;
    }
    
    public static void main(String[] args) throws Exception {
        
        SimpleCryptography obj = new SimpleCryptography();
        
        String password = "MadanChaudhary";
        
        System.out.println("password : "+password);
        
        String encrypted_password = obj.encrypt(password);
        
        System.out.println("encrypted_password : "+encrypted_password);
        
        String decrypted_password = obj.decrypt(encrypted_password);
        
        System.out.println("decrypted_password : "+decrypted_password);

    }
}

Wednesday, April 25, 2012

Java: Generate random numeric, alphabetic and alphanumeric numbers

In java many times you may require to generate random numbers. Random number could be numeric, alphabetic or both alphanumeric. Let’s see a java program which generates random numbers. You can also customize length of the number. Directly you can run the below codes and see the output no need to add any jar files.

About the example:

We have 3 methods randomAlphabetic(), randomNumeric() and randomAlphanumeric() which generates alphabetic, numeric and alphanumeric numbers respectively. Just provide the length of the number and see the output. Let’s see the self explanatory code.


/* RandomNumber.java */

import java.util.Random;

public class RandomNumber {

 private static final Random RANDOM = new Random();
 
 private String random(int length, boolean num,boolean alpha) {
  
  StringBuffer result = new StringBuffer();
  char c = 0;

  int min = 48;
  int max = 90;

  int i=0;

  while(i<length) {

   c = (char) (RANDOM.nextInt(max - min) + min);

   if((num && Character.isDigit(c)) || 
   (alpha && Character.isLetter(c)) || 
   (num && alpha && Character.isLetterOrDigit(c))) {
    result.append(c);
    i++;
   }
  }   
  return result.toString();  
 }
 
 //Function to generate only alphabetic numbers
 public String randomAlphabetic(int length) {
  
   return random(length,false,true);
  }
 
 //Function to generate only numeric numbers
  public String randomNumeric(int length) {
  
   return random(length,true,false);
  }
  
 //Function to generate alphanumeric numbers
  public String randomAlphanumeric(int length) {
   
   return random(length,true,true);
  }

 public static void main(String[] args) {

  RandomNumber obj = new RandomNumber();
  
  System.out.println(obj.randomAlphabetic(5));
  System.out.println(obj.randomNumeric(10));
  System.out.println(obj.randomAlphanumeric(15));

 }

}

Note : If you want to generate random unique numbers just add it to Set to make sure that all numbers are unique.

Tuesday, April 24, 2012

Step by step guide to consume a web service

Consuming a web service is very easy all you need to have a WSDL url and an IDE i.e Eclipse for creating web service client. Provide WSDL url and download the stubs. Below mentioned files are automatically generated by WSDL.

Lets create a simple web service client.

Step by step process to create web service client. Please see the screen shots below.





How to create a form in Liferay

You may need to create a form in liferay. As you may be aware that in liferay every page consists of portlets, hence to create a form you need to create a portlet.
Below example shows how to create a form in liferay. In this example we have a view.jsp which contains form fields and the form is submitted to another jsp (i.e. submit.jsp)

To submit the form in liferay you need to create a renderURL as shown below. Please see the self explanatory example below.

view.jsp

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui" %>

<portlet:renderURL var="submitURL">
 <portlet:param name="jspPage" value="/submit.jsp" />
</portlet:renderURL>

<aui:form action="<%= submitURL %>" method="post">

 <aui:input label="First name" name="fName" type="text" value=""/>
 <aui:input label="Last name" name="lName" type="text" value=""/>
 <aui:input label="Password" name="password" type="password" value=""/>

 <b>Gender</b>
 <aui:input label="Male" name="gender" type="radio" value="Male"/>
 <aui:input label="Female" name="gender" type="radio" value="Female"/>

 <b>Language</b>
 <aui:input label="C" name="lang" type="checkbox" value="C"/>
 <aui:input label="Java" name="lang" type="checkbox" value="Java"/>
 <aui:input label="Perl" name="lang" type="checkbox" value="Perl"/>

 <aui:input name="hiddenValue" type="hidden" value="hide it"/>

 <aui:button type="submit" value="Submit Form"/>
 <aui:button type="reset" value="Reset Values"/>

</aui:form>

Saturday, April 21, 2012

Step by step guide to publish a simple Hello World web service using tomcat

For running this example, below mentioned particulars are used.
  • Tomcat 7.0.11
  • JDK 1.6.0_21
  • MyEclipse 8.6

In this example, We have an interface HelloWS which contains a abstract method sayHello() which is to be exposed and a class HelloWSImpl.java which will implement HelloWS. Please go through each of the screen shots.

Creating a New Web Service Project

























Friday, April 20, 2012

Java Examples for JSON encoding

JSON (JavaScript Object Notation) is a lightweight data-interchange format. JSON is syntax for storing and exchanging text information same like XML. JSON is smaller than XML, and faster and easier to parse.

To know more about JSON, visit http://www.json.org/
Java API http://www.json.org/java/

Json can be used to commincate between Java & Javascript and vice versa. Lets see a simple self explanatory example.

About the example :
A simple JSP page which contains Java instance of JSONObject. This object is converted to String and passed to eval() function in javascript to convert into JSONObject object in Javascript.

To run below example you need to include json-simple-1.1.1.jar in classpath. Download the JAR file from http://code.google.com/p/json-simple/

<%@ page import="org.json.simple.JSONObject" %>
<%
 JSONObject jObject = new JSONObject();

 jObject.put("EmployeeId",new Integer(121));
 jObject.put("Name","Ramesh");  
 jObject.put("Salary",new Double(15000.00));
 jObject.put("isPermanent",new Boolean(true));
 jObject.put("Nickname",null);

 String jsonText = jObject.toJSONString();

 System.out.println("jsonText :: "+jsonText);
%>
<html>
<head>
<script type="text/javascript">
 function loadJsonObject()
 {
  var JSONObject = eval('(<%= jsonText %>)');

  document.getElementById("jId").innerHTML=JSONObject.EmployeeId;
  document.getElementById("jName").innerHTML=JSONObject.Name;
  document.getElementById("jSalary").innerHTML=JSONObject.Salary;
  document.getElementById("jParmanent").innerHTML=JSONObject.isPermanent;
  document.getElementById("jNickname").innerHTML=JSONObject.Nickname;

 }
</script>
</head>
<body onload="loadJsonObject()">
<h2>Simple JSON Example</h2>
<p>
<table border="1" width="100%">
<tr>
 <td>Employee Id</td>
 <td><span id="jId"></span</td>
</tr>
<tr>
 <td>Name</td>
 <td><span id="jName"></span></td>
</tr>
<tr>
 <td>Salary</td>
 <td><span id="jSalary"></span></td>
</tr>
<tr>
 <td>Is Permananet</td>
 <td><span id="jParmanent"></span></td>
</tr>
<tr>
 <td>Nickname</td>
 <td><span id="jNickname"></span></td>
</tr>
</table>
</body>
</html>

Output :






Note : If you get mentioned errors.
  • Only a type can be imported. org.json.simple.JSONObject resolves to a package
  • JSONObject cannot be resolved to a type
Crosscheck if json-simple-1.1.1.jar is set in classpath. Simply add the JAR file to ${Tomcat}/lib/ folder. Please download json-simple-1.1.1.jar file from http://code.google.com/p/json-simple/ and set it to classpath.

Wednesday, April 18, 2012

Singleton Design Pattern example

Singleton is the simplest design pattern and very easy to remember. As the name suggest singleton, it is used to ensure that a class has a single instance and provide a global point of access to it. Use Singleton Pattern when there must be exactly one instance of class,and it must be accessible to clients from well known access point.

The singleton class is instantiated at the time of first access and the same instance is used thereafter till the application quits.

Singleton Examples :

Clipboard Class for providing application specific copy-and-paste functionality

Step by step process to create a Singleton class.

Lets say we have a class Clipboard.java as shown below

public class Clipboard {
 private String copy;
 private String paste;

 //..
}

Client code can create as many instance as required

Clipboard instance1 = new Clipboard();
Clipboard instance2 = new Clipboard();

Now the question is How do we prevent clients from creating multiple objects? For this we can have a private constructor so that it cannot be subclassed or object cannot be created from codes outside this class.

public class Clipboard {
 private String copy;
 private String paste;
 
 private Clipboard() {

 }
 //..
}

Then how do we ensure the clients get a single instance of his class instantiated and access it? We can have a static Clipboard instance declared and a static getInstance() method which will return Clipboard object.

Lets see the complete code.

public class Clipboard {
 private String copy;
 private String paste;

 private static Clipboard instance;
 
 private Clipboard() {

 }

 public static Clipboard getInstance() {
  if(instance == null) {
   instance = new Clipboard();
  }
  return instance;
 }
 //..
}

It is also advisable to override the clone() method of the java.lang.Object class and throw CloneNotSupportedException so that another instance cannot be created by cloning the singleton object.

@Override
protected Object clone() throws CloneNotSupportedException { 
 throw new CloneNotSupportedException("Clone is not allowed.");     
} 


To avoid thread safety issues, you can also implement as shown below.

public class Clipboard {
 private String copy;
 private String paste;

 private static final Clipboard INSTANCE = new Clipboard();
 
 private Clipboard() {

 }

 public static synchronized Clipboard getInstance() {
  return INSTANCE;
 }
}

Monday, April 16, 2012

Liferay : How to call another portlet of another page

In Liferay you may need to call another portlet of another page. Lets see how we can communicate between pages and portlets.

Please follow below mentioned steps for portlet communication accross pages.

1. Add tag library as shown below

<%@ taglib uri="http://liferay.com/tld/portlet" prefix="liferay-portlet"%>

2. Import below mentioned classes

<%@ page import='com.liferay.portal.theme.PortletDisplay' %>
<%@ page import='com.liferay.portal.theme.ThemeDisplay' %>
<%@ page import='com.liferay.portal.kernel.util.WebKeys'%>


3. Get portlet id and portlet name of the JSP which need to be called. Add below codes to the JSP which need to be called.

Note : You may need to save portlet id and portlet name in session, property file etc and pass those values in calling JSP.

<%
 ThemeDisplay themeDisplay = (ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
 PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();
 long portletId = themeDisplay.getPlid();
 String portletName = portletDisplay.getId();

%>


4.  Create renderURL. Get portlet id and portlet name from stored session, property file etc and pass here for creating render url.

<liferay-portlet:renderURL var="URLName" plid="<%= portletId %>" portletName="<%= portletName %>" >
<liferay-portlet:param name="jspPage" value="/html/portletName/jspFile.jsp" />
<liferay-portlet:param name="param1" value="<%= param1 %>"></liferay-portlet:param>
<liferay-portlet:param name="param2" value="<%= param2 %>"></liferay-portlet:param>
</liferay-portlet:renderURL>


<a href="<%= URLName %>">Click Here</a>

Thursday, April 12, 2012

SEVERE: WSSERVLET11: failed to parse runtime descriptor: class:

If you get below mentioned Exception,

SEVERE: WSSERVLET11: failed to parse runtime descriptor: class: Bounceable could not be found
com.sun.xml.ws.model.RuntimeModelerException: class: Bounceable could not be found
                at com.sun.xml.ws.model.RuntimeModeler.getPortTypeName(RuntimeModeler.java:1574)
                at com.sun.xml.ws.model.RuntimeModeler.getPortTypeName(RuntimeModeler.java:1558)
                at com.sun.xml.ws.server.EndpointFactory.create(EndpointFactory.java:225)
                at com.sun.xml.ws.server.EndpointFactory.createEndpoint(EndpointFactory.java:145)
                at com.sun.xml.ws.api.server.WSEndpoint.create(WSEndpoint.java:569)
                at com.sun.xml.ws.api.server.WSEndpoint.create(WSEndpoint.java:552)
                at com.sun.xml.ws.transport.http.DeploymentDescriptorParser.parseAdapters(DeploymentDescriptorParser.java:261)
                at com.sun.xml.ws.transport.http.DeploymentDescriptorParser.parse(DeploymentDescriptorParser.java:153)
                at com.sun.xml.ws.transport.http.servlet.WSServletContextListener.parseAdaptersAndCreateDelegate(WSServletContextListener.java:131)
                at com.sun.xml.ws.transport.http.servlet.WSServletContextListener.contextInitialized(WSServletContextListener.java:152)
                at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4681)
                at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5184)
                at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5179)
                at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
                at java.util.concurrent.FutureTask.run(FutureTask.java:138)
                at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
                at java.lang.Thread.run(Thread.java:619)
Apr 9, 2012 6:06:04 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class com.sun.xml.ws.transport.http.servlet.WSServletContextListener
com.sun.xml.ws.transport.http.servlet.WSServletException: WSSERVLET11: failed to parse runtime descriptor: class: Bounceable could not be found
                at com.sun.xml.ws.transport.http.servlet.WSServletContextListener.parseAdaptersAndCreateDelegate(WSServletContextListener.java:141)
                at com.sun.xml.ws.transport.http.servlet.WSServletContextListener.contextInitialized(WSServletContextListener.java:152)
                at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4681)
                at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5184)
                at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5179)
                at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
                at java.util.concurrent.FutureTask.run(FutureTask.java:138)
                at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
                at java.lang.Thread.run(Thread.java:619)
Caused by: com.sun.xml.ws.model.RuntimeModelerException: class: Bounceable could not be found
                at com.sun.xml.ws.model.RuntimeModeler.getPortTypeName(RuntimeModeler.java:1574)
                at com.sun.xml.ws.model.RuntimeModeler.getPortTypeName(RuntimeModeler.java:1558)
                at com.sun.xml.ws.server.EndpointFactory.create(EndpointFactory.java:225)
                at com.sun.xml.ws.server.EndpointFactory.createEndpoint(EndpointFactory.java:145)
                at com.sun.xml.ws.api.server.WSEndpoint.create(WSEndpoint.java:569)
                at com.sun.xml.ws.api.server.WSEndpoint.create(WSEndpoint.java:552)
                at com.sun.xml.ws.transport.http.DeploymentDescriptorParser.parseAdapters(DeploymentDescriptorParser.java:261)
                at com.sun.xml.ws.transport.http.DeploymentDescriptorParser.parse(DeploymentDescriptorParser.java:153)
                at com.sun.xml.ws.transport.http.servlet.WSServletContextListener.parseAdaptersAndCreateDelegate(WSServletContextListener.java:131)
                ... 9 more


Possible reason could be WSServlet is not able to locate endpoint class mentioned in sun-jaxws.xml.

sun-jaxws.xml (defines web service implementation class)
${Tomcat}/webapps/SimpleWebservice/WEB-INF/sun-jaxws.xml

<?xml version="1.0" encoding="UTF-8"?>
<endpoints
  xmlns="
http://java.sun.com/xml/ns/jax-ws/ri/runtime"
  version="2.0">
  <endpoint
      name="HelloWS"
      implementation="com.javaxp.HelloWSImpl"
      url-pattern="/hellows"/>
</endpoints>


Please see the below link.

How to Publish, Consume a simple web service using Tomcat?

SEVERE: WSSERVLET11: failed to parse runtime descriptor: A @WebService.targetNamespace must be specified on classes with no package.


If you get below mentioned exception.


SEVERE: WSSERVLET11: failed to parse runtime descriptor: A @WebService.targetNamespace must be specified on classes with no package.  Class: Ball
com.sun.xml.ws.model.RuntimeModelerException: A @WebService.targetNamespace must be specified on classes with no package.  Class: Ball
                at com.sun.xml.ws.model.RuntimeModeler.getServiceName(RuntimeModeler.java:1489)
                at com.sun.xml.ws.model.RuntimeModeler.getServiceName(RuntimeModeler.java:1459)
                at com.sun.xml.ws.server.EndpointFactory.getDefaultServiceName(EndpointFactory.java:472)
                at com.sun.xml.ws.server.EndpointFactory.getDefaultServiceName(EndpointFactory.java:461)
                at com.sun.xml.ws.transport.http.DeploymentDescriptorParser.parseAdapters(DeploymentDescriptorParser.java:236)
                at com.sun.xml.ws.transport.http.DeploymentDescriptorParser.parse(DeploymentDescriptorParser.java:153)
                at com.sun.xml.ws.transport.http.servlet.WSServletContextListener.parseAdaptersAndCreateDelegate(WSServletContextListener.java:131)
                at com.sun.xml.ws.transport.http.servlet.WSServletContextListener.contextInitialized(WSServletContextListener.java:152)
                at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4681)
                at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5184)
                at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5179)
                at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
                at java.util.concurrent.FutureTask.run(FutureTask.java:138)
                at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
                at java.lang.Thread.run(Thread.java:619)
Apr 9, 2012 6:04:00 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class com.sun.xml.ws.transport.http.servlet.WSServletContextListener
com.sun.xml.ws.transport.http.servlet.WSServletException: WSSERVLET11: failed to parse runtime descriptor: A @WebService.targetNamespace must be specified on classes with no package.  Class: Ball
                at com.sun.xml.ws.transport.http.servlet.WSServletContextListener.parseAdaptersAndCreateDelegate(WSServletContextListener.java:141)
                at com.sun.xml.ws.transport.http.servlet.WSServletContextListener.contextInitialized(WSServletContextListener.java:152)
                at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4681)
                at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5184)
                at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5179)
                at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
                at java.util.concurrent.FutureTask.run(FutureTask.java:138)
                at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
                at java.lang.Thread.run(Thread.java:619)
Caused by: com.sun.xml.ws.model.RuntimeModelerException: A @WebService.targetNamespace must be specified on classes with no package.  Class: Ball
                at com.sun.xml.ws.model.RuntimeModeler.getServiceName(RuntimeModeler.java:1489)
                at com.sun.xml.ws.model.RuntimeModeler.getServiceName(RuntimeModeler.java:1459)
                at com.sun.xml.ws.server.EndpointFactory.getDefaultServiceName(EndpointFactory.java:472)
                at com.sun.xml.ws.server.EndpointFactory.getDefaultServiceName(EndpointFactory.java:461)
                at com.sun.xml.ws.transport.http.DeploymentDescriptorParser.parseAdapters(DeploymentDescriptorParser.java:236)
                at com.sun.xml.ws.transport.http.DeploymentDescriptorParser.parse(DeploymentDescriptorParser.java:153)
                at com.sun.xml.ws.transport.http.servlet.WSServletContextListener.parseAdaptersAndCreateDelegate(WSServletContextListener.java:131)
                ... 9 more

You shoud check for package name for Java Classes and Interfaces within the Web service project. Default package is not allowed for them. You should explicitly add them to some package.

Please see belwo link.

How to Publish, Consume a simple web service using Tomcat?

Exception in thread "main" javax.xml.ws.WebServiceException: Failed to access the WSDL at


If You get below mentioned exception, possible reason could be -

1. Your WSDL url is not correct
2. Your WSDL url is not responding.


Check by hiting the URL into your browser, it should appear as shown below.




Exception :

Exception in thread "main" javax.xml.ws.WebServiceException: Failed to access the WSDL at: http://localhost:8080/HelloWS?wsdl. It failed with:
                Connection refused: connect.
                at com.sun.xml.ws.wsdl.parser.RuntimeWSDLParser.tryWithMex(RuntimeWSDLParser.java:162)
                at com.sun.xml.ws.wsdl.parser.RuntimeWSDLParser.parse(RuntimeWSDLParser.java:144)
                at com.sun.xml.ws.client.WSServiceDelegate.parseWSDL(WSServiceDelegate.java:263)
                at com.sun.xml.ws.client.WSServiceDelegate.(WSServiceDelegate.java:226)
                at com.sun.xml.ws.client.WSServiceDelegate.(WSServiceDelegate.java:174)
                at com.sun.xml.ws.spi.ProviderImpl.createServiceDelegate(ProviderImpl.java:104)
                at javax.xml.ws.Service.(Service.java:56)
                at simple.SimpleServiceImplService.(SimpleServiceImplService.java:53)
                at simple.TestClient.main(TestClient.java:17)
Caused by: java.net.ConnectException: Connection refused: connect
                at java.net.PlainSocketImpl.socketConnect(Native Method)
                at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
                at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
                at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
                at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
                at java.net.Socket.connect(Socket.java:529)
                at java.net.Socket.connect(Socket.java:478)
                at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
                at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
                at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
                at sun.net.www.http.HttpClient.(HttpClient.java:233)
                at sun.net.www.http.HttpClient.New(HttpClient.java:306)
                at sun.net.www.http.HttpClient.New(HttpClient.java:323)
                at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:860)
                at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:801)
                at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:726)
                at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)
                at java.net.URL.openStream(URL.java:1010)
                at com.sun.xml.ws.wsdl.parser.RuntimeWSDLParser.createReader(RuntimeWSDLParser.java:805)
                at com.sun.xml.ws.wsdl.parser.RuntimeWSDLParser.resolveWSDL(RuntimeWSDLParser.java:262)
                at com.sun.xml.ws.wsdl.parser.RuntimeWSDLParser.parse(RuntimeWSDLParser.java:129)
                ... 7 more

How to Publish, Consume a simple web service using Tomcat?

 

How to Publish, Consume a simple web service using Tomcat


Web services are platform independent hence it is used to communicate between different languages over http protocol. Web Services can convert your application into a Web-application, which can publish its function or message to the rest of the world. The basic Web Services platform is XML and HTTP.

Publishing and Consuming a Helloworld web service is very easy, all you need to have is a JDK (1.6 or higher),a Tomcat server and a IDE (e.g. Eclipse) to create a web service client you need to download stub. In this article we will see how to publish a simple JAX-WS web services using Tomcat servlet container. Also we will see how to create a simple web serive client. i.e. How to consume web service?

How to publish simple web service?

For running this example, below mentioned particulars are used.
  • Tomcat 7.0.11
  • JDK 1.6.0_21
  • MyEclipse 8.6
In this example, We have an interface HelloWS which contains a abstract method sayHello() which is to be exposed and a class HelloWSImpl.java which will implement HelloWS.

Please go through each of the screen shots.

Creating a New Web Service Project


Add project name, lets say SimpleWebservice



/* HelloWS.java */

package com.javaxp;

import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

@WebService
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface HelloWS {

public String sayHello(String name);
}

/* HelloWSImpl.java */

package com.javaxp;

import javax.jws.WebService;

@WebService(endpointInterface="com.javaxp.HelloWS")
public class HelloWSImpl implements HelloWS {

public String sayHello(String name) {

return "Hello "+name+"!! this is your first web service.";
}
}

web.xml (defines WSServletContextListener)
${Tomcat}/webapps/SimpleWebservice/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
                xmlns="http://java.sun.com/xml/ns/javaee"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <listener>
        <listener-class>
                com.sun.xml.ws.transport.http.servlet.WSServletContextListener
        </listener-class>
    </listener>
</web-app>

sun-jaxws.xml (defines web service implementation class)
${Tomcat}/webapps/SimpleWebservice/WEB-INF/sun-jaxws.xml

<?xml version="1.0" encoding="UTF-8"?>
<endpoints
  xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"
  version="2.0">
  <endpoint
      name="HelloWS"
      implementation="com.javaxp.HelloWSImpl"
      url-pattern="/hellows"/>
</endpoints>


If JAXB is not bundled with your tomcat you have to add below mentioned JAR files in ${Tomcat}/lib.
Download JAR file from https://jax-ws.java.net/

  • gmbal-api-only.jar
  • ha-api.jar
  • jaxb-impl.jar
  • jaxws-api.jar
  • jaxws-rt.jar
  • jaxb-api.jar
  • management-api.jar
  • policy.jar
  • stax-ex.jar
  • streambuffer.jar
  • jaxb-core.jar

Friday, April 6, 2012

How to get rid of "Address already in use: JVM_Bind" in windows OR linux


You may get below errors in your server console on your server startup.

SEVERE: Failed to initialize end point associated with ProtocolHandler ["http-bio-8080"]
java.net.BindException: Address already in use: JVM_Bind :8080
 at org.apache.tomcat.util.net.JIoEndpoint.bind(JIoEndpoint.java:378)
 at org.apache.tomcat.util.net.AbstractEndpoint.init(AbstractEndpoint.java:483)
 at org.apache.coyote.AbstractProtocolHandler.init(AbstractProtocolHandler.java:345)
 at org.apache.coyote.http11.AbstractHttp11JsseProtocol.init(AbstractHttp11JsseProtocol.java:119)
 at org.apache.catalina.connector.Connector.initInternal(Connector.java:910)
 at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:101)
 at org.apache.catalina.core.StandardService.initInternal(StandardService.java:559)
 at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:101)
 at org.apache.catalina.core.StandardServer.initInternal(StandardServer.java:781)
 at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:101)
 at org.apache.catalina.startup.Catalina.load(Catalina.java:572)
 at org.apache.catalina.startup.Catalina.load(Catalina.java:595)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)


Caused by: java.net.BindException: Address already in use: JVM_Bind
 at java.net.PlainSocketImpl.socketBind(Native Method)
 at java.net.PlainSocketImpl.bind(Unknown Source)
 at java.net.ServerSocket.bind(Unknown Source)
 at java.net.ServerSocket.(Unknown Source)
 at java.net.ServerSocket.(Unknown Source)
 at org.apache.tomcat.util.net.DefaultServerSocketFactory.createSocket(DefaultServerSocketFactory.java:48)
 at org.apache.tomcat.util.net.JIoEndpoint.bind(JIoEndpoint.java:365)
 ... 17 more

As the error suggest there is already another server running on the same port (in our case 8080) . you can either kill that service or change your web server to run on another port.
 

Java : Simple JAXB marshalling and unmarshalling Hello World Example



JAXB is an acronym derived from Java Architecture for XML Binding. This articles shows how to convert Java object to XML using JAXB annotation and vice versa. If you would like to know more about JAXB, see below links.


Marshalling - Convesrting a Java object to XML is known as Marshalling.
Unmarshalling - Converting a XML to Java Object is known as Unmarshalling.

About the example :

We have a Employee class which contains Name class reference in it. i.e HAS-A relation. Along with emplId and dept. TestMarshalling.java contains marshalIt() and unmarshalIt() method. marshalIt() as the name suggest, it accepts Employee object and return XML string out of it. And similarly unmarshalIt() method takes Class name and XML string and return Employee object out of it.

marshalIt(Object objectName) method uses JAXBContext to create Marshaller object

JAXBContext jaxbContext = JAXBContext.newInstance(objectName.getClass());
Marshaller marshaller = jaxbContext.createMarshaller();

Similarly unmarshalIt(Class className,String xml) method use JAXBContext to create Unmarshaller object

JAXBContext jaxbContext = JAXBContext.newInstance(className);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

No need to include any JAR file if you are using Java 1.6 and above because JAXB is bundled in JDK 1.6. Directly you can run below example and see the output. However if you are using Java 1.5 or lower version you need to include JAR file (e.g JAXB2_20120218.jar ) from http://jaxb.java.net/

Below are the self explanatory Java example. Directly you can run the example and see the output no need to have any IDE (e.g. Eclipse)


Name.java

/* Name.java */

public class Name {

 private
String firstName;
 private
String lastName;

 public String getFirstName() {
  return firstName;
 }


 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }


 public String getLastName() {
  return lastName;
 }


 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
}
 

Wednesday, April 4, 2012

java.lang.NoClassDefFoundError: org/glassfish/ha/store/api/BackingStoreException


If you get below error, Please add ha-api.jar file in your classpath.

SEVERE: WSSERVLET11: failed to parse runtime descriptor: java.lang.NoClassDefFoundError: org/glassfish/ha/store/api/BackingStoreException
java.lang.NoClassDefFoundError: org/glassfish/ha/store/api/BackingStoreException
 at com.sun.xml.ws.transport.http.servlet.ServletAdapter.(ServletAdapter.java:95)
 at com.sun.xml.ws.transport.http.servlet.ServletAdapterList.createHttpAdapter(ServletAdapterList.java:77)
 at com.sun.xml.ws.transport.http.servlet.ServletAdapterList.createHttpAdapter(ServletAdapterList.java:53)
 at com.sun.xml.ws.transport.http.HttpAdapterList.createAdapter(HttpAdapterList.java:77)
 at com.sun.xml.ws.transport.http.HttpAdapterList.createAdapter(HttpAdapterList.java:71)
 at com.sun.xml.ws.transport.http.DeploymentDescriptorParser.parseAdapters(DeploymentDescriptorParser.java:267)
 at com.sun.xml.ws.transport.http.DeploymentDescriptorParser.parse(DeploymentDescriptorParser.java:153)
 at com.sun.xml.ws.transport.http.servlet.WSServletContextListener.parseAdaptersAndCreateDelegate(WSServletContextListener.java:131)
 at com.sun.xml.ws.transport.http.servlet.WSServletContextListener.contextInitialized(WSServletContextListener.java:152)
 at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4681)




You may need to add ha-api.jar jar file in your lib folder of the server OR the project in which you are getting the above error.

You can download latest version of JAR file (E.g. JAXWS2.2.6-20120220.zip ) from http://jax-ws.java.net/
Extract the file in your local machine you will find this file jaxws-ri/lib/ha-api.jar. Add it to your class path and i hope you may get rid of the above error.