KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opencms > workplace > CmsAdminDatabase


1 /*
2 * File : $Source: /usr/local/cvs/opencms/src-modules/com/opencms/workplace/CmsAdminDatabase.java,v $
3 * Date : $Date: 2005/06/27 23:22:07 $
4 * Version: $Revision: 1.7 $
5 *
6 * This library is part of OpenCms -
7 * the Open Source Content Mananagement System
8 *
9 * Copyright (C) 2001 The OpenCms Group
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 OpenCms, please see the
22 * OpenCms Website: http://www.opencms.org
23 *
24 * You should have received a copy of the GNU Lesser General Public
25 * License along with this library; if not, write to the Free Software
26 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
27 */

28
29 package com.opencms.workplace;
30
31 import org.opencms.file.CmsObject;
32 import org.opencms.importexport.CmsVfsImportExportHandler;
33 import org.opencms.main.CmsException;
34 import org.opencms.main.CmsLog;
35 import org.opencms.main.OpenCms;
36 import org.opencms.report.A_CmsReportThread;
37 import org.opencms.workplace.threads.CmsDatabaseImportThread;
38 import org.opencms.workplace.threads.CmsExportThread;
39
40 import com.opencms.core.I_CmsSession;
41 import com.opencms.legacy.CmsCosImportExportHandler;
42 import com.opencms.legacy.CmsLegacyException;
43 import com.opencms.legacy.CmsLegacyModuleAction;
44 import com.opencms.legacy.CmsXmlTemplateLoader;
45
46 import java.io.File JavaDoc;
47 import java.io.FileOutputStream JavaDoc;
48 import java.io.OutputStream JavaDoc;
49 import java.util.Arrays JavaDoc;
50 import java.util.Enumeration JavaDoc;
51 import java.util.Hashtable JavaDoc;
52 import java.util.Iterator JavaDoc;
53 import java.util.StringTokenizer JavaDoc;
54 import java.util.Vector JavaDoc;
55
56 /**
57  * This class manages the templates for import and export of the database.<p>
58  *
59  * @author Alexander Kandzior (a.kandzior@alkacon.com)
60  * @author Andreas Schouten
61  * @version $Revision: 1.7 $
62  * @see com.opencms.workplace.CmsXmlWpTemplateFile
63  *
64  * @deprecated Will not be supported past the OpenCms 6 release.
65  */

66 public class CmsAdminDatabase extends CmsWorkplaceDefault {
67
68     private static String JavaDoc C_DATABASE_THREAD = "databse_im_export_thread";
69
70     /**
71      * Gets a database importfile from the client and copys it to the server.<p>
72      *
73      * @param cms The CmsObject.
74      * @param session The session.
75      *
76      * @return the name of the file.
77      */

78     private String JavaDoc copyFileToServer(
79         CmsObject cms,
80         I_CmsSession session )
81     throws CmsException{
82         // get the filename
83
String JavaDoc filename = null;
84         Enumeration JavaDoc files = CmsXmlTemplateLoader.getRequest(cms.getRequestContext()).getFileNames();
85         while(files.hasMoreElements()) {
86             filename = (String JavaDoc)files.nextElement();
87         }
88         if(filename != null) {
89             session.putValue(CmsWorkplaceDefault.C_PARA_RESOURCE, filename);
90         }
91         filename = (String JavaDoc)session.getValue(CmsWorkplaceDefault.C_PARA_RESOURCE);
92
93         // get the filecontent
94
byte[] filecontent = new byte[0];
95         if(filename != null) {
96             filecontent = CmsXmlTemplateLoader.getRequest(cms.getRequestContext()).getFile(filename);
97         }
98         if(filecontent != null) {
99             session.putValue(CmsWorkplaceDefault.C_PARA_FILECONTENT, filecontent);
100         }
101         filecontent = (byte[])session.getValue(CmsWorkplaceDefault.C_PARA_FILECONTENT);
102         // first create the folder if it doesnt exists
103
File JavaDoc discFolder = new File JavaDoc(OpenCms.getSystemInfo().getAbsoluteRfsPathRelativeToWebInf(OpenCms.getSystemInfo().getPackagesRfsPath() + File.separator));
104         if(!discFolder.exists()) {
105             boolean success = discFolder.mkdir();
106             if(CmsLog.getLog(this).isWarnEnabled() && (!success)) {
107                 CmsLog.getLog(this).warn("Couldn't create folder " + discFolder.getAbsolutePath());
108             }
109         }
110
111         // now write the file into the modules dierectory in the exportpaht
112
File JavaDoc discFile = new File JavaDoc(OpenCms.getSystemInfo().getAbsoluteRfsPathRelativeToWebInf(OpenCms.getSystemInfo().getPackagesRfsPath() + File.separator + filename));
113         try {
114
115             // write the new file to disk
116
OutputStream JavaDoc s = new FileOutputStream JavaDoc(discFile);
117             s.write(filecontent);
118             s.close();
119         }
120         catch(Exception JavaDoc e) {
121             throw new CmsLegacyException("[" + this.getClass().getName() + "] " + e.getMessage());
122         }
123         return filename;
124     }
125
126     /**
127      * Gets the content of a defined section in a given template file and its subtemplates
128      * with the given parameters.
129      *
130      * @see #getContent(CmsObject, String, String, Hashtable, String)
131      * @param cms CmsObject Object for accessing system resources.
132      * @param templateFile Filename of the template file.
133      * @param elementName Element name of this template in our parent template.
134      * @param parameters Hashtable with all template class parameters.
135      * @param templateSelector template section that should be processed.
136      */

137     public byte[] getContent(
138         CmsObject cms,
139         String JavaDoc templateFile,
140         String JavaDoc elementName,
141         Hashtable JavaDoc parameters,
142         String JavaDoc templateSelector
143     ) throws CmsException {
144         if(C_DEBUG && CmsLog.getLog(this).isDebugEnabled()) {
145             CmsLog.getLog(this).debug("Getting content of element "
146                             + ((elementName == null) ? "<root>" : elementName));
147             CmsLog.getLog(this).debug("Template file is: " + templateFile);
148             CmsLog.getLog(this).debug("Delected template section is: "
149                             + ((templateSelector == null) ? "<default>" : templateSelector));
150         }
151
152         CmsXmlWpTemplateFile xmlTemplateDocument = new CmsXmlWpTemplateFile(cms, templateFile);
153         I_CmsSession session = CmsXmlTemplateLoader.getSession(cms.getRequestContext(), true);
154         CmsXmlLanguageFile lang = xmlTemplateDocument.getLanguageFile();
155
156         // get the parameters
157
// String folder = (String)parameters.get("selectallfolders");
158
String JavaDoc fileName = (String JavaDoc)parameters.get("filename");
159         String JavaDoc existingFile = (String JavaDoc)parameters.get("existingfile");
160         String JavaDoc action = (String JavaDoc)parameters.get("action");
161         String JavaDoc allResources = (String JavaDoc)parameters.get("ALLRES");
162         String JavaDoc allModules = (String JavaDoc)parameters.get("ALLMOD");
163         String JavaDoc step = (String JavaDoc)parameters.get("step");
164  
165         // here we show the report updates when the threads are allready running.
166
// This is used for import (action=showResult) and for export (action=showExportResult).
167
if("showResult".equals(action)){
168             // thread for import is started and we need to update the report information
169
A_CmsReportThread doTheWork = (A_CmsReportThread)session.getValue(C_DATABASE_THREAD);
170             //still working?
171
if(doTheWork.isAlive()){
172                 xmlTemplateDocument.setData("endMethod", "");
173                 xmlTemplateDocument.setData("text", "");
174             }else{
175                 xmlTemplateDocument.setData("endMethod", xmlTemplateDocument.getDataValue("endMethod"));
176                 xmlTemplateDocument.setData("autoUpdate","");
177                 xmlTemplateDocument.setData("text", lang.getLanguageValue("database.label.importend"));
178                 session.removeValue(C_DATABASE_THREAD);
179             }
180             xmlTemplateDocument.setData("data", doTheWork.getReportUpdate());
181             return startProcessing(cms, xmlTemplateDocument, elementName, parameters, "updateReport");
182         }else if("showExportResult".equals(action)){
183             // thread for emport is started and we need to update the report information
184
A_CmsReportThread doTheWork = (A_CmsReportThread)session.getValue(C_DATABASE_THREAD);
185             //still working?
186
if(doTheWork.isAlive()){
187                 xmlTemplateDocument.setData("endMethod", "");
188                 xmlTemplateDocument.setData("text", "");
189             }else{
190                 xmlTemplateDocument.setData("endMethod", xmlTemplateDocument.getDataValue("endMethod"));
191                 xmlTemplateDocument.setData("autoUpdate","");
192                 xmlTemplateDocument.setData("text", lang.getLanguageValue("database.label.exportend"));
193                 session.removeValue(C_DATABASE_THREAD);
194             }
195             xmlTemplateDocument.setData("data", doTheWork.getReportUpdate());
196             return startProcessing(cms, xmlTemplateDocument, elementName, parameters, "updateReport");
197         }
198
199         if(action == null) {
200             // this is an initial request of the database administration page
201
// generate datablocks for checkboxes in the HTML form
202
if(!cms.getRequestContext().currentProject().isOnlineProject()) {
203                 xmlTemplateDocument.setData("nounchanged",
204                         xmlTemplateDocument.getProcessedDataValue("nounchangedbox", this, parameters));
205             }
206             if(cms.isAdmin()) {
207                 xmlTemplateDocument.setData("userdata",
208                         xmlTemplateDocument.getProcessedDataValue("userdatabox", this, parameters));
209             }
210             xmlTemplateDocument.setData("moduleselect", this.getModuleSelectbox(cms, xmlTemplateDocument));
211         }
212
213         try {
214             if("export".equals(action)) {
215                 // export the VFS
216
Vector JavaDoc resourceNames = parseResources(allResources);
217                 String JavaDoc[] exportPaths = new String JavaDoc[resourceNames.size()];
218                 for(int i = 0;i < resourceNames.size();i++) {
219                     // modify the foldername if nescessary (the root folder is always given
220
// as a nice name)
221
if(lang.getLanguageValue("title.rootfolder").equals(resourceNames.elementAt(i))) {
222                         resourceNames.setElementAt("/", i);
223                     }
224                     exportPaths[i] = (String JavaDoc)resourceNames.elementAt(i);
225                 }
226                 
227                 // default content age is 0 (Unix 1970 time, this should export all resources)
228
long contentAge = 0;
229                 String JavaDoc contentAgePara = (String JavaDoc)parameters.get("contentage");
230                 if (contentAgePara != null && (! "".equals(contentAgePara)) && (! "(none)".equals(contentAgePara))) {
231                     try {
232                         contentAge = Long.parseLong(contentAgePara);
233                     } catch (NumberFormatException JavaDoc numEx) {
234                         // in case a invalid number was returned, use 0 (ie. export all files)
235
contentAge = 0;
236                     }
237                 }
238                 
239                 boolean excludeSystem = false;
240                 if (parameters.get("nosystem") != null) {
241                     excludeSystem = true;
242                 }
243                 boolean excludeUnchanged = false;
244                 if (parameters.get("nounchanged") != null) {
245                     excludeUnchanged = true;
246                 }
247                 boolean exportUserdata = false;
248                 if (parameters.get("userdata") != null) {
249                     exportUserdata = true;
250                 }
251                 
252                 // start the thread for: export
253
CmsVfsImportExportHandler vfsExportHandler = new CmsVfsImportExportHandler();
254                 vfsExportHandler.setFileName(OpenCms.getSystemInfo().getAbsoluteRfsPathRelativeToWebInf(OpenCms.getSystemInfo().getPackagesRfsPath() + File.separator + fileName));
255                 vfsExportHandler.setExportPaths(Arrays.asList(exportPaths));
256                 vfsExportHandler.setIncludeSystem(!excludeSystem);
257                 vfsExportHandler.setIncludeUnchanged(!excludeUnchanged);
258                 vfsExportHandler.setExportUserdata(exportUserdata);
259                 vfsExportHandler.setContentAge(contentAge);
260                 vfsExportHandler.setDescription("Database VFS export to " + vfsExportHandler.getFileName());
261                 A_CmsReportThread doExport = new CmsExportThread(cms, vfsExportHandler, true);
262                                     
263                 doExport.start();
264                 session.putValue(C_DATABASE_THREAD, doExport);
265                 xmlTemplateDocument.setData("time", "10");
266                 xmlTemplateDocument.setData("contentage", "" + contentAge);
267                 xmlTemplateDocument.setData("currenttime", "" + System.currentTimeMillis());
268                 templateSelector = "showresult";
269
270             } else if("exportmoduledata".equals(action)) {
271                 // export the COS and the COS data
272
Vector JavaDoc channelNames = parseResources(allResources);
273                 String JavaDoc[] exportChannels = new String JavaDoc[channelNames.size()];
274                 for (int i = 0;i < channelNames.size();i++) {
275                     // modify the foldername if nescessary (the root folder is always given
276
// as a nice name)
277
if(lang.getLanguageValue("title.rootfolder").equals(channelNames.elementAt(i))) {
278                         channelNames.setElementAt("/", i);
279                     }
280                     exportChannels[i] = (String JavaDoc)channelNames.elementAt(i);
281                 }
282                 
283                 // get the selected modulenames
284
Vector JavaDoc moduleNames = parseResources(allModules);
285                 String JavaDoc[] exportModules = new String JavaDoc[moduleNames.size()];
286                 for (int i = 0;i < moduleNames.size();i++) {
287                     exportModules[i] = (String JavaDoc)moduleNames.elementAt(i);
288                 }
289                 
290                 // start the thread for: exportmodules
291
CmsCosImportExportHandler cosExportHandler = new CmsCosImportExportHandler();
292                 cosExportHandler.setFileName(OpenCms.getSystemInfo().getAbsoluteRfsPathRelativeToWebInf(OpenCms.getSystemInfo().getPackagesRfsPath() + File.separator + fileName));
293                 cosExportHandler.setExportChannels(exportChannels);
294                 cosExportHandler.setExportModules(exportModules);
295                 cosExportHandler.setDescription("Database COS export to " + cosExportHandler.getFileName());
296                 A_CmsReportThread doExport = new CmsExportThread(cms, cosExportHandler, true);
297                                             
298                 doExport.start();
299                 session.putValue(C_DATABASE_THREAD, doExport);
300                 xmlTemplateDocument.setData("time", "10");
301                 xmlTemplateDocument.setData("currenttime", "" + System.currentTimeMillis());
302                 templateSelector = "showresult";
303
304             } else if("import".equals(action)) {
305                 // look for the step
306
if ("local".equals(step) || "server".equals(step)){
307                     templateSelector = step;
308                 } else if("localupload".equals(step)){
309                     // get the filename and set step to 'go'
310
existingFile = copyFileToServer(cms, session);
311                     step = "go";
312                 }
313                 if ("go".equals(step) ){
314                     // start the thread for: import
315
A_CmsReportThread doImport = new CmsDatabaseImportThread(cms,
316                         OpenCms.getSystemInfo().getAbsoluteRfsPathRelativeToWebInf(OpenCms.getSystemInfo().getPackagesRfsPath() + existingFile), true);
317                     doImport.start();
318                     session.putValue(C_DATABASE_THREAD, doImport);
319                     xmlTemplateDocument.setData("time", "10");
320                     templateSelector = "showresult";
321                 }
322             }
323         } catch (CmsException exc) {
324             xmlTemplateDocument.setData("details", CmsException.getStackTraceAsString(exc));
325             templateSelector = "error";
326         }
327
328         // now load the template file and start the processing
329
return startProcessing (cms, xmlTemplateDocument, elementName, parameters, templateSelector);
330     }
331
332     /**
333      * Gets all export-files from the export-path.<p>
334      *
335      * The given vectors <code>names</code> and <code>values</code> will
336      * be filled with the appropriate information to be used for building
337      * a select box.<p>
338      *
339      * <code>names</code> will contain language specific view descriptions
340      * and <code>values</code> will contain the correspondig URL for each
341      * of these views after returning from this method.<p>
342      *
343      * @param cms CmsObject Object for accessing system resources.
344      * @param lang reference to the currently valid language file
345      * @param names Vector to be filled with the appropriate values in this method.
346      * @param values Vector to be filled with the appropriate values in this method.
347      * @param parameters Hashtable containing all user parameters <em>(not used here)</em>.
348      * @return Index representing the user's current filter view in the vectors.
349      * @throws CmsException
350      */

351     public Integer JavaDoc getExportFiles(
352         CmsObject cms,
353         CmsXmlLanguageFile lang,
354         Vector JavaDoc values,
355         Vector JavaDoc names,
356         Hashtable JavaDoc parameters
357     ) throws CmsException {
358         // get the systems-exportpath
359
String JavaDoc exportpath = OpenCms.getSystemInfo().getPackagesRfsPath();
360         exportpath = OpenCms.getSystemInfo().getAbsoluteRfsPathRelativeToWebInf(exportpath);
361         File JavaDoc folder = new File JavaDoc(exportpath);
362         if (!folder.exists()) {
363             folder.mkdirs();
364         }
365         // get a list of all files
366
String JavaDoc[] list = folder.list();
367         for (int i = 0; i < list.length; i++) {
368             try {
369                 File JavaDoc diskFile = new File JavaDoc(exportpath, list[i]);
370                 // check if it is a file
371
if (diskFile.isFile() && diskFile.getName().endsWith(".zip")) {
372                     values.addElement(list[i]);
373                     names.addElement(list[i]);
374                 } else if (diskFile.isDirectory()
375                     && !diskFile.getName().equalsIgnoreCase("modules")
376                     && ((new File JavaDoc(diskFile + File.separator + "manifest.xml")).exists())) {
377                         values.addElement(list[i] + "/");
378                         names.addElement(list[i]);
379                 }
380             } catch (Throwable JavaDoc t) {
381                 // ignore and continue
382
}
383         }
384         return new Integer JavaDoc(0);
385     }
386
387     /**
388      * Indicates that the results of this class are not cacheable.<p>
389      *
390      * @param cms CmsObject Object for accessing system resources
391      * @param templateFile Filename of the template file
392      * @param elementName Element name of this template in our parent template.
393      * @param parameters Hashtable with all template class parameters.
394      * @param templateSelector template section that should be processed.
395      * @return <code>false</code>
396      */

397     public boolean isCacheable(
398         CmsObject cms,
399         String JavaDoc templateFile,
400         String JavaDoc elementName,
401         Hashtable JavaDoc parameters,
402         String JavaDoc templateSelector
403     ) {
404         return false;
405     }
406
407     /**
408      * Gets all exportable modules for a select box.<p>
409      *
410      * The given vectors <code>names</code> and <code>values</code> will
411      * be filled with the appropriate information to be used for building
412      * a select box.<p>
413      *
414      * @param cms CmsObject Object for accessing system resources.
415      * @param names Vector to be filled with the appropriate values in this method.
416      * @param values Vector to be filled with the appropriate values in this method.
417      * @param parameters Hashtable containing all user parameters <em>(not used here)</em>.
418      * @return Index representing the current value in the vectors.
419      * @throws CmsException
420      */

421     public int getModules(
422         CmsObject cms,
423         CmsXmlLanguageFile lang,
424         Vector JavaDoc names,
425         Vector JavaDoc values,
426         Hashtable JavaDoc parameters
427     ) throws CmsException {
428         // get all exportable modules
429
Iterator JavaDoc it = CmsLegacyModuleAction.getLegacyModulePublishClasses().iterator();
430         // fill the names and values
431
while (it.hasNext()) {
432             String JavaDoc name = (String JavaDoc)it.next();
433             String JavaDoc value = name;
434             names.addElement(name);
435             values.addElement(value);
436         }
437         return 0;
438     }
439
440     /**
441      * Gets all exportable modules for a select box.<p>
442      *
443      * The method returns a string with option tags that contains the module information
444      * to be used for building a select box.<p>
445      *
446      * @param cms CmsObject Object for accessing system resources.
447      * @param template The current template
448      * @return String with the modules optiontags.
449      * @throws CmsException
450      */

451     public String JavaDoc getModuleSelectbox(
452         CmsObject cms,
453         CmsXmlWpTemplateFile template
454     ) throws CmsException {
455         StringBuffer JavaDoc selectBox = new StringBuffer JavaDoc();
456         if (template.hasData("selectoption")) {
457             // get all exportable modules
458
Iterator JavaDoc it = CmsLegacyModuleAction.getLegacyModulePublishClasses().iterator();
459             while (it.hasNext()) {
460                 String JavaDoc name = (String JavaDoc)it.next();
461                 String JavaDoc value = name;
462                 template.setData("name", name);
463                 template.setData("value", value);
464                 try {
465                     selectBox.append(template.getProcessedDataValue("selectoption", this));
466                 } catch (Exception JavaDoc e) {
467                     // do not throw exception because selectbox might not exist
468
}
469             }
470         }
471         return selectBox.toString();
472     }
473
474     /**
475      * Parse the string which holds all resources.<p>
476      *
477      * @param resources containts the full pathnames of all the resources, separated by semicolons
478      * @return A vector with the same resources
479      */

480     private Vector JavaDoc parseResources(
481         String JavaDoc resources
482     ) {
483         Vector JavaDoc ret = new Vector JavaDoc();
484         if (resources != null) {
485             StringTokenizer JavaDoc resTokenizer = new StringTokenizer JavaDoc(resources, ";");
486             while (resTokenizer.hasMoreElements()) {
487                 String JavaDoc path = (String JavaDoc)resTokenizer.nextElement();
488                 ret.addElement(path);
489             }
490         }
491         return ret;
492     }
493 }
494
Popular Tags