KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * File : $Source: /usr/local/cvs/opencms/src/org/opencms/main/CmsShellCommands.java,v $
3  * Date : $Date: 2006/09/21 09:34:48 $
4  * Version: $Revision: 1.84 $
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.CmsDbEntryNotFoundException;
35 import org.opencms.db.CmsLoginMessage;
36 import org.opencms.file.CmsFile;
37 import org.opencms.file.CmsGroup;
38 import org.opencms.file.CmsObject;
39 import org.opencms.file.CmsProject;
40 import org.opencms.file.CmsPropertyDefinition;
41 import org.opencms.file.CmsResource;
42 import org.opencms.file.CmsResourceFilter;
43 import org.opencms.file.CmsUser;
44 import org.opencms.file.types.CmsResourceTypeFolder;
45 import org.opencms.i18n.CmsLocaleManager;
46 import org.opencms.i18n.CmsMessages;
47 import org.opencms.importexport.CmsVfsImportExportHandler;
48 import org.opencms.module.CmsModule;
49 import org.opencms.module.CmsModuleImportExportHandler;
50 import org.opencms.report.CmsShellReport;
51 import org.opencms.report.I_CmsReport;
52 import org.opencms.security.CmsAccessControlEntry;
53 import org.opencms.security.CmsAccessControlList;
54 import org.opencms.security.CmsRole;
55 import org.opencms.security.I_CmsPrincipal;
56 import org.opencms.staticexport.CmsLinkManager;
57 import org.opencms.util.CmsFileUtil;
58 import org.opencms.util.CmsUUID;
59 import org.opencms.workplace.CmsWorkplace;
60
61 import java.util.ArrayList JavaDoc;
62 import java.util.Collections JavaDoc;
63 import java.util.HashMap JavaDoc;
64 import java.util.Hashtable JavaDoc;
65 import java.util.Iterator JavaDoc;
66 import java.util.List JavaDoc;
67 import java.util.Locale JavaDoc;
68 import java.util.Random JavaDoc;
69 import java.util.Set JavaDoc;
70 import java.util.StringTokenizer JavaDoc;
71
72 /**
73  * Provides additional commands for the CmsShell.<p>
74  *
75  * Such additional commands can access OpenCms functions not available on "regular" OpenCms classes.
76  * Also, wrapping methods to access some important functions in the CmsObject that
77  * require complex data type parameters are provided.<p>
78  *
79  * @author Alexander Kandzior
80  *
81  * @version $Revision: 1.84 $
82  *
83  * @since 6.0.0
84  */

85 class CmsShellCommands implements I_CmsShellCommands {
86
87     /** The OpenCms context object. */
88     private CmsObject m_cms;
89
90     /** The Cms shell object. */
91     private CmsShell m_shell;
92
93     /**
94      * Generate a new instance of the command processor.<p>
95      *
96      * To initilize the command processor, you must call {@link #initShellCmsObject(CmsObject, CmsShell)}.
97      *
98      * @see #initShellCmsObject(CmsObject, CmsShell)
99      */

100     protected CmsShellCommands() {
101
102         // noop
103
}
104
105     /**
106      * Adds a web user.<p>
107      *
108      * @param name the name of the new web user
109      * @param password the password
110      * @param group the default group name
111      * @param description the description
112      * @return the created user
113      * @throws Exception if something goes wrong
114      * @see CmsObject#addWebUser(String, String, String, String, Hashtable)
115      */

116     public CmsUser addWebUser(String JavaDoc name, String JavaDoc password, String JavaDoc group, String JavaDoc description) throws Exception JavaDoc {
117
118         return m_cms.addWebUser(name, password, group, description, new Hashtable JavaDoc());
119     }
120
121     /**
122      * Changes the current folder (i.e. the URI in the VFS).<p>
123      *
124      * @param target the new URI
125      * @throws Exception if something goes wrong
126      * @see org.opencms.file.CmsRequestContext#setUri(String)
127      */

128     public void cd(String JavaDoc target) throws Exception JavaDoc {
129
130         String JavaDoc folder = CmsResource.getFolderPath(m_cms.getRequestContext().getUri());
131         if (!target.endsWith("/")) {
132             target += "/";
133         }
134         String JavaDoc resolvedTarget = CmsLinkManager.getAbsoluteUri(target, folder);
135         CmsResource res = m_cms.readResource(resolvedTarget);
136         if (!res.isFolder()) {
137             throw new CmsIllegalArgumentException(Messages.get().container(Messages.ERR_NOT_A_FOLDER_1, resolvedTarget));
138         }
139         m_cms.getRequestContext().setUri(resolvedTarget);
140         System.out.println('\n' + getMessages().key(Messages.GUI_SHELL_CURRENT_FOLDER_1, new Object JavaDoc[] {resolvedTarget}));
141         System.out.println();
142     }
143
144     /**
145      * Changes the access control for a given resource and a given principal(user/group).
146      *
147      * @param resourceName name of the resource
148      * @param principalType the type of the principal (group or user)
149      * @param principalName name of the principal
150      * @param permissionString the permissions in the format ((+|-)(r|w|v|c|i))*
151      * @throws CmsException if something goes wrong
152      * @see CmsObject#chacc(String, String, String, String)
153      */

154     public void chacc(String JavaDoc resourceName, String JavaDoc principalType, String JavaDoc principalName, String JavaDoc permissionString)
155     throws CmsException {
156
157         m_cms.lockResource(resourceName);
158         if (I_CmsPrincipal.PRINCIPAL_GROUP.equalsIgnoreCase(principalType.trim())) {
159             principalName = OpenCms.getImportExportManager().translateGroup(principalName);
160         } else {
161             principalName = OpenCms.getImportExportManager().translateUser(principalName);
162         }
163         m_cms.chacc(resourceName, principalType, principalName, permissionString);
164     }
165
166     /**
167      * Clears all OpenCms internal caches.<p>
168      *
169      * @throws Exception if something goes wrong
170      */

171     public void clearCaches() throws Exception JavaDoc {
172
173         OpenCms.fireCmsEvent(new CmsEvent(I_CmsEventListener.EVENT_CLEAR_CACHES, Collections.EMPTY_MAP));
174     }
175
176     /**
177      * Prints the OpenCms copyright information.<p>
178      */

179     public void copyright() {
180
181         String JavaDoc[] copy = Messages.COPYRIGHT_BY_ALKACON;
182         for (int i = 0; i < copy.length; i++) {
183             System.out.println(copy[i]);
184         }
185     }
186
187     /**
188      * Creates a default project.<p>
189      *
190      * This created project has the following properties:<ul>
191      * <li>The users groups is the default user group
192      * <li>The project managers group is the default project manager group
193      * <li>All resources are contained in the project
194      * <li>The project will remain after publishing</ul>
195      *
196      * @param name the name of the project to create
197      * @param description the description for the new project
198      * @throws Exception if something goes wrong
199      */

200     public void createDefaultProject(String JavaDoc name, String JavaDoc description) throws Exception JavaDoc {
201
202         m_cms.getRequestContext().saveSiteRoot();
203         m_cms.getRequestContext().setSiteRoot("/");
204         try {
205             CmsProject project = m_cms.createProject(
206                 name,
207                 description,
208                 OpenCms.getDefaultUsers().getGroupUsers(),
209                 OpenCms.getDefaultUsers().getGroupProjectmanagers(),
210                 CmsProject.PROJECT_TYPE_NORMAL);
211             m_cms.getRequestContext().setCurrentProject(project);
212             m_cms.copyResourceToProject("/");
213         } finally {
214             m_cms.getRequestContext().restoreSiteRoot();
215         }
216         if (m_cms.hasRole(CmsRole.SEARCH_MANAGER)) {
217             // re-initialize the search indexes after default project generation
218
OpenCms.getSearchManager().initialize(m_cms);
219         }
220     }
221
222     /**
223      * Creates a new folder in the given target folder.<p>
224      *
225      * @param targetFolder the target folder
226      * @param folderName the new folder to create in the target folder
227      * @return the created folder
228      * @throws Exception if somthing goes wrong
229      */

230     public CmsResource createFolder(String JavaDoc targetFolder, String JavaDoc folderName) throws Exception JavaDoc {
231
232         return m_cms.createResource(targetFolder + folderName, CmsResourceTypeFolder.RESOURCE_TYPE_ID);
233     }
234
235     /**
236      * Creates a group.<p>
237      *
238      * @param name the name of the new group
239      * @param description the description of the new group
240      * @return the created group
241      * @throws Exception if something goes wrong
242      * @see CmsObject#createGroup(String, String, int, String)
243      */

244     public CmsGroup createGroup(String JavaDoc name, String JavaDoc description) throws Exception JavaDoc {
245
246         return m_cms.createGroup(name, description, I_CmsPrincipal.FLAG_ENABLED, null);
247     }
248
249     /**
250      * Creates a property definition for the given resource type.<p>
251      *
252      * @param name the name of the property definition to create
253      * @return the created property definition
254      * @throws Exception if something goes wrong
255      * @see CmsObject#createPropertyDefinition(String)
256      */

257     public CmsPropertyDefinition createPropertydefinition(String JavaDoc name) throws Exception JavaDoc {
258
259         return m_cms.createPropertyDefinition(name);
260     }
261
262     /**
263      * Creates a new user.<p>
264      *
265      * @param name the name for the new user
266      * @param password the password for the new user
267      * @param description the description for the new user
268      *
269      * @throws Exception if something goes wrong
270      * @see CmsObject#createUser(String, String, String, Hashtable)
271      * @return the created user
272      */

273     public CmsUser createUser(String JavaDoc name, String JavaDoc password, String JavaDoc description) throws Exception JavaDoc {
274
275         return m_cms.createUser(name, password, description, new Hashtable JavaDoc());
276     }
277
278     /**
279      * Creates a user with some additional information.<p>
280      *
281      * @param name the name of the new user
282      * @param password the password
283      * @param description the description
284      * @param firstname the users first name
285      * @param lastname the users he last name
286      * @param email the users email address
287      * @return the created user
288      *
289      * @throws Exception if something goes wrong
290      * @see CmsObject#createUser(String, String, String, Hashtable)
291      */

292     public CmsUser createUser(
293         String JavaDoc name,
294         String JavaDoc password,
295         String JavaDoc description,
296         String JavaDoc firstname,
297         String JavaDoc lastname,
298         String JavaDoc email) throws Exception JavaDoc {
299
300         CmsUser user = m_cms.createUser(name, password, description, new Hashtable JavaDoc());
301         user.setEmail(email);
302         user.setFirstname(firstname);
303         user.setLastname(lastname);
304         m_cms.writeUser(user);
305         return user;
306     }
307
308     /**
309      * Deletes the versions from the backup tables that are older then the given weeks.<p>
310      *
311      * @param weeks a numer of weeks, all older backups are deleted
312      * @throws Exception if something goes wrong
313      * @see CmsObject#deleteBackups(long, int, org.opencms.report.I_CmsReport)
314      */

315     public void deleteBackups(int weeks) throws Exception JavaDoc {
316
317         long oneWeek = 604800000;
318         long maxDate = System.currentTimeMillis() - (weeks * oneWeek);
319         m_cms.deleteBackups(maxDate, 100, new CmsShellReport(m_cms.getRequestContext().getLocale()));
320     }
321
322     /**
323      * Deletes a module.<p>
324      *
325      * @param moduleName the name of the module
326      * @throws Exception if something goes wrong
327      */

328     public void deleteModule(String JavaDoc moduleName) throws Exception JavaDoc {
329
330         OpenCms.getModuleManager().deleteModule(
331             m_cms,
332             moduleName,
333             false,
334             new CmsShellReport(m_cms.getRequestContext().getLocale()));
335     }
336
337     /**
338      * Deletes a project by name.<p>
339      *
340      * @param name the name of the project to delete
341
342      * @throws Exception if something goes wrong
343      *
344      * @see CmsObject#deleteProject(int)
345      */

346     public void deleteProject(String JavaDoc name) throws Exception JavaDoc {
347
348         m_cms.deleteProject(m_cms.readProject(name).getId());
349     }
350
351     /**
352      * Delete a property definition for a resource.<p>
353      *
354      * @param name the name of the property definition to delete
355      * @throws Exception if something goes wrong
356      * @see CmsObject#deletePropertyDefinition(String)
357      */

358     public void deletepropertydefinition(String JavaDoc name) throws Exception JavaDoc {
359
360         m_cms.deletePropertyDefinition(name);
361     }
362
363     /**
364      * Turns the echo status for the shell on or off.<p>
365      *
366      * @param echo if "on", echo is turned on, otherwise echo is turned off
367      */

368     public void echo(String JavaDoc echo) {
369
370         if (echo == null) {
371             return;
372         }
373         boolean b = "on".equalsIgnoreCase(echo.trim());
374         m_shell.setEcho(b);
375         if (b) {
376             System.out.println(getMessages().key(Messages.GUI_SHELL_ECHO_ON_0));
377         } else {
378             System.out.println(getMessages().key(Messages.GUI_SHELL_ECHO_OFF_0));
379         }
380     }
381
382     /**
383      * Exits the shell.<p>
384      */

385     public void exit() {
386
387         m_shell.exit();
388     }
389
390     /**
391      * Exports all resources from the current site root to a ZIP file.<p>
392      *
393      * @param exportFile the name (absolute path) of the ZIP file to export to
394      * @throws Exception if something goes wrong
395      */

396     public void exportAllResources(String JavaDoc exportFile) throws Exception JavaDoc {
397
398         List exportPaths = new ArrayList JavaDoc(1);
399         exportPaths.add("/");
400
401         CmsVfsImportExportHandler vfsExportHandler = new CmsVfsImportExportHandler();
402         vfsExportHandler.setFileName(exportFile);
403         vfsExportHandler.setExportPaths(exportPaths);
404         vfsExportHandler.setIncludeSystem(true);
405         vfsExportHandler.setIncludeUnchanged(true);
406         vfsExportHandler.setExportUserdata(false);
407
408         OpenCms.getImportExportManager().exportData(
409             m_cms,
410             vfsExportHandler,
411             new CmsShellReport(m_cms.getRequestContext().getLocale()));
412     }
413
414     /**
415      * Exports the module with the given name to the default location.<p>
416      *
417      * @param moduleName the name of the module to export
418      *
419      * @throws Exception if something goes wrong
420      */

421     public void exportModule(String JavaDoc moduleName) throws Exception JavaDoc {
422
423         CmsModule module = OpenCms.getModuleManager().getModule(moduleName);
424
425         if (module == null) {
426             throw new CmsDbEntryNotFoundException(Messages.get().container(Messages.ERR_UNKNOWN_MODULE_1, moduleName));
427         }
428
429         String JavaDoc filename = OpenCms.getSystemInfo().getAbsoluteRfsPathRelativeToWebInf(
430             OpenCms.getSystemInfo().getPackagesRfsPath()
431                 + CmsSystemInfo.FOLDER_MODULES
432                 + moduleName
433                 + "_"
434                 + OpenCms.getModuleManager().getModule(moduleName).getVersion().toString());
435
436         String JavaDoc[] resources = new String JavaDoc[module.getResources().size()];
437         System.arraycopy(module.getResources().toArray(), 0, resources, 0, resources.length);
438
439         // generate a module export handler
440
CmsModuleImportExportHandler moduleExportHandler = new CmsModuleImportExportHandler();
441         moduleExportHandler.setFileName(filename);
442         moduleExportHandler.setAdditionalResources(resources);
443         moduleExportHandler.setModuleName(module.getName().replace('\\', '/'));
444         moduleExportHandler.setDescription(getMessages().key(
445             Messages.GUI_SHELL_IMPORTEXPORT_MODULE_HANDLER_NAME_1,
446             new Object JavaDoc[] {moduleExportHandler.getModuleName()}));
447
448         // export the module
449
OpenCms.getImportExportManager().exportData(
450             m_cms,
451             moduleExportHandler,
452             new CmsShellReport(m_cms.getRequestContext().getLocale()));
453     }
454
455     /**
456      * Exports a list of resources from the current site root to a ZIP file.<p>
457      *
458      * The resource names in the list must be separated with a ";".<p>
459      *
460      * @param exportFile the name (absolute path) of the ZIP file to export to
461      * @param pathList the list of resource to export, separated with a ";"
462      * @throws Exception if something goes wrong
463      */

464     public void exportResources(String JavaDoc exportFile, String JavaDoc pathList) throws Exception JavaDoc {
465
466         StringTokenizer JavaDoc tok = new StringTokenizer JavaDoc(pathList, ";");
467         List exportPaths = new ArrayList JavaDoc();
468         while (tok.hasMoreTokens()) {
469             exportPaths.add(tok.nextToken());
470         }
471         boolean includeSystem = false;
472         if (pathList.startsWith(CmsWorkplace.VFS_PATH_SYSTEM)
473             || (pathList.indexOf(";" + CmsWorkplace.VFS_PATH_SYSTEM) > -1)) {
474             includeSystem = true;
475         }
476
477         CmsVfsImportExportHandler vfsExportHandler = new CmsVfsImportExportHandler();
478         vfsExportHandler.setFileName(exportFile);
479         vfsExportHandler.setExportPaths(exportPaths);
480         vfsExportHandler.setIncludeSystem(includeSystem);
481         vfsExportHandler.setIncludeUnchanged(true);
482         vfsExportHandler.setExportUserdata(false);
483
484         OpenCms.getImportExportManager().exportData(
485             m_cms,
486             vfsExportHandler,
487             new CmsShellReport(m_cms.getRequestContext().getLocale()));
488     }
489
490     /**
491      * Exports a list of resources from the current site root and the user data to a ZIP file.<p>
492      *
493      * The resource names in the list must be separated with a ";".<p>
494      *
495      * @param exportFile the name (absolute path) of the ZIP file to export to
496      * @param pathList the list of resource to export, separated with a ";"
497      * @throws Exception if something goes wrong
498      */

499     public void exportResourcesAndUserdata(String JavaDoc exportFile, String JavaDoc pathList) throws Exception JavaDoc {
500
501         StringTokenizer JavaDoc tok = new StringTokenizer JavaDoc(pathList, ";");
502         List exportPaths = new ArrayList JavaDoc();
503         while (tok.hasMoreTokens()) {
504             exportPaths.add(tok.nextToken());
505         }
506         boolean includeSystem = false;
507         if (pathList.startsWith(CmsWorkplace.VFS_PATH_SYSTEM)
508             || (pathList.indexOf(";" + CmsWorkplace.VFS_PATH_SYSTEM) > -1)) {
509             includeSystem = true;
510         }
511
512         CmsVfsImportExportHandler vfsExportHandler = new CmsVfsImportExportHandler();
513         vfsExportHandler.setFileName(exportFile);
514         vfsExportHandler.setExportPaths(exportPaths);
515         vfsExportHandler.setIncludeSystem(includeSystem);
516         vfsExportHandler.setIncludeUnchanged(true);
517         vfsExportHandler.setExportUserdata(true);
518
519         OpenCms.getImportExportManager().exportData(
520             m_cms,
521             vfsExportHandler,
522             new CmsShellReport(m_cms.getRequestContext().getLocale()));
523     }
524
525     /**
526      * Displays the access control list of a given resource.<p>
527      *
528      * @param resourceName the name of the resource
529      * @throws Exception if something goes wrong
530      * @see CmsObject#getAccessControlList(String)
531      */

532     public void getAcl(String JavaDoc resourceName) throws Exception JavaDoc {
533
534         CmsAccessControlList acList = m_cms.getAccessControlList(resourceName);
535         Iterator JavaDoc principals = acList.getPrincipals().iterator();
536         while (principals.hasNext()) {
537             I_CmsPrincipal p = m_cms.lookupPrincipal((CmsUUID)principals.next());
538             System.out.println(p.getName() + ": " + acList.getPermissions(p).getPermissionString());
539         }
540     }
541
542     /**
543      * Returns the Locales available on the system ready to use on Method
544      * {@link #setLocale(String)} from the <code>CmsShell</code>. <p>
545      *
546      * Note that the full name containing language, country and optional variant seperated
547      * by underscores is returned always but the latter two parts may be left out. <p>
548      *
549      */

550     public void getLocales() {
551
552         System.out.println(getMessages().key(Messages.GUI_SHELL_LOCALES_AVAILABLE_0));
553         Locale JavaDoc[] locales = Locale.getAvailableLocales();
554         for (int i = locales.length - 1; i >= 0; i--) {
555             System.out.println(" \"" + locales[i].toString() + "\"");
556         }
557     }
558
559     /**
560      * Provides help information for the CmsShell.<p>
561      */

562     public void help() {
563
564         System.out.println();
565         System.out.println(getMessages().key(Messages.GUI_SHELL_HELP1_0));
566         System.out.println(getMessages().key(Messages.GUI_SHELL_HELP2_0));
567         System.out.println(getMessages().key(Messages.GUI_SHELL_HELP3_0));
568         System.out.println(getMessages().key(Messages.GUI_SHELL_HELP4_0));
569         System.out.println();
570     }
571
572     /**
573      * Executes the given help command.<p>
574      *
575      * @param command the help command to execute
576      */

577     public void help(String JavaDoc command) {
578
579         if ("*".equalsIgnoreCase(command)) {
580             m_shell.help(null);
581         } else if ("help".equalsIgnoreCase(command)) {
582             help();
583         } else {
584             m_shell.help(command);
585         }
586     }
587
588     /**
589      * Imports a module.<p>
590      *
591      * @param importFile the absolute path of the import module file
592      * @throws Exception if something goes wrong
593      * @see org.opencms.importexport.CmsImportExportManager#importData(CmsObject, String, String, org.opencms.report.I_CmsReport)
594      */

595     public void importModule(String JavaDoc importFile) throws Exception JavaDoc {
596
597         OpenCms.getImportExportManager().importData(
598             m_cms,
599             importFile,
600             null,
601             new CmsShellReport(m_cms.getRequestContext().getLocale()));
602     }
603
604     /**
605      * Imports a module (zipfile) from the default module directory,
606      * creating a temporary project for this.<p>
607      *
608      * @param importFile the name of the import module located in the default module directory
609      * @throws Exception if something goes wrong
610      * @see org.opencms.importexport.CmsImportExportManager#importData(CmsObject, String, String, org.opencms.report.I_CmsReport)
611      */

612     public void importModuleFromDefault(String JavaDoc importFile) throws Exception JavaDoc {
613
614         String JavaDoc exportPath = OpenCms.getSystemInfo().getPackagesRfsPath();
615         String JavaDoc fileName = OpenCms.getSystemInfo().getAbsoluteRfsPathRelativeToWebInf(
616             exportPath + CmsSystemInfo.FOLDER_MODULES + importFile);
617         OpenCms.getImportExportManager().importData(
618             m_cms,
619             fileName,
620             null,
621             new CmsShellReport(m_cms.getRequestContext().getLocale()));
622     }
623
624     /**
625      * Exists so that the setup script can run without the wizard, does nothing.<p>
626      */

627     public void importModulesFromSetupBean() {
628
629         // noop, exists so that the setup script can run without the wizard
630
}
631
632     /**
633      * Imports a resource into the Cms.<p>
634      *
635      * @param importFile the name (absolute Path) of the import resource (zip or folder)
636      * @param importPath the name (absolute Path) of folder in which should be imported
637      * @throws Exception if something goes wrong
638      */

639     public void importResources(String JavaDoc importFile, String JavaDoc importPath) throws Exception JavaDoc {
640
641         OpenCms.getImportExportManager().importData(
642             m_cms,
643             OpenCms.getSystemInfo().getAbsoluteRfsPathRelativeToWebInf(importFile),
644             importPath,
645             new CmsShellReport(m_cms.getRequestContext().getLocale()));
646     }
647
648     /**
649      * Imports a folder or a ZIP file to the root folder of the
650      * current site, creating a temporary project for this.<p>
651      *
652      * @param importFile the absolute path of the import resource
653      * @throws Exception if something goes wrong
654      */

655     public void importResourcesWithTempProject(String JavaDoc importFile) throws Exception JavaDoc {
656
657         CmsProject project = m_cms.createProject(
658             "SystemUpdate",
659             getMessages().key(Messages.GUI_SHELL_IMPORT_TEMP_PROJECT_NAME_0),
660             OpenCms.getDefaultUsers().getGroupAdministrators(),
661             OpenCms.getDefaultUsers().getGroupAdministrators(),
662             CmsProject.PROJECT_TYPE_TEMPORARY);
663         int id = project.getId();
664         m_cms.getRequestContext().setCurrentProject(project);
665         m_cms.copyResourceToProject("/");
666         OpenCms.getImportExportManager().importData(
667             m_cms,
668             importFile,
669             "/",
670             new CmsShellReport(m_cms.getRequestContext().getLocale()));
671         m_cms.unlockProject(id);
672         m_cms.publishProject();
673     }
674
675     /**
676      * @see org.opencms.main.I_CmsShellCommands#initShellCmsObject(org.opencms.file.CmsObject, org.opencms.main.CmsShell)
677      */

678     public void initShellCmsObject(CmsObject cms, CmsShell shell) {
679
680         m_cms = cms;
681         m_shell = shell;
682     }
683
684     /**
685      * Displays a list of all currently installed modules.<p>
686      *
687      * @throws Exception if something goes wrong
688      */

689     public void listModules() throws Exception JavaDoc {
690
691         Set JavaDoc modules = OpenCms.getModuleManager().getModuleNames();
692         System.out.println("\n" + getMessages().key(Messages.GUI_SHELL_LIST_MODULES_1, new Integer JavaDoc(modules.size())));
693         Iterator JavaDoc i = modules.iterator();
694         while (i.hasNext()) {
695             String JavaDoc moduleName = (String JavaDoc)i.next();
696             System.out.println(moduleName);
697         }
698         System.out.println();
699     }
700
701     /**
702      * Log a user in to the the CmsSell.<p>
703      *
704      * @param username the name of the user to log in
705      * @param password the password of the user
706      */

707     public void login(String JavaDoc username, String JavaDoc password) {
708
709         username = OpenCms.getImportExportManager().translateUser(username);
710         try {
711             m_cms.loginUser(username, password);
712             // reset the settings, this will switch the startup site root etc.
713
m_shell.initSettings();
714             System.out.println(getMessages().key(Messages.GUI_SHELL_LOGIN_1, whoami().getName()));
715             // output the login message if required
716
CmsLoginMessage message = OpenCms.getLoginManager().getLoginMessage();
717             if ((message != null) && (message.isActive())) {
718                 System.out.println(message.getMessage());
719             }
720         } catch (Exception JavaDoc exc) {
721             System.out.println(getMessages().key(Messages.GUI_SHELL_LOGIN_FAILED_0));
722         }
723     }
724
725     /**
726      * Displays a list of all resources in the current folder.<p>
727      *
728      * @throws Exception if something goes wrong
729      * @see CmsObject#getResourcesInFolder(String, CmsResourceFilter)
730      */

731     public void ls() throws Exception JavaDoc {
732
733         String JavaDoc folder = CmsResource.getFolderPath(m_cms.getRequestContext().getUri());
734         List resources = m_cms.getResourcesInFolder(folder, CmsResourceFilter.IGNORE_EXPIRATION);
735         System.out.println("\n" + getMessages().key(Messages.GUI_SHELL_LS_2, folder, new Integer JavaDoc(resources.size())));
736         Iterator JavaDoc i = resources.iterator();
737         while (i.hasNext()) {
738             CmsResource r = (CmsResource)i.next();
739             System.out.println(m_cms.getSitePath(r));
740         }
741         System.out.println();
742     }
743
744     /**
745      * Lists the access control entries of a given resource.<p>
746      *
747      * @param resourceName the name of the resource
748      * @throws Exception if something goes wrong
749      */

750     public void lsacc(String JavaDoc resourceName) throws Exception JavaDoc {
751
752         List acList = m_cms.getAccessControlEntries(resourceName);
753         for (int i = 0; i < acList.size(); i++) {
754             CmsAccessControlEntry ace = (CmsAccessControlEntry)acList.get(i);
755             I_CmsPrincipal acePrincipal = m_cms.lookupPrincipal(ace.getPrincipal());
756             if (true) {
757                 String JavaDoc pName = (acePrincipal != null) ? acePrincipal.getName() : ace.getPrincipal().toString();
758                 System.out.println(pName + ": " + ace.getPermissions().getPermissionString() + " " + ace);
759             }
760         }
761     }
762
763     /**
764      * Lists the access control entries belonging to the given principal.<p>
765      *
766      * @param resourceName the name of the resource
767      * @param principalName the name of the principal
768      * @throws Exception if something goes wrong
769      */

770     public void lsacc(String JavaDoc resourceName, String JavaDoc principalName) throws Exception JavaDoc {
771
772         I_CmsPrincipal principal = m_cms.lookupPrincipal(principalName);
773         List acList = m_cms.getAccessControlEntries(resourceName);
774         for (int i = 0; i < acList.size(); i++) {
775             CmsAccessControlEntry ace = (CmsAccessControlEntry)acList.get(i);
776             I_CmsPrincipal acePrincipal = m_cms.lookupPrincipal(ace.getPrincipal());
777             if (acePrincipal.equals(principal)) {
778                 String JavaDoc pName = (acePrincipal != null) ? acePrincipal.getName() : ace.getPrincipal().toString();
779                 System.out.println(pName + ": " + ace.getPermissions().getPermissionString() + " " + ace);
780             }
781         }
782     }
783
784     /**
785      * Does performance measurements of the OpenCms core.<p>
786      *
787      * @throws Exception if something goes wrong
788      */

789     public void perf() throws Exception JavaDoc {
790
791         int maxTests = 50000;
792         m_cms.getRequestContext().saveSiteRoot();
793         m_cms.getRequestContext().setSiteRoot("/");
794         try {
795             Random JavaDoc random = new Random JavaDoc();
796             // create a resource filter to get the resources with
797
List testResources = m_cms.readResources("/", CmsResourceFilter.ALL);
798             int resourceCount = testResources.size();
799             System.out.println("#Resources:\t" + resourceCount);
800             long start, time;
801             long totalTime = 0;
802             long minTime = Long.MAX_VALUE;
803             long maxTime = Long.MIN_VALUE;
804             System.out.print("readFileHeader:\t");
805             for (int i = maxTests; i > 0; --i) {
806                 int index = random.nextInt(resourceCount);
807                 CmsResource resource = (CmsResource)testResources.get(index);
808                 start = System.currentTimeMillis();
809                 m_cms.readResource(m_cms.getSitePath(resource), CmsResourceFilter.ALL);
810                 time = System.currentTimeMillis() - start;
811                 totalTime += time;
812                 if (time < minTime) {
813                     minTime = time;
814                 }
815                 if (time > maxTime) {
816                     maxTime = time;
817                 }
818                 if ((i % 100) == 0) {
819                     System.out.print('.');
820                 }
821             }
822             System.out.println("\nreadFileHeader:\t"
823                 + minTime
824                 + "\t"
825                 + maxTime
826                 + "\t"
827                 + (((float)totalTime) / maxTests)
828                 + " ms");
829
830         } finally {
831             m_cms.getRequestContext().restoreSiteRoot();
832         }
833     }
834
835     /**
836      * Sets the current shell prompt.<p>
837      *
838      * @param prompt the prompt to set
839      * @see CmsShell#setPrompt(String)
840      */

841     public void prompt(String JavaDoc prompt) {
842
843         m_shell.setPrompt(prompt);
844     }
845
846     /**
847      * Purges the jsp repository.<p>
848      *
849      * @throws Exception if something goes wrong
850      *
851      * @see org.opencms.flex.CmsFlexCache#cmsEvent(org.opencms.main.CmsEvent)
852      */

853     public void purgeJspRepository() throws Exception JavaDoc {
854
855         OpenCms.fireCmsEvent(new CmsEvent(
856             I_CmsEventListener.EVENT_FLEX_PURGE_JSP_REPOSITORY,
857             new HashMap JavaDoc(0)));
858     }
859
860     /**
861      * Returns the current folder set as URI in the request context.<p>
862      *
863      * @return the current folder
864      * @throws Exception if something goes wrong
865      * @see org.opencms.file.CmsRequestContext#getUri()
866      * @see CmsResource#getFolderPath(String)
867      */

868     public String JavaDoc pwd() throws Exception JavaDoc {
869
870         return CmsResource.getFolderPath(m_cms.getRequestContext().getUri());
871     }
872
873     /**
874      * Exits the shell.<p>
875      *
876      * @see #exit()
877      */

878     public void quit() {
879
880         exit();
881     }
882
883     /**
884      * Returns the selected files contentsls as a String.<p>
885      *
886      * @param filename the file to read the contents from
887      * @throws CmsException if something goes wrong
888      * @return the selected files contents
889      */

890     public String JavaDoc readFileContent(String JavaDoc filename) throws CmsException {
891
892         filename = CmsLinkManager.getAbsoluteUri(
893             filename,
894             CmsResource.getFolderPath(m_cms.getRequestContext().getUri()));
895         CmsFile file = m_cms.readFile(filename, CmsResourceFilter.IGNORE_EXPIRATION);
896         return new String JavaDoc(file.getContents());
897     }
898
899     /**
900      * Returns the users group of a project.<p>
901      *
902      * @param project the id of the project to return the users group for
903      * @return the users group of the project
904      * @throws Exception if something goes wrong
905      */

906     public CmsGroup readGroupOfProject(int project) throws Exception JavaDoc {
907
908         return m_cms.readGroup(m_cms.readProject(project));
909     }
910
911     /**
912      * Returns the manager group of a project.<p>
913      *
914      * @param project the id of the project to return the manager group for
915      * @return the manager group of the project
916      * @throws Exception if something goes wrong
917      */

918     public CmsGroup readManagerGroup(int project) throws Exception JavaDoc {
919
920         return m_cms.readManagerGroup(m_cms.readProject(project));
921     }
922
923     /**
924      * Returns the owner of a project.<p>
925      *
926      * @param project the id of the project
927      * @return the owner of the project
928      * @throws Exception if something goes wrong
929      */

930     public CmsUser readOwnerOfProject(int project) throws Exception JavaDoc {
931
932         return m_cms.readOwner(m_cms.readProject(project));
933     }
934
935     /**
936      * Rebuilds (if required creates) all configured search indexes.<p>
937      *
938      * @throws Exception if something goes wrong
939      *
940      * @see org.opencms.search.CmsSearchManager#rebuildAllIndexes(org.opencms.report.I_CmsReport)
941      */

942     public void rebuildAllIndexes() throws Exception JavaDoc {
943
944         I_CmsReport report = new CmsShellReport(m_cms.getRequestContext().getLocale());
945         try {
946             OpenCms.getSearchManager().rebuildAllIndexes(report, true);
947         } catch (CmsException e) {
948             report.println(e);
949         }
950     }
951
952     /**
953      * Rebuilds (if required creates) the given search index.<p>
954      *
955      * @param index name of the index to update
956      * @throws Exception if something goes wrong
957      * @see org.opencms.search.CmsSearchManager#rebuildIndex(String, org.opencms.report.I_CmsReport)
958      */

959     public void rebuildIndex(String JavaDoc index) throws Exception JavaDoc {
960
961         OpenCms.getSearchManager().rebuildIndex(index, new CmsShellReport(m_cms.getRequestContext().getLocale()));
962     }
963
964     /**
965      * Replaces a module with another revision.<p>
966      *
967      * @param moduleName the name of the module
968      * @param importFile the name of the import file
969      *
970      * @throws Exception if something goes wrong
971      */

972     public void replaceModule(String JavaDoc moduleName, String JavaDoc importFile) throws Exception JavaDoc {
973
974         if (OpenCms.getModuleManager().getModule(moduleName) != null) {
975             OpenCms.getModuleManager().deleteModule(
976                 m_cms,
977                 moduleName,
978                 true,
979                 new CmsShellReport(m_cms.getRequestContext().getLocale()));
980         }
981
982         importModule(importFile);
983     }
984
985     /**
986      * Replaces a module with another revision.<p>
987      *
988      * @param moduleName the name of the module
989      * @param importFile the name of the import file
990      * @throws Exception if something goes wrong
991      */

992     public void replaceModuleFromDefault(String JavaDoc moduleName, String JavaDoc importFile) throws Exception JavaDoc {
993
994         if (OpenCms.getModuleManager().getModule(moduleName) != null) {
995             OpenCms.getModuleManager().deleteModule(
996                 m_cms,
997                 moduleName,
998                 true,
999                 new CmsShellReport(m_cms.getRequestContext().getLocale()));
1000        }
1001
1002        importModuleFromDefault(importFile);
1003    }
1004
1005    /**
1006     * Sets the current project to the provided project id.<p>
1007     *
1008     * @param id the project id to set
1009     * @return the project set
1010     * @throws Exception if something goes wrong
1011     */

1012    public CmsProject setCurrentProject(int id) throws Exception JavaDoc {
1013
1014        return m_cms.getRequestContext().setCurrentProject(m_cms.readProject(id));
1015    }
1016
1017    /**
1018     * Sets the current project to the provided project name.<p>
1019     *
1020     * @param name the project name to set
1021     * @return the project set
1022     * @throws Exception if something goes wrong
1023     */

1024    public CmsProject setCurrentProject(String JavaDoc name) throws Exception JavaDoc {
1025
1026        return m_cms.getRequestContext().setCurrentProject(m_cms.readProject(name));
1027    }
1028
1029    /**
1030     * Set the locale of the current user logged in. <p>
1031     *
1032     * This method will always set a valid Locale for the current user!
1033     * If the provided locale name is not valid (i.e. leads to an Exception
1034     * when trying to create the Locale, then the configured default Locale is set.<p>
1035     *
1036     * The full name must consist of language code,
1037     * country code(optional), variant(optional) separated by "_".<p>
1038     *
1039     * @see Locale#getLanguage()
1040     * @see Locale#getCountry()
1041     * @see Locale#getVariant()
1042     * @param localeName the full locale name
1043     *
1044     * @throws CmsException if something goes wrong
1045     *
1046     */

1047    public void setLocale(String JavaDoc localeName) throws CmsException {
1048
1049        Locale JavaDoc locale = CmsLocaleManager.getLocale(localeName);
1050        System.out.println(getMessages().key(
1051            Messages.GUI_SHELL_SETLOCALE_2,
1052            locale,
1053            m_cms.getRequestContext().currentUser().getName()));
1054
1055        m_shell.setLocale(locale);
1056        System.out.println(getMessages().key(Messages.GUI_SHELL_SETLOCALE_POST_1, locale));
1057    }
1058
1059    /**
1060     * @see org.opencms.main.I_CmsShellCommands#shellExit()
1061     */

1062    public void shellExit() {
1063
1064        System.out.println();
1065        System.out.println(getMessages().key(Messages.GUI_SHELL_GOODBYE_0));
1066    }
1067
1068    /**
1069     * @see org.opencms.main.I_CmsShellCommands#shellStart()
1070     */

1071    public void shellStart() {
1072
1073        System.out.println();
1074        System.out.println(getMessages().key(Messages.GUI_SHELL_WELCOME_0));
1075        System.out.println();
1076
1077        // print the version information
1078
version();
1079        // print the copyright message
1080
copyright();
1081        // print the help information
1082
help();
1083    }
1084
1085    /**
1086     * Unlocks the current project, required before publishing.<p>
1087     * @throws Exception if something goes wrong
1088     */

1089    public void unlockCurrentProject() throws Exception JavaDoc {
1090
1091        m_cms.unlockProject(m_cms.getRequestContext().currentProject().getId());
1092    }
1093
1094    /**
1095     * Loads a file from the "real" file system to the VFS.<p>
1096     *
1097     * @param localfile the file upload
1098     * @param folder the folder in the VFS to place the file into
1099     * @param filename the name of the uploaded file in the VFS
1100     * @param type the type of the new file in the VFS
1101     * @return the createed file
1102     * @throws Exception if something goes wrong
1103     * @throws CmsIllegalArgumentException if the concatenation of String arguments
1104     * <code>folder</code> and <code>localfile</code> is of length 0
1105     *
1106     */

1107    public CmsResource uploadFile(String JavaDoc localfile, String JavaDoc folder, String JavaDoc filename, String JavaDoc type)
1108    throws Exception JavaDoc, CmsIllegalArgumentException {
1109
1110        int t = OpenCms.getResourceManager().getResourceType(type).getTypeId();
1111        return m_cms.createResource(folder + filename, t, CmsFileUtil.readFile(localfile), null);
1112    }
1113
1114    /**
1115     * Returns the version information for this OpenCms instance.<p>
1116     */

1117    public void version() {
1118
1119        System.out.println();
1120        System.out.println(getMessages().key(Messages.GUI_SHELL_VERSION_1, OpenCms.getSystemInfo().getVersionName()));
1121    }
1122
1123    /**
1124     * Returns the current user.<p>
1125     *
1126     * @return the current user
1127     */

1128    public CmsUser whoami() {
1129
1130        return m_cms.getRequestContext().currentUser();
1131    }
1132
1133    /**
1134     * Returns the localized messages object for the current user.<p>
1135     *
1136     * @return the localized messages object for the current user
1137     */

1138    protected CmsMessages getMessages() {
1139
1140        return m_shell.getMessages();
1141    }
1142}
Popular Tags