Java Mobiles Agents with Aglets. University of Patras ERASMUS

Jul 14, 2002 - The ASDK is free for download and can be used following the ... dispatch method with the URL of the remote host as the argument. ..... [Book] Danny B. Lange, Mitsuru Oshima, Programming and Deploying Java Mobile.
1MB taille 26 téléchargements 248 vues
Java Mobiles Agents with Aglets.

University of Patras ERASMUS Program March – June 2002

Responsible : M. Logothetis

François Lopitaux

Department : Computer

14/07/2002

End of studies report

François Lopitaux

2/48

End of studies report

1.

Introduction .................................................................................................................... 5 1.1 What are mobile agents? ........................................................................................ 5 1.2 What is the Aglets Software Development Kit? .................................................... 5 1.3 What is an aglet? .................................................................................................... 5 1.4 Subject.................................................................................................................... 5 2. Aglet ............................................................................................................................... 6 2.1 Aglets Software Developer Kit .............................................................................. 6 2.1.1 Agent Environment ........................................................................................ 6 2.1.1.1 The Runtime............................................................................................... 6 2.1.1.2 The Agents ................................................................................................. 7 2.1.2 Agent Life Cycle ............................................................................................ 7 2.1.3 Agent Mobility ............................................................................................... 7 2.1.4 Agent Communication ................................................................................... 8 2.1.5 Security Features ............................................................................................ 9 2.1.6 Usability and Documentation......................................................................... 9 2.2 Patterns ................................................................................................................. 10 2.2.1 Master Slave................................................................................................. 10 2.2.1.1 Definition ................................................................................................. 10 2.2.1.2 Purpose ..................................................................................................... 10 2.2.1.3 Applicability............................................................................................. 10 2.2.1.4 Participants ............................................................................................... 11 2.2.1.5 Collaboration............................................................................................ 11 2.2.1.6 Consequences ........................................................................................... 12 2.2.2 Itinerary ........................................................................................................ 12 2.2.2.1 Definition ................................................................................................. 12 2.2.2.2 Purpose ..................................................................................................... 12 2.2.2.3 Applicability............................................................................................. 13 2.2.2.4 Participants ............................................................................................... 13 2.2.2.5 Collaboration............................................................................................ 14 2.2.2.6 Consequences ........................................................................................... 15 2.2.3 Master Slave Revisited................................................................................. 15 3. Examples ...................................................................................................................... 17 3.1 Network Mapping ................................................................................................ 17 3.1.1 Definition ..................................................................................................... 17 3.1.2 Purpose ......................................................................................................... 17 3.1.3 Applicability................................................................................................. 17 3.1.4 Participants ................................................................................................... 17 3.1.5 Collaboration................................................................................................ 18 3.1.6 Consequences ............................................................................................... 19 3.1.7 Implementation............................................................................................. 19 3.1.7.1 AgletDB ................................................................................................... 19 3.1.7.2 TimerAglet ............................................................................................... 19 3.1.7.3 HostDeclareMaster................................................................................... 20 3.1.7.4 HostDeclareMessager............................................................................... 20 3.2 Network Management .......................................................................................... 21 3.2.1 Purpose ......................................................................................................... 21 3.2.2 Applicability................................................................................................. 21 3.2.3 Participants ................................................................................................... 21 François Lopitaux

3/48

End of studies report

3.2.4 Collaboration................................................................................................ 21 3.2.5 Consequences ............................................................................................... 22 3.2.6 Implementation............................................................................................. 22 3.2.6.1 DeploymentNetwork ................................................................................ 22 3.2.6.2 ConcreteMaster and ConcreteSlave ......................................................... 22 3.2.7 Application ................................................................................................... 22 3.2.7.1 NetworkDirectoryList .............................................................................. 22 3.2.7.1.1 Purpose ............................................................................................... 22 3.2.7.1.2 Implementation................................................................................... 22 3.2.7.1.2.1 NetworkDirectoryList ................................................................. 22 3.2.7.1.2.2 SlaveNetworkDirectoryList ........................................................ 23 3.2.7.2 ExecuteCommandRuntime....................................................................... 23 3.2.7.2.1 Purpose ............................................................................................... 23 3.2.7.2.2 Implementation................................................................................... 23 3.2.7.2.2.1 ExecuteRuntimeCommand.......................................................... 23 3.2.7.2.2.2 SlaveExecuteRuntimeCommand................................................. 24 3.2.7.2.2.3 ReadOutput.................................................................................. 24 4. Conclusion.................................................................................................................... 25 5. Annexes........................................................................................................................ 26 5.1 Bibliographies ...................................................................................................... 26 5.2 How to install? ..................................................................................................... 26 5.3 How to use?.......................................................................................................... 29 5.4 Code ..................................................................................................................... 29 5.4.1 Package com.morkai.utils ............................................................................ 29 5.4.1.1 Slave ......................................................................................................... 29 5.4.1.2 Itinerary .................................................................................................... 31 5.4.1.3 SeqItinerary .............................................................................................. 32 5.4.1.4 AgletUtils ................................................................................................. 32 5.4.2 Package com.morkai.examples .................................................................... 35 5.4.2.1 AgletDB ................................................................................................... 35 5.4.2.2 HostDeclareMaster................................................................................... 36 5.4.2.3 HostDeclareMessager............................................................................... 38 5.4.2.4 TimerAglet ............................................................................................... 40 5.4.2.5 DeploymentNetwork ................................................................................ 40 5.4.2.6 NetworkDirectoryList .............................................................................. 42 5.4.2.7 SlaveNetworkDirectoryList ..................................................................... 44 5.4.2.8 ExecuteRuntimeCommand....................................................................... 44 5.4.2.9 SlaveExecuteRuntimeCommand.............................................................. 46 5.4.2.10 ReadOutput.............................................................................................. 47

François Lopitaux

4/48

End of studies report

1.

Introduction

1.1 What are mobile agents? Mobile network agents are programs that can be dispatched from one computer and transported to a remote computer for execution. Arriving at the remote computer, they present their credentials and obtain access to local services and data. The remote computer may also serve as a broker by bringing together agents with similar interests and compatible goals, thus providing a meeting place at which agents can interact.

1.2 What is the Aglets Software Development Kit? The Aglets Software Development Kit is an environment for programming mobile Internet agents in Java TM.

1.3 What is an aglet? The aglet represents the next leap forward in the evolution of executable content on the Internet, introducing program code that can be transported along with state information. Aglets are Java objects that can move from one host on the Internet to another. That is, an aglet that executes on one host can suddenly halt execution, dispatch itself to a remote host, and resume execution there. When the aglet moves, it takes along its program code as well as its data.

1.4 Subject My job consists to demonstrate the capacities Mobile Agent. For this, I must write some examples using ASDK and showing the advantages of Mobile Agent. First, I must learn the aglet working to find the best examples. Second, I must write these examples and comment them.

François Lopitaux

5/48

End of studies report

2.

Aglet

I used the ASDK 2.0.2. It can be downloading on www.sourgeforge.org/aglet. To compile and execute I used the JDK 1.4 found on java.sun.com.

2.1 Aglets Software Developer Kit The Aglets Software Developer Kit (ASDK) is developed at the IBM Research Laboratory in Japan. The first version was released in 1996. Since February 2002 the ASDK 2.0.2 is available as a release of the platform with a IBM International License Agreement for Non-Warranted Programs. The ASDK is not a commercial product because it is not sold and no official support is provided by IBM. The Aglets team can be contacted by e-mail and there is also a mailing list which is not hosted by IBM. The ASDK is entirely written in Java. It requires the JDK 1.2 or higher to be installed. The Aglets transport and communication is based on the proprietary Agent Transfer Protocol (ATP), which is modeled on the HTTP protocol. It is accessed through the Agent Transfer and Communication Interface (ATCI), which allows an abstraction from the underlying transport protocol. The ASDK is free for download and can be used following the license agreement for noncommercial purposes. The distribution contains all source code for the Aglets server but not for the visual agent manager called Tahiti, an installation Guide, an API documentation created with javadoc, the Aglets specification draft and example programs. As additional component, IBM has developed the Java-based Moderator Templates (JMT), a set of Java class libraries, for coordinating the behaviour of autonomous agents which can be used for ASKD. The templates define the basic collaborative behaviour of agents. They allow the creation of a complex working plan by simply combining the building blocks so that multiple agents can work together towards a common goal.

2.1.1

Agent Environment

2.1.1.1

The Runtime

François Lopitaux

6/48

End of studies report

The ASDK runtime consists only of one aglets server which has to be run on each host where aglets may reside. This server contains an ATP daemon that receives incoming aglets over the network and the visual agent manager Tahiti.

2.1.1.2

The Agents

The ASDK provides a clearly structured and extensible architecture for programming aglets which are mobile agents with an easy-to-use API. An aglet is a mobile Javaobject that can migrate between aglet-enabled hosts. Each aglet runs in its own thread of execution and is able to respond to incoming messages. An aglet is protected from direct access to its public methods by the use of proxy-objects. Each aglet is only accessible through its corresponding proxy. The aglet context is the workspace of aglets. The context is a stationary object that provides a uniform execution environment. It allows the maintaining and management of running aglets and protects the host system against malicious aglets. There are no further place or region concepts.

2.1.2

Agent Life Cycle

Aglets can only be created in the local aglet context. The creation process assigns to each aglet a globally unique identifier (GUID) and provides a reference to the proxyobject of the new aglet. A clone primitive allows the creation of an identical copy of an aglet. Only the assigned identifier differs and the execution restarts in the new aglet. Special functions for the limitation of the life span do not exist. An aglet can be deactivated for a predetermined amount of time or until another aglet has requested its reactivation through the proxy-object. The deactivation removes the aglet from the current context and stores it on a secondary storage. This provides a simple persistence support.

2.1.3

Agent Mobility

Since ASDK is implemented in Java, the serialization of the execution stack is not supported. Therefore one fixed entry point is defined which is called at every arrival. This limitation requires that the current execution state of the aglet task has to be stored by itself in a serializable Java data structure. Then the execution state can be restored after migration from that data. ASDK uses the Java-Object-Serialization of the JDK to marshal and un-marshal Java-objects. Aglets can migrate to another context by calling the dispatch method with the URL of the remote host as the argument. The aglets and the

François Lopitaux

7/48

End of studies report

contained data objects will be serialized. The classes necessary to build the aglet in the new context will be loaded by the class loader from the given code base. Currently, the proxy-objects do not keep track of roaming aglets. Once an aglet is dispatched, the proxy-objects referring to it are no longer valid. A mechanism for preserving the reference to the moving aglet is announced for the future. A migrating proxy-object remains valid. An aglet can migrate on its own will, forced by another aglet, by the user via the GUI, and by the agent system. It can also be fetched back by using the retract-method from the GUI. Additionally, the ASDK provides the itinerary-class which can be used to specify elaborate travel plans. The ASDK does not distinguish between mobile and stationary agents.

2.1.4

Agent Communication

Aglets communicate with each other by message passing. That allows dynamic communication with unknown as well as with well-known aglets. The communication is based on a simple call back scheme that requires an aglet to implement the necessary handlers for each kind of message. The messages are sent by invoking a send message method on the proxy-object. The proxy-objects enable location transparency for aglets with the restriction that proxy-objects for moving aglets become invalid. For the communication it makes no difference whether the receiving aglet exits locally or remotely. The generation of proxy-classes is not required because all aglets have to implement the same message handler. Messages may contain arguments of any Java type that implements java.io.Serializable. Atomic messages can be created by using predefined constructors. Non-atomic messages with multiple arguments are handled as a list of key and value pairs. A remote message does not cause any transfer of byte code. The classes used in the message have to be installed in both hosts. ASDK supports synchronous, asynchronous and multicast messages. For asynchronous messaging an object reference is returned which can be used to check for incoming replies. Multicast messages can be sent to all aglets within a local context that have subscribed to this kind of message. All incoming messages are stored in a message queue and then handled one by one. This serializes the message handling and ensures that the handling of the current message is finished before the message handler of the aglet is invoked again. This process can be customized to allow the handling of the messages in order of their priority depending on their type and to synchronize messages with the aglets’ state. The ASDK defines a number of methods that are called in case of a major event (e.g. on creation, on cloning, on arrival). These methods can be overwritten by the aglets

François Lopitaux

8/48

End of studies report

programmer to react to a special event. Message forwarding and dynamic invocation interfaces are not supported. The ASDK provides a very simple directory services for aglets. A list of hosted aglets can be retrieved only for the current context. Since proxyobjects are not valid after the migration of the referenced aglet, it is very difficult to keep track of a moving aglet and to establish a connection to a remote aglet with unknown globally unique identifier (GUID). For the creation of proxy-objects the URL of the host system and the GUID is needed.

2.1.5

Security Features

The ASKD provides an aglet Security Manager which is based on the security manager of Java. The aglet Security Manager controls the access of aglets to critical methods and could be used to implement own security policies. Each aglet contains information about its identity and its owner, but this information is not used for authentication of the aglet. Therefore aglets may have only two different levels of trust. All aglets that have a local code base and are launched locally are trusted. All other aglets are treated as un-trusted. Only a trusted aglet can create another trusted aglet on the same host. The agent manager Tahiti provides a simple policy database to customize some permissions for trusted and un-trusted aglets. This concerns mainly the access to the local file system and the access to network ports. It is not possible to customize the rules determining the trusted or un-trusted state of an aglet. Currently, Tahiti places very severe security restrictions on the activities of un-trusted aglets similar to the restrictions for applets on HTTP-browsers. The ASDK makes no use of cryptography and therefore does not provide authentication or secure agent transport and communication, replay detection or writing of special log-files related to security.

2.1.6

Usability and Documentation

The ASDK is delivered as a self-extracting file with automatic installation. The ASDK is shipped with a visual agent manager called Tahiti. Its GUI provides an overview of aglets currently hosted in the context, allows the monitoring and control of their execution and the configuration of the aglet server. Therefore the configuration of the ASDK is unsophisticated. The ASDK provides no tools or class support for a centralized management of the agent systems. The available documentation has only a draft status and does not describe all details of the platform.

François Lopitaux

9/48

End of studies report

2.2 Patterns I describe now some pattern what I want use to create my examples. These patterns are implemented in the ASDK.

2.2.1

Master Slave

2.2.1.1

Definition

The Master Slave pattern defines whereby a master aglet can delegate a task to a slave aglet.

2.2.1.2

Purpose

There are several reasons that some aglets masters would like to create other aglets slaves and delegate tasks to them. One reason is performance. A master aglet can continue to perform other tasks in parallel with the slave aglet. Another reason is illustrated via the following example. Consider an aglet-based application that provides a GUI for accepting data input and displaying the intermediate results of a specific task to be performed remotely. With a single aglet to provide the GUI and perform that task, it would not be possible to maintain the GUI (for example, to maintain an open window) after the aglet has traveled from its origin to a remote destination. Alternatively, a stationary master aglet can provide and maintain a GUI while a slave aglet moves to another destination, performs the assigned task, and delivers the task's result to the master aglet, which displays it to the client. The key idea of the Master-Slave pattern is to use an abstract class, S1 have, to localize the invariant parts of delegating a task between master and slave aglets: dispatching a slave to a remote destination, initiating the task's execution, and handling exceptions while performing the task. Concrete slave aglets are defined as subclasses of S1 have, in which only varying parts, such as what task to perform, are implemented. In practice, the master aglet defines a message handler that takes care of the task's result. The S1 have class has two abstract methods initializeTask and doTask which define the initialization steps to be performed before the aglet travels to a new destination and the concrete task.

2.2.1.3

Applicability

Use the Master-Slave pattern in the following cases:

François Lopitaux

10/48

End of studies report

Ø When an aglet needs to perform a task in parallel with other tasks for which it is responsible Ø When a stationary aglet wants to perform a task at a remote destination Both cases concern tasks to be executed at a single destination.

2.2.1.4

Participants

Three participate in the Master-Slave pattern. Ø Slave defines a skeleton of a slave, using abstract methods (InitializeTask and Task) to be overridden in the ConcreteSlave class. Ø ConcreteSlave implements the two abstract methods of the class. Ø Master implements the aglet that creates the slave aglet and receives the slave’s result message.

2.2.1.5

Collaboration

The collaboration between the participants in the Master-Slave pattern is as follows :

(1) A master aglet creates a slave aglet. (2) The slave initializes its task (3) The slave moves to a remote host and performs its task

François Lopitaux

11/48

End of studies report

(4) The slave sends the result of the task to the master (5) The slave disposes of itself

2.2.1.6

Consequences

The Master-Slave pattern provides a fundamental way to reuse code among aglet classes. In practice, aglet design and implementation are simplified by letting developers implement only the variable aspects of predefined patterns. One drawback of an inheritance-based pattern is that the behavior of a slave aglet is fixed at design time. For example, an aglet cannot be transformed into a slave at runtime, nor can a slave aglet easily be assigned to perform new tasks. A more sophisticated version of this pattern can use a delegation-based model, in which the task is objectified and a slave aglet can be assigned any task object during its lifetime.

2.2.2

Itinerary

2.2.2.1

Definition

The Itinerary pattern objectifies aglets’ itineraries and their navigation among multiple destinations.

2.2.2.2

Purpose

Being an autonomous mobile entity, an itinerary-based aglet can navigate independently to multiple hosts. Specifically, it should be able to handle exceptions such as unknown

François Lopitaux

12/48

End of studies report

hosts while trying to dispatch itself to new destinations. It might even need to modify its itinerary dynamically depending on local information. For example, it might dispatch itself to inquire about a local Yellow Pages service, extract relevant destinations, and add them on-the-fly to its itinerary. The key idea of this pattern is to shift the responsibility for navigation from the aglet to its associated Itinerary object. The Itinerary class will provide an interface to maintain or modify the aglet's itinerary and to dispatch the aglet to new destinations. An aglet object and an Itinerary object will be connected as follows. The aglet will create the Itinerary object and initialize it with (1) a list of destinations to be visited sequentially and (2) a reference to the aglet. Then the aglet will use the go method to dispatch itself to the next available destination in its itinerary. To support this, it is necessary that the Itinerary object be transferred together with the aglet.

2.2.2.3

Applicability

Use this pattern when you wish to do the following: Ø Hide the specifics of an aglet's travel plan from its behavior to promote modularity of both parts Ø Provide a uniform interface for the traveling of aglets Ø Define travel plans that can be reused and shared by aglets

2.2.2.4

Participants

The figure shows the structural relationships among the participants of this pattern. Ø Itinerary defines a skeleton of an itinerary, with two abstract methods: go and hasMoreDestinations. Ø ConcreteItinerary implements the abstract methods of the Itinerary class and keeps track of the current destination of the aglet. Ø Aglet is the Aglet base class.

François Lopitaux

13/48

End of studies report

2.2.2.5

Collaboration

The figure shows collaboration according to this pattern:

(1) The ConcreteItinerary object is initialized by the aglet. (2) The ConcreteItinerary dispatches the aglet to the first destination. (3)

When the aglet invokes the itinerary’s go method, the aglet is dispatched to the next destination.

François Lopitaux

14/48

End of studies report

2.2.2.6

Consequences

The Master-Slave pattern provides a fundamental way to reuse code among aglet classes. In practice, aglet design and implementation are simplified by letting developers implement only the variable aspects of predefined patterns. One drawback of an inheritance-based pattern is that the behavior of a slave aglet is fixed at design time. For example, an aglet cannot be transformed into a slave at runtime, nor can a slave aglet easily be assigned to perform new tasks. A more sophisticated version of this pattern can use a delegation-based model, in which the task is objectified and a slave aglet can be assigned any task object during its lifetime.

2.2.3

Master Slave Revisited

So far we have described only slaves that have fairly simple single-destination travel plans. The slave aglet dispatches to a remote host, performs its task, and returns the result. Now we can incorporate the Itinerary pattern into the Master-Slave pattern. Not surprisingly, the result is a slave aglet that travels according to its itinerary. It visits multiple hosts, and executes its task on each host (doTask()). The figure shows a collaboration diagram for the master aglet and its itinerant slave aglet.

François Lopitaux

15/48

End of studies report

François Lopitaux

16/48

End of studies report

3.

Examples

In this part, I describe the examples I’ve implemented.

3.1 Network Mapping 3.1.1

Definition

Network Mappings permit (allow) to have a URL list of all the computers on a LAN or on Internet.

3.1.2

Purpose

One of something that misses with the aglet is the possibility to locate all the Tahiti servers on the network. To deploy the aglets, it’s very important to know this. This example permits it. Each server can subscribe to a main URL list. And after each server can obtain this URL list.

3.1.3

Applicability

Use this example when you wish to do the following: Ø map our network. Ø execute an aglet on all the computers on the LAN. Ø distribute the execution of a program

3.1.4

Participants

Four classes participate in the Network Mapping. Ø TimerAglet implements the aglet that sends every minute a message to HostDeclareMaster. Ø HostDeclareMaster implements the aglet that launches the HostMasterSlave when TimerAglet sends a message, and he also keeps the URL list. Ø HostDeclareMessager implements the aglet that goes on the main server to send a message to AgletDB and sends the URL list received from AgletDB to HostDeclareMaster. Ø AgletDB implements the aglet that centralizes the subscription and sends the URL list to HostDeclareMessager.

François Lopitaux

17/48

End of studies report

3.1.5

Collaboration

The collaboration between the participants in this examples is as following: (1) TimerAglet sends a message every minute to HostDeclareMaster to wakes up it. (2) HostDeclareMaster instances HostDeclareMessager. (3) HostDeclareMessager dispatches itself on the server. (4) HostDeclareMessager sends a message with the URL client to AgletDB. (5) AgletDB writes this URL in it list and sends the list to HostDeclareMessage (6) HostDeclareMessager sends this list to HostDeclareMaster.

TimerAglet 1

SendMessage() - Wakeup

HostDeclareMaster

HostDeclareMessager

2

SendMessage() – URL List 6

3

SendMessage() – Subscribe IP AgletDB

4

HostDeclareMessager

5 SendMessage() – URL List

François Lopitaux

18/48

End of studies report

3.1.6

Consequences

With this example, we can easily recover the URL list to after having deployed the aglets on the network. It’s easy also to share others things than URL, we can for example change a little bit this examples and share after the owner of each host.

3.1.7

Implementation

To implement this examples, I used the patterns defined before, Master Slave with Itinerary.

3.1.7.1

AgletDB

AgletDB OnCreation() is used to initialize the aglet.

onCreation()

handleMessage() deals the message received by the

handleMessage()

proxy doNetworkMapService()

for

the

aglet.

This

method

launches

doNetworkMapService() if the message has as kind

doSubscribe()

“NetworkMapService”.

doUnsubscribe()

doNetworkMapService() is used to know if the client would like to subscribe or to unsubscribe.

doSubscribe() is used to add the URL on the list and to send to DeclareHostSlave the new URL list. doUnsubscribe() is used to delete the URL on the URL List.

3.1.7.2

TimerAglet

TimerAglet onCreation()

onCreation() is used to initialize the aglet. It creates a message to send to DeclareHostMaster and it stocks the address of its proxy.

run() sendMessage()

François Lopitaux

19/48

End of studies report

run() is the main method, first it launches the method sendMessage() and after it desactives itself for 1 minute. After 1 minute, the aglet is activated and the method run() is launched again. sendMessage() sends the message to HostDeclareMaster with the kind “GetUp”.

3.1.7.3

HostDeclareMaster HostDeclareMaster onCreation() handleMessage()

onCreation() is used to instance the TimerAglet. handleMessage() deals 3 kind of message either from the TimerAglet

doCreateSlave()

to

launch

doCreateSlave(),

or

from

HostDeclareMessager to receive and stock the URL list, or

doSendURLList()

from other aglet which want the URL List.

onDisposing()

doCreateSlave() is used to instance HostDeclareSlave. doSendURLList() is used to send the URL list to the aglets

which asked it. onDisposing() is used to unsubscribe the URL on the server. It is launched by the Tahiti Server when we dispose the aglet.

3.1.7.4

HostDeclareMessager HostDeclareMessager

This class inherited from Slave, is described before in 2.2.3 Master Slave Revisited.

initializeTask() doTask() initializedTask() is used to get the URL to subcribe. doSubscribe() doTask() is used to find the proxy of AgletDB on the foreign doUnsuscribe()

host

and

after

to

launch

either

doSubscribe()

or

doUnsubscribe(). doSubscribe() is used to send the URL to AgletDB to update the URL list and to recover the URL list from AgletDB. doUnsubscribe() is used to send to AgletDB the URL to delete it from the list.

François Lopitaux

20/48

End of studies report

3.2 Network Management 3.2.1

Purpose

This example is used to recover the URL List, and after to launch on each computer an aglet.

3.2.2

Applicability

Use this example when you wish to do the following: Ø search some file on the network Ø ask something at all your user Ø spy our network user.

3.2.3

Participants

Three classes participate in this example. Ø DeploymentNetwork defines a skeleton of a master deployment aglet, using abstract methods (onCreation() and handleMessage()) to be overridden in the ConcreteMaster class. Ø ConcreteMaster

implements

the

three

abstract

methods

of

the

class

DeploymentNetwork. Ø ConcreteSlave implements the two abstract method of the class Slave.

3.2.4

Collaboration

The collaboration between the participants in this example is as follows: (1) ConcreteMaster recovers the URL list from HostDeclareMaster and create ConcreteSlave with the method createSlave() defined by DeploymentNetwork. (2) ConcreteSlave deploys itself to the first destination of the URL list. (3) ConcreteSlave runs the method doTask on this host and send the result to ConcreteMaster. (4) ConcreteSlave deploys itself to the next destination if there are no more destinations, it sends message to ConcreteMaster to say it is the end of its execution.

François Lopitaux

21/48

End of studies report

3.2.5

Consequences

With this new pattern you can run on each computer on your network some command and you can have a report of this action very easily.

3.2.6

Implementation

3.2.6.1

DeploymentNetwork

DeploymentNetwork

createSlave() is used to create the ConcreteSlave with the URL list. To recover the URL list, it uses the method

createSlave()

recoverURLList().

recoverURLList() onCreation()

onCreation() and handleMessage() are abstract methods.

handleMessage()

3.2.6.2

ConcreteMaster and ConcreteSlave

ConcreteMaster

overridde

these

abstract

method

of

the

DeploymentNetwork,

onCreation() and handleMessage().

ConcreteSlave is the same as in the 2.2.3 Master Slave Revisited.

3.2.7

Application

3.2.7.1

NetworkDirectoryList

3.2.7.1.1

Purpose

This aglet permits to know (allows knowing) the content of “C:/”. It deploys itself on the network and on each host it lists the content of “C:/”. On each host, it sends the result to the main host to generate a HTML report. 3.2.7.1.2

Implementation

I implemented for this the two concrete classes corresponding to ConcreteMaster and ConcreteSlave.

3.2.7.1.2.1

François Lopitaux

NetworkDirectoryList

22/48

End of studies report

NetworkDirectoryList

onCreation() recovers the URL List and creates the SlaveNetworkDirectoryList.

onCreation()

handleMessage() can receive and steal two kind of messages:

handleMessage() doWorkToFinish()

Ø Result:

from

the

SlaveNetworkDirectoryList,

it

contents a Vector with the list of folders and files for a host. It receives a message by host.

Ø Finish: from the SlaveNetworkDirectoryList, it tells to NetworkDirectoryList that the deployment is finish and it can deal the result and generate the HTML page. doWorkToFinish() is called when SlaveNetworkDirectoryList has finished its deployment, this method generate the HTML report with the Vector send by the Slave.

3.2.7.1.2.2

SlaveNetworkDirectoryList

SlaveNetworkDirectoryList initializeTask()

initializeTask() is not used in this examples. doTask() executes the commands on each host and sends to NetworkDirectoryList the result under the

doTask()

3.2.7.2

Vector format.

ExecuteCommandRuntime

3.2.7.2.1

Purpose

This example has the same purpose than the previous one. There is only one difference, the command is not written in java but it executes the binaries files with the RunTime package. 3.2.7.2.2

Implementation

As for the last examples, I wrote two Concrete Classes and also a third to recover the result of the command.

3.2.7.2.2.1

François Lopitaux

ExecuteRuntimeCommand

23/48

End of studies report

ExecuteRuntimeCommand

It’s the same function as in the previous examples.

onCreation() handleMessage() doWorkToFinish()

3.2.7.2.2.2

SlaveExecuteRuntimeCommand

SlaveExecutionRuntimeCommand

It’s the same function as in the previous examples.

initializeTask() It’s in doTask() that there is a call to the doTask()

package java.lang.RunTime to launch the binaries. And doTask() instances ReadOutput

to recover the stdout and stderr, and to obtain the command result.

3.2.7.2.2.3

ReadOutput

ReadOutput

start() is used to catch either the stdout or the stderr.

start()

François Lopitaux

24/48

End of studies report

4.

Conclusion

During these 3 months, I had to understand the Aglet and to use it to develop some examples.

I think that now I have good knowledge about the Aglets and the ASDK.

I tried to develop these examples to prove the possibilities of this package but also to implement aglets that can be reused to construct some new more complex examples.

François Lopitaux

25/48

End of studies report

5.

Annexes

5.1 Bibliographies [Link1] the SourgeForge Projects on the ASDK, http://sourceforge.net/projects/aglets/ . [Link2] the site of IBM on the aglets, http://www.trl.ibm.com/aglets/index_e.htm . [Book] Danny B. Lange, Mitsuru Oshima, Programming and Deploying Java Mobile Agnets with Aglets, November 1998, 225 pages.

Mailling List : A mailing list to the users of Aglets : [email protected] A mailing list to the developers of Aglets : [email protected]

5.2 How to install? Ø Download the JDK 1.4 at http://java.sun.com/j2se/1.4/download.html. Ø Install the JDK 1.4 on each computer where you want to use Aglet. Ø Download the ASDK 2.0.2 at http://sourceforge.net/projects/aglets/. Ø Install the ASDK on each computer where you want to use Aglet. Ø Compile the ASDK: in %AGLET_HOME%\bin launch ant and ant install-home Ø Create a folder to put the package com.morkai.examples Ø Put the package com.morkai.utils in the folder %AGLET_HOME%\public. Ø Configure the file in %AGLET_HOME%\cnf\aglets.props. For example , the file I used is:

# (mandatory) A path under where aglets is installed. Set on command # line by agletsd but can be overridden here. aglets.home=%HOME_AGLET% # (optional) A path to the directory under where ".aglets" # directory resides. This is also where your KEYSTORE must be. # default: $HOME (unix) or %HOME% (win32) user.home=D:\\Windows\\

François Lopitaux

26/48

End of studies report

# (optional) Location of aglets.policy file, # default: (user.home)/.aglets/security/aglets.policy #java.policy= # (optional) Which protocol to use(atp or rmi) # default: atp #maf.protocol=atp # (optional) Port number used by agents server. # default: 4434 #maf.port=4434 # (optional) Host name of Finder used to register/lookup # the locations of agents. # default: Not used #maf.finder.host=artemis.trl.ibm.com # (optional) Port number of Finder used to register/lookup # the locations of agents. # default: 4435 #maf.finder.port=4435 # (optional) Registry name of the Finder. # default: MAFFinder #maf.finder.name=MAFFinder # (optional) verbose output # default: false verbose=true # (optional) Default search path for class files. # Windows: ';' separated path list # Unix: ':' separated path list # default: (aglets.home)/public aglets.class.path=%PATH_FOR_COM.MORKAI.EXAMPLES% # (optional) Directory which are exported to other aglets servers. # default: (aglets.home)/public aglets.public.root=%PATH_FOR_COM.MORKAI.EXAMPLES% # (optional) Aliases used for codebase of aglets. #aglets.public.aliases=\ # ~tai=/home/tai,\ # ~mima=/home/mima # (optional) If false, every activities of aglets in the server # will be allowed. # default: true aglets.secure=false

François Lopitaux

27/48

End of studies report

# (optional) Class name of an AgletContextListner (Viewer) # To run server with no UI, set null. # i.e. "aglets.viewer=" # default: com.ibm.aglets.tahiti.Tahiti # (ALT: com.ibm.aglets.tahiti.CommandLine) #aglets.viewer=com.ibm.aglets.tahiti.Tahiti # (optional) aglets.logfile=aglets.log # (optional) # default: false aglets.cleanstart=true # (optional) Comma(,) separated list of URLs(or class names) of aglets # which should be created just after the server starts. #aglets.startup= # examples.hello.HelloAglet,\ # atp://yourhost:434/examples.hello.HelloAglet # (optional) Resolve the domain name of the host by querying DNS server. # default: false atp.resolve=true # (optional) TCP/IP domain name of the host #atp.domain=wcl.ee.upatras.gr # (optional) Set server's hostname to "localhost". This is useful if # the host does not have any network adapter. # default: false #atp.offline=true # (optional) Authenticate other servers when the server try to communicate # each other. Servers form security domains. # default: false atp.authentication=false # (optional) Use secure random seed generation which is provided by JDK. # If this is set to false, aglet server uses a proprietary one, # which is unsecure but fast. # default: true #atp.secureseed=true # (optional) User servers ip address in server URL instead of # logical name. This is useful if you don't have a DNS entry. # default: false #atp.userip=true

François Lopitaux

28/48

End of studies report

# User ID for authorization. This key must exist in your keystore. # See keytool documentation for info on creating entry. (genkey) aglets.owner.name=aglet_key # Password for above user ID. Must be same as entered as the key password # used with keytool. aglets.owner.password=aglets # Keystore password. Same as used with keytool. aglets.keystore.password=aglets # Logger class for ASDK. # For log4j - org.aglets.log.log4j.Log4jInitializer # For output to standard out - org.aglets.log.console.ConsoleInitializer # For quiet - org.aglets.log.quiet.QuietInitializer # Default: org.aglets.log.quiet.QuietInitializer #aglets.logger.class=org.aglets.log.log4j.Log4jInitializer aglets.logger.class=org.aglets.log.quiet.QuietInitializer #aglets.logger.class=org.aglets.log.console.ConsoleInitializer #aglets.logger.class=com.ibm.awb.launcher.Console Ø Add in your CLASSPATH, %AGLET_HOME%\public. Ø Configure the file AgletUtils and put the address of your main server that centralizes the URL list. Ø Now you can compile all the class files.

5.3 How to use? Ø Launch

the

Tahiti

Server

with

%AGLET_HOME%\bin\aglets.bat

–f

..\cnf\aglets.props. Ø Launch the aglet com.morkai.AgletDB on your server. Ø Launch the aglet com.morkai.examples.HostDeclareMaster on each host that you want use. Ø Now you can launch the examples com.morkai.NetworkDirectoryList, the HTML report is on your %AGLET_HOME%\bin directory.

5.4 Code 5.4.1

Package com.morkai.utils

5.4.1.1

Slave

François Lopitaux

29/48

End of studies report

package com.morkai.utils; import com.ibm.aglet.*; import com.ibm.aglet.event.*; import com.ibm.agletx.util.MetaItinerary; import java.net.*; public abstract class Slave extends Aglet { protected Itinerary m_itinerary; protected AgletProxy m_master; protected String m_data; protected MetaItinerary m_meta; public void onCreation(Object args) { try { m_itinerary = (Itinerary) ((Object[]) args)[0]; m_master = (AgletProxy) ((Object[]) args)[1]; m_data = (String)((Object[]) args)[2]; initializeTask(); m_meta = new MetaItinerary(this); addMobilityListener( new MobilityAdapter() { public void onArrival(MobilityEvent me) { try { if (m_data == null) m_master.sendMessage(new Message("Result", doTask())); else if (m_data.equals("Unsubscribe")) doTask(); else m_master.sendMessage(new Message("Result", doTask())); if (m_itinerary.hasMoreDestinations()) m_itinerary.go(); else { if (m_data == null) m_master.sendMessage(new Message("Finish", m_meta)); dispose(); } } catch (Exception e) { e.printStackTrace(); dispose(); } } } ); m_itinerary.init(this);

François Lopitaux

30/48

End of studies report

dispose(); System.out.println("No destination"); } catch (Exception e) { e.printStackTrace(); } } protected abstract void initializeTask(); protected abstract Object doTask(); }

5.4.1.2

Itinerary

package com.morkai.utils; import com.ibm.aglet.*; import java.io.*; import java.net.*; public abstract class Itinerary implements Serializable { protected URL m_origin protected AgletProxy m_aglet

= null; = null;

public Itinerary(URL origin) { m_origin = origin; } public void init(Aglet aglet) { System.out.println(aglet.getAgletID() + " : method init()"); m_aglet = aglet.getAgletContext().getAgletProxy(aglet.getAgletID()); System.out.println(aglet.getAgletID() + " : method init() - 1"); go(); } public URL getOrigin() { return m_origin; } protected void go(URL destination) throws Exception { System.out.println("Itinerary : method do(" + destination.toString() +")"); m_aglet.dispatch(destination); } public abstract void go(); public abstract boolean hasMoreDestinations();

François Lopitaux

31/48

End of studies report

public abstract URL getNextDestination(); }

5.4.1.3

SeqItinerary

package com.morkai.utils; import java.util.*; import java.net.*; public class SeqItinerary extends Itinerary { private Vector m_destinations = null; public SeqItinerary(URL origin, Vector destinations) { super(origin); m_destinations = (Vector) destinations.clone(); AgletUtils.viewVectorContent(m_destinations); } public void go() { URL dest = getNextDestination(); if (dest != null) { m_destinations.removeElementAt(0); try { go(dest); } catch (Exception e) { go(); } } } public boolean hasMoreDestinations() { return m_destinations.size() > 0; } public URL getNextDestination() { if (hasMoreDestinations()) return (URL) m_destinations.firstElement(); else return null; } }

5.4.1.4

AgletUtils

package com.morkai.utils;

François Lopitaux

32/48

End of studies report

import java.net.*; import java.util.*; import com.ibm.aglet.*; public class AgletUtils { public final static String NETWORK_MAP_SERVICE = "NetworkMapService"; public final static String HOST_FOR_DB = "atp://150.140.187.216:4434"; public final static String COMMAND_NAME_TO_RECOVER_URL_LIST = "RecoverURLList"; public final static String AGLET_NAME_TO_RECOVER_URL_LIST = "com.morkai.examples.AgletDB"; public final static int SLEEP = 1000 * 60; // 1 minut public static Object recoverInformation(Aglet aglet, String strClassName, String strCommand) throws Exception { AgletProxy proxy; proxy = findServiceAglet(aglet, strClassName); if (proxy != null) return sendMessageToRescover(proxy, strCommand); else return null; } private static void dispatchTo(Aglet aglet, String strServiceHost) throws Exception { URL url; url = new URL(strServiceHost); if (aglet.getAgletContext().getHostingURL().equals(url)) { aglet.run(); } else { aglet.dispatch(url); } } private static void dispatchTo(Aglet aglet, URL url) throws Exception { if (aglet.getAgletContext().getHostingURL().equals(url)) { aglet.run(); } else { aglet.dispatch(url); } } private static void returnHome(Aglet aglet) throws Exception { URL url; url = new URL(aglet.getProxy().getAgletInfo().getOrigin()); dispatchTo(aglet, url); }

François Lopitaux

33/48

End of studies report

private static boolean isHome(Aglet aglet) { URL url; url = null; try { url = new URL(aglet.getAgletInfo().getOrigin()); } catch (Exception e) { e.printStackTrace(); } return aglet.getAgletContext().getHostingURL().equals(url); } public static AgletProxy findServiceAglet(Aglet aglet, String strClassName) throws InvalidAgletException { Enumeration eProxies; AgletProxy proxy; eProxies = aglet.getAgletContext().getAgletProxies(); while (eProxies.hasMoreElements()) { proxy = (AgletProxy) eProxies.nextElement(); if (proxy.getAgletClassName().equals(strClassName)) { System.out.println(aglet.getAgletID() + ": proxy found"); if (! proxy.isActive()) { try { proxy.activate(); } catch (Exception e) { e.printStackTrace(); } } return proxy; } } System.out.println(aglet.getAgletID() + ": no proxy found"); return null; } private static Object sendMessageToRescover(AgletProxy proxy, String strCommand) throws Exception { Message msg; msg = new Message(strCommand); return proxy.sendMessage(msg); } public static void viewVectorContent(Vector vector) { Enumeration enum; URL url; int i;

François Lopitaux

34/48

End of studies report

enum = vector.elements(); i = 1; System.out.println("########## BEGINNING OF THE LIST ############"); while (enum.hasMoreElements()) { url = (URL) enum.nextElement(); System.out.println("In this vector we are " + i++ + " the url " + url.toString()); } System.out.println("########## END OF THE LIST ############"); } }

5.4.2

Package com.morkai.examples

5.4.2.1

AgletDB

package com.morkai.examples; import com.ibm.aglet.*; import com.morkai.utils.*; import java.net.*; import java.util.*;

public class AgletDB extends Aglet { private final static String SERVICE_NAME = AgletUtils.NETWORK_MAP_SERVICE; private Vector m_vURLList; public void onCreation(Object init) { m_vURLList = new Vector(); } public boolean handleMessage(Message msg) { System.out.println(getAgletID() + " : Message receive with kind " + msg.getKind()); if (msg.sameKind(SERVICE_NAME)) { System.out.println(getAgletID() + " : Message processed "); doNetworkMapService(msg); return true; } return false; } public void doSendURLList(Message msg) { msg.sendReply(m_vURLList); }

François Lopitaux

35/48

End of studies report

public void doNetworkMapService(Message msg) { URL url = null; try { url = new URL(msg.getArg("URL").toString()); } catch (MalformedURLException e) { e.printStackTrace(); } if (msg.getArg("Command").equals("Subscribe")) { doSubscribe(url); System.out.println("AgletDB"); AgletUtils.viewVectorContent(m_vURLList); msg.sendReply(m_vURLList); } else if (msg.getArg("Command").equals("Unsubscribe")) doUnsubscribe(url); } public void doSubscribe(URL url) { //check if the URL is new or not if (! m_vURLList.contains(url)) { //URL is new it add this at the list m_vURLList.addElement(url); System.out.println(getAgletID() + " : URL added"); } } public void doUnsubscribe(URL url) { //check if the URL exists still if (m_vURLList.contains(url)) { m_vURLList.removeElement(url); System.out.println(getAgletID() + " : URL removed"); } } }

5.4.2.2

HostDeclareMaster

package com.morkai.examples; import com.ibm.aglet.*; import com.morkai.utils.*; import java.util.*; import java.net.*; public class HostDeclareMaster extends Aglet {

François Lopitaux

36/48

End of studies report

private final String HOST = AgletUtils.HOST_FOR_DB; private final String SLAVE = "com.morkai.examples.HostDeclareMessager"; private final String COMMAND_NAME = AgletUtils.COMMAND_NAME_TO_RECOVER_URL_LIST; private final String TIMER = "com.morkai.examples.TimerAglet"; private final String SUBSCRIBE = "Subscribe"; private final String UNSUBSCRIBE = "Unsubscribe"; private Object[] m_args; private URL m_origin; private Vector m_vURLList; private AgletProxy m_timerProxy; public void onCreation(Object init) { try { m_timerProxy = getAgletContext().createAglet(getCodeBase(), TIMER , getProxy()); } catch (Exception e) { e.printStackTrace(); } } public void doCreateSlave(String strSubscribe) { Vector vDestinations = null; URL url = null; SeqItinerary itinerary = null; vDestinations = new Vector(); try { url = new URL(HOST); vDestinations.addElement(url); itinerary = new SeqItinerary(m_origin, vDestinations); m_args = new Object[] { itinerary, getProxy(), strSubscribe }; getAgletContext().createAglet(getCodeBase(), SLAVE, m_args); } catch (Exception e) { e.printStackTrace(); } } public void onDisposing() { doCreateSlave(UNSUBSCRIBE); try { if (! m_timerProxy.isActive()) m_timerProxy.activate(); m_timerProxy.dispose(); } catch (Exception e) { e.printStackTrace(); } }

François Lopitaux

37/48

End of studies report

public boolean handleMessage(Message msg) { System.out.println(getAgletID() + " : Message receive with kind " + msg.getKind()); if (msg.sameKind("Result")) { m_vURLList = (Vector) msg.getArg(); System.out.println(getAgletID() + " : handleMessage end"); AgletUtils.viewVectorContent(m_vURLList); return true; } else if (msg.sameKind(COMMAND_NAME)) { doSendURLList(msg); System.out.println(getAgletID() + " : handleMessage end"); return true; } else if (msg.sameKind("GetUp")) { doCreateSlave(SUBSCRIBE); return true; } System.out.println(getAgletID() + " : handleMessage end"); return false; } public void doSendURLList(Message msg) { msg.sendReply(m_vURLList); } }

5.4.2.3

HostDeclareMessager

package com.morkai.examples; import com.ibm.aglet.*; import com.morkai.utils.*; import java.net.*; import java.util.*;

public class HostDeclareMessager extends Slave { private final String SERVICE_NAME = AgletUtils.NETWORK_MAP_SERVICE; private final String AGLET_NAME = AgletUtils.AGLET_NAME_TO_RECOVER_URL_LIST; private boolean private URL

m_bSubscribe; m_originURL;

public Object doTask() { AgletProxy proxy; Message msg; System.out.println(getAgletID() + " : method doTask"); proxy = null; try {

François Lopitaux

38/48

End of studies report

proxy = AgletUtils.findServiceAglet(this,AGLET_NAME); } catch (Exception e) { e.printStackTrace(); } if (m_data.equals("Subscribe")) return sendSubscribe(proxy); else if (m_data.equals("Unsubscribe")) sendUnsubscribe(proxy); return null; } public Vector sendSubscribe(AgletProxy proxy) { Message msg; Vector vURLList; if (proxy == null) { System.out.println(getAgletID() + " : proxy in null"); return null; } vURLList = null; msg = new Message(SERVICE_NAME); msg.setArg("Command","Subscribe"); msg.setArg("URL",m_originURL); System.out.println(getAgletID() + " : Subscribe send"); try { vURLList = (Vector) proxy.sendMessage(msg); AgletUtils.viewVectorContent(vURLList); } catch (Exception e) { e.printStackTrace(); } return vURLList; } public void sendUnsubscribe(AgletProxy proxy) { Message msg; msg = new Message(SERVICE_NAME); msg.setArg("Command","Unsubscribe"); msg.setArg("URL",m_originURL); try { proxy.sendMessage(msg); dispose(); } catch (Exception e) { //e.printStackTrace(); } System.out.println(getAgletID() + " : Unsubscribe send");

François Lopitaux

39/48

End of studies report

} public void initializeTask() { System.out.println(getAgletID() + " : method initializeTask()"); m_originURL = getAgletContext().getHostingURL(); } }

5.4.2.4

TimerAglet

package com.morkai.examples; import com.ibm.aglet.*; import com.morkai.utils.*; public class TimerAglet extends Aglet { private final int SLEEP = AgletUtils.SLEEP; private AgletProxy m_proxy; private Message m_msg;

public void onCreation(Object init) { m_proxy = (AgletProxy) init; m_msg = new Message("GetUp"); } public void run() { sendMessage(); try { deactivate(SLEEP); } catch (Exception e) { e.printStackTrace(); } } public void sendMessage() { try { m_proxy.sendMessage(m_msg); } catch (Exception e) { e.printStackTrace(); } } }

5.4.2.5

DeploymentNetwork

François Lopitaux

40/48

End of studies report

package com.morkai.examples; import com.ibm.aglet.*; import com.morkai.utils.*; import java.util.*; public abstract class DeploymentNetwork extends Aglet { private final String AGLET_NAME = "com.morkai.examples.HostDeclareMaster"; private final String COMMAND_NAME = AgletUtils.COMMAND_NAME_TO_RECOVER_URL_LIST; protected void createSlave(String strAgletName) { Vector vURLList = null;; SeqItinerary itinerary = null; Object[] args = null; vURLList = recoverURLList(); itinerary = new SeqItinerary(getAgletContext().getHostingURL(), vURLList); args = new Object[] { itinerary, getProxy() , null }; try { getAgletContext().createAglet(getCodeBase(), strAgletName, args); } catch (Exception e) { e.printStackTrace(); } } private Vector recoverURLList() { Vector vURLList = null; System.out.println(getAgletID() + ": method recoverURLList"); try { vURLList = (Vector) AgletUtils.recoverInformation(this, AGLET_NAME, COMMAND_NAME); } catch (Exception e) { e.printStackTrace(); } if (vURLList == null) System.out.println(getAgletID() + ": no vector recovered"); System.out.println(getAgletID() + ": vector recovered"); AgletUtils.viewVectorContent(vURLList); return vURLList; } public abstract void onCreation(Object init); public abstract boolean handleMessage(Message msg); }

François Lopitaux

41/48

End of studies report

5.4.2.6

NetworkDirectoryList

package com.morkai.examples; import java.util.*; import java.net.*; import java.io.*; import com.ibm.aglet.*; import com.ibm.agletx.util.MetaItinerary;

public class NetworkDirectoryList extends DeploymentNetwork { private final String SLAVE = "com.morkai.examples.SlaveNetworkDirectoryList"; private MetaItinerary m_meta; private Vector m_vResult; public void onCreation(Object init) { m_vResult = new Vector(); createSlave(SLAVE); } public void doWorkToFinish() { System.out.println(getAgletID() + ": method doWorkToFinish"); File file; FileOutputStream os = null; PrintWriter pw; Enumeration enumHost; Enumeration enumDir; String strURL; String[] strDir; int j; file = new File("result" + System.currentTimeMillis() + ".html"); try { file.createNewFile(); } catch (IOException e) { System.out.println("Can not create File"); e.printStackTrace(); } try { os = new FileOutputStream(file); } catch (FileNotFoundException e) { System.out.println("File not Found"); e.printStackTrace(); } pw = new PrintWriter(os, true); pw.print("");

François Lopitaux

42/48

End of studies report

pw.print(""); pw.print(""); pw.print("Result of the request"); pw.print(""); pw.print(""); pw.print(""); pw.print("

Result of the request

"); pw.print("

The Aglet Travel

"); enumHost = m_meta.getVisitedHosts(); while (enumHost.hasMoreElements()) { strURL = (String) enumHost.nextElement(); pw.print("Aglet has run on " + strURL + "
"); } pw.print("

The list of file and directory on c:

"); enumHost = m_meta.getVisitedHosts(); enumDir = m_vResult.elements(); while (enumHost.hasMoreElements()) { strURL = (String) enumHost.nextElement(); strDir = (String[]) enumDir.nextElement(); pw.print("
"); pw.print("

The directory of " + strURL+ "

"); pw.print("
"); for (j = 0 ; j < strDir.length ; j++) { pw.print(strDir[j] + "
"); } pw.print("
"); } pw.print(""); pw.print(""); try { pw.close(); os.close(); } catch (IOException e) { System.out.println("Can not close FileOutputStream"); e.printStackTrace(); } System.out.println("Excecution finished"); } public boolean handleMessage(Message msg) { System.out.println( getAgletID() + " : Message receive with kind " + msg.getKind()); if (msg.sameKind("Result")) { if (msg.getArg() != null) m_vResult.addElement(msg.getArg()); return true; } else if (msg.sameKind("Finish")) { m_meta = (MetaItinerary) msg.getArg();

François Lopitaux

43/48

End of studies report

doWorkToFinish(); dispose(); return true; } return false; } }

5.4.2.7

SlaveNetworkDirectoryList

package com.morkai.examples; import java.io.*; import com.morkai.utils.*; public class SlaveNetworkDirectoryList extends Slave { protected void initializeTask() { } protected Object doTask() { System.out.println(getAgletID() + " : metod doTask()"); String[] line; File directory = new File("C:\\"); line = null; return directory.list(); } }

5.4.2.8

ExecuteRuntimeCommand

package com.morkai.examples; import com.ibm.aglet.*; import com.ibm.agletx.util.MetaItinerary; import java.util.*; import java.io.*; public class ExecuteRuntimeCmd extends DeploymentNetwork { private String SLAVE = "com.morkai.examples.SlaveExecuteRuntimeCmd"; private MetaItinerary m_meta; private Vector m_vResult; public void onCreation(Object init) { m_vResult = new Vector(); createSlave(SLAVE); }

François Lopitaux

44/48

End of studies report

public void doWorkToFinish() { File file; FileOutputStream os = null; PrintWriter pw; Enumeration enumHost; Enumeration enumDir; String strURL; String[] strDir; int j; file = new File("result" + System.currentTimeMillis() + ".html"); try { file.createNewFile(); } catch (IOException e) { System.out.println("Can not create File"); e.printStackTrace(); } try { os = new FileOutputStream(file); } catch (FileNotFoundException e) { System.out.println("File not Found"); e.printStackTrace(); } pw = new PrintWriter(os, true); pw.print(""); pw.print(""); pw.print(""); pw.print("Result of the request"); pw.print(""); pw.print(""); pw.print(""); pw.print("

Result of the request

"); pw.print("

The Aglet Travel

"); enumHost = m_meta.getVisitedHosts(); while (enumHost.hasMoreElements()) { strURL = (String) enumHost.nextElement(); pw.print("Aglet has run on " + strURL + "
"); } pw.print("

The list of file and directory on c:

"); enumHost = m_meta.getVisitedHosts(); enumDir = m_vResult.elements(); while (enumHost.hasMoreElements()) { strURL = (String) enumHost.nextElement(); if (enumDir.hasMoreElements()) { strDir = (String[]) enumDir.nextElement(); pw.print("
");

François Lopitaux

45/48

End of studies report

pw.print("

The directory of " + strURL+ "

"); pw.print("
"); for (j = 0 ; j < strDir.length ; j++) { pw.print(strDir[j] + "
"); } pw.print("
"); } } pw.print(""); pw.print(""); try { pw.close(); os.close(); } catch (IOException e) { System.out.println("Can not close FileOutputStream"); e.printStackTrace(); } System.out.println("Excecution finished"); dispose(); } public boolean handleMessage(Message msg) { System.out.println( getAgletID() + " : Message receive with kind " + msg.getKind()); if (msg.sameKind("Result")) { if (msg.getArg() != null) m_vResult.addElement(msg.getArg()); return true; } else if (msg.sameKind("Finish")) { m_meta = (MetaItinerary) msg.getArg(); doWorkToFinish(); dispose(); return true; } return false; } }

5.4.2.9

SlaveExecuteRuntimeCommand

package com.morkai.examples; import java.io.*; import com.morkai.utils.*; public class SlaveExecuteRuntimeCmd extends Slave { protected void initializeTask() { }

François Lopitaux

46/48

End of studies report

protected Object doTask() { System.out.println(getAgletID() + " : metod doTask()"); String[] line = null; Process proc = null; BufferedReader br = null; ReadOutput readis = null; ReadOutput reades = null; Runtime runTime; String[] command = { "command.com", "/c", "ver" }; try { System.out.println("Execution ok"); runTime = Runtime.getRuntime(); proc = runTime.exec(command); System.out.println("Execution ok1"); readis = new ReadOutput(proc.getInputStream()); reades = new ReadOutput(proc.getErrorStream()); line = readis.go(); reades.go(); System.out.println(proc.waitFor()); } catch (Exception e) { e.printStackTrace(); proc.destroy(); } System.out.println("End of doTask()"); return line; } }

5.4.2.10 ReadOutput package com.morkai.examples; import java.io.*; public class ReadOutput extends Thread { private InputStream m_is; public ReadOutput(InputStream is) { m_is = is; } public String[] go() { String[] line = null;

François Lopitaux

47/48

End of studies report

String strTemp = null; BufferedReader br = null; int i = 0; try { br = new BufferedReader (new InputStreamReader (m_is)); System.out.println("ReadOutput"); while ((strTemp = br.readLine())!= null) { line[i] = strTemp; System.out.println("The line " + i + " is " + line[i]); i++; } br.close(); } catch (Exception e) { e.printStackTrace(); } return line; }

}

François Lopitaux

48/48