KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opencms > main > CmsShell


1 /*
2  * File : $Source: /usr/local/cvs/opencms/src/org/opencms/main/CmsShell.java,v $
3  * Date : $Date: 2006/03/28 13:10:02 $
4  * Version: $Revision: 1.48 $
5  *
6  * This library is part of OpenCms -
7  * the Open Source Content Mananagement System
8  *
9  * Copyright (c) 2005 Alkacon Software GmbH (http://www.alkacon.com)
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  * Lesser General Public License for more details.
20  *
21  * For further information about Alkacon Software GmbH, please see the
22  * company website: http://www.alkacon.com
23  *
24  * For further information about OpenCms, please see the
25  * project website: http://www.opencms.org
26  *
27  * You should have received a copy of the GNU Lesser General Public
28  * License along with this library; if not, write to the Free Software
29  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30  */

31
32 package org.opencms.main;
33
34 import org.opencms.db.CmsUserSettings;
35 import org.opencms.file.CmsObject;
36 import org.opencms.i18n.CmsLocaleManager;
37 import org.opencms.i18n.CmsMessages;
38 import org.opencms.util.CmsFileUtil;
39 import org.opencms.util.CmsPropertyUtils;
40 import org.opencms.util.CmsStringUtil;
41 import org.opencms.util.CmsUUID;
42
43 import java.io.FileDescriptor JavaDoc;
44 import java.io.FileInputStream JavaDoc;
45 import java.io.IOException JavaDoc;
46 import java.io.InputStreamReader JavaDoc;
47 import java.io.LineNumberReader JavaDoc;
48 import java.io.StreamTokenizer JavaDoc;
49 import java.io.StringReader JavaDoc;
50 import java.lang.reflect.InvocationTargetException JavaDoc;
51 import java.lang.reflect.Method JavaDoc;
52 import java.lang.reflect.Modifier JavaDoc;
53 import java.util.ArrayList JavaDoc;
54 import java.util.Collection JavaDoc;
55 import java.util.Iterator JavaDoc;
56 import java.util.List JavaDoc;
57 import java.util.Locale JavaDoc;
58 import java.util.Map JavaDoc;
59 import java.util.TreeMap JavaDoc;
60
61 import org.apache.commons.collections.ExtendedProperties;
62
63 /**
64  * A commad line interface to access OpenCms functions which
65  * is used for the initial setup and also can be used to directly access the OpenCms
66  * repository without the Workplace.<p>
67  *
68  * The CmsShell has direct access to all methods in the "command objects".
69  * Currently the following classes are used as command objects:
70  * <code>{@link org.opencms.main.CmsShellCommands}</code>,
71  * <code>{@link org.opencms.file.CmsRequestContext}</code> and
72  * <code>{@link org.opencms.file.CmsObject}</code>.<p>
73  *
74  * Only public methods in the command objects that use supported data types
75  * as parameters can be called from the shell. Supported data types are:
76  * <code>String, {@link org.opencms.util.CmsUUID}, boolean, int, long, double, float</code>.<p>
77  *
78  * If a method name is ambiguous, i.e. the method name with the same numer of parameter exist
79  * in more then one of the command objects, the method is only executed on the first matching method object.<p>
80  *
81  * @author Alexander Kandzior
82  *
83  * @version $Revision: 1.48 $
84  *
85  * @since 6.0.0
86  *
87  * @see org.opencms.main.CmsShellCommands
88  * @see org.opencms.file.CmsRequestContext
89  * @see org.opencms.file.CmsObject
90  */

91 public class CmsShell {
92
93     /**
94      * Command object class.<p>
95      */

96     private class CmsCommandObject {
97
98         /** The list of methods. */
99         private Map JavaDoc m_methods;
100
101         /** The object to execute the methods on. */
102         private Object JavaDoc m_object;
103
104         /**
105          * Creates a new command object.<p>
106          *
107          * @param object the object to execute the methods on
108          */

109         protected CmsCommandObject(Object JavaDoc object) {
110
111             m_object = object;
112             initShellMethods();
113         }
114
115         /**
116          * Tries to execute a method for the provided parameters on this command object.<p>
117          *
118          * If methods with the same name and number of parameters exist in this command object,
119          * the given parameters are tried to be converted from String to matching types.<p>
120          *
121          * @param command the command entered by the user in the shell
122          * @param parameters the parameters entered by the user in the shell
123          * @return true if a method was executed, false otherwise
124          */

125         protected boolean executeMethod(String JavaDoc command, List JavaDoc parameters) {
126
127             // build the method lookup
128
String JavaDoc lookup = buildMethodLookup(command, parameters.size());
129
130             // try to look up the methods of this command object
131
List JavaDoc possibleMethods = (List JavaDoc)m_methods.get(lookup);
132             if (possibleMethods == null) {
133                 return false;
134             }
135
136             // a match for the mehod name was found, now try to figure out if the parameters are ok
137
Method JavaDoc onlyStringMethod = null;
138             Method JavaDoc foundMethod = null;
139             Object JavaDoc[] params = null;
140             Iterator JavaDoc i;
141
142             // first check if there is one method with only has String parameters, make this the fallback
143
i = possibleMethods.iterator();
144             while (i.hasNext()) {
145                 Method JavaDoc method = (Method JavaDoc)i.next();
146                 Class JavaDoc[] clazz = method.getParameterTypes();
147                 boolean onlyString = true;
148                 for (int j = 0; j < clazz.length; j++) {
149                     if (!(clazz[j].equals(String JavaDoc.class))) {
150                         onlyString = false;
151                         break;
152                     }
153                 }
154                 if (onlyString) {
155                     onlyStringMethod = method;
156                     break;
157                 }
158             }
159
160             // now check a method matches the provided parameters
161
// if so, use this method, else continue searching
162
i = possibleMethods.iterator();
163             while (i.hasNext()) {
164                 Method JavaDoc method = (Method JavaDoc)i.next();
165                 if (method == onlyStringMethod) {
166                     // skip the String only signature because this would always match
167
continue;
168                 }
169                 // now try to convert the parameters to the required types
170
Class JavaDoc[] clazz = method.getParameterTypes();
171                 Object JavaDoc[] converted = new Object JavaDoc[clazz.length];
172                 boolean match = true;
173                 for (int j = 0; j < clazz.length; j++) {
174                     String JavaDoc value = (String JavaDoc)parameters.get(j);
175                     if (clazz[j].equals(String JavaDoc.class)) {
176                         // no conversion required for String
177
converted[j] = value;
178                     } else if (clazz[j].equals(boolean.class)) {
179                         // try to convert to boolean
180
if (CmsStringUtil.TRUE.equalsIgnoreCase(value) || CmsStringUtil.FALSE.equalsIgnoreCase(value)) {
181                             converted[j] = Boolean.valueOf(value);
182                         } else {
183                             match = false;
184                         }
185                     } else if (clazz[j].equals(CmsUUID.class)) {
186                         // try to convert to CmsUUID
187
try {
188                             converted[j] = new CmsUUID(value);
189                         } catch (NumberFormatException JavaDoc e) {
190                             match = false;
191                         }
192                     } else if (clazz[j].equals(int.class)) {
193                         // try to convert to int
194
try {
195                             converted[j] = Integer.valueOf(value);
196                         } catch (NumberFormatException JavaDoc e) {
197                             match = false;
198                         }
199                     } else if (clazz[j].equals(long.class)) {
200                         // try to convert to long
201
try {
202                             converted[j] = Long.valueOf(value);
203                         } catch (NumberFormatException JavaDoc e) {
204                             match = false;
205                         }
206                     } else if (clazz[j].equals(float.class)) {
207                         // try to convert to float
208
try {
209                             converted[j] = Float.valueOf(value);
210                         } catch (NumberFormatException JavaDoc e) {
211                             match = false;
212                         }
213                     } else if (clazz[j].equals(double.class)) {
214                         // try to convert to double
215
try {
216                             converted[j] = Double.valueOf(value);
217                         } catch (NumberFormatException JavaDoc e) {
218                             match = false;
219                         }
220                     }
221                     if (!match) {
222                         break;
223                     }
224                 }
225                 if (match) {
226                     // we found a matching method signature
227
params = converted;
228                     foundMethod = method;
229                     break;
230                 }
231
232             }
233
234             if ((foundMethod == null) && (onlyStringMethod != null)) {
235                 // no match found but String only signature available, use this
236
params = parameters.toArray();
237                 foundMethod = onlyStringMethod;
238             }
239
240             if (params == null) {
241                 // no match found at all
242
return false;
243             }
244
245             // now try to invoke the method
246
try {
247                 Object JavaDoc result = foundMethod.invoke(m_object, params);
248                 if (result != null) {
249                     if (result instanceof Collection JavaDoc) {
250                         Collection JavaDoc c = (Collection JavaDoc)result;
251                         System.out.println(c.getClass().getName() + " (size: " + c.size() + ")");
252                         int count = 0;
253                         if (result instanceof Map JavaDoc) {
254                             Map JavaDoc m = (Map JavaDoc)result;
255                             Iterator JavaDoc j = m.keySet().iterator();
256                             while (j.hasNext()) {
257                                 Object JavaDoc key = j.next();
258                                 System.out.println(count++ + ": " + key + "= " + m.get(key));
259                             }
260                         } else {
261                             Iterator JavaDoc j = c.iterator();
262                             while (j.hasNext()) {
263                                 System.out.println(count++ + ": " + j.next());
264                             }
265                         }
266                     } else {
267                         System.out.println(result.toString());
268                     }
269                 }
270             } catch (InvocationTargetException JavaDoc ite) {
271                 System.out.println(Messages.get().getBundle(getLocale()).key(
272                     Messages.GUI_SHELL_EXEC_METHOD_1,
273                     new Object JavaDoc[] {foundMethod.getName()}));
274                 ite.getTargetException().printStackTrace(System.out);
275             } catch (Throwable JavaDoc t) {
276                 System.out.println(Messages.get().getBundle(getLocale()).key(
277                     Messages.GUI_SHELL_EXEC_METHOD_1,
278                     new Object JavaDoc[] {foundMethod.getName()}));
279                 t.printStackTrace(System.out);
280             }
281
282             return true;
283         }
284
285         /**
286          * Returns a signature overview of all methods containing the given search String.<p>
287          *
288          * If no method name matches the given search String, the empty String is returned.<p>
289          *
290          * @param searchString the String to search for, if null all methods are shown
291          * @return a signature overview of all methods containing the given search String
292          */

293         protected String JavaDoc getMethodHelp(String JavaDoc searchString) {
294
295             StringBuffer JavaDoc buf = new StringBuffer JavaDoc(512);
296             Iterator JavaDoc i = m_methods.keySet().iterator();
297             while (i.hasNext()) {
298                 List JavaDoc l = (List JavaDoc)m_methods.get(i.next());
299                 Iterator JavaDoc j = l.iterator();
300                 while (j.hasNext()) {
301                     Method JavaDoc method = (Method JavaDoc)j.next();
302                     if ((searchString == null)
303                         || (method.getName().toLowerCase().indexOf(searchString.toLowerCase()) > -1)) {
304                         buf.append("* ");
305                         buf.append(method.getName());
306                         buf.append("(");
307                         Class JavaDoc[] params = method.getParameterTypes();
308                         for (int k = 0; k < params.length; k++) {
309                             String JavaDoc par = params[k].getName();
310                             par = par.substring(par.lastIndexOf('.') + 1);
311                             if (k != 0) {
312                                 buf.append(", ");
313                             }
314                             buf.append(par);
315                         }
316                         buf.append(")\n");
317                     }
318                 }
319             }
320             return buf.toString();
321         }
322
323         /**
324          * Returns the object to execute the methods on.<p>
325          *
326          * @return the object to execute the methods on
327          */

328         protected Object JavaDoc getObject() {
329
330             return m_object;
331         }
332
333         /**
334          * Builds a method lookup String.<p>
335          *
336          * @param methodName the name of the method
337          * @param paramCount the parameter count of the method
338          * @return a method lookup String
339          */

340         private String JavaDoc buildMethodLookup(String JavaDoc methodName, int paramCount) {
341
342             StringBuffer JavaDoc buf = new StringBuffer JavaDoc(32);
343             buf.append(methodName.toLowerCase());
344             buf.append(" [");
345             buf.append(paramCount);
346             buf.append("]");
347             return buf.toString();
348         }
349
350         /**
351          * Initilizes the map of accessible methods.<p>
352          */

353         private void initShellMethods() {
354
355             Map JavaDoc result = new TreeMap JavaDoc();
356
357             Method JavaDoc[] methods = m_object.getClass().getMethods();
358             for (int i = 0; i < methods.length; i++) {
359                 // only public methods directly declared in the base class can be used in the shell
360
if ((methods[i].getDeclaringClass() == m_object.getClass())
361                     && (methods[i].getModifiers() == Modifier.PUBLIC)) {
362
363                     // check if the method signature only uses primitive data types
364
boolean onlyPrimitive = true;
365                     Class JavaDoc[] clazz = methods[i].getParameterTypes();
366                     for (int j = 0; j < clazz.length; j++) {
367                         if (!((clazz[j].equals(String JavaDoc.class))
368                             || (clazz[j].equals(CmsUUID.class))
369                             || (clazz[j].equals(boolean.class))
370                             || (clazz[j].equals(int.class))
371                             || (clazz[j].equals(long.class))
372                             || (clazz[j].equals(double.class)) || (clazz[j].equals(float.class)))) {
373                             // complex data type methods can not be called from the shell
374
onlyPrimitive = false;
375                             break;
376                         }
377                     }
378
379                     if (onlyPrimitive) {
380                         // add this method to the set of methods that can be called from the shell
381
String JavaDoc lookup = buildMethodLookup(methods[i].getName(), methods[i].getParameterTypes().length);
382                         List JavaDoc l;
383                         if (result.containsKey(lookup)) {
384                             l = (List JavaDoc)result.get(lookup);
385                         } else {
386                             l = new ArrayList JavaDoc(1);
387                         }
388                         l.add(methods[i]);
389                         result.put(lookup, l);
390                     }
391                 }
392             }
393             m_methods = result;
394         }
395     }
396
397     /** Prefix for "base" parameter. */
398     public static final String JavaDoc SHELL_PARAM_BASE = "-base=";
399
400     /** Prefix for "servletMapping" parameter. */
401     public static final String JavaDoc SHELL_PARAM_DEFAULT_WEB_APP = "-defaultWebApp=";
402
403     /** Prefix for "script" parameter. */
404     public static final String JavaDoc SHELL_PARAM_SCRIPT = "-script=";
405
406     /** Prefix for "servletMapping" parameter. */
407     public static final String JavaDoc SHELL_PARAM_SERVLET_MAPPING = "-servletMapping=";
408
409     /** The OpenCms context object. */
410     protected CmsObject m_cms;
411
412     /** Additional shell commands object. */
413     private I_CmsShellCommands m_additionaShellCommands;
414
415     /** All shell callable objects. */
416     private List JavaDoc m_commandObjects;
417
418     /** If set to true, all commands are echoed. */
419     private boolean m_echo;
420
421     /** Indicates if the 'exit' command has been called. */
422     private boolean m_exitCalled;
423
424     /** The messages object. */
425     private CmsMessages m_messages;
426
427     /** The OpenCms system object. */
428     private OpenCmsCore m_opencms;
429
430     /** The shell prompt format. */
431     private String JavaDoc m_prompt;
432
433     /** The current users settings. */
434     private CmsUserSettings m_settings;
435
436     /** Internal shell command object. */
437     private I_CmsShellCommands m_shellCommands;
438
439     /**
440      * Creates a new CmsShell.<p>
441      *
442      * @param webInfPath the path to the 'WEB-INF' folder of the OpenCms installation
443      * @param servletMapping the mapping of the servlet (or <code>null</code> to use the default <code>"/opencms/*"</code>)
444      * @param defaultWebAppName the name of the default web application (or <code>null</code> to use the default <code>"ROOT"</code>)
445      * @param prompt the prompt format to set
446      * @param additionalShellCommands optional object for additional shell commands, or null
447      */

448     public CmsShell(
449         String JavaDoc webInfPath,
450         String JavaDoc servletMapping,
451         String JavaDoc defaultWebAppName,
452         String JavaDoc prompt,
453         I_CmsShellCommands additionalShellCommands) {
454
455         setPrompt(prompt);
456         if (CmsStringUtil.isEmpty(servletMapping)) {
457             servletMapping = "/opencms/*";
458         }
459         if (CmsStringUtil.isEmpty(defaultWebAppName)) {
460             defaultWebAppName = "ROOT";
461         }
462         try {
463             // first initialize runlevel 1
464
m_opencms = OpenCmsCore.getInstance();
465             // Externalisation: get Locale: will be the System default since no CmsObject is up before
466
// runlevel 2
467
Locale JavaDoc locale = getLocale();
468             m_messages = Messages.get().getBundle(locale);
469             // search for the WEB-INF folder
470
if (CmsStringUtil.isEmpty(webInfPath)) {
471                 System.out.println(m_messages.key(Messages.GUI_SHELL_NO_HOME_FOLDER_SPECIFIED_0));
472                 System.out.println();
473                 webInfPath = CmsFileUtil.searchWebInfFolder(System.getProperty("user.dir"));
474                 if (CmsStringUtil.isEmpty(webInfPath)) {
475                     System.err.println(m_messages.key(Messages.GUI_SHELL_HR_0));
476                     System.err.println(m_messages.key(Messages.GUI_SHELL_NO_HOME_FOLDER_FOUND_0));
477                     System.err.println();
478                     System.err.println(m_messages.key(Messages.GUI_SHELL_START_DIR_LINE1_0));
479                     System.err.println(m_messages.key(Messages.GUI_SHELL_START_DIR_LINE2_0));
480                     System.err.println(m_messages.key(Messages.GUI_SHELL_HR_0));
481                     return;
482                 }
483             }
484             System.out.println(Messages.get().getBundle(locale).key(Messages.GUI_SHELL_WEB_INF_PATH_1, webInfPath));
485             // set the path to the WEB-INF folder (the 2nd and 3rd parameters are just reasonable dummies)
486
m_opencms.getSystemInfo().init(webInfPath, servletMapping, null, defaultWebAppName);
487
488             // now read the configuration properties
489
String JavaDoc propertyPath = m_opencms.getSystemInfo().getConfigurationFileRfsPath();
490             System.out.println(m_messages.key(Messages.GUI_SHELL_CONFIG_FILE_1, propertyPath));
491             System.out.println();
492             ExtendedProperties configuration = CmsPropertyUtils.loadProperties(propertyPath);
493
494             // now upgrade to runlevel 2
495
m_opencms = m_opencms.upgradeRunlevel(configuration);
496
497             // create a context object with 'Guest' permissions
498
m_cms = m_opencms.initCmsObject(m_opencms.getDefaultUsers().getUserGuest());
499
500             // initialize the settings of the user
501
m_settings = initSettings();
502
503             // initialize shell command object
504
m_shellCommands = new CmsShellCommands();
505             m_shellCommands.initShellCmsObject(m_cms, this);
506
507             // initialize additional shell command object
508
if (additionalShellCommands != null) {
509                 m_additionaShellCommands = additionalShellCommands;
510                 m_additionaShellCommands.initShellCmsObject(m_cms, null);
511                 m_additionaShellCommands.shellStart();
512             } else {
513                 m_shellCommands.shellStart();
514             }
515
516             m_commandObjects = new ArrayList JavaDoc();
517             if (m_additionaShellCommands != null) {
518                 // get all shell callable methods from the the additionsl shell command object
519
m_commandObjects.add(new CmsCommandObject(m_additionaShellCommands));
520             }
521             // get all shell callable methods from the CmsShellCommands
522
m_commandObjects.add(new CmsCommandObject(m_shellCommands));
523             // get all shell callable methods from the CmsRequestContext
524
m_commandObjects.add(new CmsCommandObject(m_cms.getRequestContext()));
525             // get all shell callable methods from the CmsObject
526
m_commandObjects.add(new CmsCommandObject(m_cms));
527         } catch (Throwable JavaDoc t) {
528             t.printStackTrace(System.err);
529         }
530     }
531
532     /**
533      * Main program entry point when started via the command line.<p>
534      *
535      * @param args parameters passed to the application via the command line
536      */

537     public static void main(String JavaDoc[] args) {
538
539         boolean wrongUsage = false;
540         String JavaDoc webInfPath = null;
541         String JavaDoc script = null;
542         String JavaDoc servletMapping = null;
543         String JavaDoc defaultWebApp = null;
544
545         if (args.length > 4) {
546             wrongUsage = true;
547         } else {
548             for (int i = 0; i < args.length; i++) {
549                 String JavaDoc arg = args[i];
550                 if (arg.startsWith(SHELL_PARAM_BASE)) {
551                     webInfPath = arg.substring(SHELL_PARAM_BASE.length());
552                 } else if (arg.startsWith(SHELL_PARAM_SCRIPT)) {
553                     script = arg.substring(SHELL_PARAM_SCRIPT.length());
554                 } else if (arg.startsWith(SHELL_PARAM_SERVLET_MAPPING)) {
555                     servletMapping = arg.substring(SHELL_PARAM_SERVLET_MAPPING.length());
556                 } else if (arg.startsWith(SHELL_PARAM_DEFAULT_WEB_APP)) {
557                     defaultWebApp = arg.substring(SHELL_PARAM_DEFAULT_WEB_APP.length());
558                 } else {
559                     System.out.println(Messages.get().getBundle().key(Messages.GUI_SHELL_WRONG_USAGE_0));
560                     wrongUsage = true;
561                 }
562             }
563         }
564         if (wrongUsage) {
565             System.out.println(Messages.get().getBundle().key(Messages.GUI_SHELL_USAGE_1, CmsShell.class.getName()));
566         } else {
567             FileInputStream JavaDoc stream = null;
568             if (script != null) {
569                 try {
570                     stream = new FileInputStream JavaDoc(script);
571                 } catch (IOException JavaDoc exc) {
572                     System.out.println(Messages.get().getBundle().key(Messages.GUI_SHELL_ERR_SCRIPTFILE_1, script));
573                 }
574             }
575             if (stream == null) {
576                 // no script-file, use standard input stream
577
stream = new FileInputStream JavaDoc(FileDescriptor.in);
578             }
579             CmsShell shell = new CmsShell(
580                 webInfPath,
581                 servletMapping,
582                 defaultWebApp,
583                 "${user}@${project}:${siteroot}|${uri}>",
584                 null);
585             shell.start(stream);
586         }
587     }
588
589     /**
590      * Exits this shell and destroys the OpenCms instance.<p>
591      */

592     public void exit() {
593
594         if (m_exitCalled) {
595             return;
596         }
597         m_exitCalled = true;
598         try {
599             if (m_additionaShellCommands != null) {
600                 m_additionaShellCommands.shellExit();
601             } else {
602                 m_shellCommands.shellExit();
603             }
604         } catch (Throwable JavaDoc t) {
605             t.printStackTrace();
606         }
607         try {
608             m_opencms.shutDown();
609         } catch (Throwable JavaDoc t) {
610             t.printStackTrace();
611         }
612     }
613
614     /**
615      * Private internal helper for localisation to the current user's locale
616      * within OpenCms. <p>
617      *
618      * @return the current user's <code>Locale</code>.
619      */

620     public Locale JavaDoc getLocale() {
621
622         if (getSettings() == null) {
623             return CmsLocaleManager.getDefaultLocale();
624         }
625         return getSettings().getLocale();
626     }
627
628     /**
629      * Returns the localized messages object for the current user.<p>
630      *
631      * @return the localized messages object for the current user
632      */

633     public CmsMessages getMessages() {
634
635         return m_messages;
636     }
637
638     /**
639      * Obtain the additional settings related to the current user.
640      *
641      * @return the additional settings related to the current user.
642      */

643     public CmsUserSettings getSettings() {
644
645         return m_settings;
646     }
647
648     /**
649      * Prints the shell prompt.<p>
650      */

651     public void printPrompt() {
652
653         String JavaDoc prompt = m_prompt;
654         prompt = CmsStringUtil.substitute(prompt, "${user}", m_cms.getRequestContext().currentUser().getName());
655         prompt = CmsStringUtil.substitute(prompt, "${siteroot}", m_cms.getRequestContext().getSiteRoot());
656         prompt = CmsStringUtil.substitute(prompt, "${project}", m_cms.getRequestContext().currentProject().getName());
657         prompt = CmsStringUtil.substitute(prompt, "${uri}", m_cms.getRequestContext().getUri());
658         System.out.print(prompt);
659     }
660
661     /**
662      * Sets the locale of the current user.<p>
663      *
664      * @param locale the locale to set
665      *
666      * @throws CmsException in case the locale of the current user can not be stored
667      */

668     public void setLocale(Locale JavaDoc locale) throws CmsException {
669
670         CmsUserSettings settings = getSettings();
671         if (settings != null) {
672             settings.setLocale(locale);
673             settings.save(m_cms);
674             m_messages = Messages.get().getBundle(locale);
675         }
676     }
677
678     /**
679      * Starts this CmsShell.<p>
680      *
681      * @param fileInputStream a (file) input stream from which commands are read
682      */

683     public void start(FileInputStream JavaDoc fileInputStream) {
684
685         try {
686             // execute the commands from the input stream
687
executeCommands(fileInputStream);
688         } catch (Throwable JavaDoc t) {
689             t.printStackTrace(System.err);
690         }
691     }
692
693     /**
694      * Shows the signature of all methods containing the given search String.<p>
695      *
696      * @param searchString the String to search for in the methods, if null all methods are shown
697      */

698     protected void help(String JavaDoc searchString) {
699
700         String JavaDoc commandList;
701         boolean foundSomething = false;
702         System.out.println();
703
704         Iterator JavaDoc i = m_commandObjects.iterator();
705         while (i.hasNext()) {
706             CmsCommandObject cmdObj = (CmsCommandObject)i.next();
707             commandList = cmdObj.getMethodHelp(searchString);
708             if (!CmsStringUtil.isEmpty(commandList)) {
709                 System.out.println(m_messages.key(
710                     Messages.GUI_SHELL_AVAILABLE_METHODS_1,
711                     cmdObj.getObject().getClass().getName()));
712                 System.out.println(commandList);
713                 foundSomething = true;
714             }
715         }
716
717         if (!foundSomething) {
718             System.out.println(m_messages.key(Messages.GUI_SHELL_MATCH_SEARCHSTRING_1, searchString));
719         }
720     }
721
722     /**
723      * Initializes the internal <code>CmsWorkplaceSettings</code> that contain (amongst other
724      * information) important information additional information about the current user
725      * (an instance of {@link CmsUserSettings}). <p>
726      *
727      * This step is performed within the <code>CmsShell</code> constructor directly after
728      * switching to run-level 2 and obtaining the <code>CmsObject</code> for the guest user as
729      * well as when invoking the CmsShell command <code>login</code>.
730      *
731      * @return the user settings for the current user.
732      */

733     protected CmsUserSettings initSettings() {
734
735         m_settings = new CmsUserSettings(m_cms);
736         return m_settings;
737     }
738
739     /**
740      * Sets the echo status.<p>
741      *
742      * @param echo the echo status to set
743      */

744     protected void setEcho(boolean echo) {
745
746         m_echo = echo;
747     }
748
749     /**
750      * Sets the current shell prompt.<p>
751      *
752      * To set the prompt, the following variables are available:<p>
753      *
754      * <code>$u</code> the current user name<br>
755      * <code>$s</code> the current site root<br>
756      * <code>$p</code> the current project name<p>
757      *
758      * @param prompt the prompt to set
759      */

760     protected void setPrompt(String JavaDoc prompt) {
761
762         m_prompt = prompt;
763     }
764
765     /**
766      * Executes a shell command with a list of parameters.<p>
767      *
768      * @param command the command to execute
769      * @param parameters the list of parameters for the command
770      */

771     private void executeCommand(String JavaDoc command, List JavaDoc parameters) {
772
773         if (m_echo) {
774             // echo the command to STDOUT
775
System.out.print(command);
776             for (int i = 0; i < parameters.size(); i++) {
777                 System.out.print(" " + parameters.get(i));
778             }
779             System.out.println();
780         }
781
782         // prepare to lookup a method in CmsObject or CmsShellCommands
783
boolean executed = false;
784         Iterator JavaDoc i = m_commandObjects.iterator();
785         while (!executed && i.hasNext()) {
786             CmsCommandObject cmdObj = (CmsCommandObject)i.next();
787             executed = cmdObj.executeMethod(command, parameters);
788         }
789
790         if (!executed) {
791             // method not found
792
System.out.println();
793             StringBuffer JavaDoc commandMsg = new StringBuffer JavaDoc(command).append("(");
794             for (int j = 0; j < parameters.size(); j++) {
795                 commandMsg.append("value");
796                 if (j < parameters.size() - 1) {
797                     commandMsg.append(", ");
798                 }
799             }
800             commandMsg.append(")");
801
802             System.out.println(m_messages.key(Messages.GUI_SHELL_METHOD_NOT_FOUND_1, commandMsg.toString()));
803             System.out.println(m_messages.key(Messages.GUI_SHELL_HR_0));
804             ((CmsShellCommands)m_shellCommands).help();
805         }
806     }
807
808     /**
809      * Executes all commands read from the given input stream.<p>
810      *
811      * @param fileInputStream a file input stream from which the commands are read
812      */

813     private void executeCommands(FileInputStream JavaDoc fileInputStream) {
814
815         try {
816             LineNumberReader JavaDoc lnr = new LineNumberReader JavaDoc(new InputStreamReader JavaDoc(fileInputStream));
817             while (!m_exitCalled) {
818                 printPrompt();
819                 String JavaDoc line = lnr.readLine();
820                 if (line == null) {
821                     // if null the file has been read to the end
822
try {
823                         Thread.sleep(500);
824                     } catch (Throwable JavaDoc t) {
825                         // noop
826
}
827                     break;
828                 }
829                 if ((line != null) && line.trim().startsWith("#")) {
830                     System.out.println(line);
831                     continue;
832                 }
833                 StringReader JavaDoc reader = new StringReader JavaDoc(line);
834                 StreamTokenizer JavaDoc st = new StreamTokenizer JavaDoc(reader);
835                 st.eolIsSignificant(true);
836
837                 // put all tokens into a List
838
List JavaDoc parameters = new ArrayList JavaDoc();
839                 while (st.nextToken() != StreamTokenizer.TT_EOF) {
840                     if (st.ttype == StreamTokenizer.TT_NUMBER) {
841                         parameters.add(Integer.toString(new Double JavaDoc(st.nval).intValue()));
842                     } else {
843                         parameters.add(st.sval);
844                     }
845                 }
846                 reader.close();
847
848                 // extract command and arguments
849
if ((parameters == null) || (parameters.size() == 0)) {
850                     if (m_echo) {
851                         System.out.println();
852                     }
853                     continue;
854                 }
855                 String JavaDoc command = (String JavaDoc)parameters.get(0);
856                 parameters = parameters.subList(1, parameters.size());
857
858                 // execute the command
859
executeCommand(command, parameters);
860             }
861         } catch (Throwable JavaDoc t) {
862             t.printStackTrace(System.err);
863         }
864     }
865 }
Popular Tags