Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, April 4, 2016


When I was trying to call a service via HTTPS I observed the below issue.

FATAL: Error verifying developer key: Failed to read server's response: handshake alert:  unrecognized_name
br.eti.kinoshita.testlinkjavaapi.util.TestLinkAPIException: Error verifying developer key: Failed to read server's response: handshake alert:  unrecognized_name
 at br.eti.kinoshita.testlinkjavaapi.MiscService.checkDevKey(MiscService.java:63)
 at br.eti.kinoshita.testlinkjavaapi.TestLinkAPI.<init>(TestLinkAPI.java:144)
 at hudson.plugins.testlink.TestLinkBuilder.getTestLinkSite(TestLinkBuilder.java:318)
 at hudson.plugins.testlink.TestLinkBuilder.perform(TestLinkBuilder.java:197)
 at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
 at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:782)
 at hudson.maven.MavenModuleSetBuild$MavenModuleSetBuildExecution.build(MavenModuleSetBuild.java:906)
 at hudson.maven.MavenModuleSetBuild$MavenModuleSetBuildExecution.doRun(MavenModuleSetBuild.java:857)
 at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:534)
 at hudson.model.Run.execute(Run.java:1738)
 at hudson.maven.MavenModuleSetBuild.run(MavenModuleSetBuild.java:529)
 at hudson.model.ResourceController.execute(ResourceController.java:98)
 at hudson.model.Executor.run(Executor.java:410)
Caused by: org.apache.xmlrpc.XmlRpcException: Failed to read server's response: handshake alert:  unrecognized_name
 at org.apache.xmlrpc.client.XmlRpcStreamTransport.sendRequest(XmlRpcStreamTransport.java:161)
 at org.apache.xmlrpc.client.XmlRpcHttpTransport.sendRequest(XmlRpcHttpTransport.java:143)
 at org.apache.xmlrpc.client.XmlRpcSunHttpTransport.sendRequest(XmlRpcSunHttpTransport.java:69)
 at org.apache.xmlrpc.client.XmlRpcClientWorker.execute(XmlRpcClientWorker.java:56)
 at org.apache.xmlrpc.client.XmlRpcClient.execute(XmlRpcClient.java:167)
 at org.apache.xmlrpc.client.XmlRpcClient.execute(XmlRpcClient.java:158)
 at org.apache.xmlrpc.client.XmlRpcClient.execute(XmlRpcClient.java:147)
 at br.eti.kinoshita.testlinkjavaapi.BaseService.executeXmlRpcCall(BaseService.java:90)
 at br.eti.kinoshita.testlinkjavaapi.MiscService.checkDevKey(MiscService.java:60)
 ... 12 more
Caused by: javax.net.ssl.SSLProtocolException: handshake alert:  unrecognized_name
 at sun.security.ssl.ClientHandshaker.handshakeAlert(ClientHandshaker.java:1292)
 at sun.security.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:1952)
 at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1077)
 at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
 at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
 at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
 at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:563)
 at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
 at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1091)
 at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250)
 at org.apache.xmlrpc.client.XmlRpcSunHttpTransport.writeRequest(XmlRpcSunHttpTransport.java:104)
 at org.apache.xmlrpc.client.XmlRpcStreamTransport.sendRequest(XmlRpcStreamTransport.java:151)
 ... 20 more
ERROR: Error communicating with TestLink. Check your TestLink configuration.
Finished: FAILURE

The reason for this issue is the server sends an unrecognized host in the time of handshake. And java client fails due to this. Most other clients will ignore this alert and proceed but from JAVA 7 this doesn't work like that.

This can happen due to misconfigurations in the servers. If you come across the above issue there are several ways to get this resolved. You can use the method 1 if you do not have accesses to the remote server.


1. By disabling SNI verification.

This is one of the workarounds you can follow, you can simply set the following JVM property at the client side.
-Djsse.enableSNIExtension=false

e.g : In the below example I have set this property to TomCat run-time. So SNI will be disabled globally. You can do this in class level as well.
export CATALINA_OPTS="-Djsse.enableSNIExtension=false"

2. By modifying Apche2 configurations. 

In Apache2 server configurations make sure you have set the following parameters

ServerName testlinkstaging.wso2.com
ServerAlias testlinkstaging.wso2.com

Full configs will look like following.
<VirtualHost testlinkstaging.wso2.com:443>
    ServerName testlinkstaging.wso2.com
    ServerAlias testlinkstaging.wso2.com
    SSLEngine on
    SSLCertificateFile  /etc/apache2/ssl/apache.crt
    SSLCertificateKeyFile /etc/apache2/ssl/apache.key

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/testlink

</VirtualHost>


That's it, If everything is set properly you should be able to access the SSL endpoint.

Please drop a comment if you have any queries.

Tuesday, January 19, 2016



In this post I will reveal how you can easily setup multiple java environments and switch between them easily.

This is a simple method I use, sharing in case anyone is interested. Please follow the steps below.

1. Download and extract the java version you require in your PC. I will be using Java 1.7 and Java 1.8 for the demonstration purpose. I have extracted java 1.7 and 1.8 to following locations.

e.g : /home/yasassri/soft/java/jdk1.8.0_05
        /home/yasassri/soft/java/jdk1.7.0_65

2. Now Open the bachrc file using your favorite text editor. You can use the following commands to do this.


vim ~/.bashrc

3. Now Add the following two alias at the end of the file.


# Setting Java 8
alias setjava18='export JAVA_HOME='/home/yasassri/soft/java/jdk1.8.0_05' && export PATH=$JAVA_HOME/bin:$PATH && source ~/.bashrc'

#Setting Java 7
alias setjava17='export JAVA_HOME='/home/yasassri/soft/java/jdk1.7.0_65' && export PATH=$JAVA_HOME/bin:$PATH && source ~/.bashrc'

Note : You need to replace '/home/yasassri/soft/java/jdk1.8.0_05' and '/home/yasassri/soft/java/jdk1.7.0_65' with the file location of extracted Java folders in your PC.

4. Save and exit the file.

5. Execute the following command.


source ~/.bashrc

6. Everything is set now. Now execute the following command in your terminal.


setjava18

Now check the Java version that is set with java -version, Java 8 will be set.

7. Now execute following 


setjava17

Now Java 1.7 will be set.

Thanks for reading and please drop a comment if you have any issues. 

Thursday, June 26, 2014

WebSockets

Websockets are mainly used for cross browser communication so in most cases the browser act as the client to connect to the socket server, But in some cases you might need a java client to send messages to a socket server. According to my research this area is not well documented. So I will try to implement a Java Client to access a websocket.


Prerequisites

For this sample application I will be Using a sample echo Websoket server located at "http://www.websocket.org/echo.html". You can also use wesocket server which I developed in a previous Blog post, You can Find it here.

I will be using Jetty for this implementation and Eclipse IDE for coding.

Developing the sample

Step 01

Create a new Java Project and lets call it "WebSocketJavaClient" and in the "src" directory create a new java Class with the following name in the mentioned package.



Step 02

Now add the following code segment to the newly created class.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package org.socket.client;

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

import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.StatusCode;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;

@WebSocket
public class WebSocketObject {
 
 public Session session;
 
 @OnWebSocketClose
 public void onClose(int statusCode, String reason) {
  System.out.printf("Connection closed: %d - %s%n", statusCode, reason);
  this.session = null;
 
 }

 @OnWebSocketConnect
 public void onConnect(Session session) {
  System.out.printf("Got connect: %s%n", session);
  this.session = session;
   
 }

 @OnWebSocketMessage
 public void onMessage(String msg) {
  System.out.println("Message Recieved : "+ msg.toString());
 }
 
 
 public void  sendMessage(String message){
  
  session.getRemote().sendStringByFuture(message);
  
 }
 
 public void closeConnection() {
  session.close(StatusCode.NORMAL, "[Consumer]Closing the session with the Server!!");
  
 }

}



Step 03

Now add the following Jar file as a External jar to your Class Path "jetty-all-9.2.1.v20140609.jar".

Note : I have tested it with the above version and you can use any other version and tryout, the above jar can be downloaded from here.


Step 04

Create a another java class with the following details.



Step 05

Now add the following Code snippet to the newly created class.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package org.socket.client;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.concurrent.TimeUnit;

import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
 
/**
 * Sample Websocket Client
 */
public class SocketClient {
 
    public static void main(String[] args) {
        
      //  String destUri = "ws://localhost:8080/webSocketSample/server";
        String destUri = "ws://echo.websocket.org";
        String message;
        
        WebSocketClient client = new WebSocketClient();
        WebSocketObject socket = new WebSocketObject();
        try {
            client.start();
        
            URI echoUri = new URI(destUri);
            ClientUpgradeRequest request = new ClientUpgradeRequest();
            client.connect(socket, echoUri, request);
            System.out.println("Connecting to :" +echoUri);
            Thread.sleep(1000);
            BufferedReader myReader = new BufferedReader(new InputStreamReader(System.in));
            
            while (true) {
             
    System.out.print("Enter Message : ");
    message = myReader.readLine();
    socket.sendMessage(message);
    Thread.sleep(1000);
    
   }
            
                       
          } catch (Throwable t) {
            t.printStackTrace();
        } finally {
            try {
             socket.closeConnection();
                client.stop();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Note : I have added a delay in order to synchronize the Outgoing and incoming messages viewed on console, It is not necessary

Step 06

Now run the "SocketClient.java". When You enter a message the messages will be echoed back by the server.




Note : The code can be improved alot and this is the simplest sample that I can come-up with, You can refer to Jetty documentation for more detailed information. Please fell free to comment below if you have any questions.

You cqan Fing the Code from following Location, https://github.com/ycrnet/WebSocketJavaClient.git

Thanks for reading.

What are Websockets


Websockets allow two way communication between the server and the Client resulting low latency communication between client and the server. It allows  full-duplex communications channels over a single TCP connection. It also allows to break free from the request/response paradigm on what the traditional web was based on. Websockets further enhances the AJAX capabilities, where AJAX communication is also steered by a Client.

WebSockets provide new protocol between client and server which runs over a persistent TCP connection. Through this open connection, bi-directional, full-duplex messages can be sent between the single TCP socket connection (simultaneously or back and forth).


WebSockets Diagram How do websockets work?


The sample

The Sample demonstrate a simple application that runs with web-sockets, the application will echo/ broadcast messages when the server receives it to all the active connections.

GlassFish server will be used with eclipse IDE to develop the sample.

How to Create the Application

Writing The Socket Server

Step 01

Open Eclipse and Create a new dynamic web project with the name "webSocketSample" and with all the default configurations.



Step 02

Add the Glassfish server to your Project, This can be done in many ways the easiest way is to first download the compatible version of GlassFish server and then add it. You can do this by Going to Servers Tab and Select Add new server as shown below.



Follow the wizard and make sure you add your project to configured project list so it will automatically get deployed when the server in starting.


Step 03

Expand the project and go to Javaresorces/src  directory and create a new Java class with the following Name and package.



Note : Make sure You have added all the Libraries to your Project as shown below. (The Glassfish System library contains some jars needed for this project) If not added you can these libraries manually.





Step 03

Add the following Code Snippets to your newly Created Class


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package org.socket.server;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonWriter;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.*;

@ServerEndpoint("/server")
public class SocketServer { 
 
 // Storing the sessions
 static Set <Session> clientUIs = Collections.synchronizedSet(new HashSet<Session>());
 @OnOpen
 public void handleOpened(Session clientSession) throws IOException {
  clientUIs.add(clientSession);
  
   clientSession.getBasicRemote().sendText(buildJsonData("System", "You are now connected to the Map Server!!!"));
 
  System.out.println("A New Client is Connected!!!!");
 }
 
 @OnMessage
 public void handleMessage(String message, Session clientSession) throws IOException{
   System.out.println("A Message Received!!!");
     
   Iterator<Session> iterator = clientUIs.iterator();
   while (iterator.hasNext()){
    
    iterator.next().getBasicRemote().sendText(buildJsonData("Message : ", message));
    
   }
 }
 
 @OnClose
 public void handleClose (Session id){
  
  clientUIs.remove(id);
 }

 private String buildJsonData(String id, String message) {
  // TODO Auto-generated method stub
  JsonObject json = Json.createObjectBuilder().add("message", id+ ": " +message).build();
  StringWriter strwriter = new StringWriter();
 
   try (JsonWriter jsonwriter = Json.createWriter(strwriter)) {jsonwriter.write(json);}
  
   System.out.println("The Jason : "+strwriter.toString());
  return strwriter.toString();
 }

}



Writing The Client To Access the Socket

Step 01

Now in your project go to webcontent  directory and create a file called "index.html"

And add the following code into that file. Note the Javascript code that initiate the websocket connection.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>The Map UI</title>
<script type="text/javascript">
 var websocket = new WebSocket(
   "ws://localhost:8080/webSocketSample/server");

 websocket.onmessage = function processMessage(message) {

  var jsonData = JSON.parse(message.data);
  if (jsonData != null) {
   messagesTextArea.value += jsonData.message + "\n";

  }
 }
 function sendMessage() {
  websocket.send(messageText.value);
  messageText.value = "";

 }
</script>
</head>
<body>

 <div>
  <br>
  <br>
  
  <h3>Output Console</h3>
    
  <textarea id="messagesTextArea" rows="8" cols="80"></textarea>
  <br>
  <input type="text" id="messageText" size="50" /> 
  <input id="button1" type="button" value="Send Message" onclick="sendMessage();">

 </div>


</body>
</html>


Step 02

Make sure that you don't have any errors in the code, and now start the glassfish server and go the following URL with two different browsers.

http://localhost:8080/webSocketSample/index.html 


If the application is successfully connected to the server the Output console will show a message "System: You are now connected to the Map Server!!!"

Now send a message with one browser and the message will be broadcast to all the application that are connected with the server.



You have successfully Implemented Simple Application with websockets, You can Find the Source Code at following guthub location

https://github.com/ycrnet/WEbSocketsWithGlassFish

Thank You!

Please Feel free to contact me anytime... :)


Sunday, May 25, 2014

Hi, in this Posts I will be explaining you how to develop the client to access the AXIOM based AXIS2 web service, what we created in part 1 and tested in part 2.

Ok So lets get started


Prerequisites

The service should be developped and deployed in Axis2, this is explained in part 1 of this post series.
I will be using eclipse to create my client.

Architecture of the client

Customers items will be added to the itemsList and all the items will be processes when buying the items (Final Checkout). There won't be any user inputs or interfaces, this is a simple client side application to demonstrate how a service can be accessed in Axis2 via AXIOM So all the inouts will be hard coded in the client application.

Creating the Client

Step 1

  1. Create a new Java Project and lets name it "Axis2_Webservice".
  2. Within "src" directory let's create a package as follows, "televisionshop.client"
  3. To resolve dependency issues add all the jars in the <AXIS2_HOME>/lib directory into your class path. All the jars may not be required, doing this to make things easy :)
  4. Now within the created package create a new java class named "TelevisionShopClient.java" with the following code snippets

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package televisionshop.client;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.xml.namespace.QName;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;

public class TelevisionShopClient {

 private static String namespace = "http://myshop.com/xsd";

 // Customer Items will be added to the itemList
 static HashMap<String, String> itemList = new HashMap<String, String>();

 private static EndpointReference endPointRef = new EndpointReference(
   "http://localhost:8080/axis2/services/TelevisionShopService");

 public static OMElement getProductAXIOMXML(String id) {
  OMFactory fac = OMAbstractFactory.getOMFactory();
  OMNamespace omNs = fac
    .createOMNamespace("http://myshop.com/xsd", "tns");

  OMElement method = fac.createOMElement("getProduct", omNs);
  OMElement value = fac.createOMElement("id", omNs);
  value.addChild(fac.createOMText(value, id));
  method.addChild(value);
  return method;
 }

 public static OMElement setProductAXIOMXML(String id, String model,
   String price, String qty) {
  OMFactory fac = OMAbstractFactory.getOMFactory();
  OMNamespace omNs = fac
    .createOMNamespace("http://myshop.com/xsd", "tns");

  OMElement method = fac.createOMElement("setProduct", omNs);

  OMElement value1 = fac.createOMElement("id", omNs);
  value1.addChild(fac.createOMText(value1, id));
  method.addChild(value1);

  OMElement value2 = fac.createOMElement("model", omNs);
  value2.addChild(fac.createOMText(value2, model));
  method.addChild(value2);

  OMElement value3 = fac.createOMElement("price", omNs);
  value3.addChild(fac.createOMText(value3, price));
  method.addChild(value3);

  OMElement value4 = fac.createOMElement("qty", omNs);
  value4.addChild(fac.createOMText(value4, qty));
  method.addChild(value4);

  return method;
 }

 public static void getProductDetails(String id) throws AxisFault {

  OMElement getPhonePayload = getProductAXIOMXML(id);
  Options options = new Options();
  options.setTo(endPointRef);
  options.setTransportInProtocol(Constants.TRANSPORT_HTTP);

  ServiceClient sender = new ServiceClient();
  sender.setOptions(options);

  OMElement result = sender.sendReceive(getPhonePayload);

  System.out.println("Model : "
    + result.getFirstChildWithName(new QName(namespace, "model"))
      .getText());
  System.out.println("Price  : "
    + result.getFirstChildWithName(new QName(namespace, "price"))
      .getText());
  System.out.println("QTY On Stocks : "
    + result.getFirstChildWithName(new QName(namespace, "qty"))
      .getText());
  System.out.println();

 }

 public static void updateProductDetails(String id, String model,
   String price, String qty) {

  try {
   OMElement updatePhonePayload = setProductAXIOMXML(id, model, price,
     qty);
   Options options = new Options();
   options.setTo(endPointRef);
   options.setTransportInProtocol(Constants.TRANSPORT_HTTP);

   ServiceClient sender = new ServiceClient();
   sender.setOptions(options);

   sender.fireAndForget(updatePhonePayload);

   System.out.println("Updated Product Details of Product : " + model);

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

 }

 public static void buyItems(HashMap itemList) throws AxisFault {

  Iterator it = itemList.entrySet().iterator();
  float total = 0;
  System.out.println("=================================================");
  System.out.println("===========YOUR ORDER DETAILS====================");
  System.out.println("=================================================");

  while (it.hasNext()) {
   Map.Entry entry = (Map.Entry) it.next();
   String key = (String) entry.getKey();
   String val = (String) entry.getValue();

   OMElement getPhonePayload = getProductAXIOMXML(key);
   Options options = new Options();
   options.setTo(endPointRef);
   options.setTransportInProtocol(Constants.TRANSPORT_HTTP);

   ServiceClient sender = new ServiceClient();
   sender.setOptions(options);

   OMElement result = sender.sendReceive(getPhonePayload);

   String model = result.getFirstChildWithName(
     new QName(namespace, "model")).getText();

   if (Integer.parseInt(result.getFirstChildWithName(
     new QName(namespace, "qty")).getText()) <= Integer
     .parseInt(val)) {
    System.out.println("Not Enough Stock for : " + model);
    System.out.println();
    continue;

   }
   float price = Float.parseFloat(result.getFirstChildWithName(
     new QName(namespace, "price")).getText());

   total += price * Float.parseFloat(val);

   System.out.println("Value of your Items : " + model
     + " Television : (No of Units : " + val + " ) = " + price
     * Float.parseFloat(val));

  }
  System.out.println();
  System.out.println("The Total Value of your Items = " + total);
  System.out.println();

 }

 public static void main(String[] args) throws AxisFault {

  // Adding Products to the Service
  updateProductDetails("001", "Samsung", "100", "6");
  updateProductDetails("002", "Philipse", "200", "15");

  // Retrieving information about a product
  getProductDetails("1");

  // Customer adding items to the List --> The first arguement is product
  // ID and Second is no of units
  itemList.put("001", "5");
  itemList.put("002", "3");

  // Checking out
  buyItems(itemList);

 }

}


  1. The final file structure will look like following,

  1. Now right click on the "TelevisionShopClient.java" file and select Run As >>> Java Application.


  1. The following output will be displayed on your output console of the IDE.


We have successfully developed our service and the client by using Axis2 and AXIOM.
Thank you for reading and direct me any queries you have. :)
Hi, this is the part two of the article where we are creating a complete AXIOM based web service with Axis2, If you haven't read the part one, please read it before going through this.

In this Post I will try to cover as much as possible regarding testing your webservice with SoapUI.

I will be using SoapUI 5.0 installed on top of Ubuntu 14.04.

Ok So lets begin.

What is SoapUI


SoapUI is a free tool that can be used to test web services.  SoapUI can test SOAP and REST based web services, JMS, AMF, as well as make any HTTP(S) and JDBC calls. Learn more from here.

Prerequisites


Install SoapUI on your PC, this can be done in two ways, Install SoapUI as a standalone Application or as a IDE plugin, I recommend to install this as a separate application.

Deploy your webservice created in part 1 and check whether it is deployed correctly as mentioned in that post.

Testing Your Service

Step 01

  1. Go to the Axis2 server URL and check whether the service is available. in my case the Axis2 services can be found at "http://localhost:8080/axis2/services/" 
  2. Click on the title of your service and you will be shown the WSDL of your service.


Note : The "wsdl" function following the service name will give you the WSDL of the service.

  1. Copy the url of the WSDL. 

Step 02

  1. Open SoapUI  and go to File >>> New SOAP Project.

  1. Then give an appropriate name to the project and paste the link of the WSDL of your service as shown in the following image and click OK.


  1. Now your project will be created with all service methods of your service. Note that Soap Binding 1.1 and 1.2 are automatically created by SoapUI.


  1. First lets test the "setProduct" method. Select the request which is located under setProduct method in the Soap1.1 Binding option as shown below.

  1. As you can see from the above image the full message or the payload that has to be sent to the service is not auto generated, as denoted by the "?" the necessary content has to placed in the marked position.
 Note that the message that the service expect is as following,


1
2
3
4
5
6
<tns:setProduct xmlns:tns="http://myshop.com/xsd">
   <tns:id>1</tns:id>
   <tns:model>Samsung</tns:model>
   <tns:price>100</tns:price>
   <tns:qty>6</tns:qty>
</tns:setProduct>

So lets add the required content to the correct place. make sure that your namespaces matches the namespaces defined in the service. The final message will look like following.


  1. Now click on the Submit Request button as shown in the above image. Nothing will be shown in the output window. :) Don't worry the service doesn't return anything so check the Axis2 console for any output. The Axis2 Console will show the following message if the request was successful.


The "setProduct" service is working fine now lets test the "getProduct" service.

  1. Now select the request of "getProduct" method and add the following SOAP content to the request. (make sure that you have already added the product you are going to query through setProduct method)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://service.televisionshop">
   <soapenv:Header/>
   <soapenv:Body>
     
         <!--Optional:-->
          <tns:getProduct xmlns:tns="http://myshop.com/xsd">
           <tns:id>001</tns:id>
          </tns:getProduct>
     
   </soapenv:Body>
</soapenv:Envelope>

Now click on Submit request button and the following output will be shown.



You have Successfully tested the web service you created, So in the next post I'll explain you how to write a simple client to access the service we created.

Thank for reading, and please feel free to drop a message or comment below if you have any issues. :)
Subscribe to RSS Feed Follow me on Twitter!