Getting Started with Simple WSO2 ESB Connectors


A WSO2 connector allows you to interact with a third-party product's functionality and data from your ESB message flow, enabling you to connect to and interact with the APIs of services such as Twitter, Salesforce, and JIRA. This means that if you have enabled the Twitter and Google Spreadsheet connectors in your ESB instance,
your message flow could receive requests containing a user's Twitter name and password, log into the user's Twitter account, get a list of the user's followers, and write that information to a Google spreadsheet. You can use one or more connectors in order to manage generic use cases related to a business scenario that you may need to address.

The following topics provide more information on connectors and the use of connectors in managing various business scenarios:


Synapse Template : This is the component which calling to actual end point with the given request data. This will be placed in resources directory.

Proxy : This will handle the request coming inside to the ESB and response coming from the actual end point. This is not a part of connector, but need to invoke the connector.

Request : The request which follows the API published from the connector. This request can be REST or SOAP.

Connector for which API ?
There are large number of services which is provide in the world wide web to do a specific functions. In order to use these for developers, there will be one or several web service APIs  like REST, SOAP or a client libraries in one or several languages are provided by the service provider. Out of these, REST will be the simplest one that others since it has less work. Here we are using Atom feed Which are not using any Authentication and extra works.

Run the following maven command to generate sample maven connector project   code.


mvn archetype:generate -DarchetypeGroupId=org.wso2.carbon -DarchetypeArtifactId=org.wso2.carbon.mediation.library.connectors.connector-archetype -DarchetypeVersion=4.4.0 -DgroupId=org.wso2.carbon.connector -DartifactId=org.wso2.carbon.connector -Dversion=1.0.0

You may need give a name for the connector while processing the above process. (Let's proceed with entering HelloWorldConnector as connector name.) If the project creation success, you are ready to develop a connector with the following directory structure.




Writing Synapse Template :
You can have a look on the sample Synapse template generated at helloWorld directory. Following synapse template is providing the service at helloworld. This should be placed under "helloworld" directory as helloworldconnector-template.xml.

connector.xml
this will include the all available methods we can set list the available methods through list the dependency here. here we are calling to list the methods  from the dependency with the name helloworld. we can add more then one dependency here.
<?xml version="1.0" encoding="UTF-8"?>
<connector>
<component name="HelloWorldConnector" package="org.wso2.carbon.connector" >
<dependency component="helloWorld"/>
<description>wso2 sample connector library</description>
</component>
</connector>


component.xml
this is the dependency with the name helloworld. This may contain more then one component and this have only one method call helloworldconnector-operation and its synapse configuration written in helloworldconnector-template.xml.
<?xml version="1.0" encoding="UTF-8"?>
<component name="helloWorld" type="synapse/template" >
<subComponents>
<component name="helloworldconnector-operation">
<file>HelloWorldConnector-template.xml</file>
<description>sample wso2 connector library</description>
</component>
</subComponents>
</component>


helloworldconnector-template.xml
this will have the synapse configuration for the methods. here we need only the host address for the feeds so we get the value with the name HostAddress and sent it to org.wso2.carbon.connector.HelloWorldConnector class
<template xmlns="http://ws.apache.org/ns/synapse" name="helloworldconnector-operation">
<parameter name="HostAddress"/>
<sequence>
<log level="full">
<property name="HostAddress" expression="$func:HostAddress" />
</log>
<class name="org.wso2.carbon.connector.HelloWorldConnector" />
</sequence>
</template>



HelloWorldConnector.java
finally we received the Parameters. messageContext will have the values  we can extract the values from that and can sent back also.
/*
* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.connector;

import org.apache.abdera.Abdera;
import org.apache.abdera.model.Document;
import org.apache.abdera.protocol.client.AbderaClient;
import org.apache.synapse.MessageContext;
import org.wso2.carbon.connector.core.*;
import org.apache.abdera.model.Entry;

public class HelloWorldConnector extends AbstractConnector {

Abdera abdera;
AbderaClient abderaClient;

Document<Entry> doc;
String HostAddress;

public void connect(MessageContext messageContext) throws ConnectException {

try {
/**
* Add your connector code here
*/
HostAddress = getParameter(messageContext, "HostAddress").toString();
abdera = new Abdera();
abderaClient = new AbderaClient(abdera);

// Get the Entry from Server
doc = abderaClient.get(HostAddress).getDocument();

log.info(doc.getRoot());
} catch (Exception e) {
throw new ConnectException(e);
}
}
}


Now you can build the connector code and test the implemented service foe volume search method. To build the connector, run maven clean install command from the org.wso2.carbon.connector directory.

This will generate HelloWorldConnector.zip file in the target directory. You can upload this zip file through the ESB interface under connector category. Make sure you enabled the connector after uploading.

Writing Proxy :
Now you can invoke the implemented service for search volumes, by writing a proxy through ESB server interface. (Home>Manage>Services>Add>Proxy Service>Custom Proxy>switch to source view)

<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
name="Helloworld"
transports="http,https"
statistics="disable"
trace="disable"
startOnLoad="true">
<target>
<inSequence>
<HelloWorldConnector.helloworldconnector-operation>
<HostAddress>http://wso2experience.blogspot.com/feeds/posts/default</HostAddress>
</HelloWorldConnector.helloworldconnector-operation>
<log level="full"/>
<respond/>
</inSequence>
</target>
<description/>
</proxy>



now try
https://10.100.7.64:9443/services/Helloworld?tryit


Finally you will get the output in the bellow format for Atom feeds.

<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Example Feed</title>
<subtitle>Insert witty or insightful remark here</subtitle>
<link href="http://example.org/"/>
<updated>2003-12-13T18:30:02Z</updated>
<author>
<name>WSO@ Inc</name>
<email>WSO@@wso2.com</email>
</author>
<id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
<entry>
<title>Atom-Powered Robots Run Amok</title>
<link href="http://example.org/2003/12/13/atom03"/>
<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
<updated>2003-12-13T18:30:02Z</updated>
<summary>Some text.</summary>
</entry>

</feed>

References 

What is WSO2 Enterprise Service Bus (ESB)

An enterprise service bus (ESB) is a software architecture construct that enables communication among various applications. Instead of having to make each of your applications communicate directly with each other in all their various formats, each application simply communicates with the ESB, which handles transforming and routing the messages to their appropriate destinations.

This is the Formal Definition of ESB by WSO2 So Let's see the Word ESB and how its doing the Works.

Enterprise :  ­ the concept has been originally invented to reduce complexity of enterprise application integration (EAI) within an enterprise; the restriction has become obsolete since modern Internet communication is not limited to a corporate entity only.

Service​ :denotes non­iterative and autonomously executing programs that communicate with other services through message exchange

Bus​ : ­ is used in analogy to a computer hardware bus

Why ESB?

  • Individual software applications cannot achieve much 
  • Systems should be integrated to work together 
  • Enables free data flow across the organization, data sharing and unified data
    views 
  • Improves production and management efficiency through re­use of existing
    services  
  • Application users can make better decisions using universal information rather
    than isolated fragmentary information   
  • Proper feedback loop to enhance business operations, with integrated activity
    monitoring 

How ESB Works


  1. An application sends a message to the ESB.
  2. The message is picked up by a transport.
  3. The transport sends the message through a message pipe, which handles quality of service aspects such as security. Internally, this pipe is the in-flow and out-flow of Axis2. The ESB can operate in two modes:
  4. Both message transformation and routing can be considered as a single unit. As the diagram specifies, there is no clear separation between message transformation components and routing components. In WSO2 ESB, this is known as the mediation framework. Some transformations take place before the routing decision has been made while others take place after the routing decision. This is part of the Synapse implementation.
  5. The message is injected to the separate pipes depending on the destinations. Here again, quality of service aspects of the messages are determined.
  6. The transport layer takes care of the transport protocol transformations required by the ESB.
The diagram shows how a request propagates to its actual endpoint through the ESB using its architecture. Response handling is the reverse of this operation. There are other areas like Working with Tasks and Events that are not shown in the diagram. All these components can be managed and monitored through the WSO2 ESB management console.

WSO2 ESB Architecture


Transports

A transport is responsible for carrying messages that are in a specific format. WSO2 ESB supports all the widely used transports including HTTP/s, JMS, and VFS, and domain-specific transports like FIX. You can easily add a new transport using the Axis2 transport framework and plug it into the ESB.
Transports include the following components:
  • Message builders - Identify the message using the content type and convert it to common XML. There is a message builder associated with each content type. WSO2 ESB includes message builders for text-based and binary content.
  • Message formatters - The opposite partners of the message builders. The formatter converts the message back to its original format by referencing the content type just before the message handover to the transports.
You can implement new message builders and formatters using the Axis2 framework.
See Working with Transports.

Endpoints

An endpoint defines an external destination (such as a service) for a message. An endpoint can be specified as an address endpoint, WSDL endpoint, a load balancing endpoint , and more. An endpoint is defined independently of transports, allowing you to use the same endpoint with multiple transports. When you configure a message mediation sequence or a proxy service to handle the incoming message, you specify the transport to use and the endpoint where the message will be sent.
See Working with Endpoints.

Proxy Services

Proxy services are virtual services that receive messages and optionally process them before forwarding them to a service at a given endpoint. This approach allows you to perform necessary transformations and introduce additional functionality without changing your existing service. Any available transport can be used to receive and send messages from the proxy services.
See Working with Proxy Services.

APIs

An API in WSO2 ESB is analogous to a web application deployed in the ESB runtime. Each API is anchored at a user-defined URL context, much like how a web application deployed in a servlet container is anchored at a fixed URL context. An API will only process requests that fall under its URL context. The API defines one or more resources, which is a logical component of an API that can be accessed by making a particular type of HTTP call. This approach allows you to send messages directly into the ESB using REST.
See Creating APIs.

Topics

A topic allows services to receive messages when a specific type of event occurs by subscribing to messages that have been published to a specific topic.
See Working with Topics and Events.

Mediators

Mediators are individual processing units that perform a specific function, such as sending or filtering messages. WSO2 ESB includes a comprehensive mediator library that provides functionality for implementing widely used enterprise integration patterns (EIPs). You can also easily write a custom mediator to provide additional functionality using various technologies such as Java, scripting, and Spring.
See Mediators.

Sequences

Sequences are the configuration component for mediators. Sequences allow you to organize mediators to implement pipes and filter patterns.
See Mediation Sequences.

Tasks and Commands

Tasks allow you to configure scheduled jobs in the ESB and execute internal and external commands for mediation.
See Working with Tasks.

QoS Components

Quality of Service (QoS) components implement security for the proxy services, including the Apache implementations of Rampart and Sandesha, which are provided as modules.

Registry

WSO2 ESB provides a registry with a built-in repository that stores the configuration and configuration metadata that define your messaging architecture. You can also use a remote repository.

Management and Configuration GUI

The Management Console provides a graphical user interface (GUI) that allows you to easily configure the components mentioned above as well as manage and monitor the ESB.

Flexible Deployment

You can deploy WSO2 ESB in a clustered environment with a load balancer to achieve failover and high availability.

in A Business View

First Experience in WSO2

WSO2 its an leading open source Srilankan Base Company providing high quality products as open source. so as a new employee i want to say about the working environment of wso2 palm grove office its in kollupitty, srilanka. working in wso2 is an my dream from when i heart about wso2 because of they own passion. 5th of may 2015 i joined as Associate Software Engineer in wso2 from the point I’m starting to write this blog about my experience in wso2 . not only about technical stuff there are more to tell about wso2 experience.


I faced 7 Round of interviews to get into wso2 as an employee. first 5 rounds are technical then HR and Finally CEO of Wso2 Dr. Sanjeewa. its thrilling Experience. we faced first 2 round of interviews in WSO2 Jaffna and in few weeks later other 5 rounds in Palm Grove main Branch.

from the joining date like my university orientation here also we went for 3 days orientation about wso2. lot things about wso2 we learned and its revenue model is little bit interesting because its an open source company so its product and source codes are fully freely available in internet then how? yes support and maintenance is the revenue model to wso2. 


 wso2 have own culture not like other companies there is no micro management system here so employes have full freedom here . from 17th of June 2015 we assigned for teams. basically I’m interested in IoT stuffs but i assigned for ESB Connector Team. ESB is the Major product of WSO2 and its customers also Big. So I’m Starting a new journey  my in my life i hope it will start new ere in life from a great place to work wso2

  

Implement a service - order processing service using Axis2 Web Service and WSO2 Developer Studio (Eclipse)

 Lets Build a Simple Order Process Service Sample System Based on the Previous Sample I run in the WSO2 Developer Studio  So as usual in order run this Project we need Requirements if your a web services Developer then you no need to worry about extra Dependencies and other Downloads if your using WSO2 Developer Studio Because WSO2 Studio have all requirements for Develop web Services .I'm also new to Web Services Development so WSO2 Developer Studio reduce my other works except Service Development 

  In this post I'm going to explain How to Build a Simple Order Process Service System Using Eclipse , Axis2 and Apache Tomcat the System will Work Like Below One . So here First its Ask the Options to List what are the Menu Items Available in the Restaurant and if your Regular customer you can order Directly through type 2 and item number (eg:- 2 itemNo 015 for order Koddu)   and we can order more item one by one so after Order we just Press 4 and Card Credentials (eg:- 4 CNo 123456789 PNo 123)  in this case if your credentials valid and your card have a enough amount you will get success message 


###################################################################
######### Welcome to Order Process Service Sample testing #########
###################################################################

 To list All Available Menu Items                           Press 1
 To Order a Item      Press 2 and Type itemNo and Your orderig Item
 To list The Bill                                           Press 3
 To exit type -1

Type your request Here : 1

Item Number      Item Name      Item Prize
10         Tea         50
25         Piddu         15

13         Rice         350
015         Koddu         510
12         Pizza         500

 To list All Available Menu Items                           Press 1
 To Order a Item      Press 2 and Type itemNo and Your orderig Item
 To list The Bill                                           Press 3
 To exit type -1

Type your request Here : 2 itemNo 015

Item Number      Item Name      Item Prize
015         Koddu         510

Total Amount to pay is :Rs 510/=

 To list All Available Menu Items                           Press 1
 To Order a Item      Press 2 and Type itemNo and Your orderig Item
 To list The Bill                                           Press 3
 To Pay a Bill Press 4 and Type CNo yoursCardNumber and PNo YoursPinNumber


Type your request Here : 2 itemNo 12

Item Number      Item Name      Item Prize
015         Koddu         510
12         Pizza         500

Total Amount to pay is :Rs 1520/=

 To list All Available Menu Items                           Press 1
 To Order a Item      Press 2 and Type itemNo and Your orderig Item
 To list The Bill                                           Press 3
 To Pay a Bill Press 4 and Type CNo yoursCardNumber and PNo YoursPinNumber

Type your request Here : 4 CNo 123456789 PNo 123
Successfully Bill Payed
 WelCome Back Again


Please Refer Library Project Before Try this project is to understand the Basic concept of Creating New project and learn how is Running

System Requirement
These are the tools used in the tutorial.
1) Java Development Kit  (Download)
2) WSO2 Developer Studio (Download)
3) Apache Tomcat (Download)

 First We need to Configure Java_HOME and TOMCAT_HOME and Path also

JAVA_HOME :- Set the value to jdk directory (export JAVA_HOME=/home/rajjaz/Documents/jdk1.8.0_45)
TOMCAT_HOME :- Set the value to top level directory of your Tomcat install (export TOMCAT_HOME=/home/rajjaz/Documents/apache-tomcat-6.0.44)PATH :- Set the value to bin directory of your jdk (eexport PATH=$JAVA_HOME/bin:$PATH)


Create A Project

As we created Library Project in our Previous Post Here we Need to Create New Dynamic Web Project in the Name of OrderProcessSystem
and Create New 2 Packages into the Project called OrderProcess , OrderProcess.bean in the Java Resources Folder


Now It shout be in the above Format.

Step 1 Writing the Code

In This Project we are going to use some Constants in Multiple Place so in order to Reduce the Variable name Complexity I'm going to keep common or  Variables are used in service in a separate class Called OrderServiceConstants.Java


1
2
3
4
5
6
7
8
9
package OrderProcess;

public interface OrderServiceConstants {
String AVAILABLE_ITEMS= "availableItems";
String ALL_ITEMS = "allItemList";
String ORDERED_ITEMS = "orderedItems";
String CARD_LIST = "card";
String CARD_BALANCE = "cardBalance";
}

These are the Constants we are going to use in Multiple places so keep it in separate file. Other then that we need to Initialize Some other Values also in this scenario we are going to handle with the Menu Items and Payment Cards so Let's write a Method to Handle With these

So First Lets Start From Menu Items So Create a New Class File into OrderProcess.bean Package Called MenuItems.java File




 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
package OrderProcess.bean;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;

public class MenuItems {

private String itemname;
private String prize;
private String itemnumber;

public String getitemName() {
return itemname;
}

public void setitemName(String itemname) {
this.itemname = itemname;
}

public String getPrize() {
return prize;
}

public void setPrize(String itemname) {
this.prize = itemname;
}

public String getItemNo() {
return itemnumber;
}

public void setItemNo(String itemnumber) {
this.itemnumber = itemnumber;
}

public OMElement serialize(OMFactory fac) {
return null;
}
}

Here we are Declaring Methods in Menu Items Object to handle with Menu Items Attribute Item Name, Item Number and Item Prize

OK.Now we need to Define Actions with this Menu Item So Let's Create new Class Called MenuItemList.Java For Define the Actions Related with Menu Items in the same Package



 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
package OrderProcess.bean;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;

import java.util.HashMap;
import java.util.Iterator;

public class MenuItemList {

private HashMap itemTable;
private String listName;

public MenuItemList(String listName) {
this.itemTable = new HashMap();
this.listName = listName;
}

public void addItem(MenuItems menuItems) {
//Method to add the items in the particular ListName
itemTable.put(menuItems.getItemNo().trim(), menuItems);
}

public MenuItems getItem(String itemNo) {
//Method to Return a Item With the Given Item Number
return (MenuItems) itemTable.get(itemNo.trim());
}


public HashMap getItemTable() {
//to return a Item table
return itemTable;
}

public void setItemTable(HashMap itemtable) {
//Assign a List of Tables to New Table
this.itemTable = itemtable;
}

public String getListName() {
//Get the Name of the List
return listName;
}

public void setListName(String listName) {
//Set the Name to the List
this.listName = listName;
}

public OMElement serialize(OMFactory fac) {
return null;
}

public MenuItems[] getItemList() {
//Creating New Array From itemTable hashmap
MenuItems [] items = new MenuItems[itemTable.size()];
Iterator items_itr = itemTable.values().iterator();
int count = 0;
while (items_itr.hasNext()) {
items[count] = (MenuItems) items_itr.next();
//Storing Values into array
count ++;
}
return items;
}

public MenuItemList copy() {
//add values into hashmap in the form of MenuItem Object
MenuItemList items = new MenuItemList(getListName());
MenuItems [] allItems = getItemList();
for (int i = 0; i < allItems.length; i++) {
MenuItems allItem = allItems[i];
MenuItems menuItems = new MenuItems();
menuItems.setPrize(allItem.getPrize());
menuItems.setItemNo(allItem.getItemNo());
menuItems.setitemName(allItem.getitemName());
items.addItem(menuItems);
}
return items;
}
}

In the Above Class We are Writing Some Methods Related with Menu Items Actions. Specially getItemList and copy Methods.



 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
package OrderProcess.bean;

public class Card {
private String cardNo;
private String cardBal;
private String pinNo;

public Card() {
}

public Card(String cardNo, String pinNo , String cardBal) {
this.cardNo = cardNo;
this.cardBal = cardBal;
this.pinNo = pinNo;
}

public String getPinNo() {
return pinNo;
}

public void setPinNo(String PinNo) {
this.pinNo = PinNo;
}

public String getcardNo() {
return cardNo;
}

public void setCardNo(String cardNo) {
this.cardNo = cardNo;
}


public String getCardBal() {
return cardBal;
}

public void setCardBal(String cardBal) {
this.cardBal = cardBal;
}
}





 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
package OrderProcess.bean;

import org.apache.axis2.AxisFault;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import OrderProcess.OrderServiceLifeCycle;

import java.util.HashMap;
import java.util.Iterator;

public class CardList {
private HashMap<String, Card> cardList;
private HashMap<String, Card> cardHolder;

private static final Log log = LogFactory.getLog(CardList.class);

public CardList() {
this.cardList = new HashMap<String, Card>();
cardHolder = new HashMap<String, Card>();
}

public void addUser(Card card) throws AxisFault {
if (cardList.get(card.getcardNo().trim()) != null) {
throw new AxisFault("User has already registered.");
}
cardList.put(card.getcardNo(), card);
}

public boolean billPay(String cardNo, String pinNo, String total) throws AxisFault {
Card card = cardList.get(cardNo.trim());
if (card == null) {
throw new AxisFault("user has not registerd");
}
if (card.getPinNo().equals(pinNo)) {
cardHolder.put(cardNo, card);
if(Integer.parseInt(card.getCardBal())>=Integer.parseInt(total)){
card.setCardBal(String.valueOf(Integer.parseInt(card.getCardBal())-Integer.parseInt(total)));
cardList.put(card.getcardNo(), card);
return true;
}
else{
throw new AxisFault("Check Your Balance");
}

} else {
throw new AxisFault("Invalid Card Number , Pin Number incorrect");
}
}

public Card[] getUsers() {
Card [] users = new Card[cardList.size()];
Iterator users_itr = cardList.values().iterator();
int count = 0;
while (users_itr.hasNext()) {
users[count] = (Card) users_itr.next();
count ++;
}
return users;
}
}

2nd Step



ServiceLifeCycle

When you want to initialize database connections , starting threads and etc.. at the time you deploy service. You need to implement this interface and add additional (optional) attribute into services.xml.

void startUp:
this will be called during the deployement time of the service. irrespective of the service scope this method will be called

void shutDown
this will be called during the system shut down time. irrespective of the service scope this method will be called


As Mentioned in the Formal Definition for ServiceLifeCycle Here We need to Initialize Our Connection also its mean we have our Data in Service.xml file so we need to load data into system before system start to work so ServiceLIfeCycle Method used to load the Prerequirements before system Come to the Action . Let's see about our OrderServiceLifeCycle.Java Structure and How it's Modified for Order Process Service



  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
package OrderProcess;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axiom.om.util.StAXUtils;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.databinding.utils.BeanUtil;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.description.Parameter;
import org.apache.axis2.engine.DefaultObjectSupplier;
import org.apache.axis2.engine.ServiceLifeCycle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import OrderProcess.bean.MenuItems;
import OrderProcess.bean.MenuItemList;
import OrderProcess.bean.Card;
import OrderProcess.bean.CardList;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamReader;

import java.io.*;
import java.util.Iterator;

public class OrderServiceLifeCycle implements ServiceLifeCycle {
private static final Log log = LogFactory.getLog(OrderServiceLifeCycle.class);

public void startUp(ConfigurationContext configctx,
AxisService service) {
try {
String tempDir = System.getProperty("java.io.tmpdir");
File tempFile = new File(tempDir);
File libFile = new File(tempFile, "OrderProcess.xml");
//creating temporary files for saving the data
OMElement OrderElement;
OMElement cardElement;
boolean noFile = true;
if (!libFile.exists()) {
//Service starting at the first time or user has clean the temp.dir
//if file not already available
Parameter allItems = service.getParameter(OrderServiceConstants.ALL_ITEMS);
//read the values with the above parameter name
OrderElement = allItems.getParameterElement();
//Library OMElement Successfully created
} else {
//if file already created one then start to read the existing file instead of service.xml
InputStream in = new FileInputStream(libFile);
XMLStreamReader xmlReader = StAXUtils
.createXMLStreamReader(in);
StAXOMBuilder staxOMBuilder = new StAXOMBuilder(xmlReader);
OrderElement = staxOMBuilder.getDocumentElement();
//Library OMElement Successfully created
noFile = false;
}
processOmelemnt(OrderElement, service, noFile);
} catch (Exception exception) {
log.info(exception);
}
}

public void shutDown(ConfigurationContext configctx,
AxisService service) {
try {
MenuItemList availableItemList = (MenuItemList) service.getParameterValue(OrderServiceConstants.AVAILABLE_ITEMS);
MenuItemList allItemList = (MenuItemList) service.getParameterValue(OrderServiceConstants.ALL_ITEMS);
MenuItemList orderedItemList = (MenuItemList) service.getParameterValue(OrderServiceConstants.ORDERED_ITEMS);
CardList cardList = (CardList) service.getParameterValue(OrderServiceConstants.CARD_BALANCE);

OMFactory fac = OMAbstractFactory.getOMFactory();
OMElement libElement = fac.createOMElement("OrderProcess", null);
MenuItems[] bookList = allItemList.getItemList();

libElement.addChild(BeanUtil.getOMElement(
new QName(OrderServiceConstants.ALL_ITEMS),
bookList, new QName("item"), false, null));

libElement.addChild(BeanUtil.getOMElement(
new QName(OrderServiceConstants.AVAILABLE_ITEMS),
availableItemList.getItemList(), new QName("item"), false, null));


libElement.addChild(BeanUtil.getOMElement(
new QName(OrderServiceConstants.CARD_BALANCE),
cardList.getUsers(), new QName("card"), false, null));

String tempDir = System.getProperty("java.io.tmpdir");
File tempFile = new File(tempDir);
File libFile = new File(tempFile, "OrderProcess.xml");
OutputStream out = new FileOutputStream(libFile);
libElement.serialize(out);
out.flush();
out.close();

} catch (Exception e) {
log.info(e);
}
}

private void processOmelemnt(OMElement element, AxisService service, boolean fileFound) throws AxisFault {
MenuItemList allBookList = new MenuItemList(OrderServiceConstants.ALL_ITEMS);
// log.info("created "+allBookList.toString());
OMElement bookEle = element.getFirstChildWithName(new QName(OrderServiceConstants.ALL_ITEMS));
Iterator book_itr = bookEle.getChildren();
while (book_itr.hasNext()) {
Object obj = book_itr.next();
if (obj instanceof OMElement) {
OMElement omElement = (OMElement) obj;
allBookList.addItem((MenuItems) BeanUtil.deserialize(MenuItems.class, omElement, new DefaultObjectSupplier(), "book"));
}
}
MenuItemList availableBookList = new MenuItemList(OrderServiceConstants.AVAILABLE_ITEMS);
OMElement avaliableBooksEle =
element.getFirstChildWithName(new QName(OrderServiceConstants.AVAILABLE_ITEMS));
if (avaliableBooksEle != null) {
Iterator available_book_itr = avaliableBooksEle.getChildren();
while (available_book_itr.hasNext()) {
Object obj = available_book_itr.next();
if (obj instanceof OMElement) {
OMElement omElement = (OMElement) obj;
availableBookList.addItem((MenuItems) BeanUtil.deserialize(MenuItems.class, omElement, new DefaultObjectSupplier(), "book"));
}

}
}


MenuItemList lendBookList = new MenuItemList(OrderServiceConstants.ORDERED_ITEMS);
OMElement lendBooksEle =
element.getFirstChildWithName(new QName(OrderServiceConstants.ORDERED_ITEMS));
if (lendBooksEle != null) {
Iterator lend_book_itr = lendBooksEle.getChildren();
while (lend_book_itr.hasNext()) {
Object obj = lend_book_itr.next();
if (obj instanceof OMElement) {
OMElement omElement = (OMElement) obj;
lendBookList.addItem((MenuItems) BeanUtil.deserialize(MenuItems.class, omElement, new DefaultObjectSupplier(), "book"));
}
}
}

//Creating a UserList
CardList users = new CardList();
OMElement usersEle =
element.getFirstChildWithName(new QName(OrderServiceConstants.CARD_BALANCE));
if (usersEle != null) {
Iterator usre_itr = usersEle.getChildren();
while (usre_itr.hasNext()) {
Object obj = usre_itr.next();
if (obj instanceof OMElement) {
OMElement omElement = (OMElement) obj;
users.addUser((Card) BeanUtil.deserialize(Card.class, omElement,
new DefaultObjectSupplier(), "card"));
}

}
}

if (fileFound) {
//File if not in there then we need to copy all books into available book
availableBookList = allBookList.copy();
service.addParameter(new Parameter(OrderServiceConstants.AVAILABLE_ITEMS, availableBookList));
} else {
service.addParameter(new Parameter(OrderServiceConstants.AVAILABLE_ITEMS, availableBookList));
}

service.addParameter(new Parameter(OrderServiceConstants.ALL_ITEMS, allBookList));
service.addParameter(new Parameter(OrderServiceConstants.ORDERED_ITEMS, lendBookList));
service.addParameter(new Parameter(OrderServiceConstants.CARD_BALANCE, users));
}
}

In this case While Our System Deploying Values given in the Services.xml Adding in the Running Service So Our Programme Reading the Values in a two ways one from the services.xml if it is an first time Deployment Because as mentioned in the Programme it will store values in the server temporary folder if system shutdown.
To Create the File Data File if Already not exist

            String tempDir = System.getProperty("java.io.tmpdir");
File tempFile = new File(tempDir);
File libFile = new File(tempFile, "OrderProcess.xml");
 
 
If file Not Exist Already then read from the services.xml file using its parameter name and make it as OMElement
            Parameter allItems = service.getParameter(OrderServiceConstants.ALL_ITEMS);
OrderElement = allItems.getParameterElement();

If File Already there then Read data from xml file using XMLStreamReader and Build it as OMElement Using StAXOMBuilder
            InputStream in = new FileInputStream(libFile);
XMLStreamReader xmlReader = StAXUtils.createXMLStreamReader(in);
StAXOMBuilder staxOMBuilder = new StAXOMBuilder(xmlReader);
OrderElement = staxOMBuilder.getDocumentElement();

Now we Loaded All data into OMElement Called OrderedElement .Now Time to Extract the Searialised data as individual Objects.

 MenuItemList availableItemList = new MenuItemList(OrderServiceConstants.AVAILABLE_ITEMS);
OMElement avaliableItemsEle =
element.getFirstChildWithName(new QName(OrderServiceConstants.AVAILABLE_ITEMS));
if (avaliableBooksEle != null) {
Iterator available_book_itr = avaliableBooksEle.getChildren();
while (available_book_itr.hasNext()) {
Object obj = available_book_itr.next();
if (obj instanceof OMElement) {
OMElement omElement = (OMElement) obj;
availableItemList.addItem((MenuItems) BeanUtil.deserialize(MenuItems.class, omElement, new DefaultObjectSupplier(), "book"));
}

}
}
here we are creating a MenuItemList instance and name it as availableItems then we get the child nodes of the element availableItems. then we are getting its child nodes one by one with the name of book and creating new MenuItemList with the name availableItems. like wise we want to create for userList and OrderedItemList.

our Next Task is we need to load the data into Running Axis2 Service
 service.addParameter(new Parameter(OrderServiceConstants.AVAILABLE_ITEMS, availableItemList));

here we are Adding availableItemList MenuItemList into Service With the Name availableItemsavailableItems


Another Part of this Program is that  Save the Data When Service Shutdown. So to do this Work we have a method call shutDown.

MenuItemList availableItemList = (MenuItemList) service.getParameterValue(OrderServiceConstants.AVAILABLE_ITEMS); 
 
            OMFactory fac = OMAbstractFactory.getOMFactory();
OMElement libElement = fac.createOMElement("OrderProcess", null);
 
  
            libElement.addChild(BeanUtil.getOMElement(
new QName(OrderServiceConstants.AVAILABLE_ITEMS),
availableItemList.getItemList(), new QName("item"), false, null));
 
 
 
String tempDir = System.getProperty("java.io.tmpdir");
File tempFile = new File(tempDir);
File libFile = new File(tempFile, "OrderProcess.xml");
OutputStream out = new FileOutputStream(libFile);
libElement.serialize(out);
out.flush();
out.close();
 
 
 Here first we are getting the values from the Service then creating new OMElement and Add our values into that OMElement called libElement and save the libElement into OrderProcess.xml file.


3rd Step 


The Lifecycle interface should be implemented by your back-end service class if you wish to be notified of creation and cleanup by the Axis2 framework.

void init
 init() is called when a new instance of the implementing class has been created. This occurs in sync with session/ServiceContext creation. This method gives classes a chance to do any setup work (grab resources, establish connections, etc) before they are invoked by a service request

void destroy
 destroy() is called when Axis2 decides that it is finished with a particular instance of the back-end service class. It allows classes to clean up resources.

Now We want to be Ready to Handle the Request from Client So init() is the method is to ready for getting Request its mean through init() method we are getting ready for handle the requests so in our OrderService.Java File we do some Pre allocations for Each Clients its mean creating new interface to each Request to interact with System instead of client Directly interact with Service data. Through this process we are enabling Multiple Access to our Service.   


 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
package OrderProcess;

import org.apache.axis2.AxisFault;
import org.apache.axis2.context.ServiceContext;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.description.Parameter;

import OrderProcess.OrderServiceConstants;
import OrderProcess.bean.MenuItems;
import OrderProcess.bean.MenuItemList;
import OrderProcess.bean.Card;
import OrderProcess.bean.CardList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class OrderService {

private static final Log log = LogFactory.getLog(OrderService.class);
//To store all the available Items
private MenuItemList availableMenuItems;
//to keep all the Items in the system
private MenuItemList allMenuItems;
//to keep all the Ordered Items
private MenuItemList OrderedItems;
//to keep the system card Users
private CardList cardList;


public MenuItems[] listAllItems() {
return allMenuItems.getItemList();
}

public MenuItems[] listOrderedItems() {
return OrderedItems.getItemList();
}

public MenuItems[] order(String itemNo) throws AxisFault {
MenuItems menuItems = availableMenuItems.getItem(itemNo);
if (menuItems == null) {
menuItems = OrderedItems.getItem(itemNo);
if (menuItems != null) {
throw new AxisFault("Someone has borrowed the book");
}
throw new AxisFault("Your Requested Item Not in Our System");
}
OrderedItems.addItem(menuItems);
return OrderedItems.getItemList();
}


public boolean payBill(String cardNo, String pinNO,String total) throws AxisFault {
return cardList.billPay(cardNo, pinNO ,total);
}

/**
* Session related methods
*/
public void init(ServiceContext serviceContext) {
AxisService service = serviceContext.getAxisService();
this.availableMenuItems = (MenuItemList) service.getParameterValue(OrderServiceConstants.AVAILABLE_ITEMS);

this.availableMenuItems.setListName(OrderServiceConstants.AVAILABLE_ITEMS);
this.allMenuItems = (MenuItemList) service.getParameterValue(OrderServiceConstants.ALL_ITEMS);
this.OrderedItems = (MenuItemList) service.getParameterValue(OrderServiceConstants.ORDERED_ITEMS);
this.cardList = (CardList) service.getParameterValue(OrderServiceConstants.CARD_BALANCE);
}

public void destroy(ServiceContext serviceContext) throws AxisFault {
AxisService service = serviceContext.getAxisService();
service.addParameter(new Parameter(OrderServiceConstants.AVAILABLE_ITEMS, availableMenuItems));
service.addParameter(new Parameter(OrderServiceConstants.ALL_ITEMS, allMenuItems));
service.addParameter(new Parameter(OrderServiceConstants.ORDERED_ITEMS, OrderedItems));
service.addParameter(new Parameter(OrderServiceConstants.CARD_BALANCE, cardList));
}
}

Here what we are doing is first creating new instance of service for every client request to serve the service. So we are creating new instance of service and get the copy of Data from Main Service from they Parameter values and create new instance of Item Lists

        AxisService service = serviceContext.getAxisService();
this.availableMenuItems = (MenuItemList) service.getParameterValue(OrderServiceConstants.AVAILABLE_ITEMS);

Now Instance service have the copy of all Lists .its mean all data. Then When Client make a request Every Client have the fresh copy of existing data lists so every Transactions or Actions  that client doing is saving in the local copy . When a Particular Client Finish his works or Copy of data and Leave the System Then Axis2 Server Will Call Destroy Method to Update the Transactions on Original copy of the Service Currently Running Or Server.
 service.addParameter(new Parameter(OrderServiceConstants.AVAILABLE_ITEMS, availableMenuItems));


Once you Complete the Abouve Operations Now the Time To Add Web Services to the Project So Like as I Mentioned in the Library Project Add The Web Services to this Project  And Create Services.xml File as Default One and Run The Service on Server You Will Get The Below WSDL File To Describe the Service.


 Step 4


 Now the Time To Write Services.xml File
 The description of services are specified using services.xml. Each service archive file needs to have a services.xml in order to be a valid service and it should be available in the META-INF directory of the archive file(aar)


name: The service name will be the name of the archive file if the .aar file contains only one service, or else the name of the service will be the name given by the name attribute.
scope: (Optional Attribute) The time period during which runtime information of the deployed services will be available. Scope is of several types- "application", "soapsession", "transportsession", "request". The default value (if you don't enter any value) will be "request"
class: (Optional attribute) The full qualified name of the service lifecycle implementation class. ServiceLifeCycle class is useful when you want to do some tasks when the system starts and when it shuts down.
targetNamespace: (Optional Attribute) Target name space of the service. This value will be used when generating the WSDL. If you do not specify this value, the value will be calculated from the package name of the service impl class.
Description: (Optional) If you want to display any description about the service via Axis2 web-admin module, then the description can be specified here.
transports : (Optional) The transports to which the service is going to be exposed. If the transport element is not present, then the service will be exposed in all the transports available in the system. The transport child element specifies the transport prefix (the name of the transport specified in axis2.xml).
parameters: A services.xml can have any number of top level parameters and all the specified parameters will be transformed into service properties in the corresponding AxisService. There is a compulsory parameter in services.xml called ServiceClass that specifies the Java class, which performs the above transformation. This class is loaded by the MessageReceiver.
operations : If the service impl class is Java, then all the public methods in that service will be exposed. If the user wants to override it, he has to add the "operation" tag and override it. In a non-Java scenario or if you do not have a service class, then all the operations the user wants to expose by the service has to be indicated in the services.xml. It is specified as follows:


 The only compulsory attribute here is "name", which represents the operation name that is going to be exposed. Any operation can contain module references as well as any number of parameters. The most interesting thing is that you can register custom message receivers per operation. Then the registered message receiver will be the message receiver for the corresponding operation. If you do not specify the message receiver, then the default message receiver will perform the operation.

 As mentioned Above here we need to Mention the Class Path Correctly To Communicate Service Class Correctly. And Add the data Also Here With the Appropriate Parameter Name Because Using that Name we are identifying Parameters in Programme .

          <service name="OrderService"   class="OrderProcess.OrderServiceLifeCycle">
          <parameter name="ServiceClass" locked="false">OrderProcess.OrderService</parameter>



 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
<service name="OrderService"   class="OrderProcess.OrderServiceLifeCycle">
<Description>
Simple Order Service Process
</Description>
<messageReceivers>
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only" class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver" />
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</messageReceivers>
<parameter name="ServiceClass" locked="false">OrderProcess.OrderService</parameter>
<parameter name="allItemList">
<allItemList>
<book>
<prize>500</prize>
<itemNo>12</itemNo>
<itemName>Pizza</itemName>>
</book>
<book>
<prize>350</prize>
<itemNo>13</itemNo>
<itemName>Rice</itemName>>
</book><book>
<prize>510</prize>
<itemNo>015</itemNo>
<itemName>Koddu</itemName>>
</book><book>
<prize>50</prize>
<itemNo>10</itemNo>
<itemName>Tea</itemName>>
</book><book>
<prize>15</prize>
<itemNo>25</itemNo>
<itemName>Piddu</itemName>>
</book>
</allItemList>

<cardBalance>
<card>
<cardNo>123456789</cardNo>
<cardBal>50000</cardBal>
<pinNo>123</pinNo>
</card>

<card>
<cardNo>234567891</cardNo>
<cardBal>1000</cardBal>
<pinNo>456</pinNo>
</card>

<card>
<cardNo>345678912</cardNo>
<cardBal>500</cardBal>
<pinNo>789</pinNo>
</card>

<card>
<cardNo>456789123</cardNo>
<cardBal>100</cardBal>
<pinNo>567</pinNo>
</card>

</cardBalance>
</parameter>
</service>

Now Run The Service Again in Order to Load our Data And Service Start. You Will Get Below Output When You Complete Above All Process  .







Step 5


We Finish our Works with Server Part Now the Time to Initialize the Client part So here we are going to use RPCSeviceClent .RPCServiceClient is a convenient API built on ServiceClient, the whole idea is to provide an easy API to invoke a Web service without having any understanding on Axiom. As we will see soon, we pass Java objects and get the response as Java objects, so it is just a matter of working with Java objects to invoke a Web service.

Note: One of the restriction with RPCServiceClient is that we need to have exactly the same Java classes as in the service. In other worlds we need to have service related Java libraries in the client side to do the Web service call. The main reason is Axis2 has to do the correct serialization or the de-serialization . However if the Web service only uses simple types (such as int, string, boolean etc.. ), then we do not need to have the service code
in RPCServiceClient We using the Method Called invokeBlocking with two Types of Parameter Passing .and We  will get two types of output also.

public org.apache.axiom.om.OMElement invokeBlocking(QName opName,Object[] args)throws AxisFault

Here We are Passing Operation QName (to get the body wrapper element) and Arraylist of objects and it will Return the OMElement as Responce it will have the Requested Output.

OMElement elemnt = rpcClient.invokeBlocking(new QName("http://OrderProcess",
"listAllItems"), new Object[]{null});
 
OMElement elemnt = rpcClient.invokeBlocking(new QName("http://OrderProcess",
"listOrderedItems"), new Object[]{null});

public Object[] invokeBlocking(QName opName,Object[] args,Class[] returnTypes)throws AxisFault

In this point we are Sending peration QName (to get the body wrapper element), an array of argument Objects and object extending Callback which will receive notifications. responce Will be in the Requested one Formate.


Object obj [] = rpcClient.invokeBlocking(new QName("http://OrderProcess",
"order"), args.toArray(), new Class[]{MenuItems.class});
 
Object obj [] = rpcClient.invokeBlocking(new QName("http://OrderProcess",
"payBill"), args.toArray(), new Class[]{Boolean.class});
 
So we used Two Methods here if we need OMElement We can use first Method for other output Second Method.


  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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package client;

import org.apache.axiom.om.OMElement;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.databinding.utils.BeanUtil;
import org.apache.axis2.engine.DefaultObjectSupplier;
import org.apache.axis2.rpc.client.RPCServiceClient;

import OrderProcess.bean.MenuItems;

import javax.xml.namespace.QName;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

public class OrderServiceClient {
private static final String CARD_NAME = "CNo";
private static final String PIN_NUMBER = "PNo";
private static final String ITEM_NUMBER = "itemNo";
private static int total=0;
private static boolean ordered=false;

public static void main(String[] args) throws Exception {
OrderServiceClient client = new OrderServiceClient();
client.runClient();
}

public void showOptions() {
System.out.println();
System.out.println();
System.out.println(" To list All Available Menu Items Press 1");
System.out.println(" To Order a Item Press 2 and Type itemNo and Your orderig Item");
System.out.println(" To list The Bill Press 3");
if(ordered){
System.out.println(" To Pay a Bill Press 4 and Type CNo yoursCardNumber and PNo YoursPinNumber");
}
else {
System.out.println(" To exit type -1 ");
}

System.out.println();
System.out.println();

}
public void runClient() throws Exception {
//System.out.println("Enter service End Point Reference address : ");
String epr = "http://localhost:8080/OrderProcessSystem/services/OrderService";
//String epr =getInput();
RPCServiceClient rpcClient = new RPCServiceClient();
Options opts = new Options();
opts.setTo(new EndpointReference(epr));
rpcClient.setOptions(opts);
OrderServiceClient client = new OrderServiceClient();

System.out.println();
System.out.println();
System.out.println("###################################################################");
System.out.println("######### Welcome to Order Process Service Sample testing #########");
System.out.println("###################################################################");
System.out.println();

while (true) {
showOptions();
System.out.print("Type your request Here : ");

String commandsParms = getInput();
if (commandsParms != null) {
String[] args = commandsParms.split(" ");
String firstarg = args[0];
int command;
try {
command = Integer.parseInt(firstarg);
}
catch (NumberFormatException e) {
System.out.println("Illegal argument entered.\n");
continue;
}
switch (command) {
case 1 : {
client.listAllItems(rpcClient);
break;
}
case 2 : {
String isbn = null;
String username = null;
if (args.length < 2) {
System.out.println("No enough number of arguments");
break;
}

if (ITEM_NUMBER.equals(args[1])) {
isbn = args[2];
}

else{
System.out.println("Type itemNo and your wish Item");
}
client.orderItem(isbn, rpcClient);
ordered=true;
client.listOrderedItems(rpcClient);
break;
}
case 3 : {
client.listOrderedItems(rpcClient);
break;
}
case 4 : {
String cno = null;
String pno = null;
if (args.length < 5) {
System.out.println("No enough number of arguments");
break;
}
if (CARD_NAME.equals(args[1])) {
cno = args[2];
} else if (CARD_NAME.equals(args[3])) {
cno = args[4];
}

if (PIN_NUMBER.equals(args[1])) {
pno = args[2];
} else if (PIN_NUMBER.equals(args[3])) {
pno = args[4];
}
client.payBill(cno, pno,String.valueOf(total), rpcClient);
break;
}

case -1 : {
System.exit(0);
}
default: {
System.out.println("Wrong argument.\n");
break;
}
}
}
}

// System.in.read()
}

//

private String getInput() {
try {
byte b [] = new byte [256];
int i = System.in.read(b);
String msg = "";
if (i != -1) {
msg = new String(b).substring(0, i - 1).trim();
}
return msg;
} catch (IOException e) {
System.err.println(" occurred while reading in command : " + e);
return null;
}
}


public void orderItem(String isbn,
RPCServiceClient rpcClient) throws Exception {
rpcClient.getOptions().setAction("urn:order");
ArrayList args = new ArrayList();
args.add(isbn);

try{
Object obj [] = rpcClient.invokeBlocking(new QName("http://OrderProcess",
"order"), args.toArray(), new Class[]{MenuItems.class});
}
catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage().toString());
}
}


public void payBill(String userName,
String passWord,String total,
RPCServiceClient rpcClient) throws Exception {
rpcClient.getOptions().setAction("urn:payBill");
ArrayList args = new ArrayList();
args.add(userName);
args.add(passWord);
args.add(total);
try{
Object obj [] = rpcClient.invokeBlocking(new QName("http://OrderProcess",
"payBill"), args.toArray(), new Class[]{Boolean.class});
if(((Boolean) obj[0]).booleanValue()){
System.out.println("Successfully Bill Payed \n WelCome Back Again");
System.exit(0);
}
}
catch(Exception e){
System.out.println(e.getMessage().toString());
}

}

private void printMenuItems(OMElement element) throws Exception {
if (element != null) {
// System.out.println(element);
Iterator values = element.getChildrenWithName(new QName("http://OrderProcess", "return"));
System.out.println();
System.out.println("Item Number \t Item Name \t Item Prize");
while (values.hasNext()) {
OMElement omElement = (OMElement) values.next();
MenuItems menuItems = (MenuItems) BeanUtil.deserialize(MenuItems.class, omElement, new DefaultObjectSupplier(), "item");
System.out.println(menuItems.getItemNo()+"\t \t"+menuItems.getitemName()+"\t \t"+menuItems.getPrize());
System.out.println("");
}

}
}

private void printBill(OMElement element) throws Exception {
if (element != null) {
// System.out.println(element);
Iterator values = element.getChildrenWithName(new QName("http://OrderProcess", "return"));
System.out.println();

System.out.println("Item Number \t Item Name \t Item Prize");
while (values.hasNext()) {
OMElement omElement = (OMElement) values.next();
MenuItems menuItems = (MenuItems) BeanUtil.deserialize(MenuItems.class, omElement, new DefaultObjectSupplier(), "item");
System.out.println(menuItems.getItemNo()+"\t \t"+menuItems.getitemName()+"\t \t"+menuItems.getPrize());
total=total+Integer.parseInt(menuItems.getPrize());
System.out.println("");
}

System.out.println("Total Amount to pay is :Rs "+total+"/=");

}
}

public void listAllItems(RPCServiceClient rpcClient) throws Exception {
rpcClient.getOptions().setAction("urn:listAllItems");
try{
OMElement elemnt = rpcClient.invokeBlocking(new QName("http://OrderProcess",
"listAllItems"), new Object[]{null});
printMenuItems(elemnt);
}
catch(Exception e)
{
System.out.println(e.getMessage().toString());
}

}

public void listOrderedItems(RPCServiceClient rpcClient) throws Exception {
rpcClient.getOptions().setAction("urn:listOrderedItems");
OMElement elemnt = rpcClient.invokeBlocking(new QName("http://OrderProcess",
"listOrderedItems"), new Object[]{null});
printBill(elemnt);
}

}

Othere then That In above Process we are getting the End Poind Reference Address and Connect the Service through RPCServiceClient .

1.Service
2.Client