Вы находитесь на странице: 1из 34

Using the Eclipse SOA Tools Platform plug-in and

Apache Tuscany
Developing an SCA Java RMI service

Skill Level: Intermediate

Tyler Anderson (tyleranderson5@yahoo.com)


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 Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 1 of 34
developerWorks® ibm.com/developerWorks

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

In this tutorial, you're going to build an RMI-based service that will be registered in
the server's RMI naming registry. You'll build the service according to the SCA
specification, implemented via Apache Tuscany, that will become part of your overall
SOA 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 STP
plug-in:

Eclipse Classic
Eclipse is the master platform upon which the Eclipse SOA Tools plug-in runs
on. V3.3.1 was used in this tutorial.

Eclipse STP and dependency plug-ins


These are the core plug-ins you'll need to develop with the STP. This tutorial
uses version I200710300730. There are several plug-ins available for
download, so be sure to download the one with the stp-all-in-one- suffix. This
download includes all the dependencies listed under the "Requirements"
heading.

Apache Tuscany SCA Java


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

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

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 2 of 34
ibm.com/developerWorks developerWorks®

Section 2. Introduction
SOA development is simplified with the addition of the Eclipse STP plug-ins. This
section shows how this tutorial uses the SCA plug-ins portion of the Eclipse SOA
Tools Platform.

SOA and SCA


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

The Service Component Architecture (SCA) specification is simply a model for


building a service. Through the Eclipse SOA Tools Platform, you have the tools you
need to use SOA and SCA: build and deploy one service at a time according to the
SCA specification with each individual service you create comprising your overall
SOA. Put another way, SOA specifies the organization, while SCA specifies how to
build services that use an SOA. As you can see, SOA and SCA really go hand in
hand. The service you'll build in this tutorial comes to life through the combination of
SCA and SOA.

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

Apache Tuscany effectively provides you with a SCA Java run time by allowing you
to use SCA in the development of Java components in an SOA environment. Think
of 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 the
construction of a true SOA solution.

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

Time Bomb service game


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

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 3 of 34
developerWorks® ibm.com/developerWorks

specification, we will create the Time Bomb game, which is created more simply with
the help of Eclipse STP. It is an on-your-feet trivia game that will require your
knowledge 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 are
tokens (identifiers) in the service that, when submitted to the service, start the Time
Bomb countdown for that token, returning a trivia question that will then need to be
answered within 60 seconds. If you answer incorrectly, the service responds with
how many seconds you have left and continues its countdown. If you are correct, the
service will indicate a "Correct!" response. If you lose and go past 60 seconds, the
service will answer your question with a "KABOOM!" response. If you answer
correctly, the timer resets, after which you'll need to resubmit your token to move
onto the next question.

Take a look at the Time Bomb service in action.

Listing 1. The Time Bomb service in action

Enter your token:


DEF
Question: Which planet is closest to the Sun?
Enter your answer:
Venus
Result: Uh oh!!! You better get your facts straight or spontaneous
combustion 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 being
able to create and develop SOA projects. In this section, you'll learn how to install
each of the items listed in the System requirements section and tie the Apache
Tuscany run time into Eclipse.

Installing Eclipse, the STP and dependencies


Before we get started, make sure you have already downloaded ZIP files for each of
the 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

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 4 of 34
ibm.com/developerWorks developerWorks®

(F:\programs for the purposes of this tutorial) by first moving the ZIP there, followed
by 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) to
your programs directory and unzip its contents. This automatically places the
contents of the STP ZIP file you downloaded to its proper locations in the eclipse
directory. If you're asked to replace files, click Yes to All.

Now install the required dependency plug-ins download (stp-jsr-R20070912.zip for


this tutorial) in the same manner you installed the STP plug-ins as above by first
moving the ZIP file to your programs directory and unzipping the contents. Again, if
you're asked to replace files then click Yes to All.

Last, unzip the Apache Tuscany download, also in your programs directory. This
should create a new directory there: tuscany-sca-1.0-incubating (at
F:\programs\tuscany-sca-1.0-incubating for the purposes of this tutorial). Make note
of 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 as
an 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 click
Next
• 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

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 5 of 34
developerWorks® ibm.com/developerWorks

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

Figure 2. Apache Tuscany run time successfully added

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 6 of 34
ibm.com/developerWorks developerWorks®

That's all the special configuration you need to make. Next, you'll create your first
SOA 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 process
started, click File > New > Project. Find and expand the SOA Tools folder. Select
SCA Java Component Project, as shown in Figure 3, and click Next.

Figure 3. Selecting SCA Java Component Project

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 7 of 34
developerWorks® ibm.com/developerWorks

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

Figure 4. Typing the project name

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 8 of 34
ibm.com/developerWorks developerWorks®

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

Figure 5. Selecting the appropriate run time

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 9 of 34
developerWorks® ibm.com/developerWorks

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 the
rest of the items)
• Select RMI as the Binding Type
Figure 6. Filling in the project's details

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 10 of 34
ibm.com/developerWorks developerWorks®

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

Figure 7. Last window

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 11 of 34
developerWorks® ibm.com/developerWorks

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

Figure 8. Creating your first SOA Tools SCA project

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 12 of 34
ibm.com/developerWorks developerWorks®

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

Section 4. Developing the Java SCA service


Now that the Eclipse STP and Apache Tuscany installations are done, you're ready
to move ahead and develop the Java SCA service you just created using the Eclipse
STP plug-in. This section goes over the Time Bomb application you're going to
create in more detail, along with the implementation details and Java code you're
going 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 the
service will contain. For starters, the Time Bomb service is going to need to contain
several questions and their corresponding answers. Additionally, it will need to hold
a list of tokens. Tokens are case sensitive identifiers that can represent users or

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 13 of 34
developerWorks® ibm.com/developerWorks

possibly students, registered or otherwise, that will each receive a token, giving them
access 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 invalid
when the token is inactive)
• Start time
• Needed so that each time the user responds the Time Bomb
can check to see if the user ran out of time
• Current question
• The question that the user was assigned when the token was
first activated
• Incoming responses to questions will be checked against the
right answer
To facilitate all this functionality, you're going to need the following remote service
methods:

• Question activateMe(Token)
• The above activateMe function takes in a String token as a
parameter, checks if the token is valid, activates that token, and
assigns a question to it.
• The question assigned to the token is then returned to the sender as
a 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 the
parameter and checks to see if the user answered the question within
the appropriate time limit.
• If the user failed to respond in the time allotted, the following
response is given: "KABOOM!!! You have spontaneously
combusted! Better luck next time!"
• If the user responded within the appropriate time, the service
tries to match the Answer parameter with the answer to the
question currently assigned to that user.
• If the incoming Answer matches the answer associated

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 14 of 34
ibm.com/developerWorks developerWorks®

with the question, the following response is given:


"Phew!!! You are saved from imminent spontaneous
combustion!"
• A correct answer in this case deactivates the
token, and that user is free to submit the token
again for a new question.
• If the incoming Answer does not match, the following response
is given instead: "Uh oh!!! You better get your facts straight or
spontaneous combustion is imminent! You have
<secondsLeft> seconds left!" (where secondsLeft is a
variable containing the amount of time, in seconds, left for that
user to come up with the correct answer).
• Again, if the user entered an invalid token, the response will be the
same 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 the
game. The rest of this section deals with creating the code and making the above
functionality 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 Java
classes wishing to access the Service that implements this interface. Thus, it should
contain both the methods you defined earlier (activateMe and submitAnswer).
The file already exists (TimeBomb.java) in your source (src) folder and should be
defined, 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 Request
as a parameter and Response as the response. You can also see the SCA
annotations, the @Service() and @Remotable() annotations above the interface

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 15 of 34
developerWorks® ibm.com/developerWorks

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, are
what you're going to define next.

The Response class


The Response class is simple and only contains a single String for the responses
of each RMI call. To add this class to your SCA project, create a new class by
right-clicking your project in the Navigator window, clicking New > Other, selecting
Class, clicking Next, typing as the package com.ibm.dw.tb, and as the name
Response. Clicking Finish creates the file for you. Now define it, as shown in Listing
3.

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 and
setter 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 you
did for the Response class. Name this one Request, instead of Response and
define it, as shown in Listing 4.

Listing 4. Defining the Request class

package com.ibm.dw.tb;

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 16 of 34
ibm.com/developerWorks developerWorks®

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 and
settable via getter and setter methods, respectively.

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

Setting up the TimeBombImpl class


This class is the powerhouse of the service, where all the RMI requests come to and
are processed. This one should already exist in your source (src) folder. Open it by
clicking 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;

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 17 of 34
developerWorks® ibm.com/developerWorks

...
}

Here, you can see the class definition begin and that it implements the TimeBomb
interface. There are then six variables beginning with static final. These are
constants that contain the messages returned for invalid tokens, failed and correct
responses. The last one sets how many seconds the user has to answer before time
runs out. It also specifies an SCA annotation, which specifies the interface class to
use in programmatically representing the RMI service. It also specifies an SCA
annotation (@Service), which specifies the interface class to use in
programmatically representing the RMI service. The other SCA annotation
(@Scope) specifies that an individual thread will be allocated to serve requests for
each 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 following
variable 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 Time
Bomb service. Each token is then associated with:

• A value in the valid Boolean array, which specifies whether the token is
valid
• A value in the assignedQuestions array, which specifies the question
number currently assigned to the user
• A value in the startTimes array, which specifies the start time when the
token was first activated and assigned a question
That's all that's needed for the tokens. Next, you'll see how to store questions and
associated answers.

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 18 of 34
ibm.com/developerWorks developerWorks®

Storing questions and associated answers


The questions are what is sent back to users with valid tokens. Each valid token that
calls the activateMe method is assigned a random question. Add the following
lines 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 the
static{ statement gets executed when the class is first loaded into memory,
enabling the questions and answers arrays to be initialized appropriately. Note that
both of them are initialized as String arrays of length 5, and each of the five
questions 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 to
be validated against the ones defined in Listing 6. Remember that tokens are
case-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;
}

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 19 of 34
developerWorks® ibm.com/developerWorks

}
return -1;
}

Here, you simply loop through all available tokens, and if the one passed into the
service 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 to
each 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 in
the 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 that
will be accessible via RMI, to your service (TimeBombImpl class), as shown in
Listing 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 is
valid, validToken will not equal -1. If the token is invalid, the response is simply
set to NVALID_TOKEN, and the method returns a response. Otherwise, a random
number 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 and
answers defined in Listing 7. After the question number is determined, the question's
text is set as the value in the response, the appropriate position in the valid array
is set to true, the appropriate position in the assignedQuestions array is set to
questionNum, and the appropriate position in the startTime array is set to the

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 20 of 34
ibm.com/developerWorks developerWorks®

current time. Therefore, when a subsequent call to submitAnswer is received, the


question and start time currently associated with this token can be retrieved and
processed accordingly.

Next, you'll begin coding the submitAnswer method.

Receiving an incorrect response to a question within the time


limit
After a valid activateMe request comes in and the appropriate values in the valid,
assignedQuestions and startTimes arrays are set, a call to submitAnswer
can be made in an attempt to save one's self from spontaneous combustion. Begin
by creating this function, your second implementation of a method accessible via
RMI, 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 the
answer out of the request, as well. This time, you also make sure that the token is
valid (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 question
assigned to it, you first need to make sure the answer has come within the given
time limit of 60 seconds by comparing the two times, making sure that less than 60
seconds has elapsed since the question was assigned. If the answer was received
in the allowed time frame, you need to compare the answer given to the answer to

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 21 of 34
developerWorks® ibm.com/developerWorks

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

Next, you'll define the response for answers not matching, yet are within the
60-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, yet
the user is still within the time limit. In this case, set the response to that shown in
Listing 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 from
spontaneous combustion. Next, you define the response for answers received after
the 60-second time limit has expired.

Receiving a response to a question outside the time limit: KABOOM! Uh-oh. The
time limit has expired, so the message defined in FAILURE (see Listing 5) needs to
be 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;

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 22 of 34
ibm.com/developerWorks developerWorks®

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

Resetting the token


For correct and failed responses (responses coming in after time has expired), the
token 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 valid
array 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 an
RMI client in the following section. This is where Apache Tuscany comes into play
as the SCA Java implementation behind your SOA Tools SCA Java RMI service.
Start the server by clicking Run > Open Run Dialog. A run configuration, under
Java Application, should already be created for you:
TimeBombComponent_sca_TimeBomb. Select this and click Run. You should then
see the following in the console.

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 23 of 34
developerWorks® ibm.com/developerWorks

Figure 9. Running the server

There you have it. You can close down the server by clicking the red square button
or 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 section
completes the tutorial by allowing you to create a client that finds your service
through the RMI naming registry. You'll then invoke the remote methods defined for
your 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

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 24 of 34
ibm.com/developerWorks developerWorks®

• 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

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 25 of 34
developerWorks® ibm.com/developerWorks

• 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 12
Figure 12. New Java Class window

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 26 of 34
ibm.com/developerWorks developerWorks®

• Click Finish
Last, you need to copy your Request.java and Response.java from the TimeBomb
project to your TimeBombRMIClient project. Select them in the Navigator pane
and drag them to your TimeBombRMIClient package, as shown below.

Figure 13. Copying Request and Response to the TimeBombRMIClient project

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 27 of 34
developerWorks® ibm.com/developerWorks

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't
contain any of the service annotations, etc. Open it up and define it, as shown in
Listing 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);
}

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 28 of 34
ibm.com/developerWorks developerWorks®

It's essentially the same except that it extends Remote and doesn't contain any SCA
annotations. Instead, it extends the java.rmi.Remote class, allowing this class to
hold the reference to your remote service, which you'll invoke next in the
TimeBombRMIClient 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 look
up 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 stub
try {
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's
RMI registry running your TimeBomb service. Then type in your token. Invoking the
service.activateMe remote method passes the token information you entered
along to the remote service. The response from the service is then stored in r. The
question in the response you'll get is one of the five random questions defined back

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 29 of 34
developerWorks® ibm.com/developerWorks

in Listing 7.

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

Responding with an answer, and receiving a response


Next up, you need to grab an answer to questions from the console. Do so by
continuing 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 an
answer. The answer and token entered earlier are funneled to the remote service in
the call to service.submitAnswer. By playing with the client, you should be able
to receive all three possible response types by typing a correct response within the
time frame, typing an incorrect response within the time frame, and waiting 60
seconds before submitting a response. You can play with the client by submitting
invalid 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 run
the client, click Run > Open Run Dialog. If a run configuration named
TimeBombRMIClient 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 you
specify a valid token to send to the server and begin answering trivia questions. A
sample run of the client is shown in Listing 17.

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 30 of 34
ibm.com/developerWorks developerWorks®

Listing 17. A sample run of the client

Enter your token:


DEF
Question: Which planet is closest to the Sun?
Enter your answer:
Venus
Result: Uh oh!!! You better get your facts straight or spontaneous
combustion is imminent! You have 33 seconds left!

Great! Your RMI client has successfully obtained a reference to your RMI service
that 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 Tuscany
SCA Java implementation. Additionally, you created an SOA Tools SCA project
using RMI bindings and an RMI client able to successfully communicate with the
service. One possible improvement you might want to make is to have these tokens
and questions grabbed from a database, so you can add to them as necessary
without having to muck with and rebuild the service. You can also of course create
other services taking advantage of Eclipse STP and Apache Tuscany.

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 31 of 34
developerWorks® ibm.com/developerWorks

Downloads
Description Name Size Download
method
Sample code os-eclipse-soatptuscany.sca.code.zip
7KB HTTP

Information about download methods

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 32 of 34
ibm.com/developerWorks developerWorks®

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 the
developerWorks SOA and Web services zone.
• Learn more about SCA and its relationship to SOA in the article "Service
Component Architecture."
• See another Eclipse STP tutorial titled "Use the Eclipse SOA Tools Platform
plug-in to build and deploy a Web service.
• Answers to your Eclipse questions are available in "What is Eclipse and how do
I use it?"
• Check out the extensive documentation, tutorials, presentations, and
screencasts 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 Eclipse
Platform" to learn its origin and architecture, and how to extend Eclipse with
plug-ins.
• Expand your Eclipse skills by checking out IBM developerWorks' Eclipse project
resources.
• 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 Eclipse
Platform."
• Stay current with developerWorks' Technical events and webcasts.
• Watch and learn about IBM and open source technologies and product
functions with the no-cost developerWorks On demand demos.
• Check out upcoming conferences, trade shows, webcasts, and other Events
around the world that are of interest to IBM open source developers.
• Visit the developerWorks Open source zone for extensive how-to information,

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 33 of 34
developerWorks® ibm.com/developerWorks

tools, and project updates to help you develop with open source technologies
and 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 application
development 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 questions
regarding Eclipse. (Selecting this will launch your default Usenet news reader
application and open eclipse.platform.)
• The Eclipse newsgroups has many resources for people interested in using and
extending Eclipse.
• Participate in developerWorks blogs and get involved in the developerWorks
community.

About the author


Tyler Anderson
Tyler Anderson graduated with a degree in Computer Science from
Brigham Young University in 2004 and is currently in his last semester
as a Master of Science student in Computer Engineering. In the past,
he worked as a database programmer for DPMG.COM, and he is
currently an engineer for Stexar Corp., based in Beaverton, Oregon.

Using the Eclipse SOA Tools Platform plug-in and Apache Tuscany Trademarks
© Copyright IBM Corporation 2007. All rights reserved. Page 34 of 34

Вам также может понравиться