Tuesday, May 26, 2015

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