Thursday, April 12, 2012

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.

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


}

Tuesday, January 17, 2012

java.net.ConnectException: Connection timed out: connect

 Exception in thread "main" java.net.ConnectException: Connection timed out: 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)



If you get above error, there could be one of the following reasons.
  • The domain/IP or port is incorrect
  • The domain/IP or port (i.e service) is down
  • The domain/IP is taking longer than your default timeout to respond
  • You have a firewall that is blocking requests or responses on whatever port you are using
  • You have a firewall that is blocking requests to that particular host
  • Your internet connection is down

I most of the cases there is a firewalls issue. Firewalls and port or IP blocking may be in place by your ISP.

To access URL via Firewalls, you may require to set http.proxyHost and http.proxyPort. Try using below syntax.

System.setProperty("http.proxyHost", "host name");
System.setProperty("http.proxyPort", "port number");

Some time you may also get below error.

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: http://www.google.com
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1313)

Here you may require to set User-Agent using below syntax.

connection.addRequestProperty("User-Agent", "Mozilla/4.0");

Please find the complete code below.


/* SimpleURLConnection.java */

import java.net.*;
import java.io.*;

public class SimpleURLConnection
{
    public static void main(String[] args) throws Exception
    {
        System.setProperty("http.proxyHost", "host name");
        System.setProperty("http.proxyPort", "port number");

        URL url= new URL("http://www.google.com");//provide proper url

        URLConnection connection = url.openConnection();
        connection.addRequestProperty("User-Agent", "Mozilla/4.0");

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        String line = "";

        while((line=in.readLine()) != null)
        {
            System.out.println(line);
        }

        //closing resource
        in.close();
        connection=null;
    }
}

Friday, January 13, 2012

Java : Compare two files

Other day I was required to compare contents of two files in Java. Lets see how to compare two txt files in Java?

I was wondering if there is a Java APIs for Text file comparison, which will compare contents of two txt files using java program.

Basically the java program should mimc the behaviour of diff command of LINUX. diff is a file comparison utility that outputs the differences between two files. It is typically used to show the changes between one version of a file and a former version of the same file. Diff displays the changes made per line for text files.

Output of the java program should give same as result produced by diff command. I got many codes on net but they were not working as expected. Latter i got an idea, why not we can use diff command in our java program to produce the same result. But diff command works for LINUX, what is equivalent for Windows? Well i found COMP or FC are equivalent windows command for diff in LINUX. So with the help of these commands we can build a JAVA program which will compare contents of two txt files.

Lets see the code.

No need to add any jar file, directly you can run this code and see the output.



/* CompareFiles.java */

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class CompareFiles {

    public void compare(String file1,String file2) {
       
        //For Windows
        runSystemCommand("fc /N \""+file1+"\" \""+file2+"\"");
       
        //For UNIX / LINUX
        //runSystemCommand("diff "+file1+" "+file2);
    }
   
    public void runSystemCommand(String command) {
       
        try {
            Process proc = Runtime.getRuntime().exec(command);
          
            BufferedReader inputStream = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            BufferedReader errorStream = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
           
            String strLn = "";
           
            // reading output stream of the command
            while ((strLn = inputStream.readLine()) != null) {
                System.out.println(strLn);
            }
           
            // reading errors of the command (if any)
            while ((strLn = errorStream.readLine()) != null) {
                System.out.println(strLn);
            }
          
        } catch (Exception e) {
          
            e.printStackTrace();
        }
    }
   
    public static void main(String[] args) {
   
        CompareFiles cf = new CompareFiles();
       
        cf.compare("C:\\file1.txt","C:\\file2.txt");
    }

}

UNIX / LINUX - HELP diff Command

NAME
     diff - compare two files

SYNOPSIS
     diff [-bitw] [-c | -e | -f | -h | -n | -u]  file1 file2

     diff [-bitw] [-C number | -U number]  file1 file2

     diff [-bitw] [-D string] file1 file2

     diff [-bitw] [-c | -e | -f | -h | -n | -u]  [-l]  [-r]  [-s] [-S name] directory1 directory2

DESCRIPTION
     The diff utility will compare  the  contents  of  file1  and file2  and write to standard output a list of changes necessary to convert  file1  into  file2.  This  list  should  be minimal.   Except  in rare circumstances, diff finds a smallest sufficient set of file differences. No output  will  be produced if the files are identical.

     The normal output contains lines of these forms:

     n1 a n3,n4
     n1,n2 d n3
     n1,n2 c n3,n4

     where n1  and  n2  represent  lines  file1  and  n3  and  n4 represent lines in file2 These lines resemble ed(1) commands to convert file1 to file2. By exchanging a for d and reading backward, file2 can be converted to file1. As in ed, identical pairs, where n1=n2 or n3=n4, are abbreviated as a single number.

     Following each of these lines come all the  lines  that  are affected  in  the  first  file  flagged by `<', then all the lines that are affected in the second file flagged by `>'.

OPTIONS
     The following options are supported:

     -b              Ignores trailing blanks  (spaces  and  tabs) and   treats  other  strings  of  blanks  as equivalent.

     -i              Ignores the case of  letters.  For  example, 'A' will compare equal to 'a'.

     -t              Expands characters  in  output  lines. Normal or -c output adds character(s) to the front of each line that may adversely affect the indentation of the original source lines and  make  the  output  lines  difficult  to interpret.  This  option  will  preserve the original source's indentation.

     -w              Ignores all blanks ( and   characters)  and  treats  all  other  strings of blanks   as   equivalent.    For    example, 'if ( a == b )'   will   compare   equal  to 'if(a==b)'.

     The following options are mutually exclusive:

     -c              Produces a listing of differences with three lines  of  context. With this option, output format is modified slightly. That is, output begins  with  identification  of  the  files involved and their creation dates, then each change  is  separated by a line with a dozen *'s. The lines removed from file1 are marked with  '-'.  The  lines  added  to  file2 are marked '+'. Lines that are changed from  one file  to  the other are marked in both files with '!'.

     -C number       Produces a listing of differences  identical to  that produced by -c with number lines of context.

     -D string       Creates a merged version of file1 and  file2 with  C  preprocessor  controls  included so that a compilation  of  the  result  without defining  string  is equivalent to compiling file1,  while  defining  string  will  yield file2.

     -e              Produces a script of only a, c, and  d  commands for the editor ed, which will recreate file2 from file1. In connection with the  -e option, the following shell program may help maintain multiple versions of a  file.  Only an  ancestral  file  ($1)  and  a  chain  of version-to-version  ed  scripts  ($2,$3,...) made  by  diff  need  be on hand. A ``latest version'' appears on the standard output. (shift; cat $*; echo '1,$p') | ed - $1

     -f              Produces a similar script, not  useful  with ed, in the opposite order.

     -h              Does a fast, half-hearted job. It works only when  changed  stretches  are short and well separated, but does work on files of  unlimited length. Options -c, -C, -D, -e, -f, and -n are unavailable with -h.  diff  does  not descend into directories with this option.

     -n              Produces a script similar to -e, but in  the opposite  order  and with a count of changed lines on each insert or delete command.

     -u              Produces a listing of differences with three lines  of  context. The output is similar to that of the -c option, except that the  context is "unified". Removed and changed lines in file1 are marked by  a  '-'  while  lines added  or  changed  in file2 are marked by a '+'. Both versions of changed  lines  appear in  the  output,  while  added, removed, and context lines appear only once. The identification  of  file1  and  file2 is different, with "---" and  "+++"  being  printed  where "***"  and  "---"  would  appear with the -c option. Each change is separated by  a  line of the form @@ -n1,n2 +n3,n4 @@

     -U number       Produces a listing of differences  identical to  that produced by -u with number lines of context.

     The following options are used for comparing directories:

     -l              Produces output in long format.  Before  the diff,  each text file is piped through pr(1) to  paginate  it.   Other  differences   are remembered  and  summarized  after  all text file differences are reported.

     -r              Applies diff recursively to common subdirectories encountered.

     -s              Reports  files  that  are  identical.  These identical  files would not otherwise be mentioned.

     -S name         Starts  a  directory  diff  in  the  middle, beginning with the file name.

OPERANDS
     The following operands are supported:

     file1           A path name of a file  or  directory  to  be
     file2           compared. If either file1 or file2 is -, the standard input will be used in its place.

     directory1      A path name of a directory to be compared.
     directory2

     If only one of file1 and file2 is a directory, diff will  be applied  to the non-directory file and the file contained in the directory file with a filename that is the same  as  the last component of the non-directory file.

USAGE
     See largefile(5) for the description of the behavior of diff  when encountering files greater than or equal to 2 Gbyte ( 2     **31 bytes).

EXAMPLES
     Example 1: Typical output of the diff command

     In the following command, dir1 is a directory  containing  a directory  named  x, dir2 is a directory containing a directory named x, dir1/x and dir2/x  both  contain  files  named date.out, and dir2/x contains a file named y:

     example% diff -r dir1 dir2
     Common subdirectories: dir1/x and dir2/x

     Only in dir2/x: y

     diff -r dir1/x/date.out dir2/x/date.out

     1c1

     < Mon Jul  2 13:12:16 PDT 1990

     ---

     > Tue Jun 19 21:41:39 PDT 1990

ENVIRONMENT VARIABLES
     See environ(5) for descriptions of the following environment variables  that  affect the execution of diff: LANG, LC_ALL, LC_CTYPE, LC_MESSAGES, LC_TIME, and NLSPATH.

     TZ       Determines the locale for  affecting  the  timezone used  for  calculating file timestamps written with the -C and -c options.

EXIT STATUS
     The following exit values are returned:

     0        No differences were found.

     1        Differences were found.

     >1       An error occurred.

FILES
     /tmp/d?????             temporary file used for comparison

     /usr/lib/diffh          executable file for -h option

ATTRIBUTES
     See attributes(5) for descriptions of the  following  attributes:

     ____________________________________________________________
    |       ATTRIBUTE TYPE        |       ATTRIBUTE VALUE       |
    |_____________________________|_____________________________|
    | Availability                | SUNWesu                     |
    |_____________________________|_____________________________|
    | CSI                         | Enabled                     |
    |_____________________________|_____________________________|
    | Interface Stability         | Standard                    |
    |_____________________________|_____________________________|

SEE ALSO
     bdiff(1), cmp(1), comm(1), dircmp(1), ed(1),  pr(1),  sdiff(1), attributes(5), environ(5), largefile(5), standards(5)

NOTES
     Editing scripts produced under the  -e  or  -f  options  are naive  about  creating  lines  consisting of a single period (.).

     Missing NEWLINE at end of file indicates that the last  line of the file in question did not have a NEWLINE. If the lines are different, they will be flagged and output, although the output will seem to indicate they are the same.    

COMP and FC : Windows equivalent of UNIX / LINUX diff command

COMP and FC commands can be used as Windows equivalent of UNIX / LINUX diff command.

COMP

Compares the contents of two files or sets of files.

SYNTAX :
COMP [data1] [data2] [/D] [/A] [/L] [/N=number] [/C] [/OFF[LINE]]

  data1      Specifies location and name(s) of first file(s) to compare.
  data2      Specifies location and name(s) of second files to compare.
  /D         Displays differences in decimal format.
  /A         Displays differences in ASCII characters.
  /L         Displays line numbers for differences.
  /N=number  Compares only the first specified number of lines in each file.
  /C         Disregards case of ASCII letters when comparing files.
  /OFF[LINE] Do not skip files with offline attribute set.

To compare sets of files, use wildcards in data1 and data2 parameters.

FC

Compares two files or sets of files and displays the differences between them

SYNTAX:
FC [/A] [/C] [/L] [/LBn] [/N] [/OFF[LINE]] [/T] [/U] [/W] [/nnnn]
   [drive1:][path1]filename1 [drive2:][path2]filename2
FC /B [drive1:][path1]filename1 [drive2:][path2]filename2

  /A         Displays only first and last lines for each set of differences.
  /B         Performs a binary comparison.
  /C         Disregards the case of letters.
  /L         Compares files as ASCII text.
  /LBn       Sets the maximum consecutive mismatches to the specified
             number of lines.
  /N         Displays the line numbers on an ASCII comparison.
  /OFF[LINE] Do not skip files with offline attribute set.
  /T         Does not expand tabs to spaces.
  /U         Compare files as UNICODE text files.
  /W         Compresses white space (tabs and spaces) for comparison.
  /nnnn      Specifies the number of consecutive lines that must match
             after a mismatch.
  [drive1:][path1]filename1
             Specifies the first file or set of files to compare.
  [drive2:][path2]filename2
             Specifies the second file or set of files to compare.

Monday, January 9, 2012

Java : Simple LDAP program

This is a simple LDAP program in java. Here we are using Netscape Directory SDK.To know more about Mozilla Netscape click here. To run this program you need to download ldapsdk.jar For Example ldapsdk-4.1.jar

To download ldapsdk-4.1.jar, click here. Provide appropriate data and see the output.


/* TestLDAP.java */

import java.util.Enumeration;

import netscape.ldap.LDAPAttribute;
import netscape.ldap.LDAPAttributeSet;
import netscape.ldap.LDAPConnection;
import netscape.ldap.LDAPEntry;
import netscape.ldap.LDAPException;
import netscape.ldap.LDAPSearchResults;

public class TestLDAP {

    public static void main(String[] args) {
       
        LDAPConnection ldConnection = null;
        LDAPEntry ldEntry = null;
       
        try {
            ldConnection = new LDAPConnection();
           
            String HOSTNAME = "HOSTNAME";
            int PORT = 389;
            String TREEBASE = "ou=PEOPLE,o=ha";//your DN
            //String QUERY = "(objectclass=* )";
            String QUERY = "(&(objectclass=objclass )(attribute=*value*))";
           
            ldConnection.connect( HOSTNAME, PORT );
           
            //String[] attrNames = {"*"};
            String[] attributeNames = {"val1","val2","val3","val4"};
           
            LDAPSearchResults ldSearchResult = ldConnection.search(TREEBASE,LDAPConnection.SCOPE_ONE,QUERY,attributeNames,false);
           
            if(ldSearchResult.hasMoreElements()) {
                ldEntry = ldSearchResult.next();
            }
           
            LDAPAttributeSet ldAttributeSet = ldEntry.getAttributeSet();
           
            Enumeration enumAttributeSet = ldAttributeSet.getAttributes();
           
            while(enumAttributeSet.hasMoreElements()) {
                LDAPAttribute ldAttribute = enumAttributeSet.nextElement();
                String attrName = ldAttribute.getName();
               
                String[] aVal = ldAttribute.getStringValueArray();
               
                System.out.println("----------------------");
                System.out.println("Key   : "+attrName);
                for(String val : aVal) {
                    System.out.println("Value : "+val);
                }
               
            }
        }
        catch(LDAPException LDAPex) {
            LDAPex.printStackTrace();
        }

    }

}