KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sapia > magnet > domain > system > SystemLauncher


1 package org.sapia.magnet.domain.system;
2
3 // Import of Sun's JDK classes
4
// ---------------------------
5
import java.io.File JavaDoc;
6 import java.util.ArrayList JavaDoc;
7 import java.util.Collection JavaDoc;
8 import java.util.List JavaDoc;
9 import java.util.Iterator JavaDoc;
10 import java.util.TreeMap JavaDoc;
11
12 // Import of Apache's log4j
13
// ------------------------
14
import org.apache.log4j.Logger;
15
16 // Import of Sapia's magnet classes
17
// --------------------------------
18
import org.sapia.console.CmdLine;
19 import org.sapia.magnet.Log;
20 import org.sapia.magnet.domain.DefaultLaunchHandler;
21 import org.sapia.magnet.domain.Magnet;
22 import org.sapia.magnet.domain.Param;
23 import org.sapia.magnet.domain.Profile;
24 import org.sapia.magnet.render.MagnetContext;
25 import org.sapia.magnet.render.RenderingException;
26
27
28 /**
29  *
30  *
31  * @author Jean-Cedric Desrochers
32  *
33  * <dl>
34  * <dt><b>Copyright:</b><dd>Copyright &#169; 2002-2003 <a HREF="http://www.sapia-oss.org">Sapia Open Source Software</a>. All Rights Reserved.</dd></dt>
35  * <dt><b>License:</b><dd>Read the license.txt file of the jar or visit the
36  * <a HREF="http://www.sapia-oss.org/license.html" target="sapia-license">license page</a> at the Sapia OSS web site</dd></dt>
37  * </dl>
38  */

39 public class SystemLauncher extends DefaultLaunchHandler {
40
41   /////////////////////////////////////////////////////////////////////////////////////////
42
////////////////////////////////// CLASS ATTRIBUTES ///////////////////////////////////
43
/////////////////////////////////////////////////////////////////////////////////////////
44

45   /** Defines the logger instance for this class. */
46   private static final Logger _theLogger = Logger.getLogger(SystemLauncher.class);
47
48   /////////////////////////////////////////////////////////////////////////////////////////
49
///////////////////////////////// INSTANCE ATTRIBUTES /////////////////////////////////
50
/////////////////////////////////////////////////////////////////////////////////////////
51

52   /** The system command to execute. */
53   private String JavaDoc _theCommand;
54
55   /** The working directory of the system launcher. */
56   private String JavaDoc _theWorkingDirectory;
57
58   /////////////////////////////////////////////////////////////////////////////////////////
59
//////////////////////////////////// CONSTRUCTORS /////////////////////////////////////
60
/////////////////////////////////////////////////////////////////////////////////////////
61

62   /**
63    * Creates a new SystemLauncher instance.
64    */

65   public SystemLauncher() {
66     _theWorkingDirectory = System.getProperty("user.dir");
67   }
68
69   /////////////////////////////////////////////////////////////////////////////////////////
70
////////////////////////////////// ACCESSOR METHODS ///////////////////////////////////
71
/////////////////////////////////////////////////////////////////////////////////////////
72

73   /**
74    * Returns the command of this system launch.
75    *
76    * @return The command of this system launch.
77    */

78   public String JavaDoc getCommand() {
79     return _theCommand;
80   }
81
82   /**
83    * Returns the working directory of this system launch.
84    *
85    * @return The working directory of this system launch.
86    */

87   public String JavaDoc getWorkingDirectory() {
88     return _theWorkingDirectory;
89   }
90
91   /////////////////////////////////////////////////////////////////////////////////////////
92
/////////////////////////////////// MUTATOR METHODS ///////////////////////////////////
93
/////////////////////////////////////////////////////////////////////////////////////////
94

95   /**
96    * Changes the command of this system launcher to the one passed in.
97    *
98    * @param aCommand The new command.
99    */

100   public void setCommand(String JavaDoc aCommand) {
101     _theCommand = aCommand;
102   }
103
104   /**
105    * Changes the working directory of this system launcher.
106    *
107    * @param aWorkingDirectory The new working directory.
108    */

109   public void setWorkingDirectory(String JavaDoc aWorkingDirectory) {
110     _theWorkingDirectory = aWorkingDirectory;
111   }
112
113   /////////////////////////////////////////////////////////////////////////////////////////
114
/////////////////////////////////// HELPER METHODS ////////////////////////////////////
115
/////////////////////////////////////////////////////////////////////////////////////////
116

117   /**
118    * Finds the environment identifier by the ID passed in.
119    *
120    * @param anId The identifier of the environment to retrieve.
121    * @param someMagnets The collection of magnet in which the environment is.
122    * @return The find environment of <CODE>null</CODE> if it's not found.
123    * @exception IllegalArgumentException If the id passed in is null.
124    */

125   protected Environment findEnvironment(String JavaDoc anId, Collection JavaDoc someMagnets) {
126     // Validate the arguments
127
if (anId == null) {
128       throw new IllegalArgumentException JavaDoc("The environment identifer passed in is null");
129     } else if (someMagnets == null) {
130       throw new IllegalArgumentException JavaDoc("The collection of magnet passed in is null");
131     }
132     
133     Environment aResult = null;
134     for (Iterator JavaDoc it = someMagnets.iterator(); aResult == null && it.hasNext(); ) {
135       Magnet aParentMagnet = (Magnet) it.next();
136       aResult = findEnvironment(anId, aParentMagnet);
137     }
138     
139     return aResult;
140   }
141   
142   /**
143    * Finds the environment identifier by the ID passed in.
144    *
145    * @param anId The identifier of the environment to retrieve.
146    * @param aMagnet The magnet in which the environment is.
147    * @return The find environment of <CODE>null</CODE> if it's not found.
148    * @exception IllegalArgumentException If the id passed in is null.
149    */

150   protected Environment findEnvironment(String JavaDoc anId, Magnet aMagnet) {
151     // Validate the arguments
152
if (anId == null) {
153       throw new IllegalArgumentException JavaDoc("The environment identifer passed in is null");
154     } else if (aMagnet == null) {
155       throw new IllegalArgumentException JavaDoc("The magnet passed in is null");
156     }
157
158     // Search for the environment
159
boolean isFound = false;
160     Environment aResult = null;
161
162     for (Iterator JavaDoc it = aMagnet.getObjectsFor("Environment").iterator(); !isFound && it.hasNext(); ) {
163       Environment anEnvironment = (Environment) it.next();
164       if (anId.equals(anEnvironment.getId())) {
165         isFound = true;
166         aResult = anEnvironment;
167       }
168     }
169
170     if (aResult == null && aMagnet.getParents().size() != 0) {
171       return findEnvironment(anId, aMagnet.getParents());
172     } else {
173       return aResult;
174     }
175   }
176
177   /**
178    * Extract the variables from the environment (and all it's parent) passed in.
179    *
180    * @param anEnvironment The environment from which to extrac the variables.
181    * @return The list of variables extracted.
182    * @exception IllegalArgumentException If the environment passed in is null.
183    */

184   protected List JavaDoc extractVariables(Environment anEnvironment) {
185     // Validate the arguments
186
if (anEnvironment == null) {
187       throw new IllegalArgumentException JavaDoc("The environment passed in is null");
188     }
189
190     ArrayList JavaDoc someVariables = new ArrayList JavaDoc();
191     ArrayList JavaDoc someIdentifiers = new ArrayList JavaDoc();
192     extractVariablesIter(anEnvironment, someVariables, someIdentifiers);
193
194     return someVariables;
195   }
196
197   /**
198    * Iter-recursive method to extract the variables from the environment object.
199    */

200   private void extractVariablesIter(Environment anEnvironment, List JavaDoc someVariables, List JavaDoc someIdentifiers) {
201     // Validate for circular references
202
if (someIdentifiers.contains(anEnvironment.getId())) {
203       throw new IllegalStateException JavaDoc("Circular referenced environment objects detected");
204     } else {
205       someIdentifiers.add(anEnvironment.getId());
206     }
207
208     if (anEnvironment.getParent() != null) {
209       Environment aParent = findEnvironment(anEnvironment.getParent(), getMagnet());
210       if (aParent == null) {
211         String JavaDoc aMessage = "Unable to find the parent environment: " + anEnvironment.getParent();
212         _theLogger.error(aMessage);
213         throw new RuntimeException JavaDoc(aMessage);
214       } else {
215         extractVariablesIter(aParent, someVariables, someIdentifiers);
216       }
217     }
218
219     for (Iterator JavaDoc it = anEnvironment.getVariables().iterator(); it.hasNext(); ) {
220       Variable aVariable = (Variable) it.next();
221       someVariables.add(aVariable);
222     }
223   }
224
225   /**
226    * Parses the command string of this launcher to generate an array of command arguments.
227    *
228    * @return An array of command arguments
229    */

230   protected String JavaDoc[] parseCommandString() {
231     CmdLine aCommandLine = CmdLine.parse(_theCommand);
232     return aCommandLine.toArray();
233   }
234
235   /////////////////////////////////////////////////////////////////////////////////////////
236
////////////////////////////////// OVERRIDEN METHODS //////////////////////////////////
237
/////////////////////////////////////////////////////////////////////////////////////////
238

239   /**
240    * Renders this objects to the magnet context passed in.
241    *
242    * @param aContext The magnet context to use.
243    * @exception RenderingException If an error occurs while rendering this object.
244    */

245   public void render(MagnetContext aContext) throws RenderingException {
246     // Render the super class
247
super.render(aContext);
248
249     // Find a profile object
250
Profile aProfile = findProfile(aContext.getProfile());
251
252     if (aProfile != null) {
253       // Render the profile and generate a new context
254
aProfile.render(aContext);
255       MagnetContext aSubContext = new MagnetContext(aContext);
256       for (Iterator JavaDoc it = aProfile.getParameters().getParams().iterator(); it.hasNext(); ) {
257         Param aParam = (Param) it.next();
258         aSubContext.addParameter(aParam, false);
259       }
260
261       // Resolving the attribute with the subcontext
262
_theCommand = resolveValue(aSubContext, _theCommand);
263       _theWorkingDirectory = resolveValue(aSubContext, _theWorkingDirectory);
264     } else {
265       // The profile specified is not found
266
if (aContext.getProfile() == null || aContext.getProfile().length() == 0) {
267         Log.warn("Unable to find a default profile in this system launcher", this);
268       } else {
269         Log.warn("Unable to find the profile " + aContext.getProfile() + " in this system launcher", this);
270       }
271     }
272   }
273
274   /**
275    * Executes this launch handler for the passed in profile.
276    *
277    * @param aProfileName The name of the profile to execute.
278    */

279   public void execute(String JavaDoc aProfileName) {
280     try {
281       // Find a profile object
282
Profile aProfile = findProfile(aProfileName);
283       if (aProfile == null) {
284         if (aProfileName == null || aProfileName.length() == 0) {
285           Log.warn("Skipping this system launcher --> no default profile defined", this);
286         } else {
287           Log.warn("Skipping this system launcher --> no profile found for the name " + aProfileName, this);
288         }
289         return;
290       }
291
292       Log.info("Executing profile " + aProfile.getName(), this);
293
294       // Setup the command to run
295
String JavaDoc[] someCommands = parseCommandString();
296
297       // Setup the environment variables
298
TreeMap JavaDoc someEnvironmentVariables = new TreeMap JavaDoc();
299
300       for (Iterator JavaDoc it = aProfile.getObjectsFor("environment").iterator(); it.hasNext(); ) {
301         Environment anEnvironment = (Environment) it.next();
302
303         for (Iterator JavaDoc someVariables = extractVariables(anEnvironment).iterator(); someVariables.hasNext(); ) {
304           Variable aVariable = (Variable) someVariables.next();
305           StringBuffer JavaDoc aBuffer = new StringBuffer JavaDoc();
306           aBuffer.append(aVariable.getName()).append("=").append(aVariable.getValue());
307           someEnvironmentVariables.put(aVariable.getName(), aBuffer.toString());
308         }
309       }
310
311       // Setup the working directory
312
File JavaDoc aDirectory = new File JavaDoc(_theWorkingDirectory);
313       if (aDirectory == null || !aDirectory.isDirectory()) {
314         String JavaDoc aMessage = "The working directory '" + _theWorkingDirectory + "' is invalid";
315         Log.error(aMessage, this);
316         throw new RuntimeException JavaDoc(aMessage);
317       }
318
319       // Logging the info of the process to run
320
StringBuffer JavaDoc aBuffer = new StringBuffer JavaDoc();
321       aBuffer.append("Set the working directory to '").append(_theWorkingDirectory).append("'");
322       Log.info(aBuffer.toString(), this);
323
324       aBuffer.setLength(0);
325       aBuffer.append("Running the command '").append(_theCommand).append("'");
326       Log.info(aBuffer.toString(), this);
327       
328       if (someEnvironmentVariables.size() > 0) {
329         Log.info("Environment variables of the system process:", this);
330         for (Iterator JavaDoc it = someEnvironmentVariables.values().iterator(); it.hasNext(); ) {
331           aBuffer.setLength(0);
332           aBuffer.append("\t").append(it.next());
333           Log.info(aBuffer.toString(), this);
334         }
335       }
336
337       // Create a process task and starts it in another thread
338
ProcessTask aTask = new ProcessTask(someCommands,
339               (String JavaDoc[]) someEnvironmentVariables.values().toArray(new String JavaDoc[0]), aDirectory);
340       Thread JavaDoc aThread = new Thread JavaDoc(aTask);
341       aThread.setName(getName() + "-" + aProfile.getName());
342       aThread.start();
343
344     } catch (RuntimeException JavaDoc re) {
345       String JavaDoc aMessage = "System error spawning this process";
346       _theLogger.error(aMessage, re);
347     }
348   }
349
350   /**
351    * Returns a string representation of this system launcher.
352    *
353    * @return A string representation of this system launcher.
354    */

355   public String JavaDoc toString() {
356     StringBuffer JavaDoc aBuffer = new StringBuffer JavaDoc(super.toString());
357     aBuffer.append("[command=").append(_theCommand).
358             append(" workingDirectory=").append(_theWorkingDirectory).
359             append("]");
360
361     return aBuffer.toString();
362   }
363 }
364
Popular Tags