Inside Java: Arrays.asList(T… a)

We frequently use asList method of Arrays class to convert an array to a list. In order to use this method properly we need to know what is happening behind the scene. The complete signature of this method is:   

      public static <T> List<T> asList(T... a)
 

This method is declared and defined in java.util.Arrays class. The method returns an object of ArrayList class. But here is one difference which we have to note and take care while using this.     

The object being returned does not belong to java.util.ArrayList class rather it belongs to java.util.Arrays$ArrayList class. Surprised! Actually the Arrays class defines an private static inner class named ArrayList. Following is the signature of the ArrayList class:     

      private static class ArrayList<E> extends AbstractList<E>implements RandomAccess, 
      java.io.Serializable 

 

Now let us see what the difference between the two ArrayList classes is.  

The Arrays$ArrayList class is sometimes refered as the view of java.util.ArrayList or a fixed size list. This class does not override all the methods of AbstractList class. To be more precise, following are the methods it overrides or declares:     

      public int size()  

      public Object[] toArray()

      public <T> T[] toArray(T[] a)

      public E get(int index)

      public E set(int index, E element)

      public int indexOf(Object o)

      public boolean contains(Object o)

 

Other methods if being called refer to the AbstractList class default implementation.  

For example if we try to call the add or remove method of Arrays$ArrayList class, we will get an UnsupportedOperationException . The reason behind this is the implementation of these methods in the AbstractList class which is:  

      public void add(int index, E element) {
                 throw new UnsupportedOperationException();
      }  

      public E remove(int  index) {
                 throw new  UnsupportedOperationException();
      }  

 

I hope this clears the understanding of how views are being used in java.

Let us conclude this article with the javadoc comments of Arrays.asList method: 

Returns a fixed-size list backed by the specified array.  (Changes to the returned list “write through” to the array.)  This method acts as bridge between array-based and collection-based APIs, in combination with Collection#toArray.  The returned list is serializable and implements RandomAccess.

This method also provides a convenient way to create a fixed-size list initialized to contain several elements:
List<String> stooges = Arrays.asList(“Larry”, “Moe”, “Curly”);
 

Enjoy Learning,
Kamlesh

Advertisements

Apache Pivot – Build RIA in Java

I was going through Apache’s web site and I read the news about Apache Pivot. Apache Pivot  is a Java alternative of Adobe Flex/Flash and Microsoft Silverlight.

In December 2009, Pivot has been declared a top-level Apache project and Pivot 1.4 is the latest version which is available for download.

About Pivot, this is what Apache has to say:

Apache Pivot is an open-source platform for building rich internet applications in Java. It combines the enhanced productivity and usability features of a modern RIA toolkit with the robustness of the Java platform. Pivot applications are written using a combination of Java and XML and can be run either as an applet or as a standalone, optionally offline, desktop application.

Like other modern development platforms, Pivot provides a comprehensive set of foundation classes that together comprise a “framework”. These classes form the building blocks upon which more complex and sophisticated applications can be built.

Expolre more about Apache Pivot, here.

Enjoy Learning,

Kamlesh

Axis2: Creating and consuming a web service

Objective

  • Configuring axis2
  • Exposing a POJO as a web service using axis2
  • Consuming the developed web service

Configuring AXIS-2 with Tomcat

  • Download axis2 binary distribution.
  • Set the environment variable AXIS2_HOME. Add %AXIS2_HOME%\bin in path variable.
  • Go to axis2_home/webapp directory and run ant command. Make sure ant is configured on your machine. This will create axis2.war in the %AXIS2_HOME%/ext directory.
  • Deploy the axis2.war in tomcat.
  • A welcome page at the URL http://localhost:8080/axis2/ will confirm the successful deployment of axis2. You can browse through this welcome page to see what all is there.

Creating a webservice

  • Create a directory named GreetService.
  • Create the com/technicalmusings/samples/axis2/service/GreetService.java file.
      GreetService.java
      package com.technicalmusings.samples.axis2.service; 

       public class GreetService{
           public String getServerTime(){
                return (new java.util.Date()).toString();
           }
           public String greet(String name){
                return "Hello " + name ;
           }
       }
  • Compile the class.
    GreetService>javac -g -d . com\technicalmusings\samples\axis2\service\GreetService.java
    

*The –g option is needed while compiling the class as it adds the debug information to the class and using which the java2wsdl tool generates the name of the parameters (or variables). Without the –g option the parameter name may be generated as param0 or arg0, depending in the version of axis2.

  • Create the directory META-INF in GreetService directory.
  • Create the service.xml file in the META-INF directory.
      services.xml
    <?xml version="1.0" encoding="UTF-8"?> 

    <serviceGroup>
       <service name="GreetService">
          <description>First Axis Service: Greet Service</description>
          <parameter name="ServiceClass" locked="false">
               com.technicalmusings.samples.axis2.service.GreetService
          </parameter>
          <operation name="getServerTime">
                <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only"
                  class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver" />
         </operation>
         <operation name="greet">
                <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out"
                  class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />
        </operation>
     </service>
   </serviceGroup>
  • Use the java2wsdl tool supplied with the axis2 distribution to generate the wsdl file in the META-INF directory as below:
      GreetService>%AXIS2_HOME%\bin\java2wsdl -cp . -cn 
      com.technicalmusings.samples.axis2.service.GreetService
      -of META-INF\GreetService.wsdl 
  • Create an axis archive file using the following command:
      GreetService>jar -cvf GreetService.aar .
  • Copy GreetService.aar to the deployed axis2.war to <TOMCAT_HOME>\webapps\axis2\WEB-INF\services.
  • Start/Restart the tomcat server and check to ensure the proper deployment of the service by hitting the URL, http://localhost:8080/axis2/services/listServices.

Consuming the Webservice

  • Create a directory GreetServiceClient.
  • Use the wsdl2java tool to generate the java classes for the GreetService. Execute the following command.
      GreetServiceClient>%AXIS2_HOME%\bin\wsdl2java 
      -ss -g -uri http://localhost:8080/axis2/services/GreetService?wsdl 
  • On successful execution the tool will generate the artifacts in the GreetServiceClient folder along with an ant build script and the wsdl file in the resources folder.
    You can see other options for wsdl2java tool for different configurations.
  • Write a java class to test the web service. GreetServiceClient/src/com/technicalmusings/samples/client/GreetServiceClient.java.

GreetServiceClient.java

       package com.technicalmusings.samples.axis2.service;

       import com.technicalmusings.samples.axis2.service.GetServerTimeResponse;
       import com.technicalmusings.samples.axis2.service.Greet;
       import com.technicalmusings.samples.axis2.service.GreetResponse;
       import com.technicalmusings.samples.axis2.service.GreetServiceStub;

       public class GreetServiceClient {

          public static void main(String[] args) throws Exception{
             //Create the stub
             GreetServiceStub stub =
               new GreetServiceStub("http://localhost:8080/axis2/services/GreetService");

            //Call the getServerTime method
            GetServerTimeResponse timeResponse = stub.getServerTime();
            System.out.println("The server time is:" + timeResponse.get_return());

            //Call the greet method
            Greet greetInput = new Greet();
            greetInput.setName("Axis2");
            GreetResponse greetResponse = stub.greet(greetInput);
            System.out.println("Server responded:" + greetResponse.get_return());
        }

     }
  • Now in order to compile this class we need to set the required libraries in the classpath. I am using minimum libraries needed to run the axis2 client. The version of axis2 I am using is axis2-1.5.1.
    Add following jars from %AXIS2_HOME%\bin to the classpath for compiling the client.
            activation-1.1.jar,
            axiom-api-1.2.8.jar,
            axiom-dom-1.2.8.jar,
            axiom-impl-1.2.8.jar,
            axis2-adb-1.5.1.jar,
            axis2-kernel-1.5.1.jar,
            axis2-transport-http-1.5.1.jar,
            axis2-transport-local-1.5.1.jar,
            commons-codec-1.3.jar,
            commons-fileupload-1.2.jar,
            commons-httpclient-3.1.jar,
            commons-logging-1.1.1.jar,
            geronimo-stax-api_1.0_spec-1.0.1.jar,
            httpcore-4.0.jar,
            mail-1.4.jar,
            neethi-2.0.4.jar,
            woden-api-1.0M8.jar,
            woden-impl-dom-1.0M8.jar,
            wsdl4j-1.6.2.jar,
            wstx-asl-3.2.4.jar,
            XmlSchema-1.4.3.jar

Compile the classes:

\GreetServiceClient\src>javac -d . com\technicalmusings\samples\axis2\service\*.java

Run the class:

\GreetServiceClient\src>java com.technicalmusings.samples.axis2.service.GreetServiceClient

Output:

The server time is:Mon Feb 01 17:55:29 IST 2010
Server responded:Hello Axis2

Enjoy Learning,
Kamlesh

<!–[if gte mso 9]> Normal 0 false false false EN-IN X-NONE X-NONE <![endif]–><!–[if gte mso 9]> <![endif]–> <!–[endif]–>

Objective:

  • Configuring axis2
  • Exposing a POJO as a web service using axis2
  • Consuming the developed web service

Configuring AXIS-2 with Tomcat

  • Download axis2 binary distribution.
  • Set the environment variable AXIS2_HOME. Add %AXIS2_HOME%\bin in path variable.
  • Go to axis2_home/webapp directory and run ant command. Make sure ant is configured on your machine. This will create axis2.war in the axis2_home/ext directory.
  • Deploy the axis2.war in tomcat.
  • A welcome page at the URL http://localhost:8080/axis2/ will confirm the successful deployment of axis2. You can browse through this welcome page to see what all is there.

Creating a webservice

  • Create a directory named GreetService.
  • Create the com/technicalmusings/samples/axis2/service/GreetService.java file.

GreetService.java

package com.technicalmusings.samples.axis2.service;

public class GreetService{
public String getServerTime(){
return (new java.util.Date()).toString();
}
public String greet(String name){
return “Hello ” + name ;
}
}

  • Compile the class.

GreetService>javac -d . com\technicalmusings\samples\axis2\service\GreetService.java

<!–[if !supportLineBreakNewLine]–>
<!–[endif]–>

  • Create the directory META-INF in GreetService directory.
  • Create the service.xml file in the META-INF directory.

services.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<serviceGroup>
<service name=”GreetService”>
<description>First Axis Service: Greet Service</description>
<parameter name=”ServiceClass” locked=”false”>
com.technicalmusings.samples.axis2.service.GreetService
</parameter>
<operation name=”getServerTime”>
<messageReceiver mep=”http://www.w3.org/2004/08/wsdl/in-only
class=”org.apache.axis2.rpc.receivers.RPCMessageReceiver” />
</operation>
<operation name=”greet”>
<messageReceiver mep=”http://www.w3.org/2004/08/wsdl/in-out
class=”org.apache.axis2.rpc.receivers.RPCMessageReceiver” />
</operation>
</service>
</serviceGroup>

  • Use the java2wsdl tool supplied with the axis2 distribution to generate the wsdl file in the META-INF directory as below:

GreetService>%AXIS2_HOME%\bin\java2wsdl -cp . -cn

com.technicalmusings.samples.axis2.service.GreetService -of META-

INF\GreetService.wsdl

  • Create an axis archive file using the following command:

GreetService>jar -cvf GreetService.aar .

*Note the dot(.) in the command.
<!–[if !supportLineBreakNewLine]–>
<!–[endif]–>

  • Copy GreetService.aar to the deployed axis2.war which is <TOMCAT_HOME>\webapps\axis2\WEB-INF\services.
  • Start/Restart the tomcat server and check to ensure the proper deployment of the service by hitting the URL,

http://localhost:8080/axis2/services/listServices.

Consuming the Webservice

  • Create a directory GreetServiceClient.
  • Use the wsdl2java tool to generate the java classes for the GreetService. Execute the following command.

GreetServiceClient>%AXIS2_HOME%\bin\wsdl2java -ss -g -uri

http://localhost:8080/axis2/services/GreetService?wsdl

  • On successful execution the tool will generate the artifacts in the GreetServiceClient folder along with an ant build script and the wsdl file in the resources folder.

You can see other options for wsdl2java tool for different configurations.

  • Write a java class to test the web service. GreetServiceClient/src/com/technicalmusings/samples/service/GreetServiceClient.java.

GreetServiceClient.java

package com.technicalmusings.samples.axis2.service;

import com.technicalmusings.samples.axis2.service.GetServerTimeResponse;
import com.technicalmusings.samples.axis2.service.Greet;
import com.technicalmusings.samples.axis2.service.GreetResponse;
import com.technicalmusings.samples.axis2.service.GreetServiceStub;

public class GreetServiceClient {

public static void main(String[] args) throws Exception{
//Create the stub
GreetServiceStub stub =
new GreetServiceStub(“http://localhost:8080/axis2/services/GreetService“);

//Call the getServerTime method
GetServerTimeResponse timeResponse = stub.getServerTime();
System.out.println(“The server time is:” + timeResponse.get_return());

//Call the greet method
Greet greetInput = new Greet();
greetInput.setParam0(“Axis2”);
GreetResponse greetResponse = stub.greet(greetInput);
System.out.println(“Server responded:” + greetResponse.get_return());
}

}

  • Now in order to compile this class we need to set the required libraries in the classpath. I am using minimum libraries needed to run the axis2 client.

The version of axis2 I am using is axis2-1.5.1.

Set the classpath:

\GreetServiceClient\src\com\technicalmusings\samples\axis2\service>set classpath=%AXIS2_HOME%/lib/activation-1.1.jar;

%AXIS2_HOME%/lib/axiom-api-1.2.8.jar;

%AXIS2_HOME%/lib/axiom-dom-1.2.8.jar;

%AXIS2_HOME%/lib/axiom-impl-1.2.8.jar;

%AXIS2_HOME%/lib/axis2-adb-1.5.1.jar;

%AXIS2_HOME%/lib/axis2-kernel-1.5.1.jar;

%AXIS2_HOME%/lib/axis2-transport-http-1.5.1.jar;

%AXIS2_HOME%/lib/axis2-transport-local-1.5.1.jar;

%AXIS2_HOME%/lib/commons-codec-1.3.jar;

%AXIS2_HOME%/lib/commons-fileupload-1.2.jar;

%AXIS2_HOME%/lib/commons-httpclient-3.1.jar;

%AXIS2_HOME%/lib/commons-logging-1.1.1.jar;

%AXIS2_HOME%/lib/geronimo-stax-api_1.0_spec-1.0.1.jar;

%AXIS2_HOME%/lib/httpcore-4.0.jar;

%AXIS2_HOME%/lib/mail-1.4.jar;

%AXIS2_HOME%/lib/neethi-2.0.4.jar;

%AXIS2_HOME%/lib/woden-api-1.0M8.jar;

%AXIS2_HOME%/lib/woden-impl-dom-1.0M8.jar;

%AXIS2_HOME%/lib/wsdl4j-1.6.2.jar;

%AXIS2_HOME%/lib/wstx-asl-3.2.4.jar;

%AXIS2_HOME%/lib/XmlSchema-1.4.3.jar;%classpath%;.

Compile the classes:

\GreetServiceClient\src>javac -d . com\technicalmusings\samples\axis2\service\*.java

Run the class:

\GreetServiceClient\src>java com.technicalmusings.samples.axis2.service.GreetServiceClient

Output:

The server time is:Mon Feb 01 17:55:29 IST 2010
Server responded:Hello Axis2
<!–[if !supportLineBreakNewLine]–>
<!–[endif]–>

Enjoy Learning,
Kamlesh