Home ecommerce Technical Clients   Contact Links News 01 Aug 2010
 
   
Home  
ecommerce  
Technical  
Clients  
Consultancy  
Partners  
Press pack  
News  
Contact  
Articles  
Links  
   
 
User 
Pass 
   
  Laundering your money
  Currency conversion using SOAP with Java and WAP
   
        Carl Whalley, 30-Nov-2001
Web services  
Pick up any computing journal today and you'd be forgiven for thinking the internet is nothing but a huge collection of web services waiting to happen. Web services? Yup - the cornerstone of the big boys (Microsoft .NET and Sun ONE) future net strategy is the provision of many small, targeted services which are easily accessible and communicate using the now universal platform of XML. Think of web sites you've seen which have news tickers, stock prices, the temperature in Alaska and so on tucked away in small boxes. The data which made up such content was traditionally sourced from a whole range of bizarre places: scraped from other websites (!), fed with proprietary protocols (eg RSS) or manually entered by the web administrators. The idea behind web services, and specifically SOAP, is to wrap the whole idea of providing this kind of content into one unified interface.  
The predominant protocol for the provision of web services is SOAP, the Simple Object Access Protocol. SOAP is a particular convention that clients and servers can use when passing XML documents between themselves, in fact the only way they can communicate is via XML. What's great is that it is also done over HTTP. This means that if your web browser can see it, so can your SOAP client. Suddenly a whole raft of routing and communication problems are eliminated such as proxy and firewall setups. Typically, a session may go as follows: a SOAP client is asked to get some piece of information from a SOAP server in order to process it. Say a user had surfed to a site with stock quotes - the SOAP client would be on the server he visited and the SOAP server would be remote to them both. The SOAP client creates the SOAP XML message in the correct format, basically a few mandatory elements plus the required service (data), and posts it to the url of the SOAP server. This then is analyzed and an XML message returned. To get at the data the SOAP client is interested in means understanding the XML document returned, which in our parlance means an XML parser is needed. Once the client has the required data it can be treated just like any other local item, and in our scenario displayed on the web page.  
Why Java?  
SOAP and Java fit very well together for 2 reasons. The first is XML, which as we've seen Java has huge support for. The second is the implementation of the clients and servers themselves. Java is terrific on the server because it has the ability to process the http streams directly with the use of servlets. These are small, targeted processes which run on the server and are triggered by specific events such as a url pattern match in an incoming request. Because they can control every byte which is sent back down as a http response they are perfectly suited for implementing SOAP servers. In fact, the Apache SOAP SDK (http://xml.apache.org) is made up in exactly this way.  
WAP: well, it's had its fair share of critics recently but the idea of instant information being available anywhere is certainly not to be sniffed at. Smartphones are getting more and more powerful. With the advent of 3G this idea of providing information/services in such a convenient format will become as important as putting it on your web page.  
In action  
So, let's look at bringing all this together. To demonstrate, I'll show you how you can implement a SOAP client in java to supply live currency rate exchanges to WAP devices. The service itself comes from the excellent xmethods site at http://www.xmethods.com. Here you will see a list of various services offered and the WSDL specification needed to use them. WSDL is the Web Service Description Language, implemented as (surprise, surprise) an XML document. The WSDL names the various services available and their associated parameters. It also specifies the names of the return values - remember this is a two way process and many web services and return values can be offered at the same time.  
To access a web service from Java we need the appropriate code for establishing the connections and making the calls. Fortunately, this is made very easy when using the Apache SOAP toolkit from http://xml.apache.org (version 2.2 at time of writing). This contains Java packages to support both SOAP clients as in our example and SOAP servers.  
The target platform is WAP, so in this design we use a JSP (Java Server Pages) frontend to render the WML user interface. The JSP will get the users input and call a servlet which issues the SOAP call. The servlet will then process the returned data and return to the JSP page which updates the WML with the new data. To keep things simple, I have restricted the list to 7 currencies and just allowed users to choose one and an amount before selecting the target and selecting "convert". This means all I need are 2 listboxes (source and target currencies) and an edit box for the amount. With WAP UI work we always have to consider the limited capabilities of most currently available devices.  
Once the Apache SOAP toolkit is installed (or at least soap.jar is in the applications classpath) the server code can be deployed. That's server from the point of view of the connecting WAP clients. You'll need a live internet facing server with a web container which can handle J2EE web apps. I use the excellent Resin (http://www.caucho.com), but any compliant ones will work. Update its config files to add the web app exchange, deploy the app and connect with a WAP phone. If you just want to visit the one I made earlier wapalong to http://wapinfoserv.com/exchange (targetted for the Ericsson R380).  
Server JSP  
The JSP is pretty standard stuff - note the first line tells the web container to treat the output stream as WML, otherwise your WAP phone would see a valid WML page as type HTML - not good!

<%@ page contentType='text/vnd.wap.wml' %>
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN"
 "http://www.wapforum.org/DTD/wml_1.1.xml">
<wml>
<head>
 <meta http-equiv="Cache-Control" content="max-age=0"
  forua="true"/>
</head>
 <card title="Wapinfoserv currency converter" id="init"
  newcontext="true">
  <p align="left">
   <img src="images/currencyex.wbmp" width="122" height="31"
    alt="Loading..."/>
<%
  if (request.getParameter("req") != null) {
      String outStr = request.getParameter("req")+" "
          +request.getParameter("c1")+" = ";
      outStr += request.getParameter("amt")+" "
          +request.getParameter("c2");
      out.println("</p>");
      out.println("<p>");
      out.println(outStr);
  }
  if (request.getParameter("val") != null) {
      String outStr = request.getParameter("c1")
          +"/"+request.getParameter("c2")
	  +":  "+request.getParameter("val");
      out.println("</p><p>( "+outStr+" )");
      out.println("</p>");
      out.println("<p>");
  }
%>
  Src
  <select name="c1" multiple="false">
   <option value="uk">GBP UK Pounds</option>
   <option value="euro">EUR Euro</option>
   <option value="france">FRF Francs</option>
   <option value="sweden">SEK Kronor</option>
   <option value="germany">DEM Deutsche Marks</option>
   <option value="usa">USD Dollar</option>
   <option value="japan">JPY Yen</option>
  </select>
  Amt [<input type="text" title="Amount:" name="amt"/>]
  </p>
  <p>
  Target
  <select name="c2" multiple="false">
   <option value="uk">GBP UK Pounds</option>
   <option value="euro">EUR Euro</option>
   <option value="france">FRF Francs</option>
   <option value="sweden">SEK Kronor</option>
   <option value="germany">DEM Deutsche Marks</option>
   <option value="usa">USD Dollar</option>
   <option value="japan">JPY Yen</option>
  </select>
  </p>
  <p>
   <do type="accept" label="Home" name="Home">
    <go href="http://wap.wapinfoserv.com"/>
   </do>
   <do type="accept" name="submit" label="Convert">
    <go method="post" href="conv">
     <postfield name="c1" value="$(c1)"/>
     <postfield name="c2" value="$(c2)"/>
     <postfield name="amt" value="$(amt)"/>
     <postfield name="returnpage" value="index.jsp"/>
    </go>
   </do>
  </p>
 </card>
</wml>
 
Server Java  
I made a small bitmap and converted it to WBMP for extra sparkle, this is currencyex.wbmp. Just remove the appropriate lines if this isn't available or required. The servlet is where all the action happens. The requested currencies and amount is passed in and it makes the SOAP call before returning back to the orginal JSP with its new values:

package com.carmichaeldata.soap;

import java.io.*;
import java.util.*;
import java.net.*;
import javax.servlet.http.*;
import javax.servlet.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import org.apache.soap.util.xml.*;
import org.apache.soap.*;
import org.apache.soap.encoding.*;
import org.apache.soap.encoding.soapenc.*;
import org.apache.soap.rpc.*;
import org.apache.soap.transport.http.SOAPHTTPConnection;

public class ConvertCurrency extends HttpServlet
{
    SOAPHTTPConnection st = null;

    public void doPost
    (
        HttpServletRequest      req,
        HttpServletResponse     res
    ) throws ServletException, IOException {
        URL url = new URL("http://services.xmethods.com:80/soap");
        String redir = req.getParameter("returnpage");
        String rate = "";

        try {
            double amount = 0.00;
            try {
                rate = ""
		  +getRate(url, req.getParameter("c1"),
		      req.getParameter("c2"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            redir += "?val="+rate;
            redir += "&c1="+req.getParameter("c1");
            redir += "&c2="+req.getParameter("c2");
            redir += "&req="+req.getParameter("amt");
            try {
                amount = (Double.valueOf(rate)).doubleValue()
		 * (Double.valueOf(
		     req.getParameter("amt")).doubleValue());
            } catch (Exception e) {
                System.err.println(e.toString());
            }
            redir += "&amt="+amount;

        } catch (Exception e) {
            System.err.println(e.toString());
        }
        res.sendRedirect(redir);
    }

    public Object getRate (URL serviceUrl,
      String currency1, String currency2) {

        SOAPHTTPConnection st = new SOAPHTTPConnection();

        Call call = new Call();
        call.setSOAPTransport(st);
        call.setTargetObjectURI("urn:xmethods-CurrencyExchange");
        call.setMethodName("getRate");
        call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
        Vector params = new Vector();
        params.addElement
	    (new Parameter("country1",
	       String.class, currency1, null));
        params.addElement
	    (new Parameter("country2",
	       String.class, currency2, null));
        call.setParams(params);

        Response resp;
        try {
            resp = call.invoke(serviceUrl, null);
        } catch(Exception e) {
            System.err.println(e.toString());
            return null;
        }

        Object value = null;

        if (!resp.generatedFault()) {
            Parameter ret = resp.getReturnValue();
            value = ret.getValue();
        } else {
            Fault fault = resp.getFault();
            System.err.println("SOAP call raised fault code:"
	        +fault.getFaultCode()
                +" Text:"+ fault.getFaultString());
        }
        return value;
    }
}

   

The net means business

Never before has it been possible to interact with such a vast market. Your business can extend right to the place you want it the most : your customers.  
Automated ebusiness is now very much an everyday reality across the globe.

Mobile Information

Instant access to realtime data. Make updates from any device and see it change on all connected systems. All views of your data are supplied from one central  
source. Use timely, accurate information where you need it the most - all secured by industry-standard encryption systems as used by the military and governments.

Your business is unique

No-one knows your business better than you. When extending it to the internet your individuality will be preserved. Methodologies exist which enable tried and  
tested business systems to be implemented modelling perfectly the business rules and logic you are using today.
Home | ecommerce | Technical | Clients | News | Contact | Consultancy | Partners | Links | Press pack |
Want your news on this web site? Have an opinion on it? Contact us
Established 1987. Copyright © 1999-2010 Carmichael Data Systems Ltd. All Rights Reserved. Privacy Statement.