Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform...

34
Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate Tyler Anderson ([email protected]) Freelance writer Backstop Media 27 Nov 2007 The Eclipse SOA Tools Platform (STP) plug-in and Apache Tuscany simplifies services development through the use of the popular Eclipse development environment. Apache Tuscany has also been integrated with the STP to provide a Service Component Architecture (SCA) Java™ run time for the services you create, allowing you to annotate your service using the SCA standard and Apache Tuscany annotations. In this tutorial, you will see STP and Apache Tuscany in action, through the creation of a Remote Method Invocation (RMI) service. Section 1. Before you start This tutorial is for new and veteran Web developers that would like to learn how to use the Eclipse SOA Tools Project to create an RMI service and see for themselves how the STP can simplify their SOA development. About this tutorial An essential characteristic of SOA is the ability to assemble new and existing services to create new applications that may consist of different technologies. SCA defines a simple service-based model for construction, assembly and deployment of network of services that is language-neutral. Apache Tuscany effectively provides Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 34

Transcript of Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform...

Page 1: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

Using the Eclipse SOA Tools Platform plug-in andApache TuscanyDeveloping an SCA Java RMI service

Skill Level: Intermediate

Tyler Anderson ([email protected])Freelance writerBackstop Media

27 Nov 2007

The Eclipse SOA Tools Platform (STP) plug-in and Apache Tuscany simplifiesservices development through the use of the popular Eclipse developmentenvironment. Apache Tuscany has also been integrated with the STP to provide aService Component Architecture (SCA) Java™ run time for the services you create,allowing you to annotate your service using the SCA standard and Apache Tuscanyannotations. In this tutorial, you will see STP and Apache Tuscany in action, throughthe creation of a Remote Method Invocation (RMI) service.

Section 1. Before you start

This tutorial is for new and veteran Web developers that would like to learn how touse the Eclipse SOA Tools Project to create an RMI service and see for themselveshow the STP can simplify their SOA development.

About this tutorial

An essential characteristic of SOA is the ability to assemble new and existingservices to create new applications that may consist of different technologies. SCAdefines a simple service-based model for construction, assembly and deployment ofnetwork of services that is language-neutral. Apache Tuscany effectively provides

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 34

Page 2: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

developers with an SCA Java run time by allowing Eclipse developers (Eclipse STPdevelopers, in this case) to use SCA in the development of Java servicecomponents in an SOA environment.

In this tutorial, you're going to build an RMI-based service that will be registered inthe server's RMI naming registry. You'll build the service according to the SCAspecification, implemented via Apache Tuscany, that will become part of your overallSOA solution. You will learn:

• How SCA ties into SOA

• How to install the Eclipse STP and Apache Tuscany run time

• How to create an SOA Tools SCA RMI-based service

• How to develop the services Time Bomb functionality

• How to create and develop a Java RMI client

• How to run and test the RMI service

System requirements

This tutorial uses Eclipse and Apache technologies for development with the STPplug-in:

Eclipse ClassicEclipse is the master platform upon which the Eclipse SOA Tools plug-in runson. V3.3.1 was used in this tutorial.

Eclipse STP and dependency plug-insThese are the core plug-ins you'll need to develop with the STP. This tutorialuses version I200710300730. There are several plug-ins available fordownload, so be sure to download the one with the stp-all-in-one- suffix. Thisdownload includes all the dependencies listed under the "Requirements"heading.

Apache Tuscany SCA JavaApache Tuscany contains the Java SCA implementation that the Eclipse STPplug-in utilizes in development of services using the SCA standard.

Later, you'll learn exactly how to install and prepare your Eclipse installation to usefor SCA development.

developerWorks® ibm.com/developerWorks

Using the Eclipse SOA Tools Platform plug-in and Apache TuscanyPage 2 of 34 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 3: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

Section 2. Introduction

SOA development is simplified with the addition of the Eclipse STP plug-ins. Thissection shows how this tutorial uses the SCA plug-ins portion of the Eclipse SOATools Platform.

SOA and SCA

SOA comprises several services that are accessible and can interact with each otherover the Internet. This contrasts to a single monolithic application that is moredifficult for developers and IT personnel to maintain. SOA is easier to maintain anddeploy since it implements one service at a time.

The Service Component Architecture (SCA) specification is simply a model forbuilding a service. Through the Eclipse SOA Tools Platform, you have the tools youneed to use SOA and SCA: build and deploy one service at a time according to theSCA specification with each individual service you create comprising your overallSOA. Put another way, SOA specifies the organization, while SCA specifies how tobuild services that use an SOA. As you can see, SOA and SCA really go hand inhand. The service you'll build in this tutorial comes to life through the combination ofSCA and SOA.

In this tutorial, in addition to the common and core STP plug-ins, we will use theService Creation Service Oriented Architecture (SC.SCA) plug-ins. They, throughthe integration of Apache Tuscany, are what allows you to annotate your serviceusing SCA and Apache Tuscany service annotations.

Apache Tuscany effectively provides you with a SCA Java run time by allowing youto use SCA in the development of Java components in an SOA environment. Thinkof Apache Tuscany as the powerhouse that implements the SCA specification,making SCA a reality, with the Eclipse STP plug-ins tying everything together —from properties and code to run-time configurations and debugging — allowing theconstruction of a true SOA solution.

You should now have a good idea of how SOA and SCA work together, so let's goover some details of the example by previewing the Time Bomb service that you'llbuild in this tutorial.

Time Bomb service game

As an illustration on how to create a SCA Java service implementing the SCA

ibm.com/developerWorks developerWorks®

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 3 of 34

Page 4: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

specification, we will create the Time Bomb game, which is created more simply withthe help of Eclipse STP. It is an on-your-feet trivia game that will require yourknowledge and fast typing abilities to answer questions within a 60-second time limit.

The service you're going to create and build is a Time Bomb service. There aretokens (identifiers) in the service that, when submitted to the service, start the TimeBomb countdown for that token, returning a trivia question that will then need to beanswered within 60 seconds. If you answer incorrectly, the service responds withhow many seconds you have left and continues its countdown. If you are correct, theservice will indicate a "Correct!" response. If you lose and go past 60 seconds, theservice will answer your question with a "KABOOM!" response. If you answercorrectly, the timer resets, after which you'll need to resubmit your token to moveonto the next question.

Take a look at the Time Bomb service in action.

Listing 1. The Time Bomb service in action

Enter your token:DEFQuestion: Which planet is closest to the Sun?Enter your answer:VenusResult: Uh oh!!! You better get your facts straight or spontaneouscombustion is imminent! You have 33 seconds left!

Next, we'll look at installing Eclipse STP.

Section 3. Quick installation guide

Installing the Eclipse STP is very simple and includes some prep work before beingable to create and develop SOA projects. In this section, you'll learn how to installeach of the items listed in the System requirements section and tie the ApacheTuscany run time into Eclipse.

Installing Eclipse, the STP and dependencies

Before we get started, make sure you have already downloaded ZIP files for each ofthe items listed in the System requirements section.

Install the first, main, Eclipse ZIP file you should have downloaded(eclipse-SDK-3.3.1-win32.zip for this tutorial) to your programs directory

developerWorks® ibm.com/developerWorks

Using the Eclipse SOA Tools Platform plug-in and Apache TuscanyPage 4 of 34 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 5: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

(F:\programs for the purposes of this tutorial) by first moving the ZIP there, followedby unzipping it. You should now have F:\programs\eclipse.

Next, move the STP all-in-one ZIP file(stp-all-in-one-incubation-R-R200710080602-200710080602.zip for this tutorial) toyour programs directory and unzip its contents. This automatically places thecontents of the STP ZIP file you downloaded to its proper locations in the eclipsedirectory. If you're asked to replace files, click Yes to All.

Now install the required dependency plug-ins download (stp-jsr-R20070912.zip forthis tutorial) in the same manner you installed the STP plug-ins as above by firstmoving the ZIP file to your programs directory and unzipping the contents. Again, ifyou're asked to replace files then click Yes to All.

Last, unzip the Apache Tuscany download, also in your programs directory. Thisshould create a new directory there: tuscany-sca-1.0-incubating (atF:\programs\tuscany-sca-1.0-incubating for the purposes of this tutorial). Make noteof this directory because you'll need to point to this directory from within Eclipse.

The installation is complete. Now you'll configure your Eclipse installation.

Configuring Eclipse STP for Java SCA usage

To let the Eclipse STP know where you've installed Java SCA, you need to add it asan Apache run time:

• Click Window > Preferences

• Expand the SOA Tools tree on the left panel

• Select Installed Runtimes

• Scroll up to find and expand the Apache folder

• Select Apache Tuscany SCA Java 1.0, as shown in Figure 1, and clickNext

• Browse to the location of your Apache Tuscany run time(F:\programs\tuscany-sca-1.0-incubating for this tutorial) and click Finish

Figure 1. Adding a new server run time

ibm.com/developerWorks developerWorks®

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 5 of 34

Page 6: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

The run time should then be listed in the list of Installed Server RuntimeEnvironments, as shown below.

Figure 2. Apache Tuscany run time successfully added

developerWorks® ibm.com/developerWorks

Using the Eclipse SOA Tools Platform plug-in and Apache TuscanyPage 6 of 34 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 7: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

That's all the special configuration you need to make. Next, you'll create your firstSOA Tools SCA project.

Creating a new SOA Tools SCA project

Creating your first SOA Tools SCA project is where it all begins. To get the processstarted, click File > New > Project. Find and expand the SOA Tools folder. SelectSCA Java Component Project, as shown in Figure 3, and click Next.

Figure 3. Selecting SCA Java Component Project

ibm.com/developerWorks developerWorks®

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 7 of 34

Page 8: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

Now type the project name, TimeBomb, as shown in Figure 4, and click Next.

Figure 4. Typing the project name

developerWorks® ibm.com/developerWorks

Using the Eclipse SOA Tools Platform plug-in and Apache TuscanyPage 8 of 34 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 9: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

Next, select the Apache Tuscany run time you just added, as shown in Figure 5, andclick Next.

Figure 5. Selecting the appropriate run time

ibm.com/developerWorks developerWorks®

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 9 of 34

Page 10: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

Now fill in the project details:

• com.ibm.dw.tb as the Package name

• TimeBomb as the Interface name (this automatically fills in values for therest of the items)

• Select RMI as the Binding Type

Figure 6. Filling in the project's details

developerWorks® ibm.com/developerWorks

Using the Eclipse SOA Tools Platform plug-in and Apache TuscanyPage 10 of 34 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 11: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

Clicking Next takes you to the last window, as shown below.

Figure 7. Last window

ibm.com/developerWorks developerWorks®

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 11 of 34

Page 12: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

Here, you can select a different host, port, or service name for your project. Or youcan leave the defaults as-is and click Finish to create the project. Click Yes to enterthe SCA Java perspective, and you should see your project and its contents asshown by the Package navigator in Figure 8.

Figure 8. Creating your first SOA Tools SCA project

developerWorks® ibm.com/developerWorks

Using the Eclipse SOA Tools Platform plug-in and Apache TuscanyPage 12 of 34 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 13: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

In the rest of the tutorial, you'll experience the SCA construction provided by theEclipse STP project.

Section 4. Developing the Java SCA service

Now that the Eclipse STP and Apache Tuscany installations are done, you're readyto move ahead and develop the Java SCA service you just created using the EclipseSTP plug-in. This section goes over the Time Bomb application you're going tocreate in more detail, along with the implementation details and Java code you'regoing to need to make it all happen.

Planning it all out

First up, you're going to see what's going to happen in the game and what data theservice will contain. For starters, the Time Bomb service is going to need to containseveral questions and their corresponding answers. Additionally, it will need to holda list of tokens. Tokens are case sensitive identifiers that can represent users or

ibm.com/developerWorks developerWorks®

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 13 of 34

Page 14: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

possibly students, registered or otherwise, that will each receive a token, giving themaccess to the Time Bomb. Associated with each token is the following:

• Whether the token is currently active

• If the token is active, there will be several valid fields (otherwise invalidwhen the token is inactive)

• Start time

• Needed so that each time the user responds the Time Bombcan check to see if the user ran out of time

• Current question

• The question that the user was assigned when the token wasfirst activated

• Incoming responses to questions will be checked against theright answer

To facilitate all this functionality, you're going to need the following remote servicemethods:

• Question activateMe(Token)

• The above activateMe function takes in a String token as aparameter, checks if the token is valid, activates that token, andassigns a question to it.

• The question assigned to the token is then returned to the sender asa String.

• If the token sent in is invalid, the following is returned in the response:"Token invalid!"

• Result submitAnswer(Token, Answer)

• The submitAnswer function takes in the user's Token as theparameter and checks to see if the user answered the question withinthe appropriate time limit.

• If the user failed to respond in the time allotted, the followingresponse is given: "KABOOM!!! You have spontaneouslycombusted! Better luck next time!"

• If the user responded within the appropriate time, the servicetries to match the Answer parameter with the answer to thequestion currently assigned to that user.

• If the incoming Answer matches the answer associated

developerWorks® ibm.com/developerWorks

Using the Eclipse SOA Tools Platform plug-in and Apache TuscanyPage 14 of 34 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 15: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

with the question, the following response is given:"Phew!!! You are saved from imminent spontaneouscombustion!"

• A correct answer in this case deactivates thetoken, and that user is free to submit the tokenagain for a new question.

• If the incoming Answer does not match, the following responseis given instead: "Uh oh!!! You better get your facts straight orspontaneous combustion is imminent! You have<secondsLeft> seconds left!" (where secondsLeft is avariable containing the amount of time, in seconds, left for thatuser to come up with the correct answer).

• Again, if the user entered an invalid token, the response will be thesame as given to activateMe for invalid tokens.

Does it sound like a fun game? Indeed it is. But what will be more fun is creating thegame. The rest of this section deals with creating the code and making the abovefunctionality come to life.

First, you'll begin with the Java interface to the service.

The TimeBomb interface

The purpose of this Java interface is to be a standard template for other Javaclasses wishing to access the Service that implements this interface. Thus, it shouldcontain both the methods you defined earlier (activateMe and submitAnswer).The file already exists (TimeBomb.java) in your source (src) folder and should bedefined, as shown in Listing 2.

Listing 2. The TimeBomb interface

package com.ibm.dw.tb;

import org.osoa.sca.annotations.Remotable;import org.osoa.sca.annotations.Service;

@Service()@Remotable()public interface TimeBomb {

public Response activateMe(Request r);public Response submitAnswer(Request r);

}

Here you have both the activateMe and submitAnswer methods with Requestas a parameter and Response as the response. You can also see the SCAannotations, the @Service() and @Remotable() annotations above the interface

ibm.com/developerWorks developerWorks®

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 15 of 34

Page 16: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

declaration. They indicate to the server that this class is a service and is remotable,or accessible over the Internet. These two classes, Response and Request, arewhat you're going to define next.

The Response class

The Response class is simple and only contains a single String for the responsesof each RMI call. To add this class to your SCA project, create a new class byright-clicking your project in the Navigator window, clicking New > Other, selectingClass, clicking Next, typing as the package com.ibm.dw.tb, and as the nameResponse. Clicking Finish creates the file for you. Now define it, as shown in Listing3.

Listing 3. Defining the Response class

package com.ibm.dw.tb;

public class Response implements Serializable {String response;public Response(String r){

response = r;}

public String getResponse(){return response;

}

public void setResponse(String r){response = r;

}}

The class contains a response variable you are able to get and set using getter andsetter methods, respectively.

Next, you'll create and define the Request class.

The Request class

The Request class contains the value for the token and the value for the answer(invalid for activateMe requests) for each RMI call. Create a new class just as youdid for the Response class. Name this one Request, instead of Response anddefine it, as shown in Listing 4.

Listing 4. Defining the Request class

package com.ibm.dw.tb;

developerWorks® ibm.com/developerWorks

Using the Eclipse SOA Tools Platform plug-in and Apache TuscanyPage 16 of 34 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 17: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

public class Request implements Serializable {String token;String answer;

public Request(String t, String a){token = t;answer = a;

}

public String getToken(){return token;

}

public String getAnswer(){return answer;

}

public void setToken(String t){token = t;

}

public void setAnswer(String a){answer = a;

}}

Here, you see the token and answer String variables, which are gettable andsettable via getter and setter methods, respectively.

Next, you'll begin coding the TimeBombImpl class, the class containing thebusiness methods of the service.

Setting up the TimeBombImpl class

This class is the powerhouse of the service, where all the RMI requests come to andare processed. This one should already exist in your source (src) folder. Open it byclicking it in the STP's navigator window and begin defining it, as shown in Listing 5.

Listing 5. Starting the code for the TimeBombImpl class

package com.ibm.dw.tb;

import org.osoa.sca.annotations.Service;

import java.util.Random;

@Scope("REQUEST")@Service(com.ibm.dw.tb.TimeBomb.class)public class TimeBombImpl implements TimeBomb {

static final String FAILURE ="KABOOM!!! You have spontaneously combusted! Better luck next time!";

static final String CORRECT ="Phew!!! You are saved from imminent spontaneous combustion!";

static final String INCORRECT1 = "Uh oh!!! You better get your facts " +"straight or spontaneous combustion is imminent! You have ";

static final String INCORRECT2 = " seconds left!";static final String INVALID_TOKEN = "Token invalid!";static final int secondsToAnswer = 60;

ibm.com/developerWorks developerWorks®

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 17 of 34

Page 18: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

...}

Here, you can see the class definition begin and that it implements the TimeBombinterface. There are then six variables beginning with static final. These areconstants that contain the messages returned for invalid tokens, failed and correctresponses. The last one sets how many seconds the user has to answer before timeruns out. It also specifies an SCA annotation, which specifies the interface class touse in programmatically representing the RMI service. It also specifies an SCAannotation (@Service), which specifies the interface class to use inprogrammatically representing the RMI service. The other SCA annotation(@Scope) specifies that an individual thread will be allocated to serve requests foreach client, allowing the use of local variables.

Next, you'll see how to store individual tokens.

Storing tokens

The tokens are going to be stored in arrays, along with the associated values,including whether the token is valid, which token is currently assigned to the token,and the start time that the question was assigned to the user. Add the followingvariable declarations to your TimeBombImpl.java class.

Listing 6. New variable declarations

static String tokens[] = {"ABC", "DEF", "GHI", "JKL", "MNO"};boolean valid[] = new boolean[2];int assignedQuestions[] = new int[2];long startTimes[] = new long[2];

The tokens String array contains valid tokens (user IDs) accepted by the TimeBomb service. Each token is then associated with:

• A value in the valid Boolean array, which specifies whether the token isvalid

• A value in the assignedQuestions array, which specifies the questionnumber currently assigned to the user

• A value in the startTimes array, which specifies the start time when thetoken was first activated and assigned a question

That's all that's needed for the tokens. Next, you'll see how to store questions andassociated answers.

developerWorks® ibm.com/developerWorks

Using the Eclipse SOA Tools Platform plug-in and Apache TuscanyPage 18 of 34 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 19: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

Storing questions and associated answers

The questions are what is sent back to users with valid tokens. Each valid token thatcalls the activateMe method is assigned a random question. Add the followinglines of code to your TimeBombImpl.java file.

Listing 7. Adding questions and answers to TimeBombImpl.java

static String questions[];static String answers[];static{

questions = new String[5];questions[0] = new String("How many planets are" +

" in the solar system?");questions[1] = new String("How many moons does " +

"the planet Mars have?");questions[2] = new String("Which planet " +

"has been disregarded as a planet by some scientists?");questions[3] = new String("Which planet is closest to the Sun?");questions[4] = new String("Which planet is " +

"also named after the goddess of love and beauty?");

answers = new String[5];answers[0] = new String("9");answers[1] = new String("2");answers[2] = new String("pluto");answers[3] = new String("mercury");answers[4] = new String("venus");

}

The first questions and answers are declared as String arrays. The code in thestatic{ statement gets executed when the class is first loaded into memory,enabling the questions and answers arrays to be initialized appropriately. Note thatboth of them are initialized as String arrays of length 5, and each of the fivequestions and answers are initialized appropriately.

Next, you'll write a quick helper function to validate tokens.

Validating a token

Each token sent into both the activateMe and submitAnswer functions needs tobe validated against the ones defined in Listing 6. Remember that tokens arecase-sensitive. Add the following function to your TimeBombImpl class.

Listing 8. The validateToken function

public int validateToken(String token){for(int i = 0; i < tokens.length; i++){

if(tokens[i].equals(token)){return i;

}

ibm.com/developerWorks developerWorks®

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 19 of 34

Page 20: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

}return -1;

}

Here, you simply loop through all available tokens, and if the one passed into theservice matches one of the valid tokens, return the index, i, that matched the token.Otherwise, return -1 (an invalid token). You'll use this index to assign a question toeach token and set the appropriate start time.

Next, you'll code the activateMe method.

Receiving a token and choosing a random question

The activateMe method takes in a token in the request and returns a question inthe response (if the token is valid, otherwise it returns the INVALID_TOKEN string,defined in Listing 5). Add this function, the implementation of your first method thatwill be accessible via RMI, to your service (TimeBombImpl class), as shown inListing 9.

Listing 9. The activateMe method

public Response activateMe(Request request){String token = request.getToken();int validToken = validateToken(token);

Response response = new Response(null);if(validToken != -1){

Random generator = new Random(239842);int questionNum = generator.nextInt(5);response.setResponse(questions[questionNum]);valid[validToken] = true;assignedQuestions[validToken] = questionNum;startTimes[validToken] = System.currentTimeMillis();

}else{

response.setResponse(INVALID_TOKEN);}

return response;}

The function starts off in the first two lines by validating the token. If the token isvalid, validToken will not equal -1. If the token is invalid, the response is simplyset to NVALID_TOKEN, and the method returns a response. Otherwise, a randomnumber generator is created, and a random integer between 0 (inclusive) and 4(inclusive) is generated. Thus, five possible values for each of the five questions andanswers defined in Listing 7. After the question number is determined, the question'stext is set as the value in the response, the appropriate position in the valid arrayis set to true, the appropriate position in the assignedQuestions array is set toquestionNum, and the appropriate position in the startTime array is set to the

developerWorks® ibm.com/developerWorks

Using the Eclipse SOA Tools Platform plug-in and Apache TuscanyPage 20 of 34 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 21: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

current time. Therefore, when a subsequent call to submitAnswer is received, thequestion and start time currently associated with this token can be retrieved andprocessed accordingly.

Next, you'll begin coding the submitAnswer method.

Receiving an incorrect response to a question within the timelimit

After a valid activateMe request comes in and the appropriate values in the valid,assignedQuestions and startTimes arrays are set, a call to submitAnswercan be made in an attempt to save one's self from spontaneous combustion. Beginby creating this function, your second implementation of a method accessible viaRMI, as defined in Listing 10.

Listing 10. Starting off the submitAnswer method

public Response submitAnswer(Request request){String token = request.getToken();String answer = request.getAnswer();int validToken = validateToken(token);

Response response = new Response(null);if(validToken != -1 && valid[validToken]){

long currentTime = System.currentTimeMillis();long startTime = startTimes[validToken];long difference = currentTime - startTime;long secondsLeft = difference/1000;if(secondsLeft <= secondsToAnswer){

String correctAnswer =questions[assignedQuestions[validToken]];

if(correctAnswer.equals(answer)){response.setResponse(CORRECT);

}else{

...else{

response.setResponse(INVALID_TOKEN);}

return response;}

You begin by retrieving and validating the token as in Listing 9, while grabbing theanswer out of the request, as well. This time, you also make sure that the token isvalid (not equal to -1) and that the token already has a question assigned to it(valid[validToken] == true). If the token is valid and has a questionassigned to it, you first need to make sure the answer has come within the giventime limit of 60 seconds by comparing the two times, making sure that less than 60seconds has elapsed since the question was assigned. If the answer was receivedin the allowed time frame, you need to compare the answer given to the answer to

ibm.com/developerWorks developerWorks®

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 21 of 34

Page 22: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

the question as defined in Listing 7. If the answers match, you set the response textto the String, as defined in the constant CORRECT (see Listing 5).

Next, you'll define the response for answers not matching, yet are within the60-second time limit.

Receiving a correct response to a question within the time limit

OK — so rather than a correct response, an incorrect response was received, yetthe user is still within the time limit. In this case, set the response to that shown inListing 11.

Listing 11. Setting the response for an incorrect answer within the time limit

public Response submitAnswer(Request request){...

if(correctAnswer.equals(answer)){...

}else{

response.setResponse(INCORRECT1 +secondsLeft + INCORRECT2);

}...

return response;}

Here, you are indicating to the user how much time is left to save himself fromspontaneous combustion. Next, you define the response for answers received afterthe 60-second time limit has expired.

Receiving a response to a question outside the time limit: KABOOM! Uh-oh. Thetime limit has expired, so the message defined in FAILURE (see Listing 5) needs tobe returned in the response. Define the code for this response in Listing 12.

Listing 12. The response for answering after time has expired

public Response submitAnswer(Request request){...

if(correctAnswer.equals(answer)){...

}else{

...}

}else{

response.setResponse(FAILURE);}

...

return response;

developerWorks® ibm.com/developerWorks

Using the Eclipse SOA Tools Platform plug-in and Apache TuscanyPage 22 of 34 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 23: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

}

Here, in the second else statement, you set the response text to the value held inthe FAILURE constant.

Resetting the token

For correct and failed responses (responses coming in after time has expired), thetoken needs to be deactivated by setting it to false. Do so, as shown in Listing 13.

Listing 13. Invalidating the token

public Response submitAnswer(Request request){...

if(correctAnswer.equals(answer)){response.setResponse(CORRECT);valid[validToken] = false;

}else{

...}

}else{

response.setResponse(FAILURE);valid[validToken] = false;

}}else{

...}

return response;}

Here, the token is simply invalidated by setting the appropriate position in the validarray to false.

This completes all the code for the service. Next, you'll run the server.

Running the server

Once you get the server running from with the Eclipse STP, you'll test it using anRMI client in the following section. This is where Apache Tuscany comes into playas the SCA Java implementation behind your SOA Tools SCA Java RMI service.Start the server by clicking Run > Open Run Dialog. A run configuration, underJava Application, should already be created for you:TimeBombComponent_sca_TimeBomb. Select this and click Run. You should thensee the following in the console.

ibm.com/developerWorks developerWorks®

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 23 of 34

Page 24: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

Figure 9. Running the server

There you have it. You can close down the server by clicking the red square buttonor by clicking Enter.

Next, you'll create and build the client using Eclipse.

Section 5. Developing the Java RMI client

With the server all worked out, you're ready to tackle the client. This sectioncompletes the tutorial by allowing you to create a client that finds your servicethrough the RMI naming registry. You'll then invoke the remote methods defined foryour service and effectively test the functionality of your game.

Creating your Time Bomb client

To create the client, you're going to need to create a new Java project:

• Click File > New > Project

• Scroll to the top and select Java Project, then click Next

• Type the name of the project as TimeBombRMIClient and click Next

• Click Finish

Now you need to create two files for the client: an interface and a class:

• Click File > New > Other

• Select Interface and click Next

• Type the package name: com.ibm.dw.tb

developerWorks® ibm.com/developerWorks

Using the Eclipse SOA Tools Platform plug-in and Apache TuscanyPage 24 of 34 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 25: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

• Type the name as TimeBomb

• Click Add

• Type remo into the Choose interfaces text box and select Remote -java.rmi, as shown in Figure 10, and click OK.Figure 10. Extended Interfaces Selection window

• Your New Java Interface window should appear, as shown in Figure 11.Figure 11. New Java Interface window

ibm.com/developerWorks developerWorks®

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 25 of 34

Page 26: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

• Click Finish

Now to create the class:

• Click File > New > Other

• Select Class and click Next

• Type the package name: com.ibm.dw.tb

• Type the name as TimeBombRMIClient

• Check the public static void main(String[] args) box

• Your New Java Class window should appear, as shown in Figure 12Figure 12. New Java Class window

developerWorks® ibm.com/developerWorks

Using the Eclipse SOA Tools Platform plug-in and Apache TuscanyPage 26 of 34 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 27: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

• Click Finish

Last, you need to copy your Request.java and Response.java from the TimeBombproject to your TimeBombRMIClient project. Select them in the Navigator paneand drag them to your TimeBombRMIClient package, as shown below.

Figure 13. Copying Request and Response to the TimeBombRMIClient project

ibm.com/developerWorks developerWorks®

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 27 of 34

Page 28: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

Great! The client is ready for you to add your magic, er, code.

The TimeBomb interface

The client's version of the TimeBomb interface is slightly different as it doesn'tcontain any of the service annotations, etc. Open it up and define it, as shown inListing 14.

Listing 14. Defining the remote TimeBomb interface

package com.ibm.dw.tb;

import java.rmi.Remote;

public interface TimeBomb extends Remote {public Response activateMe(Request r);public Response submitAnswer(Request r);

}

developerWorks® ibm.com/developerWorks

Using the Eclipse SOA Tools Platform plug-in and Apache TuscanyPage 28 of 34 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 29: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

It's essentially the same except that it extends Remote and doesn't contain any SCAannotations. Instead, it extends the java.rmi.Remote class, allowing this class tohold the reference to your remote service, which you'll invoke next in theTimeBombRMIClient class.

Sending a token and receiving the first question

It's client coding time. The first thing you're going to want to do with the client is lookup the service, then call its acitvateMe method, passing in one of the valid tokens.Begin defining this class, the TimeBombRMIClient class, as shown in Listing 15.

Listing 15. The TimeBombRMIClient class

package com.ibm.dw.tb;

import java.rmi.Naming;

public class TimeBombRMIClient {

/*** @param args*/

public static void main(String[] args) {// TODO Auto-generated method stubtry {

TimeBomb service = (TimeBomb)Naming.lookup("rmi://localhost:1099/TimeBombRemoteService");

String token = null;BufferedReader br = new BufferedReader

(new InputStreamReader(System.in));

System.out.println("Enter your token:");

try {token = br.readLine();

} catch (IOException ioe) {System.out.println("IO error trying to read your token!");

}

Response r = service.activateMe(new Request(token, null));System.out.println("Question: " + r.getResponse());

...

} catch (Exception e){e.printStackTrace();

}}

}

Within the class declaration, you look up the TimeBomb service through the server'sRMI registry running your TimeBomb service. Then type in your token. Invoking theservice.activateMe remote method passes the token information you enteredalong to the remote service. The response from the service is then stored in r. Thequestion in the response you'll get is one of the five random questions defined back

ibm.com/developerWorks developerWorks®

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 29 of 34

Page 30: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

in Listing 7.

Next, you'll code retrieving the answer from the console and send it in as yourresponse.

Responding with an answer, and receiving a response

Next up, you need to grab an answer to questions from the console. Do so bycontinuing to define TimeBombRMIClient.java, as shown below.

Listing 16. Respond to the server with an answer

...Response r = service.activateMe(new Request(token, null));System.out.println("Question: " + r.getResponse());

String answer = null;BufferedReader br = new BufferedReader

(new InputStreamReader(System.in));

System.out.println("Enter your answer:");

try {answer = br.readLine();

} catch (IOException ioe) {System.out.println("IO error trying to read your answer!");

}

Response r2 = service.submitAnswer(new Request(token, answer));System.out.println("Result: " + r2.getResponse());

...

The code in Listing 16 allows you to type a response by having the user type ananswer. The answer and token entered earlier are funneled to the remote service inthe call to service.submitAnswer. By playing with the client, you should be ableto receive all three possible response types by typing a correct response within thetime frame, typing an incorrect response within the time frame, and waiting 60seconds before submitting a response. You can play with the client by submittinginvalid tokens, as well, in order to get the invalid token response.

Running the client

Running the client allows you to test the functionality of your remote service. To runthe client, click Run > Open Run Dialog. If a run configuration namedTimeBombRMIClient under Java Application has not been created yet, click New(at top left), and it should appear for you. Clicking Run starts the client, allowing youspecify a valid token to send to the server and begin answering trivia questions. Asample run of the client is shown in Listing 17.

developerWorks® ibm.com/developerWorks

Using the Eclipse SOA Tools Platform plug-in and Apache TuscanyPage 30 of 34 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 31: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

Listing 17. A sample run of the client

Enter your token:DEFQuestion: Which planet is closest to the Sun?Enter your answer:VenusResult: Uh oh!!! You better get your facts straight or spontaneouscombustion is imminent! You have 33 seconds left!

Great! Your RMI client has successfully obtained a reference to your RMI servicethat you built according to the SCA specification, which also comprises your SOA.

Section 6. Summary

You've successfully installed and used the Eclipse STP plug-in and Apache TuscanySCA Java implementation. Additionally, you created an SOA Tools SCA projectusing RMI bindings and an RMI client able to successfully communicate with theservice. One possible improvement you might want to make is to have these tokensand questions grabbed from a database, so you can add to them as necessarywithout having to muck with and rebuild the service. You can also of course createother services taking advantage of Eclipse STP and Apache Tuscany.

ibm.com/developerWorks developerWorks®

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 31 of 34

Page 32: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

Downloads

Description Name Size Download method

Sample code os-eclipse-soatptuscany.sca.code.zip7KB HTTP

Information about download methods

developerWorks® ibm.com/developerWorks

Using the Eclipse SOA Tools Platform plug-in and Apache TuscanyPage 32 of 34 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 33: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

Resources

Learn

• Check out the Eclipse SOA Tools Platform (STP) project at Eclipse.org.

• Learn about the Eclipse Service Creation (SC) subproject.

• Learn more at the Eclipse STP wiki.

• To learn more about Service-Oriented Architecture (SOA), check out thedeveloperWorks SOA and Web services zone.

• Learn more about SCA and its relationship to SOA in the article "ServiceComponent Architecture."

• See another Eclipse STP tutorial titled "Use the Eclipse SOA Tools Platformplug-in to build and deploy a Web service.

• Answers to your Eclipse questions are available in "What is Eclipse and how doI use it?"

• Check out the extensive documentation, tutorials, presentations, andscreencasts that illuminate the Eclipse Test & Performance Tools Platform(TPTP).

• Check out the "Recommended Eclipse reading list."

• Browse all the Eclipse content on developerWorks.

• New to Eclipse? Read the developerWorks article "Get started with EclipsePlatform" to learn its origin and architecture, and how to extend Eclipse withplug-ins.

• Expand your Eclipse skills by checking out IBM developerWorks' Eclipse projectresources.

• To listen to interesting interviews and discussions for software developers,check out check out developerWorks podcasts.

• For an introduction to the Eclipse platform, see "Getting started with the EclipsePlatform."

• Stay current with developerWorks' Technical events and webcasts.

• Watch and learn about IBM and open source technologies and productfunctions with the no-cost developerWorks On demand demos.

• Check out upcoming conferences, trade shows, webcasts, and other Eventsaround the world that are of interest to IBM open source developers.

• Visit the developerWorks Open source zone for extensive how-to information,

ibm.com/developerWorks developerWorks®

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 33 of 34

Page 34: Using the Eclipse SOA Tools Platform plug-in and Apache ... · Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Developing an SCA Java RMI service Skill Level: Intermediate

tools, and project updates to help you develop with open source technologiesand use them with IBM's products.

Get products and technologies

• Download the Eclipse STP plug-in and required plug-ins.

• Download Apache Tuscany SCA Java.

• Check out the latest Eclipse technology downloads at IBM alphaWorks.

• Download Eclipse Platform and other projects from the Eclipse Foundation.

• Download IBM product evaluation versions, and get your hands on applicationdevelopment tools and middleware products from DB2®, Lotus®, Rational®,Tivoli®, and WebSphere®.

• Innovate your next open source development project with IBM trial software,available for download or on DVD.

Discuss

• Subscribe to the STP user list.

• Subscribe to the STP developer list.

• The Eclipse Platform newsgroups should be your first stop to discuss questionsregarding Eclipse. (Selecting this will launch your default Usenet news readerapplication and open eclipse.platform.)

• The Eclipse newsgroups has many resources for people interested in using andextending Eclipse.

• Participate in developerWorks blogs and get involved in the developerWorkscommunity.

About the author

Tyler AndersonTyler Anderson graduated with a degree in Computer Science from Brigham YoungUniversity in 2004 and is currently in his last semester as a Master of Sciencestudent in Computer Engineering. In the past, he worked as a database programmerfor DPMG.COM, and he is currently an engineer for Stexar Corp., based inBeaverton, Oregon.

developerWorks® ibm.com/developerWorks

Using the Eclipse SOA Tools Platform plug-in and Apache TuscanyPage 34 of 34 © Copyright IBM Corporation 1994, 2008. All rights reserved.