Previous Section  < Day Day Up >  Next Section

Hack 55 Convert Currency

figs/expert.gif figs/hack55.gif

Most people refer to a newspaper or web site to do currency conversions. Let an IRC bot using an appropriate Web Service do all the hard work for you.

Using Web Services again, you can create an easy hack that will convert currencies. Users can enter the names of two countries and see the exchange rate or convert a specified amount from one currency to another. This hack uses another service provided by XMethods. As with the other two previous Web Services examples, you need four pieces of information:


WSDL URL

http://www.xmethods.net/sd/2001/CurrencyExchangeService.wsdl


Operation

getRate


Input message parts

Country1 (a string), country 2 (a string)


Output message name

Result

A list of countries that can be used as inputs is provided near the end of this hack in Table 8-1. The first country is the currency you are converting from, and the second is the currency you are converting to. The conversion will relate one unit of currency from country1 to the calculated number of units of country2.

8.6.1 The Code

As with the other Web Service hacks [Hacks Section 8.4#53 and Section 8.5#54], very few changes other than adjusting variable values are required. Following is the code for the CurrencyService class and its method to convert currencies:

import java.util.*;

import samples.client.DynamicInvoker;



public class CurrencyService {



    static String wsdlLocation =

            "http://www.xmethods.net/sd/2001/CurrencyExchangeService.wsdl";

    static String operationName= "getRate";

    static String outputName = "Result";

    static String portName = null;



    public static String convert(String country1, String country2) {

        String[] args =

                new String[] {wsdlLocation, operationName, country1, country2};

        try {

            DynamicInvoker invoker=new DynamicInvoker(wsdlLocation);

            HashMap map = invoker.invokeMethod(operationName, portName, args);

            return map.get(outputName).toString( );

        }catch (Exception e){return null;}

    }

}

You now have a working method for using the Web Service to convert currencies. Like the previous service hacks, it will use PircBot and add code to the onMessage method. You can build this hack on top of the basic example in [Hack #35] or continue building up a multifunctional Web Services bot based on the previous Web Services hack. The bot will handle two types of messages—users can get the exchange rate or convert a specific amount of currency. To get the exchange rate, the bot will read messages in the following format:

WSBot, exchange COUNTRY1 to COUNTRY2

To process this request, you begin as with the previous example, using a StringTokenizer to parse the input:

        String query = t.nextToken( );

        if (query.equals("exchange")) {

            String response = "";

The next step will be to pull out the two country names. This is not trivial because some countries have two words in their names (e.g., Sri Lanka). Thus, you cannot just pull single tokens. The following code shows how to find the names for both countries. Since the word "to" separates the country names, you can concatenate words until you find the "to":

            String country1 = t.nextToken( );

            String next = t.nextToken( );

            while (!next.equals("to")){

                country1 = country1 + " " + next;

                next = t.nextToken( );

            }



            String country2 = t.nextToken( );



            while (t.hasMoreTokens( )) {

                next = t.nextToken( );

                country2 = country2 + " " + next;



            }

With the two country names taken care of, the only steps left are to call the Web Service and print an output message:

            sendMessage(channel, "Just a moment while I look that up...");

            String result = CurrencyService.convert(country1, country2);

            response = "1 unit of " + country1 + " currency is equal to ";

            response = response + result + " units of " + country2 + " currency.";

        } 

        sendMessage(channel, response);

    }

    ...

The second message will have an additional number, providing us with an amount to convert:

WSBot, convert AMOUNT COUNTRY1 to COUNTRY2

The code for this conversion is almost identical to the exchange rate code. The additional step requires us to get the amount of currency being converted and then multiply it by the exchange rate. The following code is identical to the previous code, except for the bold lines:

        String query = t.nextToken( );

        if (query.equals("convert")) {



            String response = "";

            String amount = t.nextToken( );

            String country1 = t.nextToken( );

            String next = t.nextToken( );

            while (!next.equals("to")){

                country1 = country1 + " " + next;

                next = t.nextToken( );

            }



            String country2 = t.nextToken( );



            while (t.hasMoreTokens( )){

                next = t.nextToken( );

                country2 = country2 + " " + next;



            }

        

            sendMessage(channel, "Just a moment while I look that up...");

            String result = CurrencyService.convert(country1, country2);



            double converted = Double.valueOf(amount).doubleValue( ) * 

                    Double.valueOf(result).doubleValue( );



            response = amount + " units of " + country1 + " 

                      currency is equal to ";

            response += converted + " units of " + country2 + " currency.";

        } 

        sendMessage(channel, response);

    }

8.6.2 Running the Hack

As with the previous Web Services hacks, you will need to ensure that you have all of the Axis components in your classpath when you compile the bot:

% javac -classpath .:pircbot.jar:axis-1_1/lib/axis.jar: \

axis-1_1/lib/axis-ant.jar: \

axis-1_1/lib/commons-discovery.jar:axis-1_1/lib/commons-logging.jar: \

axis-1_1/lib/jaxrpc.jar:axis-1_1/lib/log4j-1.2.8.jar:axis-1_1/lib/saaj.jar:\

axis-1_1/lib/wsdl4j.jar *.java

Depending on the name of your main class, you can then run the bot like so:

% java -classpath .:pircbot.jar:axis-1_1/lib/axis.jar: \ 

axis-1_1/lib/axis-ant.jar: \ 

axis-1_1/lib/commons-discovery.jar:axis-1_1/lib/commons-logging.jar: \ 

axis-1_1/lib/jaxrpc.jar:axis-1_1/lib/log4j-1.2.8.jar:axis-1_1/lib/saaj.jar:\ 

axis-1_1/lib/wsdl4j.jar  Main 

Replace Main with the correct name for your main class if it is different.

The conversions, shown in Figure 8-7, are quick and easy and can be requested by anyone in the same channel as the bot.

Figure 8-7. The Web Service bot performing currency conversions
figs/irch_0807.gif


Table 8-1 shows the list of supported countries for use with the currency conversion bot. For example, to convert 10 U.S. dollars to U.K. pounds, you say:

WSBot, convert 

10 us

 to 

uk

and the bot will respond with:

<WSBot> Just a moment while I look that up...

<WSBot> 10 units of currency from us is equal to 5.60108 units of uk currency.

Table 8-1. Country list for currency conversion Web Service
afghanistan
albania
algeria
andorra
angola
argentina
aruba
australia
austria
bahrain
bangladesh
barbados
belgium
belize
bermuda
bhutan
bolivian
botswana
brazil
england
united kingdom
uk
great britain
brunei
burundi
cambodia
canada
cape verde
cayman islands
chile
china
colombia
comoros
costa rica
croatia
cuba
cyprus
czech republic
denmark
dijibouti
dominican republic
east caribbean
ecuador
egypt
el salvador
estonia
ethiopia
euro
falkland islands
fiji
finland
france
gambia
germany
ghana
gibraltar
greece
guatemala
guinea
guyana
haiti
honduras
hong kong
hungary
iceland
india
indonesia
iraq
ireland
israel
italy
jamaica
japan
jordan
kazakhstan
kenya
korea
kuwait
laos
latvia
lebanon
lesotho
liberia
libya
lithuania
luxembourg
macau
macedonia
malaga
malawi kwacha
malaysia
maldives
malta
mauritania
mauritius
mexico
moldova
mongolia
morocco
mozambique
myanmar
namibia
nepal
netherlands
new zealand
nicaragua
nigeria
north korea
norway
oman
pakistan
panama
papua new guinea
paraguay
peru
philippines
poland
portugal
qatar
romania
russia
samoa
sao tome
saudi arabia
seychelles
sierra leone
singapore
slovakia
slovenia
solomon islands
somalia
south africa
spain
sri lanka
st. helena
sudan
suriname
swaziland
sweden
switzerland
syria
taiwan
tanzania
thailand
tonga
trinidad
tunisia
turkey
united states
us
usa
uae
united arab emirates
uganda
uk
ukraine
uzbekistan
vanuatu
venezuela
vietnam
yemen
yugoslavua
zambia
zimbabwe


Now when someone's boasting about how little they paid for a new CD when they were on holiday abroad, you can use this bot to find out what the equivalent amount is in your country.

Jennifer Golbeck

    Previous Section  < Day Day Up >  Next Section