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

    Tuesday, December 28, 2010

    JDBC: creating tables and inserting values to tables dynamically sample code

    I believe my previously written "JDBC" post has given you a basic idea to start JDBC in a windows environment. So here I go again under the same topic but this time the post will be limited to a code. In previous post I have given codes to create a database dynamically and connecting to a database. This code shows how to create tables inside that database and inserting values dynamically into that newly created table.

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.sql.*;
    import java.util.Scanner;
    
    public class Myjdbc {
    
     public static void main(String args[]) {
    
      System.out.println("now we are going to connect with a database ");
    
      try {
    
       Class.forName("com.mysql.jdbc.Driver");
    
       Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest", "root", "123");
       Statement st = con.createStatement();
    
       System.out.println("connection has been made ");
    
       Scanner scanner = new Scanner(System.in);
       System.out.println("please enter table name ");
       String tableName = scanner.next();
    
       String strr = null;
    
       System.out.println("Enter no of columns you like to use: ");
       int noc = scanner.nextInt();
    
       for (int i = 1; i <= noc; i++) {
        BufferedReader bf = new BufferedReader(new InputStreamReader(
          System.in));
        System.out.println("Enter column name with type ");
        String s1 = bf.readLine();
        if (strr == null) {
         strr = s1;
    
        } else {
         strr = strr + s1;
    
        }
    
       }
    
       st.executeUpdate("create table " + tableName + "(" + strr + ")");
       System.out.println("your table " + tableName
         + " has been created!!!");
    
       ResultSet rs = st.executeQuery("SELECT * FROM " + tableName);
       ResultSetMetaData rsmd = rs.getMetaData();
       int NumOfCol = rsmd.getColumnCount();
       System.out.println("Number of Columns of your table =" + tableName
         + " " + NumOfCol);
       System.out.println("Column names are ");
       for (int i = 1; i <= NumOfCol; i++) {
        System.out.println(rsmd.getColumnName(i));
       }
       String strn = null;
       System.out.println("please enter values you need to insert");
    
       for (int i = 1; i <= NumOfCol; i++) {
        String s5 = scanner.next();
        if (strn == null) {
         strn = s5;
    
        } else
         strn = strn + s5;
    
       }
       System.out.println(strn);
    
       st.executeUpdate("insert into " + tableName + " values" + "("
         + strn + ")");
       System.out.println("your table " + tableName
         + " has been filled!!!");
    
       con.close();
       System.out.println("connection has been colsed ");
    
      }
    
      catch (Exception e) {
    
       System.out.println(e.getMessage());
      }
    
     }
    
    }
    
    
    

    Monday, December 27, 2010

    JDBC with mysql

    What are the pre-requirements for starting JDBC?


    Mysql server can be started on windows using following command

    NET START mysql
    

    Mysql server can be stopped on windows using following command

    NET STOP mysql
    

    There is another way to start stop mysql on windows,right-click MyComputer manage-->Services and Applications-->Services find MySQL and toggle start stop or restart.

    After downloading connector/j the mysql-connector-java-5.1.14-bin.jar file can be used as an external jar file to the JDBC project. Please refer previously written post about adding external jars for java or post for adding external jars in eclipse.

    what is jdbc?

    JDBC(java Database Connectivity) is Java application programming interface that allows the Java programmers to access database management system from Java code.

    Creating a database with jdbc sample code

    package pac1;
    
    import java.io.*;
    import java.sql.*;
    
    public class CreateDatabase {
     public static void main(String[] args) {
      System.out.println("Database creation example!");
      Connection con = null;// Connection is an interface in java.sql package
            // that specifies connection with specific
            // database like MySql. The SQL statements are
            // executed within the context of the Connection
            // interface.
      try {
       Class.forName("com.mysql.jdbc.Driver");// this static method
                 // attempts to load the
                 // class and returns class
                 // instance and takes string
                 // type value (driver) after
                 // that matches class with
                 // given string
       // DriverManager is a class of java.sql package that controls a set
       // of JDBC drivers. Each driver has to be register with this class.
       con = DriverManager.getConnection("jdbc:mysql://localhost:3306",
         "root", "123");// establishes a connection to specified
             // database url
       try {
        // Statement an interface. Statement object executes the SQL
        // statement and returns the result it produces
        Statement st = con.createStatement();// method of Connection
                  // interface. which
                  // returns Statement
                  // object. This method
                  // will compile again
                  // and again whenever
                  // the program runs.
        BufferedReader bf = new BufferedReader(new InputStreamReader(
          System.in));
        System.out.println("Enter Database name:");
        String database = bf.readLine();
        st.executeUpdate("CREATE DATABASE " + database);// method also
                    // executes SQL
                    // statement
                    // that may be
                    // INSERT,
                    // UPDATE OR
                    // DELETE
                    // statement are
                    // used in the
                    // code. It
                    // takes string
                    // types
                    // parameters
                    // for SQL
                    // statement. It
                    // returns int.
        System.out.println("1 row(s) affacted");
        con.close();// disconnecting from the connection, frees all the
           // resources occupied by the database.
       } catch (SQLException s) {
        System.out.print(s.getMessage());
        System.out.println("SQL statement is not executed!");
       }
      } catch (Exception e) {
       e.printStackTrace();
      }
     }
    }
    
    


    Connecting with a database sample code

    import java.sql.*;
    
    public class MysqlConnect{
      public static void main(String[] args) {
        System.out.println("MySQL Connect Example.");
        
        try {
          Class.forName("com.mysql.jdbc.Driver");
          Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest","root","root");
          System.out.println("Connected to the database");
          conn.close();
          System.out.println("Disconnected from database");
       
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    
    

    Note that newly created databases get saved in C:\ProgramData\MySQL\MySQL Server 5.5\data.

    Tuesday, December 21, 2010

    Network multicasting with C#

    What is multicasting?

    IP multicasting allows an application to send a single packet to a selected subset of devices. The IP multicasting scheme uses a particular range of IP addresses to designate different multicast groups. Each multicast group consists of a group of devices listening to the same IP address. As packets are sent out destined for the multicast group address, each device listening to the address receives them. The IP address range 224.0.0.1 through 239.255.255.255 represents multicast groups


    In C# the Socket class supports IP multicasting by using the SetSocketOption() method of the socket.

    MultiRecv program

    The MultiRecv program creates a UDP socket in the normal way, using the standard Socket class methods. After being added to the multicast group, the socket blocks on a ReceiveFrom() method call, waiting for data to arrive


    MultiRecv.cs

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    class MultiRecv
    {
      public static void Main()
      {
       Socket sock = new Socket(AddressFamily.InterNetwork,
                    SocketType.Dgram, ProtocolType.Udp);
       Console.WriteLine("Ready to receive…");
       IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
       EndPoint ep = (EndPoint)iep;
       sock.Bind(iep);
       sock.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.AddMembership,newMulticastOption(IPAddress.Parse("224.100.0.1")));
       byte[] data = new byte[1024];
       int recv = sock.ReceiveFrom(data, ref ep);
       string stringData = Encoding.ASCII.GetString(data, 0, recv);
       Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString());
       sock.Close();
      }
    }
    
    

    MultiSend program

    MultiSend.cs program is created to send multicast packets across network boundaries. when the multicast packet is sent out, it has a TTL(Time To Live) value of 50, allowing it to traverse up to 50 hops before it is terminated. You can use the MultiRecv program to watch the multicast packet go out on the network.


    MultiSend.cs

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    class NewMultiSend
    {
      public static void Main()
      {
       Socket server = new Socket(AddressFamily.InterNetwork,
                     SocketType.Dgram, ProtocolType.Udp);
       IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9051);
       IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050);
       server.Bind(iep);
       
       byte[] data = Encoding.ASCII.GetBytes("This is a test message");
       server.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership,
                   new MulticastOption(IPAddress.Parse("224.100.0.1")));
       server.SetSocketOption(SocketOptionLevel.IP,
       SocketOptionName.MulticastTimeToLive, 50);
       server.SendTo(data, iep2);
       server.Close();
      }
    }
    
    

    Sunday, December 19, 2010

    IO and String manipulation example java code

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.PrintWriter;
    import java.util.Arrays;
    import java.util.Scanner;
    
    public class Employee {
    
     String employeeNo;
     String employeeName;
     String groupNo;
     String hourlyRate;
     String hoursWorked;
     String bonusStatus;
     PrintWriter pw;
     BufferedReader br;
    
     public void addEmployee() {
      Scanner scanner = new Scanner(System.in);// reading from console
      System.out.println("Enter name");
      employeeName = scanner.next();
    
      System.out.println("Enter no");
      employeeNo = scanner.next();
    
      System.out.println("Enter group no");
      groupNo = scanner.next();
    
      System.out.println("Enter horly rate");
      hourlyRate = scanner.next();
    
      System.out.println("Enter hours worked");
      hoursWorked = scanner.next();
      int ihw = Integer.parseInt(hoursWorked);// converting a string to a
                // number
      String stri = Integer.toString(ihw);// converting an integer to a string
    
      System.out.println("Enter Bonus status");
      bonusStatus = scanner.next();
      char c = bonusStatus.charAt(0);
    
      try {
       pw = new PrintWriter(new FileWriter("newly.txt", true));// writing
                     // to a file
                     // without
                     // overwriting
      } catch (Exception e) {
       System.out.println(e.getMessage());
      }
      String s = employeeName + "@" + employeeNo + "@" + groupNo + "@"
        + hourlyRate + "@" + hoursWorked + "@" + bonusStatus + "@";// String
                       // concatenation
      pw.write(s);
      pw.flush();
    
     }
    
     public void sortHourlyRate() {
      String l = null;
      String x = null;
      try {
       br = new BufferedReader(new FileReader("newly.txt"));// reading from
                     // a file
    
       while ((l = br.readLine()) != null) {
        x = l;
    
       }
    
       String[] array = x.split("@");// using split method
    
       String[] arr = new String[array.length];
    
       int i = 0;
       int j = 3;
       int k = 0;
    
       while (j < array.length - 2) {
    
        arr[i] = array[j];
        j = j + 6;
        i++;
    
       }
    
       String a = null;
    
       while ((arr[k]) != null) {
    
        if (arr[k + 1] != null) {
         if (a == null) {
          a = arr[k] + "@" + arr[k + 1] + "@";
         } else if (a != null) {
          a = a + arr[k + 1] + "@";
         }
    
        }
    
        System.out.println(a);
        k++;
       }
    
       String[] array2 = a.split("@");
       System.out.println(array2[0]);
       Arrays.sort(array2);
       System.out.println(Arrays.toString(array2));
      }
    
      catch (Exception e) {
       System.out.println(e.getMessage());
      }
     }
    
     public void modifyData() {
    
      String l = null;
      String x = null;
      try {
       br = new BufferedReader(new FileReader("newly.txt"));
    
       while ((l = br.readLine()) != null) {
        x = l;
    
       }
       System.out.println(x);
    
       String[] array = x.split("@");
    
       Scanner scanner = new Scanner(System.in);
       System.out.println("please enter the employee name:");
       String s = scanner.next();
       int hs = s.hashCode();
    
       for (int i = 0; i < array.length; i++) {
    
        if (array[i].hashCode() == hs) {
         System.out.println("please enter the new employee name:");
         s = scanner.next();
         array[i] = s;
    
         System.out.println("please enter the new employee no:");
         s = scanner.next();
         array[i + 1] = s;
    
         System.out.println("please enter the new group no:");
         s = scanner.next();
         array[i + 2] = s;
    
         System.out.println("please enter the new hourly rate:");
         s = scanner.next();
         array[i + 3] = s;
    
         System.out.println("please enter the new hours rate:");
         s = scanner.next();
         array[i + 4] = s;
    
         System.out.println("please enter the new bonus rate:");
         s = scanner.next();
         array[i + 5] = s;
    
        }
       }
    
       String g = null;
       int m = 0;
       for (m = 0; m < array.length; m++) {
        if (g == null) {
         g = array[m] + "@";
        } else if (g != null) {
         g = g + array[m] + "@";
        }
       }
    
       PrintWriter pwd = new PrintWriter(new FileWriter("newly.txt"));
       pwd.write(g);
       pwd.flush();
       System.out.println(g);
    
      }
    
      catch (Exception e) {
       System.out.println(e.getMessage());
      }
    
     }
    
     public static void main(String args[]) {
    
      new Employee().addEmployee();
      new Employee().addEmployee();
      new Employee().addEmployee();
      new Employee().sortHourlyRate();
      new Employee().modifyData();
    
     }
    
    }