KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > mobilitools > smi > goodies > RegionManager


1 /*
2 * MobiliTools: an implementation of the Object Management Group's
3 * Mobile Agent Facility specification.
4 * Copyright (C) 2003 France Telecom R&D
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 *
20 * MobiliTools $Name: $
21 *
22 * Contact: mobilitools-smi@lists.debian-sf.objectweb.org
23 *
24 * Authors: Bruno Dillenseger
25 */

26
27
28 package org.objectweb.mobilitools.smi.goodies;
29
30
31 import java.util.*;
32 import java.io.*;
33 import org.omg.CfMAF.*;
34 import org.omg.CORBA.ORB JavaDoc;
35 import org.omg.CORBA.SystemException JavaDoc;
36 import org.omg.CORBA.Any JavaDoc;
37 import org.omg.CORBA.BAD_PARAM JavaDoc;
38 import org.objectweb.mobilitools.util.corba.NameService;
39 import org.objectweb.mobilitools.util.corba.NameServiceException;
40 import org.objectweb.mobilitools.util.corba.CORBA;
41 import org.objectweb.mobilitools.smi.*;
42 import org.objectweb.mobilitools.smi.api.*;
43 import org.objectweb.mobilitools.smi.idl.*;
44 import mparser.*;
45
46
47 /**
48  * MobiliTools $Name: $, $Id: RegionManager.java,v 1.1.1.1 2003/03/28 14:48:06 dillense Exp $
49  * <P>
50  * A RegionManager instance makes it possible to deploy and manage agents,
51  * as well as lookup agents and agent systems, through the MAF infrastructure
52  * (i.e. implementations of MAFAgentSystem and MAFFinder interfaces).
53  * Localization of MAFAgentSystem and MAFFinder servers is based on the
54  * CORBA naming service.
55  * If one naming service is running for each region, then regions must be
56  * interconnected by federating the naming services in the naming context
57  * of region name bindings.
58  * <BR>
59  * RegionManager can also be run as a standalone programme in order to create
60  * a set of agents in various existing agencies, by specifying a property file
61  * or XML file where all necessary definitions will be read from.
62 */

63 public class RegionManager
64 {
65     NameService my_ns;
66     ORB JavaDoc my_orb;
67
68     /**
69         Creates/deploys agents in existing agencies, from definitions
70         read from a property file or an XML file.
71         @param args shall contain ORB-specific switches first, and
72         then either <code>-xml xml_file</code> or <code>-prop property_file</code>
73         switch.
74         @see #deployFromPropFile(String)
75         @see #deployFromXMLFile(String)
76     */

77     static public void main(String JavaDoc[] args)
78     {
79         try
80         {
81             RegionManager manager = new RegionManager(ORB.init(args, System.getProperties()));
82             Properties props = new Properties();
83             if (args[args.length-2].equalsIgnoreCase("-prop"))
84             {
85                 manager.deployFromPropFile(args[args.length-1]);
86             }
87             else if(args[args.length-2].equalsIgnoreCase("-xml"))
88             {
89                 manager.deployFromXMLFile(args[args.length-1]);
90             }
91             else
92             {
93                 System.out.println("usage: [ORB-specific args...] [-prop file] [-xml file]");
94             }
95         }
96         catch (Exception JavaDoc ex)
97         {
98             System.err.println(ex.toString());
99         }
100     }
101
102
103     /**
104         Parses the specified XML file in order to make the specified agent creations.
105         This file should contain DEPLOY tags, embracing AGENT tags. If both tags,
106         attributes name, region, agency, place, class, codebase, and arguments
107         may be defined. When an attribute is defined in DEPLOY tag, then its value
108         is the default value for every enclosed AGENT tag.
109         @param file the name of the XML file to be parsed.
110         @throws Exception a variety of exceptions if a parsing error occurs,
111         because of an invalid file format (check the XML content)
112     */

113     public void deployFromXMLFile(String JavaDoc file)
114         throws Exception JavaDoc
115     {
116         WMparser parser = new WMparser(file);
117         ItemParsed item;
118         Properties props = null;
119         int agentCount = 0;
120         short status = 0;
121
122         while (parser.hasMoreItems())
123         {
124             item = parser.getNextItem();
125             switch (status)
126             {
127             case 0: // looking for <DEPLOY> tag
128
if ((item.getType() == ItemParsed.ITEM_TYPE_ELEMT) && item.getName().equalsIgnoreCase("deploy"))
129                 {
130                     props = new Properties();
131                     agentCount = 0;
132                     status = 1;
133                 }
134                 else if (item.getType() == ItemParsed.ITEM_TYPE_TEXTE)
135                 {
136                     System.out.println(item.getValue());
137                 }
138                 else
139                 {
140                     System.out.println("XML deployment warning: ignoring \"" + item.getName() + "\"");
141                 }
142                 break;
143             case 1: // looking for <DEPLOY> attributes, or <AGENT> tag, or <DEPLOY> tag
144
if (item.getType() == ItemParsed.ITEM_TYPE_ATTRB)
145                 {
146                     props.setProperty(item.getName().substring("deploy.".length()), item.getValue());
147                 }
148                 else if ((item.getType() == ItemParsed.ITEM_TYPE_ELEMT) && item.getName().equalsIgnoreCase("deploy.agent"))
149                 {
150                     ++agentCount;
151                     status = 2;
152                 }
153                 else if ((item.getType() == ItemParsed.ITEM_TYPE_ELEMT) && item.getName().equalsIgnoreCase("deploy"))
154                 {
155                     props = new Properties();
156                     agentCount = 0;
157                     status = 1;
158                 }
159                 else if (item.getType() == ItemParsed.ITEM_TYPE_TEXTE)
160                 {
161                     System.out.println(item.getValue());
162                 }
163                 else
164                 {
165                     System.out.println("XML deployment warning: ignoring \"" + item.getName() + "\"");
166                 }
167                 break;
168             case 2: // looking for <AGENT> attributes, or <AGENT> tag, or <DEPLOY> tag
169
if (item.getType() == ItemParsed.ITEM_TYPE_ATTRB)
170                 {
171                     props.setProperty(
172                         item.getName().substring("deploy.agent.".length()) + "." + String.valueOf(agentCount),
173                         item.getValue());
174                 }
175                 else if ((item.getType() == ItemParsed.ITEM_TYPE_ELEMT) && item.getName().equalsIgnoreCase("deploy.agent"))
176                 {
177                     ++agentCount;
178                 }
179                 else if ((item.getType() == ItemParsed.ITEM_TYPE_ELEMT) && item.getName().equalsIgnoreCase("deploy"))
180                 {
181                     deploy(props);
182                     props = new Properties();
183                     agentCount = 0;
184                     status = 1;
185                 }
186                 else if (item.getType() == ItemParsed.ITEM_TYPE_TEXTE)
187                 {
188                     System.out.println(item.getValue());
189                 }
190                 else
191                 {
192                     System.out.println("XML deployment warning: ignoring \"" + item.getName() + "\"");
193                 }
194                 break;
195             }
196         }
197         if (props != null)
198         {
199             deploy(props);
200         }
201     }
202
203
204     /**
205         Parses the specified property file in order to make the specified agent creations.
206         @param file the name of the property file to be parsed.
207         @throws IOException if the specified file could not be read.
208         @see #deploy(Properties)
209     */

210     public void deployFromPropFile(String JavaDoc file)
211         throws IOException
212     {
213         Properties props = new Properties();
214         props.load(new FileInputStream(new File(file)));
215         deploy(props);
216     }
217
218
219     /**
220         Performs agent creations specified by the provided properties.
221         Properties are:
222         <UL>
223             <LI>name.<I>n</I> for <I>n</I>th agent name
224             <LI>class.<I>n</I> for class name of <I>n</I>th agent
225             <LI>codebase.<I>n</I> for codebase of <I>n</I>th agent
226             <LI>arguments.<I>n</I> for <I>n</I>th agent's arguments
227             <LI>region.<I>n</I> for region name of <I>n</I>th agent
228             <LI>agency.<I>n</I> for agency name of <I>n</I>th agent
229             <LI>place.<I>n</I> for place name of <I>n</I>th agent
230         </UL>
231         Where <I>n</I> increments from 1 and stops as soon as property name.<I>n</I> is undefined.
232         Any of these properties but name.<I>n</I> may be given a default
233         value for every agent by omitting ".<I>n</I>" suffix.
234     */

235     public void deploy(Properties props)
236     {
237         String JavaDoc agentname = null;
238         String JavaDoc classname = null;
239         String JavaDoc codebase = null;
240         String JavaDoc place = null;
241         String JavaDoc argumentStr = null;
242         String JavaDoc agency = null;
243         String JavaDoc region = null;
244         String JavaDoc suffix = null;
245         org.omg.CfMAF.Name mafName = null;
246         Object JavaDoc[] argument = null;
247         Location location = null;
248
249         try
250         {
251             StringTokenizer parser;
252             AgentSystemInfo agencyInfo;
253             for (int i=1 ; (agentname = props.getProperty("name." + (suffix = String.valueOf(i)))) != null ; ++i)
254             {
255                 if ((classname = props.getProperty("class." + suffix)) == null)
256                 {
257                     classname = props.getProperty("class");
258                 }
259                 if ((place = props.getProperty("place." + suffix)) == null)
260                 {
261                     place = props.getProperty("place");
262                 }
263                 if ((codebase = props.getProperty("codebase." + suffix)) == null)
264                 {
265                     codebase = props.getProperty("codebase");
266                 }
267                 if ((argumentStr = props.getProperty("arguments." + suffix)) == null)
268                 {
269                     argumentStr = props.getProperty("arguments");
270                 }
271                 if ((agency = props.getProperty("agency." + suffix)) == null)
272                 {
273                     agency = props.getProperty("agency");
274                 }
275                 if ((region = props.getProperty("region." + suffix)) == null)
276                 {
277                     region = props.getProperty("region");
278                 }
279                 if (argumentStr == null)
280                 {
281                     argument = new Object JavaDoc[0];
282                 }
283                 else
284                 {
285                     parser = new StringTokenizer(argumentStr);
286                     argument = new String JavaDoc[parser.countTokens()];
287                     for (int j=0 ; j<parser.countTokens() ; ++j)
288                     {
289                         argument[j] = parser.nextToken();
290                     }
291                 }
292                 location = new Location(region, agency);
293                 agencyInfo = resolveAgentSystem(location).get_agent_system_info();
294                 mafName = new org.omg.CfMAF.Name(System.getProperty("user.name").getBytes(), agentname.getBytes(), agencyInfo.agent_system_type);
295                 System.out.println(
296                     "Creating agent " + new org.objectweb.mobilitools.smi.api.Name(mafName) + " of class " + classname +
297                     "\n- codebase " + codebase +
298                     "\n- place " + place + " at location " + location +
299                     "\n- with " + (argumentStr == null ? "no argument." : "arguments " + argumentStr));
300                 createAgent(
301                     location,
302                     classname,
303                     codebase,
304                     new org.objectweb.mobilitools.smi.api.Name(mafName),
305                     place,
306                     new AgentProfile(
307                         Constants.LANGUAGE_ID,
308                         agencyInfo.agent_system_type,
309                         agencyInfo.agent_system_description,
310                         agencyInfo.major_version,
311                         agencyInfo.minor_version,
312                         Constants.SERIALIZATION,
313                         new Any JavaDoc[0]),
314                     null,
315                     argument);
316             }
317         }
318         catch (Exception JavaDoc ex)
319         {
320             ex.printStackTrace();
321         }
322     }
323
324
325     public RegionManager(ORB JavaDoc orb)
326         throws BadOperation
327     {
328         my_orb = orb;
329         try
330         {
331             my_ns = new NameService(orb);
332         }
333         catch (NameServiceException e)
334         {
335             System.err.println("A RegionManager instance cannot proceed without COS naming service: " + e);
336             throw new BadOperation(BadOperation.INFRASTRUCTURE, "Cannot create RegionManager instance: COS naming service not found.");
337         }
338     }
339
340
341     public RegionManager()
342         throws BadOperation
343     {
344         this(ORB.init(new String JavaDoc[0], System.getProperties()));
345     }
346
347
348     /**
349         Creates an agent in the named agency of the specified region.
350         The specified agent system is its own class provider.
351         @return the actual name of the new agent, or null if the agent
352         creation failed because the location could not be resolved.
353         @param region region name
354         @param agency name wrapper for agency MAF name
355         @param classname the agent main class name.
356         @param codebase the codebase for loading the agent classes
357         (interpreted by the specified agent system).
358         @param name the name of the new agent.
359         @param place the name of place where the agent will be located.
360         @param profile new agent profile. The agent type must be compatible
361         with the agent system type of the target agent system.
362         @param agent_data serializable object that will be passed as an argument
363         to the afterBirth() agent method, unless the arguments parameter is not null.
364         @param arguments array of arguments that will be passed as an argument
365         to the afterBirth() agent method. Arguments must be Strings or object wrappers
366         for Java primitive types. If this parameter is null, then the agent_data
367         parameter is considered instead.
368         @throws BadOperation agent creation failed.
369         @see MobileObject#afterBirth(AgentSystem, AgentInfo, Object)
370     */

371     public org.objectweb.mobilitools.smi.api.Name createAgent(
372         String JavaDoc region,
373         org.objectweb.mobilitools.smi.api.Name agency,
374         String JavaDoc classname,
375         String JavaDoc codebase,
376         org.objectweb.mobilitools.smi.api.Name name,
377         String JavaDoc place,
378         AgentProfile profile,
379         Serializable agent_data,
380         Object JavaDoc[] arguments)
381         throws BadOperation
382     {
383         return createAgent(
384             findAgency(region, agency),
385             classname,
386             codebase,
387             name,
388             place,
389             profile,
390             agent_data,
391             arguments);
392     }
393
394
395     /**
396         Creates an agent at the specified agent system location.
397         The specified agent system is its own class provider.
398         @return the actual name of the new agent, or null if the agent
399         creation failed because the location could not be resolved.
400         @param location agent system location where the agent must me created.
401         @param classname the agent main class name.
402         @param codebase the codebase for loading the agent classes
403         (interpreted by the specified agent system).
404         @param name the name of the new agent.
405         @param place the name of place where the agent will be located.
406         @param profile new agent profile. The agent type must be compatible
407         with the agent system type of the target agent system.
408         @param agent_data serializable object that will be passed as an argument
409         to the afterBirth() agent method, unless the arguments parameter is not null.
410         @param arguments array of arguments that will be passed as an argument
411         to the afterBirth() agent method. Arguments must be Strings or object wrappers
412         for Java primitive types. If this parameter is null, then the agent_data
413         parameter is considered instead.
414         @throws BadOperation agent creation failed.
415         @see MobileObject#afterBirth(AgentSystem, AgentInfo, Object)
416     */

417     public org.objectweb.mobilitools.smi.api.Name createAgent(
418         Location location,
419         String JavaDoc classname,
420         String JavaDoc codebase,
421         org.objectweb.mobilitools.smi.api.Name name,
422         String JavaDoc place,
423         AgentProfile profile,
424         Serializable agent_data,
425         Object JavaDoc argObj)
426         throws BadOperation
427     {
428         org.objectweb.mobilitools.smi.api.Name result = null;
429         MAFAgentSystem agency = resolveAgentSystem(location);
430         if (agency != null)
431         {
432             byte[] argBytes;
433             byte[] data;
434             if (argObj == null)
435             {
436                 argBytes = new byte[0];
437                 if (agent_data != null)
438                 {
439                     try
440                     {
441                         ByteArrayOutputStream dataBaos = new ByteArrayOutputStream();
442                         ObjectOutputStream objOos = new ObjectOutputStream(dataBaos);
443                         objOos.writeObject(agent_data);
444                         data = dataBaos.toByteArray();
445                     }
446                     catch (IOException e)
447                     {
448                         throw new BadOperation(
449                             BadOperation.SERIALIZATION,
450                             "Supplied data for agent creation cannot be serialized:\n" + e);
451                     }
452                 }
453                 else
454                 {
455                     data = new byte[0];
456                 }
457             }
458             else
459             {
460                 data = new byte[0];
461                 try
462                 {
463                     ByteArrayOutputStream dataBaos = new ByteArrayOutputStream();
464                     ObjectOutputStream objOos = new ObjectOutputStream(dataBaos);
465                     objOos.writeObject(argObj);
466                     argBytes = dataBaos.toByteArray();
467                 }
468                 catch (IOException e)
469                 {
470                     throw new BadOperation(
471                         BadOperation.SERIALIZATION,
472                         "Supplied argument for agent creation cannot be serialized:\n" + e);
473                 }
474             }
475             try
476             {
477                 result = new org.objectweb.mobilitools.smi.api.Name(
478                     agency.create_agent(
479                         name.getmafname(),
480                         profile,
481                         data,
482                         place,
483                         argBytes,
484                         new ClassName[] {
485                             new ClassName(
486                                 classname,
487                                 new byte[0])
488                         },
489                         codebase,
490                         null));
491             }
492             catch (SystemException JavaDoc e)
493             {
494                 e.printStackTrace();
495                 throw new BadOperation(BadOperation.INFRASTRUCTURE, "CORBA SystemException while talking to agency " + location + ":\n" + e);
496             }
497             catch (MAFExtendedException e)
498             {
499                 throw new BadOperation(
500                     BadOperation.OTHER,
501                     "Agent creation failed, probably for Java security or access modifiers reasons.");
502             }
503             catch (ClassUnknown e)
504             {
505                 throw new BadOperation(
506                     BadOperation.CLASSFAULT,
507                     "Agent could not be created because of undefined class(es).");
508             }
509             catch (ArgumentInvalid e)
510             {
511                 throw new BadOperation(
512                     BadOperation.REJECTED,
513                     "The agent refused to settle.");
514             }
515             catch (DeserializationFailed e)
516             {
517                 throw new BadOperation(
518                     BadOperation.SERIALIZATION,
519                     "Provided data for agent creation could not be deserialized.");
520             }
521         }
522         return result;
523     }
524
525
526     /**
527         Moves an agent to the named agency in the specified region.
528         @param from_region the name of the region the agent is currently residing in.
529         @param agent the name of the agent.
530         @param to_region the destination region.
531         @param to_agency the name of the destination agency in the given destination region.
532         @param place the destination place.
533         @throws BadOperation agent move has failed.
534     */

535     public void moveAgent(
536         String JavaDoc from_region,
537         org.objectweb.mobilitools.smi.api.Name agent,
538         String JavaDoc to_region,
539         org.objectweb.mobilitools.smi.api.Name to_agency,
540         String JavaDoc place)
541         throws BadOperation
542     {
543         moveAgent(
544             findAgent(from_region, agent),
545             agent,
546             findAgency(to_region, to_agency),
547             place);
548     }
549
550
551     /**
552         Moves an agent to the specified location.
553         @param from_location current agent location.
554         @param agent the name of the agent.
555         @param to_location the destination location.
556         @param place the destination place.
557         @throws BadOperation agent move has failed.
558     */

559     public void moveAgent(Location from_location, org.objectweb.mobilitools.smi.api.Name agent, Location to_location, String JavaDoc place)
560         throws BadOperation
561     {
562         MAFAgentSystemComplement agency = resolveAgentSystemComplement(from_location);
563         try
564         {
565             agency.move_agent(agent.getmafname(), to_location.toString(), place);
566         }
567         catch (SystemException JavaDoc e)
568         {
569             e.printStackTrace();
570             throw new BadOperation(
571                 BadOperation.INFRASTRUCTURE,
572                 "CORBA SystemException while talking to agency " + from_location + ":\n" + e);
573         }
574         catch (ClassUnknown e)
575         {
576             throw new BadOperation(
577                 BadOperation.CLASSFAULT,
578                 "At least one class of the moving agent is not defined in destination agency.");
579         }
580         catch (DeserializationFailed e)
581         {
582             throw new BadOperation(
583                 BadOperation.SERIALIZATION,
584                 "Agent deserialization failed.");
585         }
586         catch (ArgumentInvalid e)
587         {
588             throw new BadOperation(
589                 BadOperation.DESTINATION,
590                 "Unknown destination agency " + to_location + " (bad location format).");
591         }
592         catch (AgentRefusedToMove e)
593         {
594             throw new BadOperation(
595                 BadOperation.REJECTED,
596                 "Agent refused to move.");
597         }
598         catch (AgentSystemNotFound e)
599         {
600             throw new BadOperation(
601                 BadOperation.DESTINATION,
602                 "Destination agency is not known by source agency.");
603         }
604         catch (AgentNotFound e)
605         {
606             throw new BadOperation(
607                 BadOperation.RETRY,
608                 "Agent is not present at its known host agency (it must have moved - retry).");
609         }
610         catch (MAFExtendedException e)
611         {
612             throw new BadOperation(
613                 BadOperation.INFRASTRUCTURE,
614                 "CORBA communication or naming service problem in agent's host agency.");
615         }
616     }
617
618
619     /**
620         Resumes the activity of the specified agent in the specified region.
621         @param region the name of the region where the agent is residing.
622         @param agent the name wrapper of the agent MAF name.
623         @throws BadOperation either the agent was already running, or its resumption failed.
624     */

625     public void resumeAgent(String JavaDoc region, org.objectweb.mobilitools.smi.api.Name agent)
626         throws BadOperation
627     {
628         resumeAgent(findAgent(region, agent), agent);
629     }
630
631
632     /**
633         Resumes the activity of the specified agent residing at the specified location.
634         @param location agent location.
635         @param agent the name wrapper of the agent MAF name.
636         @throws BadOperationeither the agent was already running, or its resumption failed.
637     */

638     public void resumeAgent(Location location, org.objectweb.mobilitools.smi.api.Name agent)
639         throws BadOperation
640     {
641         MAFAgentSystem agency;
642         agency = resolveAgentSystem(location);
643         try
644         {
645             agency.resume_agent(agent.getmafname());
646         }
647         catch (SystemException JavaDoc e)
648         {
649             e.printStackTrace();
650             throw new BadOperation(
651                 BadOperation.INFRASTRUCTURE,
652                 "CORBA SystemException while talking to agency " + location + ":\n" + e);
653         }
654         catch (ResumeFailed e)
655         {
656             throw new BadOperation(
657                 BadOperation.REJECTED,
658                 "The agent could resume its activity.");
659         }
660         catch (AgentIsRunning e)
661         {
662             throw new BadOperation(
663                 BadOperation.RUNNING,
664                 "The agent was already running.");
665         }
666         catch (AgentNotFound e)
667         {
668             throw new BadOperation(
669                 BadOperation.RETRY,
670                 "Agent is not present at its known host agency (it must have moved - retry).");
671         }
672     }
673
674
675     /**
676         Suspends the activity of the specified agent in the specified region.
677         @param region the name of the region where the agent is residing.
678         @param agent the name wrapper of the agent MAF name.
679         @throws BadOperation either the agent was already suspended, or it could not be suspended.
680     */

681     public void suspendAgent(String JavaDoc region, org.objectweb.mobilitools.smi.api.Name agent)
682         throws BadOperation
683     {
684         suspendAgent(findAgent(region, agent), agent);
685     }
686
687
688     /**
689         Suspends the activity of the specified agent residing at the specified location.
690         @param location agent location.
691         @param agent the name wrapper of the agent MAF name.
692         @throws BadOperation either the agent was already suspended, or it could not be suspended.
693     */

694     public void suspendAgent(Location location, org.objectweb.mobilitools.smi.api.Name agent)
695         throws BadOperation
696     {
697         MAFAgentSystem agency;
698         agency = resolveAgentSystem(location);
699         try
700         {
701             agency.suspend_agent(agent.getmafname());
702         }
703         catch (SystemException JavaDoc e)
704         {
705             e.printStackTrace();
706             throw new BadOperation(
707                 BadOperation.INFRASTRUCTURE,
708                 "CORBA SystemException while talking to agency " + location + ":\n" + e);
709         }
710         catch (SuspendFailed e)
711         {
712             throw new BadOperation(
713                 BadOperation.REJECTED,
714                 "The agent could suspend its activity.");
715         }
716         catch (AgentIsSuspended e)
717         {
718             throw new BadOperation(
719                 BadOperation.SUSPENDED,
720                 "The agent was already suspended.");
721         }
722         catch (AgentNotFound e)
723         {
724             throw new BadOperation(
725                 BadOperation.RETRY,
726                 "Agent is not present at its known host agency (it must have moved - retry).");
727         }
728     }
729
730
731     /**
732         @return true if the specified agent in the specified region is currently active.
733         @param region the name of the region where the agent is residing.
734         @param agent wrapper of the agent MAF name.
735         @throws BadOperation could not get agent activity status.
736     */

737     public boolean isRunning(String JavaDoc region, org.objectweb.mobilitools.smi.api.Name agent)
738         throws BadOperation
739     {
740         return isRunning(findAgent(region, agent), agent);
741     }
742
743
744     /**
745         @return true if the specified agent in the specified region is currently active.
746         @param location agent location.
747         @param agent the name wrapper of the agent MAF name.
748         @throws BadOperation could not get agent activity status.
749     */

750     public boolean isRunning(Location location, org.objectweb.mobilitools.smi.api.Name agent)
751         throws BadOperation
752     {
753         MAFAgentSystem agency;
754         agency = resolveAgentSystem(location);
755         try
756         {
757             return agency.get_agent_status(agent.getmafname()) == AgentStatus.CfMAFRunning;
758         }
759         catch (SystemException JavaDoc e)
760         {
761             e.printStackTrace();
762             throw new BadOperation(
763                 BadOperation.INFRASTRUCTURE,
764                 "CORBA SystemException while talking to agency " + location + ":" + e);
765         }
766         catch (AgentNotFound e)
767         {
768             throw new BadOperation(
769                 BadOperation.RETRY,
770                 "Agent is not present at its known host agency (it must have moved - retry).");
771         }
772     }
773
774
775     /**
776         Terminates the specified agent in the specified region.
777         @param region the name of the region where the agent is residing.
778         @param agent the name wrapper of the agent MAF name.
779         @throws BadOperation
780     */

781     public void terminateAgent(String JavaDoc region, org.objectweb.mobilitools.smi.api.Name agent)
782         throws BadOperation
783     {
784         terminateAgent(findAgent(region, agent), agent);
785     }
786
787
788     /**
789         Terminates the specified agent in the specified region.
790         @param location agent location.
791         @param agent the name wrapper of the agent MAF name.
792         @throws BadOperation
793     */

794     public void terminateAgent(Location location, org.objectweb.mobilitools.smi.api.Name agent)
795         throws BadOperation
796     {
797         MAFAgentSystem agency = resolveAgentSystem(location);
798         try
799         {
800             agency.terminate_agent(agent.getmafname());
801         }
802         catch (SystemException JavaDoc e)
803         {
804             e.printStackTrace();
805             throw new BadOperation(
806                 BadOperation.INFRASTRUCTURE,
807                 "CORBA SystemException while talking to agency " + location + ":\n" + e);
808         }
809         catch (AgentNotFound e)
810         {
811             throw new BadOperation(
812                 BadOperation.RETRY,
813                 "Agent " + agent + " is not present at its known host agency (it must have moved - retry).");
814         }
815         catch (TerminateFailed e)
816         {
817             throw new BadOperation(
818                 BadOperation.REJECTED,
819                 "Termination failed for agent " + agent + ".");
820         }
821     }
822
823
824     /**
825         Terminates the specified agency in the specified region.
826         @param region the name of the region where the agency belongs to.
827         @param agency wrapper of the agency MAF name.
828         @throws BadOperation agency could not be terminated.
829     */

830     public void terminateAgency(String JavaDoc region, org.objectweb.mobilitools.smi.api.Name agency)
831         throws BadOperation
832     {
833         terminateAgency(findAgency(region, agency));
834     }
835
836
837     /**
838         Terminates the specified agency in the specified region.
839         @param location agency location.
840         @throws BadOperation agency could not be terminated
841     */

842     public void terminateAgency(Location location)
843         throws BadOperation
844     {
845         MAFAgentSystem agency;
846         agency = resolveAgentSystem(location);
847         try
848         {
849             agency.terminate_agent_system();
850         }
851         catch (SystemException JavaDoc e)
852         {
853             e.printStackTrace();
854             throw new BadOperation(
855                 BadOperation.INFRASTRUCTURE,
856                 "CORBA SystemException while talking to agency " + location + ":\n" + e);
857         }
858         catch (TerminateFailed e)
859         {
860             throw new BadOperation(
861                 BadOperation.REJECTED,
862                 "Agency at " + location + " refused to terminate.");
863         }
864     }
865
866
867     /**
868         @return an array of agency locations where agents matching the specified properties
869         reside, in the specified region.
870         This array is zero-sized if no agent matches the given properties (or if there is no agent at all).
871         @param region target region
872         @param properties agent properties to match; may be null if all agents are wanted.
873         @throws BadOperation could not get list of agent location
874     */

875     public Location[] listAgentLocations(String JavaDoc region, Properties properties)
876         throws BadOperation
877     {
878         Location[] result;
879         MAFFinder finder = resolveFinder(region);
880         try
881         {
882             AgentProfile profile = Misc.newDummyAgentProfile();
883             profile.properties = Misc.property2any(properties, my_orb);
884             String JavaDoc[] locations = finder.lookup_agent(
885                 Misc.DUMMYNAME,
886                 profile);
887             result = new Location[locations.length];
888             for (int i=0 ; i<locations.length ; ++i)
889             {
890                 result[i] = new Location(locations[i]);
891             }
892         }
893         catch (SystemException JavaDoc e)
894         {
895             e.printStackTrace();
896             throw new BadOperation(
897                 BadOperation.INFRASTRUCTURE,
898                 "CORBA SystemException while talking to region " + region + "'s MAFFinder:\n" + e);
899         }
900         catch (BadOperation e)
901         {
902             e.printStackTrace();
903             throw new BadOperation(
904                 BadOperation.INFRASTRUCTURE,
905                 "Unsupported location format found in MAFFinder (" + e.getMessage() + ")");
906         }
907         catch (EntryNotFound e)
908         {
909             result = new Location[0];
910         }
911         return result;
912     }
913
914
915     /**
916         @return an array of names of agents matching the specified properties in the specified region.
917         The returned array is zero-sized if no agent matching the given properties could be found.
918         @param region target region.
919         @param properties agent properties to match; may be null if all agents are wanted.
920         @throws BadOperation could not get agents list.
921     */

922     public org.objectweb.mobilitools.smi.api.Name[] listAgentNames(String JavaDoc region, Properties properties)
923         throws BadOperation
924     {
925         org.objectweb.mobilitools.smi.api.Name[] result;
926         MAFFinderComplement finder = resolveFinderComplement(region);
927         try
928         {
929             AgentProfile profile = Misc.newDummyAgentProfile();
930             profile.properties = Misc.property2any(properties, my_orb);
931             org.omg.CfMAF.Name[] names = finder.lookup_agent_names(profile);
932             result = new org.objectweb.mobilitools.smi.api.Name[names.length];
933             for (int i=0 ; i<names.length ; ++i)
934             {
935                 result[i] = new org.objectweb.mobilitools.smi.api.Name(names[i]);
936             }
937         }
938         catch (SystemException JavaDoc e)
939         {
940             e.printStackTrace();
941             throw new BadOperation(
942                 BadOperation.INFRASTRUCTURE,
943                 "CORBA SystemException while talking to region " + region + "'s MAFFinder:" + e);
944         }
945         return result;
946     }
947
948
949     /**
950         @return the names of all the agents at the specified agency location.
951         The returned array is zero-sized if there is no agent at given location.
952         @param location target agent system location
953         @throws BadOperation could not get agents list.
954     */

955     public org.objectweb.mobilitools.smi.api.Name[] listAgentsIn(Location location)
956         throws BadOperation
957     {
958         org.objectweb.mobilitools.smi.api.Name[] result;
959         MAFAgentSystem agentSystem = resolveAgentSystem(location);
960         org.omg.CfMAF.Name[] names = null;
961         try
962         {
963             names = agentSystem.list_all_agents();
964             result = new org.objectweb.mobilitools.smi.api.Name[names.length];
965             for (int i=0 ; i<names.length ; ++i)
966             {
967                 result[i] = new org.objectweb.mobilitools.smi.api.Name(names[i]);
968             }
969         }
970         catch (SystemException JavaDoc e)
971         {
972             e.printStackTrace();
973             throw new BadOperation(
974                 BadOperation.INFRASTRUCTURE,
975                 "CORBA SystemException while talking to agency " + location + ":\n" + e);
976         }
977         return result;
978     }
979
980
981     /**
982         @return the names of the agents matching a given profile at the specified agency location.
983         The returned array is zero-sized if there is no agent at given location.
984         @param location target agent system location
985         @param profile agent profile to match.
986         @throws BadOperation could not get agents list
987     */

988     public org.objectweb.mobilitools.smi.api.Name[] listAgentsIn(Location location, AgentProfile profile)
989         throws BadOperation
990     {
991         org.objectweb.mobilitools.smi.api.Name[] result;
992         MAFAgentSystemComplement agentSystem = resolveAgentSystemComplement(location);
993         org.omg.CfMAF.Name[] names = null;
994         try
995         {
996             names = agentSystem.list_agents(profile);
997             result = new org.objectweb.mobilitools.smi.api.Name[names.length];
998             for (int i=0 ; i<names.length ; ++i)
999             {
1000                result[i] = new org.objectweb.mobilitools.smi.api.Name(names[i]);
1001            }
1002        }
1003        catch (SystemException JavaDoc e)
1004        {
1005            e.printStackTrace();
1006            throw new BadOperation(
1007                BadOperation.INFRASTRUCTURE,
1008                "CORBA SystemException while talking to agency " + location + ":\n" + e);
1009        }
1010        return result;
1011    }
1012
1013
1014    /**
1015        @return the locations of all the agent systems matching the given properties
1016        in the specified region.
1017        The returned array is zero-sized if no agent system matches the properties (or if there is no agent system at all).
1018        @param region target region.
1019        @param properties properties that selected agencies must match;
1020        may be null if all agencies are wanted.
1021        @throws BadOperation could not get agencies list
1022    */

1023    public Location[] listAgencies(String JavaDoc region, Properties properties)
1024        throws BadOperation
1025    {
1026        Location[] result;
1027        MAFFinder finder = resolveFinder(region);
1028        try
1029        {
1030            AgentSystemInfo info = Misc.newDummyAgentSystemInfo();
1031            info.properties = Misc.property2any(properties, my_orb);
1032            String JavaDoc[] locations = finder.lookup_agent_system(
1033                Misc.DUMMYNAME,
1034                info);
1035            result = new Location[locations.length];
1036            for (int i=0 ; i<locations.length ; ++i)
1037            {
1038                result[i] = new Location(locations[i]);
1039            }
1040        }
1041        catch (SystemException JavaDoc e)
1042        {
1043            e.printStackTrace();
1044            throw new BadOperation(
1045                BadOperation.INFRASTRUCTURE,
1046                "CORBA SystemException while talking to region " + region + "'s MAFFinder:\n" + e);
1047        }
1048        catch (EntryNotFound e)
1049        {
1050            result = new Location[0];
1051        }
1052        catch (BadOperation e)
1053        {
1054            e.printStackTrace();
1055            throw new BadOperation(
1056                BadOperation.INFRASTRUCTURE,
1057                "Unsupported location format found in MAFFinder (" + e.getMessage() + ").");
1058        }
1059        return result;
1060    }
1061
1062
1063    /**
1064        @return the location of the named agent residing at the specified region.
1065        @param region target region.
1066        @param agent name wrapper of agent MAF name.
1067        @throws BadOperation the agent could not be found.
1068    */

1069    public Location findAgent(String JavaDoc region, org.objectweb.mobilitools.smi.api.Name agent)
1070        throws BadOperation
1071    {
1072        MAFFinder finder = resolveFinder(region);
1073        try
1074        {
1075            return new Location(
1076                finder.lookup_agent(
1077                    agent.getmafname(),
1078                    Misc.DUMMYAGENTPROFILE)[0]);
1079        }
1080        catch (SystemException JavaDoc e)
1081        {
1082            e.printStackTrace();
1083            throw new BadOperation(
1084                BadOperation.INFRASTRUCTURE,
1085                "CORBA SystemException while talking to region " + region + "'s MAFFinder:\n" + e);
1086        }
1087        catch (EntryNotFound e)
1088        {
1089            throw new BadOperation(
1090                BadOperation.UNKNOWNAGENT,
1091                "Unknown agent " + agent + " in region " + region + ".");
1092        }
1093        catch (BadOperation e)
1094        {
1095            e.printStackTrace();
1096            throw new BadOperation(
1097                BadOperation.INFRASTRUCTURE,
1098                "Unsupported location format found in MAFFinder (" + e.getMessage() + ").");
1099        }
1100    }
1101
1102
1103    /**
1104        @return the location of the named agent system belonging to the specified region.
1105        @param region target region.
1106        @param agent name wrapper of agent system MAF name.
1107        @throws BadOperation the agency could not be found.
1108    */

1109    public Location findAgency(String JavaDoc region, org.objectweb.mobilitools.smi.api.Name agency)
1110        throws BadOperation
1111    {
1112        MAFFinder finder = resolveFinder(region);
1113        try
1114        {
1115            return new Location(
1116                finder.lookup_agent_system(
1117                    agency.getmafname(),
1118                    Misc.DUMMYAGENTSYSTEMINFO)[0]);
1119        }
1120        catch (SystemException JavaDoc e)
1121        {
1122            e.printStackTrace();
1123            throw new BadOperation(
1124                BadOperation.INFRASTRUCTURE,
1125                "CORBA SystemException while talking to region " + region + "'s MAFFinder:\n" + e);
1126        }
1127        catch (EntryNotFound e)
1128        {
1129            throw new BadOperation(
1130                BadOperation.INFRASTRUCTURE,
1131                "Unknown agency " + agency + " in region " + region + ".");
1132        }
1133        catch (BadOperation e)
1134        {
1135            e.printStackTrace();
1136            throw new BadOperation(
1137                BadOperation.INFRASTRUCTURE,
1138                "Unsupported location format found in MAFFinder (" + e.getMessage() + ").");
1139        }
1140    }
1141
1142
1143    /**
1144        @return the properties of the named agent residing in the specified region.
1145        @param region target region.
1146        @param name wrapper of agent MAF name.
1147        @exception BadOperation agent properties could not be obtained.
1148    */

1149    public Properties getAgentProperties(String JavaDoc region, org.objectweb.mobilitools.smi.api.Name name)
1150        throws BadOperation
1151    {
1152        MAFFinderComplement finder = null;
1153        try
1154        {
1155            finder = MAFFinderComplementHelper.narrow(resolveFinder(region));
1156        }
1157        catch (SystemException JavaDoc e)
1158        {
1159            throw new BadOperation(
1160                BadOperation.INFRASTRUCTURE,
1161                "The MAFFinder for region " + region + " does not implement MAFFinderComplement.");
1162        }
1163        try
1164        {
1165            return Misc.any2property(finder.get_agent_profile(name.getmafname()).properties);
1166        }
1167        catch (SystemException JavaDoc e)
1168        {
1169            throw new BadOperation(
1170                BadOperation.INFRASTRUCTURE,
1171                "CORBA SystemException while talking to region " + region + "'s MAFFinder:\n" + e);
1172        }
1173        catch (AgentNotFound e)
1174        {
1175            throw new BadOperation(
1176                BadOperation.RETRY,
1177                "Agent is not present at its known host agency (it must have moved - retry).");
1178        }
1179    }
1180
1181
1182    /**
1183        @return the CORBA object reference to the MAFAgentSystem implementation
1184        at the specified location.
1185        @param location agent system location.
1186        @throws BadOperation the location did not resolve to an agent system.
1187    */

1188    MAFAgentSystem resolveAgentSystem(Location location)
1189        throws BadOperation
1190    {
1191        MAFAgentSystem result = null;
1192        try
1193        {
1194            result = MAFAgentSystemHelper.narrow(my_ns.resolve(location.getCosNamingName()));
1195        }
1196        catch (NameServiceException e)
1197        {
1198            if (e.exception instanceof SystemException JavaDoc)
1199            {
1200                e.printStackTrace();
1201                throw new BadOperation(
1202                    BadOperation.INFRASTRUCTURE,
1203                    "CORBA SystemException while talking to naming service:\n" + e);
1204            }
1205            else
1206            {
1207                throw new BadOperation(
1208                    BadOperation.UNKNOWNAGENCY,
1209                    "Unknown agency " + location);
1210            }
1211        }
1212        catch (SystemException JavaDoc e)
1213        {
1214            throw new BadOperation(
1215                BadOperation.INFRASTRUCTURE,
1216                "CORBA SystemException while trying to reach agency " + location + ":\n" + e);
1217        }
1218        if (result == null)
1219        {
1220            throw new BadOperation(
1221                BadOperation.INFRASTRUCTURE,
1222                "Could not narrow object to a MAFAgentSystem implementation.");
1223        }
1224        return result;
1225    }
1226
1227
1228    /**
1229        @return the CORBA object reference to the MAFAgentSystemComplement implementation
1230        at the specified location.
1231        @param location agent system location.
1232        @throws BadOperation the location did not resolve to an extended agent system.
1233    */

1234    MAFAgentSystemComplement resolveAgentSystemComplement(Location location)
1235        throws BadOperation
1236    {
1237        MAFAgentSystemComplement result = null;
1238        try
1239        {
1240            result = MAFAgentSystemComplementHelper.narrow(resolveAgentSystem(location));
1241        }
1242        catch (SystemException JavaDoc e)
1243        {
1244            e.printStackTrace();
1245            throw new BadOperation(
1246                BadOperation.INFRASTRUCTURE,
1247                "Agent's host agency is unreachable or does not implement MAFAgentSystemComplement.");
1248        }
1249        if (result == null)
1250        {
1251            throw new BadOperation(
1252                BadOperation.INFRASTRUCTURE,
1253                "Could not narrow object to a MAFAgentSystemComplement implementation.");
1254        }
1255        return result;
1256    }
1257
1258
1259    /**
1260        @return the CORBA object reference to the MAFFinder implementation
1261        for the specified region.
1262        @param region the name of the region the requested MAFFinder is bound to.
1263        @throws BadOperation could not find a MAFFinder implementation for given region.
1264    */

1265    MAFFinder resolveFinder(String JavaDoc region)
1266        throws BadOperation
1267    {
1268        MAFFinder result = null;
1269        String JavaDoc finderName =
1270            System.getProperty(Constants.regionPrefixProp, Constants.regionPrefixDefault) +
1271            "/" + region + "/" +
1272            System.getProperty(Constants.finderNameProp, Constants.finderNameDefault);
1273        try
1274        {
1275            result = MAFFinderHelper.narrow(my_ns.resolve(finderName));
1276        }
1277        catch (NameServiceException e)
1278        {
1279            if (e.exception instanceof SystemException JavaDoc)
1280            {
1281                e.printStackTrace();
1282                throw new BadOperation(
1283                    BadOperation.INFRASTRUCTURE,
1284                    "CORBA SystemException while talking to naming service:\n" + e);
1285            }
1286            else
1287            {
1288                throw new BadOperation(
1289                    BadOperation.INFRASTRUCTURE,
1290                    "It seems that region " + region + " does not have a MAF Finder.");
1291            }
1292        }
1293        catch (SystemException JavaDoc e)
1294        {
1295            throw new BadOperation(
1296                BadOperation.INFRASTRUCTURE,
1297                "CORBA SystemException while trying to reach region " + region + "'s MAF Finder:\n" + e);
1298        }
1299        if (result == null)
1300        {
1301            throw new BadOperation(
1302                BadOperation.INFRASTRUCTURE,
1303                "Can not resolve object to a MAFFinder.");
1304        }
1305        return result;
1306    }
1307
1308
1309    /**
1310        @return the CORBA object reference to the MAFFinderComplement implementation
1311        for the specified region.
1312        @param region the name of the region the requested MAFFinder is bound to.
1313        @throws BadOperation could not find a MAFFinderComplement implementation for given region.
1314    */

1315    MAFFinderComplement resolveFinderComplement(String JavaDoc region)
1316        throws BadOperation
1317    {
1318        MAFFinderComplement result = null;
1319        try
1320        {
1321            result = MAFFinderComplementHelper.narrow(resolveFinder(region));
1322        }
1323        catch (SystemException JavaDoc e)
1324        {
1325            throw new BadOperation(
1326                BadOperation.INFRASTRUCTURE,
1327                "The MAFFinder for region " + region + " does not implement MAFFinderComplement.");
1328        }
1329        if (result == null)
1330        {
1331            throw new BadOperation(
1332                BadOperation.INFRASTRUCTURE,
1333                "Can not nerrow object to a MAFFinderComplement implementation.");
1334        }
1335        return result;
1336    }
1337}
1338
Popular Tags