KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > continuent > sequoia > console > text > ConsoleLauncher


1 /**
2  * Sequoia: Database clustering technology.
3  * Copyright (C) 2002-2004 French National Institute For Research In Computer
4  * Science And Control (INRIA).
5  * Contact: sequoia@continuent.org
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * Initial developer(s): Nicolas Modrzyk.
20  * Contributor(s): Mathieu Peltier.
21  */

22
23 package org.continuent.sequoia.console.text;
24
25 import java.io.FileInputStream JavaDoc;
26 import java.io.FileNotFoundException JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.io.InputStream JavaDoc;
29 import java.net.InetAddress JavaDoc;
30 import java.net.UnknownHostException JavaDoc;
31 import java.util.Properties JavaDoc;
32
33 import org.apache.commons.cli.CommandLine;
34 import org.apache.commons.cli.CommandLineParser;
35 import org.apache.commons.cli.GnuParser;
36 import org.apache.commons.cli.HelpFormatter;
37 import org.apache.commons.cli.Option;
38 import org.apache.commons.cli.OptionGroup;
39 import org.apache.commons.cli.Options;
40 import org.apache.commons.cli.ParseException;
41 import org.continuent.sequoia.common.i18n.ConsoleTranslate;
42 import org.continuent.sequoia.common.jmx.JmxConstants;
43 import org.continuent.sequoia.common.util.Constants;
44 import org.continuent.sequoia.console.jmx.RmiJmxClient;
45 import org.continuent.sequoia.console.text.module.AbstractConsoleModule;
46
47 /**
48  * This class defines a ConsoleLauncher
49  *
50  * @author <a HREF="mailto:Nicolas.Modrzyk@inria.fr">Nicolas Modrzyk </a>
51  * @author <a HREF="mailto:mathieu.peltier@inrialpes.fr">Mathieu Peltier </a>
52  * @version 1.0
53  */

54 public class ConsoleLauncher
55 {
56   /**
57    * Product name to be displayed at console startup
58    */

59   public static final String JavaDoc PRODUCT_NAME;
60
61   static
62   {
63     Properties JavaDoc props = new Properties JavaDoc();
64     try
65     {
66       String JavaDoc propertiesFile = System.getProperty("console.commands", //$NON-NLS-1$
67
AbstractConsoleModule.DEFAULT_COMMAND_PROPERTIES_FILE);
68       props.load(ClassLoader.getSystemResourceAsStream(propertiesFile));
69       PRODUCT_NAME = props.getProperty("product.name"); //$NON-NLS-1$
70
}
71     catch (IOException JavaDoc e)
72     {
73       throw new ExceptionInInitializerError JavaDoc(e.getMessage());
74     }
75   }
76
77   /**
78    * Launchs the Sequoia console. The available options are: <il>
79    * <li><code>-d</code> or <code>--debug</code>: show stack trace when
80    * error occurs.</li>
81    * <li><code>-f</code> or <code>--file</code>: use a given file as the
82    * source of commands instead of reading commands interactively.</li>
83    * <li><code>-h</code> or <code>--help</code>: displays usage
84    * information.</li>
85    * <li><code>-i</code> or <code>--ip</code>: IP address of the host name
86    * where the JMX Server hosting the controller is running (the default is
87    * '0.0.0.0').</li>
88    * <li><code>-n</code> or <code>--nocolor</code>: do not print colors in
89    * interactive mode for supported systems.</li>
90    * <li><code>-e</code> or <code>--exitonerror</code>: exit on error in
91    * non interactive mode.</li>
92    * <li><code>-p</code> or <code>--port</code>: JMX/RMI Port number of
93    * (the default is
94    * {@link org.continuent.sequoia.common.jmx.JmxConstants#DEFAULT_JMX_RMI_PORT}).
95    * </li>
96    * <li><code>-s</code> or <code>--secret</code>: password for JMX
97    * connection.</li>
98    * <li><code>-u</code> or <code>--username</code>: username for JMX
99    * connection.</li>
100    * <li><code>-m</code> or <code>--multiline</code>: enable multiline
101    * statements in the SQL console (disabled by default for backwards
102    * compatibility)</li>
103    * <li><code>-r</code> or <code>--requestdelimiter</code>: Request
104    * delimiter to use when multiline statement is enabled (<code>;</code> by
105    * default) connection.</li>
106    * <li><code>-v</code> or <code>--version</code>: displays version
107    * information.</li>
108    * </ul>
109    *
110    * @param args command line arguments (see above)
111    * @throws Exception if fails
112    */

113   public static void main(String JavaDoc[] args) throws Exception JavaDoc
114   {
115     // Create options object
116
Options options = createOptions();
117
118     // Parse command line
119
CommandLineParser parser = new GnuParser();
120     CommandLine commandLine = null;
121     try
122     {
123       commandLine = parser.parse(options, args);
124     }
125     catch (ParseException e)
126     {
127       System.err.println("Syntax error (" + e + ")");
128       printUsage(options);
129       System.exit(1);
130     }
131
132     // Non-recognized options
133
int n = commandLine.getArgs().length;
134     for (int i = 0; i < n; i++)
135     {
136       System.err.println("Syntax error (unrecognized option: "
137           + commandLine.getArgs()[i] + ")");
138       printUsage(options);
139       System.exit(1);
140     }
141
142     // Handle --help option
143
if (commandLine.hasOption('h'))
144     {
145       if (commandLine.getOptions().length > 1)
146         System.err.println("Syntax error");
147
148       printUsage(options);
149       System.exit(1);
150     }
151
152     // Handle --version option
153
if (commandLine.hasOption('v'))
154     {
155       if (commandLine.getOptions().length > 1)
156       {
157         System.err.println("Syntax error");
158         printUsage(options);
159       }
160       else
161         System.out.println(ConsoleTranslate.get("console.version",
162             new String JavaDoc[]{PRODUCT_NAME, Constants.VERSION}));
163
164       System.exit(1);
165     }
166
167     startTextConsole(commandLine);
168   }
169
170   /**
171    * Starts the text console with the given commandline
172    *
173    * @param commandLine parameters for the text console
174    * @throws Exception if fails
175    */

176   public static void startTextConsole(CommandLine commandLine) throws Exception JavaDoc
177   {
178     // check if we are in interactive mode, and if so, output no traces
179
boolean isInteractive = !commandLine.hasOption('f');
180
181     // Handle --ip option
182
String JavaDoc ip;
183     try
184     {
185       // localhost
186
ip = InetAddress.getByName(null).getHostName();
187     }
188     catch (UnknownHostException JavaDoc e1)
189     {
190       // not IPv6 compliant, but "null" is never unknown anyway
191
ip = "127.0.0.1";
192     }
193     if (commandLine.hasOption('i'))
194     {
195       String JavaDoc tmp = commandLine.getOptionValue('i');
196       if (tmp != null)
197       {
198         ip = tmp;
199       }
200     }
201
202     boolean exitOnError = commandLine.hasOption('e');
203
204     // Handle --debug option
205
boolean debug = commandLine.hasOption('d');
206     // Handle --silent option
207
boolean silent = commandLine.hasOption('l');
208
209     // Launch the console (handle --file option)
210
Console console;
211     InputStream JavaDoc in = null;
212     if (commandLine.hasOption('f'))
213     {
214       String JavaDoc filename = commandLine.getOptionValue('f');
215       if ("-".equals(filename))
216       {
217         in = System.in;
218       }
219       else
220       {
221         try
222         {
223           in = new FileInputStream JavaDoc(filename);
224         }
225         catch (FileNotFoundException JavaDoc e)
226         {
227           System.err.println("Failed to open file '" + filename + "' (" + e
228               + ")");
229           System.exit(1);
230         }
231       }
232     }
233     else
234     {
235       System.out.println(ConsoleTranslate.get(
236           "console.interactive.mode", PRODUCT_NAME)); //$NON-NLS-1$
237
in = System.in;
238     }
239
240     RmiJmxClient jmxClient = null;
241     boolean sqlClientOnly = commandLine.hasOption('q');
242     if (! sqlClientOnly)
243     {
244         jmxClient = getJmxClient(commandLine, ip, exitOnError);
245     }
246     console = new Console(jmxClient, in, isInteractive, debug, silent,
247         exitOnError, sqlClientOnly);
248     console.setPrintColor(!commandLine.hasOption('n'));
249     console.enableMultilineStatements(commandLine.hasOption('m'));
250     if (commandLine.hasOption('r'))
251     {
252       console.setRequestDelimiter(commandLine.getOptionValue('r'));
253     }
254     console.handlePrompt();
255     System.exit(0);
256   }
257
258   static RmiJmxClient getJmxClient(CommandLine commandLine, String JavaDoc ip,
259       boolean exitOnError) throws IOException JavaDoc
260   {
261     // Handle --port option
262
int port;
263     if (commandLine.hasOption('p'))
264     {
265       String JavaDoc s = commandLine.getOptionValue('p');
266       if (s == null)
267       {
268         port = JmxConstants.DEFAULT_JMX_RMI_PORT;
269       }
270       else
271         try
272         {
273           port = Integer.parseInt(s);
274         }
275         catch (NumberFormatException JavaDoc e)
276         {
277           System.err.println("Bad port number (" + e + "), using default "
278               + JmxConstants.DEFAULT_JMX_RMI_PORT + " port number");
279           port = JmxConstants.DEFAULT_JMX_RMI_PORT;
280         }
281     }
282     else
283     {
284       port = JmxConstants.DEFAULT_JMX_RMI_PORT;
285     }
286     // Handle --secret and --username options
287
RmiJmxClient jmxClient = null;
288     if (commandLine.hasOption('u') && commandLine.hasOption('s'))
289     {
290       String JavaDoc username = commandLine.getOptionValue('u');
291       String JavaDoc password = commandLine.getOptionValue('s');
292       jmxClient = new RmiJmxClient("" + port, ip, username, password);
293     }
294     else
295     {
296       try
297       {
298         jmxClient = new RmiJmxClient("" + port, ip, null);
299       }
300       catch (Exception JavaDoc e)
301       {
302         System.err
303             .println("Cannot connect to the administration port of the controller. Is a controller running at "
304                 + ip + ":" + port + " ?");
305         // SEQUOIA-714: exit the console if the flag ''--exitonerror' is
306
// set
307
if (exitOnError)
308         {
309           System.exit(1);
310         }
311         // SEQUOIA-708: let the console start if the user wants to use
312
// the SQL
313
// console.
314
}
315     }
316
317     return jmxClient;
318   }
319
320   /**
321    * Creates <code>Options</code> object that contains all available options
322    * that can be used launching Sequoia console.
323    *
324    * @return an <code>Options</code> instance
325    */

326   private static Options createOptions()
327   {
328     Options options = new Options();
329     OptionGroup group = new OptionGroup();
330
331     // help, verbose, text only console and file options (mutually exclusive
332
// options)
333
group.addOption(new Option("h", "help", false,
334         "Displays usage information."));
335     group.addOption(new Option("t", "text", false,
336         "Ignored - only for previous version compatibility."));
337     group.addOption(new Option("v", "version", false,
338         "Displays version information."));
339     group
340         .addOption(new Option(
341             "f",
342             "file",
343             true,
344             "Use a given file as the source of commands instead of reading commands interactively."));
345     options.addOptionGroup(group);
346
347     /**
348      * Controller JMX ip option, defined in
349      * {@link org.continuent.sequoia.controller.core.ControllerConstants.DEFAULT_IP}
350      */

351     String JavaDoc defaultIp = "0.0.0.0";
352     // should probably better be: InetAddress.anyLocalAddress().getHostAddress()
353
options.addOption(new Option("i", "ip", true,
354         "The JMX server of the controller binds to this address (the default is '"
355             + defaultIp + "')."));
356
357     // controller port option
358
options.addOption(new Option("p", "port", true,
359         "JMX/RMI port number of (the default is "
360             + JmxConstants.DEFAULT_JMX_RMI_PORT + ")."));
361
362     // JMX options
363
options.addOption(new Option("u", "username", true,
364         "Username for JMX connection."));
365     options.addOption(new Option("s", "secret", true,
366         "Password for JMX connection."));
367
368     options.addOption(new Option("d", "debug", false,
369         "Show stack trace when error occurs."));
370     options.addOption(new Option("l", "silent", false,
371         "Show only most meaningful messages."));
372
373     options.addOption(new Option("n", "nocolor", false,
374         "Do not print colors in interactive mode for supported systems."));
375
376     options.addOption(new Option("e", "exitonerror", false,
377         "Stop on error in non interactive mode."));
378
379     options.addOption(new Option("r", "requestdelimiter", true,
380         "Request delimiter for multiline statements in the SQL console."));
381
382     options.addOption(new Option("m", "multiline", false,
383         "Enable multiline statements in the SQL console."));
384
385     options.addOption(new Option("q", "sqlclient", false,
386         "Launch SQL client console."));
387
388     return options;
389   }
390
391   /**
392    * Displays usage message.
393    *
394    * @param options available command line options
395    */

396   private static void printUsage(Options options)
397   {
398     String JavaDoc header = ConsoleTranslate.get("console.launches", PRODUCT_NAME)
399         + System.getProperty("line.separator") + "Options:";
400
401     (new HelpFormatter()).printHelp(80, "console(.sh|.bat) [options]", header,
402         options, "");
403   }
404
405 }
Popular Tags