Monday, January 31, 2011

Crypto Samples in java part two - Message Digest Streams

SendStream.java writes data along with message digest to a file "test".

SendStream.java

import java.io.*;
import java.security.*;

public class SendStream {
 public static void main(String args[]) {
  try {

   // We need to write data + message digest to this file.
   // Basically this is the file we need to send to the receiver
   FileOutputStream fos = new FileOutputStream("test");

   // We are going to calculate the message digest with SHA
   MessageDigest md = MessageDigest.getInstance("SHA");

   // Updates the associated message digest
   // using the bits going through the stream.
   DigestOutputStream dos = new DigestOutputStream(fos, md);

   ObjectOutputStream oos = new ObjectOutputStream(dos);

   String data = "This have I thought good to deliver thee, "
     + "that thou mightst not lose the dues of rejoicing "
     + "by being ignorant of what greatness is promised thee.";

   // Write the specified object to the ObjectOutputStream
   // Now the message being written to the FileOutputStream
   // Also - this will update the message digest of the written data as well..
   oos.writeObject(data);

   // urns the digest function on or off. The default is on. When it is on, a call to one
   // of the write methods results in an update on the message digest. But when it is off,
   // the message digest is not updated.
   dos.on(false);

   // Now let's also write the message digest to the file,
   oos.writeObject(md.digest());

  } catch (Exception e) {
   System.out.println(e);
  }
 }
}



RecieveStream.java takes file "test" as an input reads the data and calculate digest of that data and compare it with the original message digest read from the file "test".

RecieveStream.java

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;

public class RecieveStream {
 public static void main(String args[]) {
  try {

   // Here we get a file from the sender - and we need to verify it's message digest
   // The file contains both the message and the digest.
   FileInputStream fis = new FileInputStream("test");

   // We are going to calculate the message digest with SHA
   MessageDigest md = MessageDigest.getInstance("SHA");

   // Updates the associated message digest
   // using the bits going through the stream.
   DigestInputStream dis = new DigestInputStream(fis, md);

   ObjectInputStream oos = new ObjectInputStream(dis);

   // Read the message from the file
   String data = (String) oos.readObject();
   
   dis.on(false);

   // Original message digest from the input file.
   byte[] originalDigest = (byte[]) oos.readObject();

   if (MessageDigest.isEqual(originalDigest, dis.getMessageDigest().digest())) {
    System.out.println("VALID");
   } else {
    System.out.println("INVALID");
   }

  } catch (Exception e) {
   System.out.println(e);
  }
 }
}


Saturday, January 29, 2011

Crypto Samples in java part one - Message Digest

Here is a simple java program illustrating how to calculate a message digest and how to verify the message digest.

import java.security.MessageDigest;

public class SimpleHashing {
 public static void main(String args[]) {
  try {

   // ----------- Calculating digest ---------------------------

   // We are going to calculate the message digest with SHA
   MessageDigest md = MessageDigest.getInstance("SHA");

   String data = "This have I thought good to deliver thee, "
     + "that thou might not lose the dues of rejoicing "
     + "by being ignorant of what greatness is promised thee.";

   md.update(data.getBytes());
   byte[] digest = md.digest();

   // -----------Verifying Digest -----------------------------

   // We are going to calculate the message digest with SHA
   MessageDigest md2 = MessageDigest.getInstance("SHA");

   String data2 = "This have I thought good to deliver thee, "
     + "that thou might not lose the dues of rejoicing "
     + "by being ignorant of what greatness is promised thee.";

   md2.update(data2.getBytes());
   byte[] digestOriginal = digest;
   byte[] digestCalc = md2.digest();

   if (MessageDigest.isEqual(digestOriginal, digestCalc)) {
    System.out.println("VALID");
   } else {
    System.out.println("INVALID");
   }

  } catch (Exception e) {
   System.out.println(e);
  }
 }

}

Sunday, January 2, 2011

Synchronous Cilent Server application in java

Client code

Client.java

This program creates a socket connection with the server running on port 9050 on localhost and gets the input stream from the socket by chaining the BufferedReader with the InputStreamReader.


package clientserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

public class client {

 public static void main(String args[]) {

  try {
   Socket s = new Socket("127.0.0.1", 9050);

   InputStreamReader streamreader = new InputStreamReader(
     s.getInputStream());
   BufferedReader br = new BufferedReader(streamreader);

   String number = br.readLine();

   System.out.println("Today's number is " + number);
   br.close();

  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }

 }

}



Server code

Server.java

This program makes a ServerSocket and waits for client Requests. When a client tries to connect the server creates a new socket in a random port(using accept() method), which knows about the ip address and the port number of the client and makes the connection to the client. Also here server uses PrintWriter to sned messages to client.


package mainserver;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

public class Server {

 public static void main(String args[]) {

  try {
   ServerSocket serverSock = new ServerSocket(9050);

   while (true) {

    Socket sock = serverSock.accept();
    PrintWriter pw = new PrintWriter(sock.getOutputStream());
    String TodayNum = new Server().getNumber();
    pw.println(TodayNum);
    pw.close();
    System.out.println(TodayNum);

   }

  } catch (IOException e) {
   e.printStackTrace();
  }

 }

 public String getNumber() {

  Random rg = new Random();
  int num = rg.nextInt(100);
  String numb = Integer.toString(num);
  return numb;

 }

}



Output

Saturday, January 1, 2011

Writing a C# client to an Axis2 service

Before moving into today's post content I would like to wish all the readers a happy new year 2011!

I am writing this post assuming you already have read my previous post subjected "Getting started with Apache Axis2". In there the client code has written in java, assume a situation where you need to write a client with C#, it is even simpler than writing a client in java.All you have to do is create a new project using microsoft visual studio and add the wsdl of your service(for the given example it is http://localhost:8080/axis2/services/mywebservice?wsdl) as service references and give a desired name for it(in following sample client code it is webserviceref), write the client code and run it



Client.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using webservice.clients.webserviceref;//name space of the service reference

namespace webservice.clients
{
    class Myclient
    {
        static void Main(string[] args)
        {

            webserviceref.mywebservicePortTypeClient cli = new mywebservicePortTypeClient("mywebserviceHttpSoap12Endpoint");
            Console.WriteLine(cli.sayHello("Hello"));
            Console.ReadLine();

        }
    }
}


Note that you have to start axis2 server before running the program.

Thursday, December 30, 2010

Getting started with Apache Axis2

I believe my previous post helped you to setup Apache Axis2 on windows. Now let's have a look at how to host a simple Web service with Apache Axis2.


Start an eclipse project and write a simple java class which will output a string "Hello!!!".

Sample1.java

package webservices.samples;

public class Sample1 {

 public String sayHello(String name) {

  return name;

 }

}


Inside src folder of your eclipse project create a new folder called META-INF and create a new file called services.xml in it.





 
  
 
 webservices.samples.Sample1
 
 


The service element has information about one service, inside service element specify the full qualified class name of your webservice (in this case it is webservices.samples.Sample1). In the child element of service element set the attribute name to the operation name you need to invoke through webservice (in this case it is sayHello)


Using Eclipse build the project and export only the relevant package and the META-INF inside bin folder as an archive file(.aar) to the repository\services folder inside axis2 home folder.


Start Axis2 server by double clicking on axis2server.bat inside bin folder. Now it will show deploying your service.


Now fire up a web browser and paste the following address in address bar http://localhost:8080/axis2/services/. It will list down the deployed services. Now your service should also be in that list.


Generating client to access the service

Goto bin folder inside axis2 home folder using command prompt and run the following command.

wsdl2Java.bat -uri http://localhost:8080/axis2/services/mywebservice?wsdl -o C:\myfile -uw

now go to C:\myfile folder using command prompt and give the following command

ant

Make sure you have set Apache ant bin folder to environment variable path before using this command. It will create a folder called build inside it there will be a folder called lib and mywebservice-test-client.jar will be generated inside it. You must use mywebservice-test-client.jar as an external jar file in your client project. Not only that jar you must add another set of external jar files in to your client project. All those jar files reside in lib folder inside axis2 home. Here I have list them out.


axis2-kernel-1.5.jar
axiom-api-1.2.8.jar
axiom-dom-1.2.8.jar
axiom-impl-1.2.8.jar
commons-logging-1.1.1.jar
wsdl4j-1.6.2.jar
XmlSchema-1.4.3.jar
neethi-2.0.4.jar
axis2-transport-local-1.5.jar
axis2-transport-http-1.5.jar
commons-httpclient-3.1.jar
mail-1.4.jar
commons-fileupload-1.2.jar
woden-api-1.0M8.jar
woden-impl-dom-1.0M8.jar
httpcore-4.0.jar
commons-codec-1.3.jar
geronimo-stax-api_1.0_spec-1.0.1.jar
wstx-asl-3.2.4.jar
axis2-jaxws-1.5.jar
axis2-adb-1.5.4.jar

Now you can write the client code. Build the project and run it. Make sure you have started axis2 server when you run the client.


Cilent.java
package webclient.samples;

import webservices.samples.MywebserviceStub;

public class Client {
 
 public static void main(String args[]){

 try {
 MywebserviceStub stub =new MywebserviceStub("http://localhost:8080/axis2/services/mywebservice");
 System.out.println(stub.sayHello("Hello"));
 }catch (Exception e){
 }
 
 }

}


Note: in axis2 home inside conf folder there is axis2.xml file open it and set hotupdate="true", this will auto update axis2 service whenever you update an already deployed service without restarting the axis2 service.

Setting up Apache Axis2 on windows

Download Apache Axis2 and extract the downloaded zip file to a desired location.


Make two new environment variables set first one's variable name as AXIS2_HOME and variable value as path to Axis2 home folder(in my case it is C:\Users\thilini\Desktop\axis2-1.5.4) and second one's variable name as JAVA_HOME and variabale value as path to Java home folder(in my case it is C:\Program Files\Java\jdk1.6.0_16).


Goto bin folder inside Axis2 home folder and double click on axis2server.bat file to start Axis2 service.


Now it's time to test whether installation is successful or not. Just fire up a web browser and paste the following address in address bar http://localhost:8080/axis2/services/. If installation is successful it will list down a service called "Version".


Wednesday, December 29, 2010

java RMI


Making the Remote Service
Step one: Make a Remote interface
  • Remote interface should extend java.rmi.Remote interface

  • Declare that all methods throw a RemoteException as every remote call is considered risky

  • Arguments and return values of remote methods must be either primitive or serializable(Strings, arrays, collections etc), if passing self defined types be sure to implement serializable interface to the class.

  • Step two: Make a Remote Implementation
  • Implement the Remote interface created earlier.

  • Extend java.rmi.server.UnicastRemoteObject to the class

  • As the super class UnicastRemoteObject's constructor throws a Remote Exception it is necessary to write a no-arg constructor that declares a Remote exception in our class.

  • To make available the remote service to clients register the service with RMI registry

  • Step three: Generate Stubs
  • Compile java files

  • Runrmic on the remote implementation class. To do this use the following command: rmic MyRemoteImplementation. This will create MyRemoteImplementation_Stub.class which is going to be the client helper.

  • Step four: run rmiregistry
  • Open a new terminal and goto the directory where your class files reside using command cd

  • Start rmiregistry using following command: rmiregistry

  • Step five: Start the service
  • open a new terminal and run the service following way: java MyRemoteImplementation

  • Server Code
    Remote interface
    import java.rmi.*;
    public interface MyRemoteInterface extends Remote{ //step 1.1 
    public int doCalc(int a,int b) throws RemoteException; //step 1.2 & step 1.3
    }
    
    Remote service
    import java.net.MalformedURLException;
    import java.rmi.*;
    import java.rmi.server.UnicastRemoteObject;
    
    public class MyRemoteImplementation extends UnicastRemoteObject implements MyRemoteInterface {//step 2.1 & 2.2
     
     public MyRemoteImplementation() throws RemoteException {} //step 2.3
    
     public int doCalc(int a,int b){  
      int result=a+b;
      System.out.println("Returned the result= "+result+" to client!");
      return result;
     }
     
     public static void main(String args[]){
      
      MyRemoteInterface service=null;
      try {
       service = new MyRemoteImplementation();
      } catch (RemoteException e) {
       e.printStackTrace();
      }
      try {
       Naming.rebind("welcome", service); //step 2.4 and be sure to give a name without spaces
      } catch (RemoteException e) {
       e.printStackTrace();
      } catch (MalformedURLException e) {
       e.printStackTrace();
      }
      
     }
    }
    
    
    
    Note: Server should have following three classes to work.
  • MyRemoteInterface.class

  • MyRemoteImplementation.class

  • MyRemoteImplementation_Stub.class

  • How client works?
    Note: Client should have following three classes to work.
  • MyRemoteInterface.class

  • MyRemoteClient.class

  • MyRemoteImplementation_Stub.class

  • Client does a lookup on the RMI registry and RMI registry returns the stub object. Stub pretends to be the real service and let client invokes the method in it.
    Client Code
    import java.rmi.*;
    
    public class MyRemoteClient {
     
     public static void main(String args[]){
      
      new MyRemoteClient().getResult();
      
     }
     
     public void getResult(){
      
    try{
       
       MyRemoteInterface service=(MyRemoteInterface)Naming.lookup("rmi://127.0.0.1/welcome");//Client does 
    //the lookup on the RMI registry
       int result=service.doCalc(1,2);
       System.out.println("hello I got the result "+result);
       
       }catch(Exception e){
        e.printStackTrace();
       }
      
     }
    
    
    }
    
    
    

    Output