KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sapia > magnet > MagnetRunner


1 package org.sapia.magnet;
2
3 // Import of Sun's JDK classes
4
// ---------------------------
5
import java.io.File JavaDoc;
6 import java.io.FileInputStream JavaDoc;
7 import java.io.InputStream JavaDoc;
8 import java.io.FileNotFoundException JavaDoc;
9 import java.io.IOException JavaDoc;
10 import java.net.MalformedURLException JavaDoc;
11 import java.util.ArrayList JavaDoc;
12 import java.util.Iterator JavaDoc;
13 import java.util.List JavaDoc;
14
15 // Import of Apache's log4j
16
// ------------------------
17
import org.apache.log4j.Appender;
18 import org.apache.log4j.ConsoleAppender;
19 import org.apache.log4j.FileAppender;
20 import org.apache.log4j.Level;
21 import org.apache.log4j.Logger;
22 import org.apache.log4j.LogManager;
23 import org.apache.log4j.PatternLayout;
24
25 // Import of Sapia's magnet classes
26
// --------------------------------
27
import org.sapia.corus.interop.client.InteropClient;
28 import org.sapia.corus.interop.http.HttpProtocol;
29 import org.sapia.magnet.domain.Launcher;
30 import org.sapia.magnet.domain.Magnet;
31 import org.sapia.magnet.render.MagnetContext;
32
33
34 /**
35  * Main class that executes a magnet file. A magnet can be executed either using the <code>magnet</code>
36  * script at the command line or programatically by calling the <code>runFile()</code> method.<p>
37  *
38  * The execution of a magnet is seperated into three phases:
39  * <ol>
40  * <li><b>Parsing:</b> parse the magnet xml file to generate an object representation of the magnet definition.</li>
41  * <li><b>Rendering:</b> pre-processing of the magnet objects that includes variable interpolation, script execution
42  * and ordering definition of the overloaded entities.</li>
43  * <li><b>Execution:</b> Execute each launcher of every magnet, wainting between each launcher if a wait time is
44  * specified in a launcher.</li>
45  * </ol>
46  *
47  * @author Jean-Cedric Desrochers
48  * <dl>
49  * <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>
50  * <dt><b>License:</b><dd>Read the license.txt file of the jar or visit the
51  * <a HREF="http://www.sapia-oss.org/license.html" target="sapia-license">license page</a> at the Sapia OSS web site</dd></dt>
52  * </dl>
53  */

54 public class MagnetRunner {
55
56   /////////////////////////////////////////////////////////////////////////////////////////
57
////////////////////////////////// CLASS ATTRIBUTES ///////////////////////////////////
58
/////////////////////////////////////////////////////////////////////////////////////////
59

60   /** Defines the default magnet configuration filename. */
61   public static final String JavaDoc DEFAULT_MAGNET_FILENAME = "magnet.xml";
62
63   /** Defines the logger instance for this class. */
64   private static Logger _theLogger;
65   
66   /** The log level used by the runner. */
67   private static Level _theLogLevel;
68   
69   /** The filename in which to log. */
70   private static String JavaDoc _theLogFilename;
71
72   /////////////////////////////////////////////////////////////////////////////////////////
73
/////////////////////////////////// STATIC METHODS ////////////////////////////////////
74
/////////////////////////////////////////////////////////////////////////////////////////
75

76   /**
77    * Main method to execute this MagnetRunner. See the class javadoc for
78    * details on the options and arguments.
79    *
80    * @param args The options and arguments to use to run the magnet.
81    */

82   public static void main(String JavaDoc[] args) {
83     try {
84       String JavaDoc aMagnetFilename = DEFAULT_MAGNET_FILENAME;
85       String JavaDoc aProfile = "";
86       ArrayList JavaDoc otherArgs = new ArrayList JavaDoc();
87       _theLogLevel = Level.OFF;
88
89       if (args.length == 0) {
90         version();
91         usage();
92         return;
93       } else {
94         for (int i = 0; i < args.length; i++) {
95           String JavaDoc anArgument = args[i];
96
97           if (anArgument.equals("-help") || anArgument.equals("-h")) {
98             usage();
99             return;
100
101           } else if (anArgument.equals("-version") || anArgument.equals("-v")) {
102             version();
103             return;
104
105           } else if (anArgument.equals("-magnetfile") ||
106                   anArgument.equals("-file") || anArgument.equals("-f")) {
107             aMagnetFilename = args[++i];
108
109           } else if (anArgument.equals("-logfile") ||
110                   anArgument.equals("-log")) {
111             _theLogFilename = args[++i];
112
113           } else if (anArgument.equals("-debug")) {
114             _theLogLevel = Level.DEBUG;
115
116           } else if (anArgument.equals("-info")) {
117             _theLogLevel = Level.INFO;
118
119           } else if (anArgument.equals("-warn")) {
120             _theLogLevel = Level.WARN;
121
122           } else if (anArgument.equals("-profile") || anArgument.equals("-p")) {
123             aProfile = args[++i];
124
125           } else if (anArgument.startsWith("-")) {
126             System.out.println("Unknown option: " + anArgument);
127             usage();
128             return;
129             
130           } else {
131             otherArgs.add(anArgument);
132           }
133         }
134         
135         // Process the other arguments to be used as ${magnet.args.1}
136
int i = 0;
137         StringBuffer JavaDoc allArgs = new StringBuffer JavaDoc();
138         for (Iterator JavaDoc it = otherArgs.iterator(); it.hasNext(); ) {
139           String JavaDoc anArg = (String JavaDoc) it.next();
140           System.setProperty("magnet.args." + ++i, anArg);
141           allArgs.append(anArg).append(" ");
142         }
143         
144         if (i > 0) {
145           System.setProperty("magnet.args.*", allArgs.toString());
146         }
147       }
148       
149       // Run the magnet
150
runFile(aMagnetFilename, aProfile);
151     } catch (MagnetException me) {
152       Log.error(Log.extactMessage(me));
153       System.exit(1);
154
155     } catch (RuntimeException JavaDoc re) {
156       Log.error("System error running the magnet - " + re.getMessage());
157       System.exit(1);
158     }
159   }
160
161   /**
162    * Runs the magnet specified by the input stream for the profile passed in.
163    *
164    * @param aMagnetStream The magnet configuration input stream.
165    * @param aProfile The profile of the magnet to execute.
166    * @exception MagnetException If an error occurs running the magnet input stream.
167    */

168   public static void run(InputStream JavaDoc aMagnetStream, String JavaDoc aProfile) throws MagnetException {
169     // Configure log4j
170
PatternLayout aLayout = new PatternLayout("%r [%t] %p %c %x - %m%n");
171     Appender anAppender = null;
172
173     if (_theLogFilename == null) {
174       anAppender = new ConsoleAppender(aLayout);
175     } else {
176       try {
177         anAppender = new FileAppender(aLayout, _theLogFilename);
178       } catch (IOException JavaDoc ioe) {
179         Log.warn(ioe.getMessage());
180         Log.warn("Unable to set logfile to '" + _theLogFilename + "' - setting log to the console");
181         anAppender = new ConsoleAppender(aLayout);
182       }
183     }
184     Logger aRootLogger = LogManager.getLogger("org.sapia");
185     aRootLogger.setAdditivity(false);
186     aRootLogger.addAppender(anAppender);
187     aRootLogger.setLevel(_theLogLevel);
188     _theLogger = Logger.getLogger(MagnetRunner.class);
189
190     // Add the executed profile into the system property
191
System.setProperty("magnet.profile.name", aProfile);
192     
193     // Start the interop process
194
try {
195       Log.info("MAGNET - Starting Corus interop module...");
196       InteropClient.getInstance().setProtocol(new HttpProtocol());
197     } catch (MalformedURLException JavaDoc mue) {
198       Log.error("Unable to start the Corus interop module - " + mue.getMessage(), mue);
199     } catch (RuntimeException JavaDoc re) {
200       Log.error("System error starting the Corus interop module - " + re.getMessage(), re);
201     }
202
203     // Parse the magnet input stream
204
if (_theLogger.isInfoEnabled()) {
205       _theLogger.info("Parsing the magnet input stream...");
206     }
207     MagnetParser aMagnetParser = new MagnetParser();
208     List JavaDoc someMagnets = aMagnetParser.parse(aMagnetStream);
209
210     // Render the magnet
211
if (_theLogger.isInfoEnabled()) {
212       _theLogger.info("Rendering the magnets...");
213     }
214     MagnetRenderer aMagnetRenderer = new MagnetRenderer();
215     MagnetContext aContext = aMagnetRenderer.render(someMagnets, aProfile);
216
217     // Logging the system properties
218
_theLogger.info(Log.formatProperties(System.getProperties()));
219
220     // Execute the launchers of each magnet
221
for (Iterator JavaDoc it = someMagnets.iterator(); it.hasNext(); ) {
222       Magnet aMagnet = (Magnet) it.next();
223       Log.info("\n----------------------------------------------\nMAGNET - Executing the magnet " + aMagnet.getName());
224
225       for (Iterator JavaDoc someLaunchers = aMagnet.getLaunchers().iterator(); someLaunchers.hasNext(); ) {
226         Launcher aLauncher = (Launcher) someLaunchers.next();
227         aLauncher.execute(aProfile);
228         
229         if (aLauncher.getLaunchHandler().geWaitTime() > 0) {
230           try {
231             if (aLauncher.getLaunchHandler().geWaitTime() > 1) {
232               Log.info("MAGNET - Waiting for " + (aLauncher.getLaunchHandler().geWaitTime()/1000f) + " second...");
233             } else {
234               Log.info("MAGNET - Waiting for " + (aLauncher.getLaunchHandler().geWaitTime()/1000f) + " seconds...");
235             }
236             Thread.sleep(aLauncher.getLaunchHandler().geWaitTime());
237           } catch (InterruptedException JavaDoc ie) {
238           }
239         }
240       }
241     }
242     Log.info("MAGNET - All launchers executed");
243     
244   }
245
246   /**
247    * Runs the magnet specified by the configuration filename for the profile
248    * passed in.
249    *
250    * @param aMagnetFilename The magnet configuration filename.
251    * @param aProfile The profile of the magnet to execute.
252    * @exception MagnetException If an error occurs running the magnet file.
253    */

254   public static void runFile(String JavaDoc aMagnetFilename, String JavaDoc aProfile) throws MagnetException {
255     File JavaDoc aMagnetFile = new File JavaDoc(aMagnetFilename);
256
257     if (!aMagnetFile.exists()) {
258       throw new MagnetException("The magnet file " + aMagnetFilename + " does not exist.");
259     } else if (aMagnetFile.isDirectory()) {
260       throw new MagnetException("The magnet file " + aMagnetFilename + " is a directory.");
261     }
262
263     try {
264       StringBuffer JavaDoc aBuffer = new StringBuffer JavaDoc();
265       aBuffer.append("MAGNET - Starting magnet with file [").append(aMagnetFile);
266
267       if (aProfile == null || aProfile.length()== 0) {
268          aBuffer.append("] using the default profile...");
269       } else {
270          aBuffer.append("] using the profile '").append(aProfile).append("'");
271       }
272       version();
273       Log.info(aBuffer.toString());
274
275       FileInputStream JavaDoc anInputStream = new FileInputStream JavaDoc(aMagnetFile);
276       run(anInputStream, aProfile);
277
278     } catch (FileNotFoundException JavaDoc fnfe) {
279       throw new MagnetException("Could not find magnet file " + aMagnetFilename);
280     }
281   }
282
283   /**
284    * Prints out on the standard output the usage of the main method of this class.
285    */

286   public static void usage() {
287     StringBuffer JavaDoc aBuffer = new StringBuffer JavaDoc("\n");
288     aBuffer.append("Usage: magnet [vm options...] [options...] [args...]\n").
289             append("VM Options:\n").
290             append(" Options that affect the Java VM that will be started. The Vm options\n").
291             append(" can be one or many of the following:\n").
292             append(" -javahome <path> \tto define the home of the java runtime\n").
293             append("\t\t\tthis option overrides the JAVA_HOME environement variable\n").
294             append(" -client \t\tto start java with the \"client\" VM\n").
295             append(" -server \t\tto start java with the \"server\" VM\n").
296             append(" -X<option> \t\tto start java with non-standard options\n").
297             append(" -D<name>=<value> \tto set a system property\n\n").
298             append("Options:\n").
299             append(" Options that will define the behavior of the magnet runtime on the Java\n").
300             append(" VM is started. The magnet options can be one or more of the following:\n").
301             append(" -help, -h\t\tprint this message\n").
302             append(" -version\t\tprint the version information and exit\n").
303             append(" -logfile <file>\tuse the given file to log\n").
304             append(" -log <file>\t ''\n").
305             append(" -debug\t\tprint debugging information\n").
306             append(" -info\t\tprint information that can help to diagnose\n").
307             append(" -warn\t\tprint warning and error information\n").
308             append(" -magnetfile <file>\tuse the given magnet configuration file\n").
309             append(" -file <file>\t ''\n\n").
310             append(" -profile <name>\tthe name of the profile to execute in the magnet. If\n").
311             append(" -p <name>\tthe profile is not provided, only the launchers with a\n").
312             append("\t\t\t default profile are executed\n\n").
313             append("Args:\n").
314             append(" The application arguments that can be passed to magnet at every execution.\n").
315             append(" Each argument will be assigned to a system property of the name magnet.args.n\n").
316             append(" where the 'n' is replaced by the number of the argument in the list. The additionnal\n").
317             append(" system property magnet.args.* contains the entire list of arguments as a whole String\n\n").
318             append("Example: magnet -server -magnetfile TimeServer.xml test\n").
319             append("Example: magnet -javahome /opt/jdk1.4 -magnetfile TimeServer.xml test\n").
320             append("Example: magnet -Xms8m -Xmx256m -Dfoo=bar -magnetfile TransactionServer.xml prod\n").
321             append("Example: magnet -magnetfile MetricConversion.xml weight 10 50 125\n");
322
323     Log.info(aBuffer.toString());
324   }
325
326   /**
327    * Prints out on the standard output the version information of this class.
328    */

329   public static void version() {
330     StringBuffer JavaDoc aBuffer = new StringBuffer JavaDoc("\n");
331     aBuffer.append("Sapia Magnet version 1.0");
332
333     Log.info(aBuffer.toString());
334   }
335 }
336
Popular Tags