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.

Wednesday, March 28, 2012

Java : Simple Refection API example

In Java, have you ever needed to call a method at Run time. i.e. A method should be called depending upon some parameter at runtime, you dont know the methods name at compile time. If your answer is yes then Java Reflection API is the best way to proceed, However it has few disadvantage as well.

Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time.

To know about about Reflection API, click here

Invoking Methods using Method Object

Method method = MyClass.class.getMethod("methodName", Object... parameter);
Object returnValue = method.invoke(MyClassObject, "parameterValue");

Loading Class

You can load Class if you know the class name while compile time as shown below.

Class classObject = MyClass.class;

Else you can also load class at run time as shown below.

Note: This may throw ClassNotFoundException if fully qualified class name is not found.

Class classObject = Class.forName("com.MyClass");

Lets see a simple runnable example on this.
/* TestReflection.java */

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestReflection 
{
 public String Add(int param1,int param2) {
  return "Addition : "+(param1 + param2);
 }

 public String Subtract(int param1,int param2) {
  return "Subtraction : "+(param1 - param2);
 }
 public static void main(String[] args)  throws SecurityException, 
NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
InvocationTargetException
 {
  TestReflection t = new TestReflection();

  //String methodToCall = "Add";
  String methodToCall = "Subtract";

  Method m = TestReflection.class.getMethod(methodToCall, int.class,int.class);

  String returnVal = (String) m.invoke(t, 3,2);

  System.out.println(returnVal);
 }
}


Note : If JVM is not able to find method name then it will throw NoSuchMethodException exception

Exception in thread "main" java.lang.NoSuchMethodException: TestReflection.unknownMethod(int, int)
        at java.lang.Class.getMethod(Unknown Source)
        at TestReflection.main(TestReflection.java:21)

Tuesday, February 7, 2012

Java Threads - Wait and Notify Example

This is a simple Thread example which demonstrates wait and notify functionality of a Thread. In this example we have a main class i.e. MainThread which will call AnotherThread, so that you can see both running simultaneously. Now our main thread enters into wait state till AnotherThread notifies it.


Please see the self explanatory code. Directly you can this code and see the output.


MainThread.java



/* MainThread.java */


public class MainThread {


public static void main(String[] args) {

//Start another thread
Thread anotherThreadObject = new Thread(new AnotherThread());
anotherThreadObject.start();

//Main thread continues
for(int i=0;i<10;i++) {

System.out.println(Thread.currentThread().getName()+" : "+i);

//this thread halts for 500 millisecond
try {
Thread.sleep(1 * 500);
} catch (InterruptedException e) {
e.printStackTrace();
}

//when counter reaches 5 wait for Other thread to notify it
if(i == 5) {
try {
synchronized(MainThread.class) {
System.out.println("MainThread is Waiting....");
MainThread.class.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}//for
}//main


}