Dears,

This blog is moved to a new blog at:

The new update will be found at that new blog, please follow it!
This blog is no more updated.
Thanks for your visit!

Tuesday, September 17, 2013

Service oriented programming with Web service

Objective
This topic will present how to config the server Tomcat to run a Web service, and how to use a Web service in an application. The example will be taken with a Web service for four basic operators: add, subdivision, multiple, and division

Config Tomcat server for a Web service
- Step 1: Download Tomcat server from Apache site: http://tomcat.apache.org/download-70.cgi (version 6.0 and higher)
- Step 2: Download  web service (AXIS) library of Apache: http://axis.apache.org/axis/
- Step 3: unzip the axis folder, copy axis folder into Tomcat\webapps. And then copy xerces.jar from Tomcat\common\lib into Tomcat\webapps\axis\WEB-INF\lib



 - Step 4: setup your environment variables:
JAVA_HOME = absolute path to your java root directory
AXIS_HOME = absolute path to your unzipped axis folder
CATALINA_HOME = absolute path to your Tomcat folder
DEPLOY_HOME = {CATALINA_HOME}\webapps\axis\WEB-INF\lib


Create a Web service
- Step 5: Go to the directory: \Tomcat\webapps\axis, create a file named Calculators.jws with this content:

public class Calculators{
    public String Add(double x, double y){
        return (x+y)+"";
    }
   
    public String Sub(double x, double y){
        return (x-y)+"";
    }
   
    public String Mul(double x, double y){
        return (x*y)+"";
    }
   
    public String Div(double x, double y){
        return (x/y)+"";
    }
}

- Step 6: Verifying your Web service by running Tomcat server (run the file Tomcat\bin\startup.bat), then running your web browser and typing the URL into address bar:
http://localhost:8080/axis/Calculators.jws?wsdl
If this content appears, your Web service is well created!




 Using a Web service
We now develop an application that uses this Web service:
- There is a GUI to enter two numbers and four buttons for four operators
- Once a button is clicked, the application will call the corresponding function from Web service to calculate the results, and then returns the results to the interface to display.

There are three main classes based on MVC model:
- Calculator (model class): contains two numbers
- CalculView (view class): play the role of GUI to receive numbers and operator, and then display the results
- CalculControl (control class): binding the Web service, calculate and return the results to view class. It has four inner class to perform actions from four operator buttons.




Calculator.java
package ws;
import java.io.Serializable;

public class Calculator implements Serializable{
    private double firstnumber;
    private double secondnumber;
   
    public Calculator(){
    }
   
    public Calculator(double a, double b){
        firstnumber = a;
        secondnumber = b;
    }

    public double getFirstnumber() {
        return firstnumber;
    }

    public void setFirstnumber(double firstnumber) {
        this.firstnumber = firstnumber;
    }

    public double getSecondnumber() {
        return secondnumber;
    }

    public void setSecondnumber(double secondnumber) {
        this.secondnumber = secondnumber;
    }   
}

CalculView.java
package ws;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class CalculView extends JFrame implements ActionListener{
    private JTextField txtFirstnumber;
    private JTextField txtSecondnumber;
    private JButton btnAdd, btnSub, btnMul, btnDiv;
   
    public CalculView(){
        super("Calculator using web service");
       
        txtFirstnumber = new JTextField(8);
        txtSecondnumber = new JTextField(8);
        btnAdd = new JButton("Add");
        btnSub = new JButton("Subvision");
        btnMul = new JButton("Multiple");
        btnDiv = new JButton("Division");
       
        JPanel content = new JPanel();
        content.setLayout(new FlowLayout());
        content.add(new JLabel("First number:"));
        content.add(txtFirstnumber);
        content.add(new JLabel("Second number:"));
        content.add(txtSecondnumber);
        content.add(btnAdd);
        content.add(btnSub);
        content.add(btnMul);
        content.add(btnDiv);
                 
        this.setContentPane(content);
        this.pack();
       
        this.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                System.exit(0);
            }
        });
    }

    public void actionPerformed(ActionEvent e) {
    }
   
    public Calculator getNumbers(){
        Calculator cal = null;
        try{
            double a = Double.parseDouble(txtFirstnumber.getText());
            double b = Double.parseDouble(txtSecondnumber.getText());
            cal = new Calculator(a,b);
        }catch(Exception e){
           
        }
        return cal;       
    }
   
    public void showMessage(String msg){
        JOptionPane.showMessageDialog(this, msg);
    }
   
    public void addAddListener(ActionListener log) {
          btnAdd.addActionListener(log);
    }
   
    public void addSubListener(ActionListener log) {
          btnSub.addActionListener(log);
    }
   
    public void addMulListener(ActionListener log) {
          btnMul.addActionListener(log);
    }
   
    public void addDivListener(ActionListener log) {
          btnDiv.addActionListener(log);
    }
}


CalculControl.java
package ws;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.apache.axis.client.Service;
import org.apache.axis.client.Call;
import org.apache.axis.encoding.XMLType;
import javax.xml.rpc.ParameterMode;

public class CalculControl {
    private CalculView view;
   
    public CalculControl(CalculView view){
        this.view = view;
        view.addAddListener(new AddListener());
        view.addSubListener(new SubListener());
        view.addMulListener(new MulListener());
        view.addDivListener(new DivListener());
    }
   
    class AddListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            try {
                Calculator cal = view.getNumbers();
                if(cal != null){
                    String result = calculate("Add", cal);
                    view.showMessage("Add of " + cal.getFirstnumber() + " and " + cal.getSecondnumber() + " is: " + result);
                }else{
                    view.showMessage("Input data is not in well format!");
                }               
            } catch (Exception ex) {
                view.showMessage(ex.getStackTrace().toString());
            }
        }
    }
   
    class SubListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            try {
                Calculator cal = view.getNumbers();
                if(cal != null){
                    String result = calculate("Sub", cal);
                    view.showMessage("Subvision of " + cal.getFirstnumber() + " and " + cal.getSecondnumber() + " is: " + result);
                } else{
                    view.showMessage("Input data is not in well format!");
                }              
            } catch (Exception ex) {
                view.showMessage(ex.getStackTrace().toString());
            }
        }
    }
   
    class MulListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            try {
                Calculator cal = view.getNumbers();
                if(cal != null){
                    String result = calculate("Mul", cal);
                    view.showMessage("Multiple of " + cal.getFirstnumber() + " and " + cal.getSecondnumber() + " is: " + result);
                }else{
                    view.showMessage("Input data is not in well format!");
                }               
            } catch (Exception ex) {
                view.showMessage(ex.getStackTrace().toString());
            }
        }
    }
   
    class DivListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            try {
                Calculator cal = view.getNumbers();
                if((cal != null)&&(cal.getSecondnumber() != 0)){
                    String result = calculate("Div", cal);
                    view.showMessage("Division of " + cal.getFirstnumber() + " and " + cal.getSecondnumber() + " is: " + result);
                }else{
                    view.showMessage("Input data is not in well format!");
                }
            } catch (Exception ex) {
                view.showMessage(ex.getStackTrace().toString());
            }
        }
    }
   
    private String calculate(String methodName, Calculator cal){
        String result = "";
        String endpointURL = "http://localhost:8080/axis/Calculators.jws";
        Service service = new Service();
        try{
            Call call = (Call)service.createCall();
            call.setTargetEndpointAddress(new java.net.URL(endpointURL));
            call.setOperationName(methodName);
            call.addParameter("a", XMLType.XSD_DOUBLE, ParameterMode.PARAM_MODE_IN);
            call.addParameter("b", XMLType.XSD_DOUBLE, ParameterMode.PARAM_MODE_IN);
            call.setReturnType(XMLType.XSD_STRING);
            result=(String)call.invoke(    new Object[]{cal.getFirstnumber(),cal.getSecondnumber()});
        }catch(Exception ex){
            view.showMessage("Err: "+ex);
        }
        return result;
    }

    public static void main(String[] args) {
        CalculView view = new CalculView();
        CalculControl control = new CalculControl(view);
        view.setVisible(true);
    }
}


Results






 

 

 

2 comments:

  1. Sau nhiều năm lặn lội và bôn ba, cuối cùng e lại tra ra đúng bài giảng của thầy năm xưa :D

    ReplyDelete
    Replies
    1. Khi được người ta tận tình hướng dẫn tử tế thì có chịu học đâu, bây giờ lại phải tự mà lặn lội bôn ba! :p

      Delete