KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opencms > importexport > CmsExport


1 /*
2  * File : $Source: /usr/local/cvs/opencms/src/org/opencms/importexport/CmsExport.java,v $
3  * Date : $Date: 2006/03/27 14:52:54 $
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.importexport;
33
34 import org.opencms.file.CmsFile;
35 import org.opencms.file.CmsFolder;
36 import org.opencms.file.CmsGroup;
37 import org.opencms.file.CmsObject;
38 import org.opencms.file.CmsProperty;
39 import org.opencms.file.CmsResource;
40 import org.opencms.file.CmsResourceFilter;
41 import org.opencms.file.CmsUser;
42 import org.opencms.file.CmsVfsException;
43 import org.opencms.i18n.CmsMessageContainer;
44 import org.opencms.loader.CmsLoaderException;
45 import org.opencms.main.CmsEvent;
46 import org.opencms.main.CmsException;
47 import org.opencms.main.CmsLog;
48 import org.opencms.main.I_CmsEventListener;
49 import org.opencms.main.OpenCms;
50 import org.opencms.report.CmsShellReport;
51 import org.opencms.report.I_CmsReport;
52 import org.opencms.security.CmsAccessControlEntry;
53 import org.opencms.security.CmsRole;
54 import org.opencms.security.CmsRoleViolationException;
55 import org.opencms.util.CmsDateUtil;
56 import org.opencms.util.CmsFileUtil;
57 import org.opencms.util.CmsUUID;
58 import org.opencms.util.CmsXmlSaxWriter;
59 import org.opencms.workplace.CmsWorkplace;
60
61 import java.io.ByteArrayOutputStream JavaDoc;
62 import java.io.FileOutputStream JavaDoc;
63 import java.io.IOException JavaDoc;
64 import java.io.ObjectOutputStream JavaDoc;
65 import java.io.StringWriter JavaDoc;
66 import java.util.ArrayList JavaDoc;
67 import java.util.Collections JavaDoc;
68 import java.util.HashSet JavaDoc;
69 import java.util.Iterator JavaDoc;
70 import java.util.List JavaDoc;
71 import java.util.Set JavaDoc;
72 import java.util.zip.ZipEntry JavaDoc;
73 import java.util.zip.ZipOutputStream JavaDoc;
74
75 import org.apache.commons.codec.binary.Base64;
76 import org.apache.commons.logging.Log;
77
78 import org.dom4j.Document;
79 import org.dom4j.DocumentHelper;
80 import org.dom4j.Element;
81 import org.dom4j.io.SAXWriter;
82 import org.xml.sax.SAXException JavaDoc;
83
84 /**
85  * Provides the functionality to export files from the OpenCms VFS to a ZIP file.<p>
86  *
87  * The ZIP file written will contain a copy of all exported files with their contents.
88  * It will also contain a <code>manifest.xml</code> file in wich all meta-information
89  * about this files are stored, like permissions etc.<p>
90  *
91  * @author Alexander Kandzior
92  * @author Michael Emmerich
93  *
94  * @version $Revision: 1.84 $
95  *
96  * @since 6.0.0
97  */

98 public class CmsExport {
99
100     /** The log object for this class. */
101     private static final Log LOG = CmsLog.getLog(CmsExport.class);
102
103     private static final int SUB_LENGTH = 4096;
104
105     /** The CmsObject to do the operations. */
106     private CmsObject m_cms;
107
108     /** Max file age of contents to export. */
109     private long m_contentAge;
110
111     /** Counter for the export. */
112     private int m_exportCount;
113
114     /** Set of all exported pages, required for later page body file export. */
115     private Set JavaDoc m_exportedPageFiles;
116
117     /** Set of all exported files, required for later page body file export. */
118     private Set JavaDoc m_exportedResources;
119
120     /** The export ZIP file to store resources in. */
121     private String JavaDoc m_exportFileName;
122
123     /** Indicates if the user data and group data should be included to the export. */
124     private boolean m_exportUserdata;
125
126     /** Indicates if the webuser data should be included to the export. */
127     private boolean m_exportWebusers;
128
129     /** The export ZIP stream to write resources to. */
130     private ZipOutputStream JavaDoc m_exportZipStream;
131
132     /** Indicates if the system should be included to the export. */
133     private boolean m_includeSystem;
134
135     /** Indicates if the unchanged resources should be included to the export .*/
136     private boolean m_includeUnchanged;
137
138     /** Recursive flag, if set the folders are exported recursively. */
139     private boolean m_recursive;
140
141     /** The report for the log messages. */
142     private I_CmsReport m_report;
143
144     /** The top level file node where all resources are appended to. */
145     private Element m_resourceNode;
146
147     /** The SAX writer to write the output to. */
148     private SAXWriter m_saxWriter;
149
150     /** Cache for previously added super folders. */
151     private List JavaDoc m_superFolders;
152
153     /**
154      * Constructs a new uninitialized export, required for special subclass data export.<p>
155      */

156     public CmsExport() {
157
158         // empty constructor
159
}
160
161     /**
162      * Constructs a new export.<p>
163      *
164      * @param cms the cmsObject to work with
165      * @param exportFile the file or folder to export to
166      * @param resourcesToExport the paths of folders and files to export
167      * @param includeSystem if true, the system folder is included
168      * @param includeUnchanged <code>true</code>, if unchanged files should be included
169      * @throws CmsImportExportException if something goes wrong
170      * @throws CmsRoleViolationException if the current user has not the required role
171      */

172     public CmsExport(
173         CmsObject cms,
174         String JavaDoc exportFile,
175         List JavaDoc resourcesToExport,
176         boolean includeSystem,
177         boolean includeUnchanged)
178     throws CmsImportExportException, CmsRoleViolationException {
179
180         this(cms, exportFile, resourcesToExport, includeSystem, includeUnchanged, null, false, 0, new CmsShellReport(
181             cms.getRequestContext().getLocale()));
182     }
183
184     /**
185      * Constructs a new export.<p>
186      *
187      * @param cms the cmsObject to work with
188      * @param exportFile the file or folder to export to
189      * @param resourcesToExport the paths of folders and files to export
190      * @param includeSystem if true, the system folder is included
191      * @param includeUnchanged <code>true</code>, if unchanged files should be included
192      * @param moduleElement module informations in a Node for module export
193      * @param exportUserdata if true, the user and group data will also be exported
194      * @param exportWebusers if true, the webuser data will also be exported
195      * @param contentAge export contents changed after this date/time
196      * @param report to handle the log messages
197      * @param recursive recursive flag
198      *
199      * @throws CmsImportExportException if something goes wrong
200      * @throws CmsRoleViolationException if the current user has not the required role
201      */

202     public CmsExport(
203         CmsObject cms,
204         String JavaDoc exportFile,
205         List JavaDoc resourcesToExport,
206         boolean includeSystem,
207         boolean includeUnchanged,
208         Element moduleElement,
209         boolean exportUserdata,
210         boolean exportWebusers,
211         long contentAge,
212         I_CmsReport report,
213         boolean recursive)
214     throws CmsImportExportException, CmsRoleViolationException {
215
216         setCms(cms);
217         setReport(report);
218         setExportFileName(exportFile);
219
220         // check if the user has the required permissions
221
cms.checkRole(CmsRole.EXPORT_DATABASE);
222
223         m_includeSystem = includeSystem;
224         m_includeUnchanged = includeUnchanged;
225         m_exportUserdata = exportUserdata;
226         m_exportWebusers = exportWebusers;
227         m_contentAge = contentAge;
228         m_exportCount = 0;
229         m_recursive = recursive;
230
231         // clear all caches
232
report.println(Messages.get().container(Messages.RPT_CLEARCACHE_0), I_CmsReport.FORMAT_NOTE);
233         OpenCms.fireCmsEvent(new CmsEvent(I_CmsEventListener.EVENT_CLEAR_CACHES, Collections.EMPTY_MAP));
234
235         try {
236             Element exportNode = openExportFile();
237
238             if (moduleElement != null) {
239                 // add the module element
240
exportNode.add(moduleElement);
241                 // write the XML
242
digestElement(exportNode, moduleElement);
243             }
244
245             exportAllResources(exportNode, resourcesToExport);
246
247             // export userdata and groupdata if selected
248
if (m_exportUserdata || m_exportWebusers) {
249                 Element userGroupData = exportNode.addElement(CmsImportExportManager.N_USERGROUPDATA);
250                 getSaxWriter().writeOpen(userGroupData);
251
252                 exportGroups(userGroupData);
253                 exportUsers(userGroupData);
254
255                 getSaxWriter().writeClose(userGroupData);
256                 exportNode.remove(userGroupData);
257             }
258
259             closeExportFile(exportNode);
260         } catch (SAXException JavaDoc se) {
261             getReport().println(se);
262
263             CmsMessageContainer message = Messages.get().container(
264                 Messages.ERR_IMPORTEXPORT_ERROR_EXPORTING_TO_FILE_1,
265                 getExportFileName());
266             if (LOG.isDebugEnabled()) {
267                 LOG.debug(message.key(), se);
268             }
269
270             throw new CmsImportExportException(message, se);
271         } catch (IOException JavaDoc ioe) {
272             getReport().println(ioe);
273
274             CmsMessageContainer message = Messages.get().container(
275                 Messages.ERR_IMPORTEXPORT_ERROR_EXPORTING_TO_FILE_1,
276                 getExportFileName());
277             if (LOG.isDebugEnabled()) {
278                 LOG.debug(message.key(), ioe);
279             }
280
281             throw new CmsImportExportException(message, ioe);
282         }
283     }
284
285     /**
286      * Constructs a new export.<p>
287      *
288      * @param cms the cmsObject to work with
289      * @param exportFile the file or folder to export to
290      * @param resourcesToExport the paths of folders and files to export
291      * @param includeSystem if true, the system folder is included
292      * @param includeUnchanged <code>true</code>, if unchanged files should be included
293      * @param moduleElement module informations in a Node for module export
294      * @param exportUserdata if true, the user and grou pdata will also be exported
295      * @param contentAge export contents changed after this date/time
296      * @param report to handle the log messages
297      *
298      * @throws CmsImportExportException if something goes wrong
299      * @throws CmsRoleViolationException if the current user has not the required role
300      */

301     public CmsExport(
302         CmsObject cms,
303         String JavaDoc exportFile,
304         List JavaDoc resourcesToExport,
305         boolean includeSystem,
306         boolean includeUnchanged,
307         Element moduleElement,
308         boolean exportUserdata,
309         long contentAge,
310         I_CmsReport report)
311     throws CmsImportExportException, CmsRoleViolationException {
312
313         this(
314             cms,
315             exportFile,
316             resourcesToExport,
317             includeSystem,
318             includeUnchanged,
319             moduleElement,
320             exportUserdata,
321             contentAge,
322             report,
323             true);
324     }
325
326     /**
327      * Constructs a new export.<p>
328      *
329      * @param cms the cmsObject to work with
330      * @param exportFile the file or folder to export to
331      * @param resourcesToExport the paths of folders and files to export
332      * @param includeSystem if true, the system folder is included
333      * @param includeUnchanged <code>true</code>, if unchanged files should be included
334      * @param moduleElement module informations in a Node for module export
335      * @param exportUserdata if true, the user and grou pdata will also be exported
336      * @param contentAge export contents changed after this date/time
337      * @param report to handle the log messages
338      * @param recursive recursive flag
339      *
340      * @throws CmsImportExportException if something goes wrong
341      * @throws CmsRoleViolationException if the current user has not the required role
342      */

343     public CmsExport(
344         CmsObject cms,
345         String JavaDoc exportFile,
346         List JavaDoc resourcesToExport,
347         boolean includeSystem,
348         boolean includeUnchanged,
349         Element moduleElement,
350         boolean exportUserdata,
351         long contentAge,
352         I_CmsReport report,
353         boolean recursive)
354     throws CmsImportExportException, CmsRoleViolationException {
355
356         this(
357             cms,
358             exportFile,
359             resourcesToExport,
360             includeSystem,
361             includeUnchanged,
362             moduleElement,
363             exportUserdata,
364             false,
365             contentAge,
366             report,
367             recursive);
368     }
369
370     /**
371      * Exports the given folder and all child resources.<p>
372      *
373      * @param folderName to complete path to the resource to export
374      * @throws CmsImportExportException if something goes wrong
375      * @throws SAXException if something goes wrong procesing the manifest.xml
376      * @throws IOException if not all resources could be appended to the ZIP archive
377      */

378     protected void addChildResources(String JavaDoc folderName) throws CmsImportExportException, IOException JavaDoc, SAXException JavaDoc {
379
380         try {
381             // get all subFolders
382
List JavaDoc subFolders = getCms().getSubFolders(folderName, CmsResourceFilter.IGNORE_EXPIRATION);
383             // get all files in folder
384
List JavaDoc subFiles = getCms().getFilesInFolder(folderName, CmsResourceFilter.IGNORE_EXPIRATION);
385
386             // walk through all files and export them
387
for (int i = 0; i < subFiles.size(); i++) {
388                 CmsResource file = (CmsResource)subFiles.get(i);
389                 int state = file.getState();
390                 long age = file.getDateLastModified() < file.getDateCreated() ? file.getDateCreated()
391                 : file.getDateLastModified();
392
393                 if (getCms().getRequestContext().currentProject().isOnlineProject()
394                     || (m_includeUnchanged)
395                     || state == CmsResource.STATE_NEW
396                     || state == CmsResource.STATE_CHANGED) {
397                     if ((state != CmsResource.STATE_DELETED)
398                         && (!file.getName().startsWith("~"))
399                         && (age >= m_contentAge)) {
400                         String JavaDoc export = getCms().getSitePath(file);
401                         if (checkExportResource(export)) {
402                             exportFile(getCms().readFile(export, CmsResourceFilter.IGNORE_EXPIRATION));
403                         }
404                     }
405                 }
406                 // release file header memory
407
subFiles.set(i, null);
408             }
409             // all files are exported, release memory
410
subFiles = null;
411
412             // walk through all subfolders and export them
413
for (int i = 0; i < subFolders.size(); i++) {
414                 CmsResource folder = (CmsResource)subFolders.get(i);
415                 if (folder.getState() != CmsResource.STATE_DELETED) {
416                     // check if this is a system-folder and if it should be included.
417
String JavaDoc export = getCms().getSitePath(folder);
418                     if (checkExportResource(export)) {
419
420                         long age = folder.getDateLastModified() < folder.getDateCreated() ? folder.getDateCreated()
421                         : folder.getDateLastModified();
422                         // export this folder only if age is above selected age
423
// default for selected age (if not set by user) is <code>long 0</code> (i.e. 1970)
424
if (age >= m_contentAge) {
425                             // only export folder data to manifest.xml if it has changed
426
appendResourceToManifest(folder, false);
427                         }
428
429                         // export all sub-resources in this folder
430
addChildResources(getCms().getSitePath(folder));
431                     }
432                 }
433                 // release folder memory
434
subFolders.set(i, null);
435             }
436         } catch (CmsImportExportException e) {
437
438             throw e;
439         } catch (CmsException e) {
440
441             CmsMessageContainer message = Messages.get().container(
442                 Messages.ERR_IMPORTEXPORT_ERROR_ADDING_CHILD_RESOURCES_1,
443                 folderName);
444             if (LOG.isDebugEnabled()) {
445                 LOG.debug(message.key(), e);
446             }
447
448             throw new CmsImportExportException(message, e);
449         }
450     }
451
452     /**
453      * Closes the export ZIP file and saves the XML document for the manifest.<p>
454      *
455      * @param exportNode the export root node
456      * @throws SAXException if something goes wrong procesing the manifest.xml
457      * @throws IOException if something goes wrong while closing the export file
458      */

459     protected void closeExportFile(Element exportNode) throws IOException JavaDoc, SAXException JavaDoc {
460
461         // close the <export> Tag
462
getSaxWriter().writeClose(exportNode);
463
464         // close the XML document
465
CmsXmlSaxWriter xmlSaxWriter = (CmsXmlSaxWriter)getSaxWriter().getContentHandler();
466         xmlSaxWriter.endDocument();
467
468         // create zip entry for the manifest XML document
469
ZipEntry JavaDoc entry = new ZipEntry JavaDoc(CmsImportExportManager.EXPORT_MANIFEST);
470         getExportZipStream().putNextEntry(entry);
471
472         // complex substring operation is required to ensure handling for very large export manifest files
473
StringBuffer JavaDoc result = ((StringWriter JavaDoc)xmlSaxWriter.getWriter()).getBuffer();
474         int steps = result.length() / SUB_LENGTH;
475         int rest = result.length() % SUB_LENGTH;
476         int pos = 0;
477         for (int i = 0; i < steps; i++) {
478             String JavaDoc sub = result.substring(pos, pos + SUB_LENGTH);
479             getExportZipStream().write(sub.getBytes(OpenCms.getSystemInfo().getDefaultEncoding()));
480             pos += SUB_LENGTH;
481         }
482         if (rest > 0) {
483             String JavaDoc sub = result.substring(pos, pos + rest);
484             getExportZipStream().write(sub.getBytes(OpenCms.getSystemInfo().getDefaultEncoding()));
485         }
486
487         // close the zip entry for the manifest XML document
488
getExportZipStream().closeEntry();
489
490         // finally close the zip stream
491
getExportZipStream().close();
492     }
493
494     /**
495      * Writes the output element to the XML output writer and detaches it
496      * from it's parent element.<p>
497      *
498      * @param parent the parent element
499      * @param output the output element
500      * @throws SAXException if something goes wrong procesing the manifest.xml
501      */

502     protected void digestElement(Element parent, Element output) throws SAXException JavaDoc {
503
504         m_saxWriter.write(output);
505         parent.remove(output);
506     }
507
508     /**
509      * Exports all resources and possible sub-folders form the provided list of resources.
510      *
511      * @param parent the parent node to add the resources to
512      * @param resourcesToExport the list of resources to export
513      * @throws CmsImportExportException if something goes wrong
514      * @throws SAXException if something goes wrong procesing the manifest.xml
515      * @throws IOException if not all resources could be appended to the ZIP archive
516      */

517     protected void exportAllResources(Element parent, List JavaDoc resourcesToExport)
518     throws CmsImportExportException, IOException JavaDoc, SAXException JavaDoc {
519
520         // export all the resources
521
String JavaDoc resourceNodeName = getResourceNodeName();
522         m_resourceNode = parent.addElement(resourceNodeName);
523         getSaxWriter().writeOpen(m_resourceNode);
524
525         if (m_recursive) {
526             // remove the possible redundancies in the list of resources
527
resourcesToExport = CmsFileUtil.removeRedundancies(resourcesToExport);
528         }
529
530         // distinguish folder and file names
531
List JavaDoc folderNames = new ArrayList JavaDoc();
532         List JavaDoc fileNames = new ArrayList JavaDoc();
533         Iterator JavaDoc it = resourcesToExport.iterator();
534         while (it.hasNext()) {
535             String JavaDoc resource = (String JavaDoc)it.next();
536             if (CmsResource.isFolder(resource)) {
537                 folderNames.add(resource);
538             } else {
539                 fileNames.add(resource);
540             }
541         }
542
543         // init sets required for the body file exports
544
m_exportedResources = new HashSet JavaDoc();
545         m_exportedPageFiles = new HashSet JavaDoc();
546
547         // export the folders
548
for (int i = 0; i < folderNames.size(); i++) {
549             String JavaDoc path = (String JavaDoc)folderNames.get(i);
550             if (m_recursive) {
551                 // first add superfolders to the xml-config file
552
addParentFolders(path);
553                 addChildResources(path);
554             } else {
555                 CmsFolder folder;
556                 try {
557                     folder = getCms().readFolder(path, CmsResourceFilter.IGNORE_EXPIRATION);
558                 } catch (CmsException e) {
559                     CmsMessageContainer message = Messages.get().container(
560                         Messages.ERR_IMPORTEXPORT_ERROR_ADDING_PARENT_FOLDERS_1,
561                         path);
562                     if (LOG.isDebugEnabled()) {
563                         LOG.debug(message.key(), e);
564                     }
565                     throw new CmsImportExportException(message, e);
566                 }
567                 int state = folder.getState();
568                 long age = folder.getDateLastModified() < folder.getDateCreated() ? folder.getDateCreated()
569                 : folder.getDateLastModified();
570
571                 if (getCms().getRequestContext().currentProject().isOnlineProject()
572                     || (m_includeUnchanged)
573                     || state == CmsResource.STATE_NEW
574                     || state == CmsResource.STATE_CHANGED) {
575                     if ((state != CmsResource.STATE_DELETED) && (age >= m_contentAge)) {
576                         // check if this is a system-folder and if it should be included.
577
String JavaDoc export = getCms().getSitePath(folder);
578                         if (checkExportResource(export)) {
579                             appendResourceToManifest(folder, false);
580                         }
581                     }
582                 }
583             }
584             m_exportedResources.add(path);
585         }
586         // export the files
587
addFiles(fileNames);
588         // export all body files that have not already been exported
589
addPageBodyFiles();
590
591         // write the XML
592
getSaxWriter().writeClose(m_resourceNode);
593         parent.remove(m_resourceNode);
594         m_resourceNode = null;
595     }
596
597     /**
598      * Returns the OpenCms context object this export was initialized with.<p>
599      *
600      * @return the OpenCms context object this export was initialized with
601      */

602     protected CmsObject getCms() {
603
604         return m_cms;
605     }
606
607     /**
608      * Returns the name of the export file.<p>
609      *
610      * @return the name of the export file
611      */

612     protected String JavaDoc getExportFileName() {
613
614         return m_exportFileName;
615     }
616
617     /**
618      * Returns the name of the main export node.<p>
619      *
620      * @return the name of the main export node
621      */

622     protected String JavaDoc getExportNodeName() {
623
624         return CmsImportExportManager.N_EXPORT;
625     }
626
627     /**
628      * Returns the zip output stream to write to.<p>
629      *
630      * @return the zip output stream to write to
631      */

632     protected ZipOutputStream JavaDoc getExportZipStream() {
633
634         return m_exportZipStream;
635     }
636
637     /**
638      * Returns the report to write progess messages to.<p>
639      *
640      * @return the report to write progess messages to
641      */

642     protected I_CmsReport getReport() {
643
644         return m_report;
645     }
646
647     /**
648      * Returns the name for the main resource node.<p>
649      *
650      * @return the name for the main resource node
651      */

652     protected String JavaDoc getResourceNodeName() {
653
654         return "files";
655     }
656
657     /**
658      * Returns the SAX baesed xml writer to write the XML output to.<p>
659      *
660      * @return the SAX baesed xml writer to write the XML output to
661      */

662     protected SAXWriter getSaxWriter() {
663
664         return m_saxWriter;
665     }
666
667     /**
668      * Checks if a property should be written to the export or not.<p>
669      *
670      * @param property the property to check
671      * @return if true, the property is to be ignored, otherwise it should be exported
672      */

673     protected boolean isIgnoredProperty(CmsProperty property) {
674
675         if (property == null) {
676             return true;
677         }
678         // default implementation is to export all properties not null
679
return false;
680     }
681
682     /**
683      * Opens the export ZIP file and initializes the internal XML document for the manifest.<p>
684      *
685      * @return the node in the XML document where all files are appended to
686      * @throws SAXException if something goes wrong procesing the manifest.xml
687      * @throws IOException if something goes wrong while closing the export file
688      */

689     protected Element openExportFile() throws IOException JavaDoc, SAXException JavaDoc {
690
691         // create the export-zipstream
692
setExportZipStream(new ZipOutputStream JavaDoc(new FileOutputStream JavaDoc(getExportFileName())));
693         // generate the SAX XML writer
694
CmsXmlSaxWriter saxHandler = new CmsXmlSaxWriter(
695             new StringWriter JavaDoc(4096),
696             OpenCms.getSystemInfo().getDefaultEncoding());
697         saxHandler.setEscapeXml(true);
698         saxHandler.setEscapeUnknownChars(true);
699         // initialize the dom4j writer object as member variable
700
setSaxWriter(new SAXWriter(saxHandler, saxHandler));
701         // the XML document to write the XMl to
702
Document doc = DocumentHelper.createDocument();
703         // start the document
704
saxHandler.startDocument();
705
706         // the node in the XML document where the file entries are appended to
707
String JavaDoc exportNodeName = getExportNodeName();
708         // add main export node to XML document
709
Element exportNode = doc.addElement(exportNodeName);
710         getSaxWriter().writeOpen(exportNode);
711
712         // add the info element. it contains all infos for this export
713
Element info = exportNode.addElement(CmsImportExportManager.N_INFO);
714         info.addElement(CmsImportExportManager.N_CREATOR).addText(getCms().getRequestContext().currentUser().getName());
715         info.addElement(CmsImportExportManager.N_OC_VERSION).addText(OpenCms.getSystemInfo().getVersionName());
716         info.addElement(CmsImportExportManager.N_DATE).addText(CmsDateUtil.getHeaderDate(System.currentTimeMillis()));
717         info.addElement(CmsImportExportManager.N_PROJECT).addText(
718             getCms().getRequestContext().currentProject().getName());
719         info.addElement(CmsImportExportManager.N_VERSION).addText(CmsImportExportManager.EXPORT_VERSION);
720
721         // write the XML
722
digestElement(exportNode, info);
723
724         return exportNode;
725     }
726
727     /**
728      * Sets the OpenCms context object this export was initialized with.<p>
729      *
730      * @param cms the OpenCms context object this export was initialized with
731      */

732     protected void setCms(CmsObject cms) {
733
734         m_cms = cms;
735     }
736
737     /**
738      * Sets the name of the export file.<p>
739      *
740      * @param exportFileName the name of the export file
741      */

742     protected void setExportFileName(String JavaDoc exportFileName) {
743
744         // ensure the export file name ends with ".zip"
745
if (!exportFileName.toLowerCase().endsWith(".zip")) {
746             m_exportFileName = exportFileName + ".zip";
747         } else {
748             m_exportFileName = exportFileName;
749         }
750     }
751
752     /**
753      * Sets the zip output stream to write to.<p>
754      *
755      * @param exportZipStream the zip output stream to write to
756      */

757     protected void setExportZipStream(ZipOutputStream JavaDoc exportZipStream) {
758
759         m_exportZipStream = exportZipStream;
760     }
761
762     /**
763      * Sets the report to write progess messages to.<p>
764      *
765      * @param report the report to write progess messages to
766      */

767     protected void setReport(I_CmsReport report) {
768
769         m_report = report;
770     }
771
772     /**
773      * Sets the SAX baesed xml writer to write the XML output to.<p>
774      *
775      * @param saxWriter the SAX baesed xml writer to write the XML output to
776      */

777     protected void setSaxWriter(SAXWriter saxWriter) {
778
779         m_saxWriter = saxWriter;
780     }
781
782     /**
783      * Adds all files in fileNames to the manifest.xml file.<p>
784      *
785      * @param fileNames list of path Strings, e.g. <code>/folder/index.html</code>
786      *
787      * @throws CmsImportExportException if something goes wrong
788      * @throws IOException if a file could not be exported
789      * @throws SAXException if something goes wrong procesing the manifest.xml
790      */

791     private void addFiles(List JavaDoc fileNames) throws CmsImportExportException, IOException JavaDoc, SAXException JavaDoc {
792
793         if (fileNames != null) {
794             for (int i = 0; i < fileNames.size(); i++) {
795                 String JavaDoc fileName = (String JavaDoc)fileNames.get(i);
796
797                 try {
798                     CmsFile file = getCms().readFile(fileName, CmsResourceFilter.IGNORE_EXPIRATION);
799                     if ((file.getState() != CmsResource.STATE_DELETED) && (!file.getName().startsWith("~"))) {
800                         if (checkExportResource(fileName)) {
801                             if (m_recursive) {
802                                 addParentFolders(fileName);
803                             }
804                             exportFile(file);
805                         }
806                     }
807                 } catch (CmsImportExportException e) {
808
809                     throw e;
810                 } catch (CmsException e) {
811                     if (e instanceof CmsVfsException) { // file not found
812
CmsMessageContainer message = Messages.get().container(
813                             Messages.ERR_IMPORTEXPORT_ERROR_ADDING_FILE_1,
814                             fileName);
815                         if (LOG.isDebugEnabled()) {
816                             LOG.debug(message.key(), e);
817                         }
818
819                         throw new CmsImportExportException(message, e);
820                     }
821                 }
822             }
823         }
824     }
825
826     /**
827      * Exports all page body files that have not explicityl been added by the user.<p>
828      *
829      * @throws CmsImportExportException if something goes wrong
830      * @throws IOException if a file could not be exported
831      * @throws SAXException if something goes wrong procesing the manifest.xml
832      */

833     private void addPageBodyFiles() throws CmsImportExportException, IOException JavaDoc, SAXException JavaDoc {
834
835         Iterator JavaDoc i;
836
837         List JavaDoc bodyFileNames = new ArrayList JavaDoc();
838         String JavaDoc bodyPath = CmsCompatibleCheck.VFS_PATH_BODIES.substring(
839             0,
840             CmsCompatibleCheck.VFS_PATH_BODIES.lastIndexOf("/"));
841
842         // check all exported page files if their body has already been exported
843
i = m_exportedPageFiles.iterator();
844         while (i.hasNext()) {
845             String JavaDoc filename = (String JavaDoc)i.next();
846             // check if the site path is within the filename. If so,this export is
847
// started from the root site and the path to the bodies must be modifed
848
// this is not nice, but it works.
849
if (filename.startsWith(CmsResource.VFS_FOLDER_SITES)) {
850                 filename = filename.substring(CmsResource.VFS_FOLDER_SITES.length() + 1, filename.length());
851                 filename = filename.substring(filename.indexOf("/"), filename.length());
852             }
853             String JavaDoc body = bodyPath + filename;
854             bodyFileNames.add(body);
855         }
856
857         // now export the body files that have not already been exported
858
addFiles(bodyFileNames);
859     }
860
861     /**
862      * Adds the parent folders of the given resource to the config file,
863      * starting at the top, excluding the root folder.<p>
864      *
865      * @param resourceName the name of a resource in the VFS
866      * @throws CmsImportExportException if something goes wrong
867      * @throws SAXException if something goes wrong procesing the manifest.xml
868      */

869     private void addParentFolders(String JavaDoc resourceName) throws CmsImportExportException, SAXException JavaDoc {
870
871         try {
872             // this is a resource in /system/ folder and option includeSystem is not true
873
if (!checkExportResource(resourceName)) {
874                 return;
875             }
876
877             // Initialize the "previously added folder cache"
878
if (m_superFolders == null) {
879                 m_superFolders = new ArrayList JavaDoc();
880             }
881             List JavaDoc superFolders = new ArrayList JavaDoc();
882
883             // Check, if the path is really a folder
884
if (resourceName.lastIndexOf("/") != (resourceName.length() - 1)) {
885                 resourceName = resourceName.substring(0, resourceName.lastIndexOf("/") + 1);
886             }
887             while (resourceName.length() > "/".length()) {
888                 superFolders.add(resourceName);
889                 resourceName = resourceName.substring(0, resourceName.length() - 1);
890                 resourceName = resourceName.substring(0, resourceName.lastIndexOf("/") + 1);
891             }
892             for (int i = superFolders.size() - 1; i >= 0; i--) {
893                 String JavaDoc addFolder = (String JavaDoc)superFolders.get(i);
894                 if (!m_superFolders.contains(addFolder)) {
895                     // This super folder was NOT added previously. Add it now!
896
CmsFolder folder = getCms().readFolder(addFolder, CmsResourceFilter.IGNORE_EXPIRATION);
897                     appendResourceToManifest(folder, false);
898                     // Remember that this folder was added
899
m_superFolders.add(addFolder);
900                 }
901             }
902         } catch (CmsImportExportException e) {
903
904             throw e;
905         } catch (CmsException e) {
906
907             CmsMessageContainer message = Messages.get().container(
908                 Messages.ERR_IMPORTEXPORT_ERROR_ADDING_PARENT_FOLDERS_1,
909                 resourceName);
910             if (LOG.isDebugEnabled()) {
911                 LOG.debug(message.key(), e);
912             }
913
914             throw new CmsImportExportException(message, e);
915         }
916     }
917
918     /**
919      * Writes the data for a resource (like access-rights) to the <code>manifest.xml</code> file.<p>
920      *
921      * @param resource the resource to get the data from
922      * @param source flag to show if the source information in the xml file must be written
923      * @throws CmsImportExportException if something goes wrong
924      * @throws SAXException if something goes wrong procesing the manifest.xml
925      */

926     private void appendResourceToManifest(CmsResource resource, boolean source)
927     throws CmsImportExportException, SAXException JavaDoc {
928
929         try {
930             CmsProperty property = null;
931             String JavaDoc key = null, value = null;
932             Element propertyElement = null;
933
934             // define the file node
935
Element fileElement = m_resourceNode.addElement(CmsImportExportManager.N_FILE);
936
937             // only write <source> if resource is a file
938
String JavaDoc fileName = trimResourceName(getCms().getSitePath(resource));
939             if (resource.isFile()) {
940                 if (source) {
941                     fileElement.addElement(CmsImportExportManager.N_SOURCE).addText(fileName);
942                 }
943             } else {
944                 m_exportCount++;
945                 I_CmsReport report = getReport();
946                 // output something to the report for the folder
947
report.print(org.opencms.report.Messages.get().container(
948                     org.opencms.report.Messages.RPT_SUCCESSION_1,
949                     String.valueOf(m_exportCount)), I_CmsReport.FORMAT_NOTE);
950                 report.print(Messages.get().container(Messages.RPT_EXPORT_0), I_CmsReport.FORMAT_NOTE);
951                 report.print(org.opencms.report.Messages.get().container(
952                     org.opencms.report.Messages.RPT_ARGUMENT_1,
953                     getCms().getSitePath(resource)));
954                 report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0));
955                 report.println(
956                     org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0),
957                     I_CmsReport.FORMAT_OK);
958
959                 if (LOG.isInfoEnabled()) {
960                     LOG.info(Messages.get().getBundle().key(
961                         Messages.LOG_EXPORTING_OK_2,
962                         String.valueOf(m_exportCount),
963                         getCms().getSitePath(resource)));
964                 }
965             }
966
967             // <destination>
968
fileElement.addElement(CmsImportExportManager.N_DESTINATION).addText(fileName);
969             // <type>
970
fileElement.addElement(CmsImportExportManager.N_TYPE).addText(
971                 OpenCms.getResourceManager().getResourceType(resource.getTypeId()).getTypeName());
972
973             if (resource.isFile()) {
974                 // <uuidresource>
975
fileElement.addElement(CmsImportExportManager.N_UUIDRESOURCE).addText(
976                     resource.getResourceId().toString());
977             }
978
979             // <datelastmodified>
980
fileElement.addElement(CmsImportExportManager.N_DATELASTMODIFIED).addText(
981                 CmsDateUtil.getHeaderDate(resource.getDateLastModified()));
982             // <userlastmodified>
983
String JavaDoc userNameLastModified = null;
984             try {
985                 userNameLastModified = getCms().readUser(resource.getUserLastModified()).getName();
986             } catch (CmsException e) {
987                 userNameLastModified = OpenCms.getDefaultUsers().getUserAdmin();
988             }
989             fileElement.addElement(CmsImportExportManager.N_USERLASTMODIFIED).addText(userNameLastModified);
990             // <datecreated>
991
fileElement.addElement(CmsImportExportManager.N_DATECREATED).addText(
992                 CmsDateUtil.getHeaderDate(resource.getDateCreated()));
993             // <usercreated>
994
String JavaDoc userNameCreated = null;
995             try {
996                 userNameCreated = getCms().readUser(resource.getUserCreated()).getName();
997             } catch (CmsException e) {
998                 userNameCreated = OpenCms.getDefaultUsers().getUserAdmin();
999             }
1000            fileElement.addElement(CmsImportExportManager.N_USERCREATED).addText(userNameCreated);
1001            // <release>
1002
if (resource.getDateReleased() != CmsResource.DATE_RELEASED_DEFAULT) {
1003                fileElement.addElement(CmsImportExportManager.N_DATERELEASED).addText(
1004                    CmsDateUtil.getHeaderDate(resource.getDateReleased()));
1005            }
1006            // <expire>
1007
if (resource.getDateExpired() != CmsResource.DATE_EXPIRED_DEFAULT) {
1008                fileElement.addElement(CmsImportExportManager.N_DATEEXPIRED).addText(
1009                    CmsDateUtil.getHeaderDate(resource.getDateExpired()));
1010            }
1011            // <flags>
1012
int resFlags = resource.getFlags();
1013            resFlags &= ~CmsResource.FLAG_LABELED;
1014            fileElement.addElement(CmsImportExportManager.N_FLAGS).addText(Integer.toString(resFlags));
1015
1016            // write the properties to the manifest
1017
Element propertiesElement = fileElement.addElement(CmsImportExportManager.N_PROPERTIES);
1018            List JavaDoc properties = getCms().readPropertyObjects(getCms().getSitePath(resource), false);
1019            for (int i = 0, n = properties.size(); i < n; i++) {
1020                property = (CmsProperty)properties.get(i);
1021
1022                if (isIgnoredProperty(property)) {
1023                    continue;
1024                }
1025
1026                key = property.getName();
1027
1028                for (int j = 0; j < 2; j++) {
1029                    // iterations made here:
1030
// 0) append individual/structure property value
1031
// 1) append shared/resource property value
1032
if ((j == 0 && (value = property.getStructureValue()) != null)
1033                        || (j == 1 && (value = property.getResourceValue()) != null)) {
1034                        propertyElement = propertiesElement.addElement(CmsImportExportManager.N_PROPERTY);
1035
1036                        if (j == 1) {
1037                            // add a type attrib. to the property node in case of a shared/resource property value
1038
propertyElement.addAttribute(
1039                                CmsImportExportManager.N_PROPERTY_ATTRIB_TYPE,
1040                                CmsImportExportManager.N_PROPERTY_ATTRIB_TYPE_SHARED);
1041                        }
1042
1043                        propertyElement.addElement(CmsImportExportManager.N_NAME).addText(key);
1044                        propertyElement.addElement(CmsImportExportManager.N_VALUE).addCDATA(value);
1045                    }
1046                }
1047            }
1048
1049            // append the nodes for access control entries
1050
Element acl = fileElement.addElement(CmsImportExportManager.N_ACCESSCONTROL_ENTRIES);
1051
1052            // read the access control entries
1053
List JavaDoc fileAcEntries = getCms().getAccessControlEntries(getCms().getSitePath(resource), false);
1054            Iterator JavaDoc i = fileAcEntries.iterator();
1055
1056            // create xml elements for each access control entry
1057
while (i.hasNext()) {
1058                CmsAccessControlEntry ace = (CmsAccessControlEntry)i.next();
1059                Element a = acl.addElement(CmsImportExportManager.N_ACCESSCONTROL_ENTRY);
1060
1061                // now check if the principal is a group or a user
1062
int flags = ace.getFlags();
1063                String JavaDoc acePrincipalName = "";
1064                CmsUUID acePrincipal = ace.getPrincipal();
1065                if ((flags & CmsAccessControlEntry.ACCESS_FLAGS_GROUP) > 0) {
1066                    // the principal is a group
1067
acePrincipalName = getCms().readGroup(acePrincipal).getPrefixedName();
1068                } else {
1069                    // the principal is a user
1070
acePrincipalName = getCms().readUser(acePrincipal).getPrefixedName();
1071                }
1072
1073                a.addElement(CmsImportExportManager.N_ACCESSCONTROL_PRINCIPAL).addText(acePrincipalName);
1074                a.addElement(CmsImportExportManager.N_FLAGS).addText(Integer.toString(flags));
1075
1076                Element b = a.addElement(CmsImportExportManager.N_ACCESSCONTROL_PERMISSIONSET);
1077                b.addElement(CmsImportExportManager.N_ACCESSCONTROL_ALLOWEDPERMISSIONS).addText(
1078                    Integer.toString(ace.getAllowedPermissions()));
1079                b.addElement(CmsImportExportManager.N_ACCESSCONTROL_DENIEDPERMISSIONS).addText(
1080                    Integer.toString(ace.getDeniedPermissions()));
1081            }
1082
1083            // write the XML
1084
digestElement(m_resourceNode, fileElement);
1085        } catch (CmsImportExportException e) {
1086
1087            throw e;
1088        } catch (CmsException e) {
1089
1090            CmsMessageContainer message = Messages.get().container(
1091                Messages.ERR_IMPORTEXPORT_ERROR_APPENDING_RESOURCE_TO_MANIFEST_1,
1092                resource.getRootPath());
1093            if (LOG.isDebugEnabled()) {
1094                LOG.debug(message.key(), e);
1095            }
1096
1097            throw new CmsImportExportException(message, e);
1098        }
1099    }
1100
1101    /**
1102     * Returns true if the checked resource name can be exported depending on the include settings.<p>
1103     *
1104     * @param resourcename the absolute path of the resource
1105     * @return true if the checked resource name can be exported depending on the include settings
1106     */

1107    private boolean checkExportResource(String JavaDoc resourcename) {
1108
1109        return (// other folder than "/system/" will be exported
1110
!resourcename.startsWith(CmsWorkplace.VFS_PATH_SYSTEM) // OR always export "/system/"
1111
|| resourcename.equalsIgnoreCase(CmsWorkplace.VFS_PATH_SYSTEM) // OR always export "/system/bodies/"
1112
|| resourcename.startsWith(CmsCompatibleCheck.VFS_PATH_BODIES) // OR always export "/system/galleries/"
1113
|| resourcename.startsWith(CmsWorkplace.VFS_PATH_GALLERIES) // OR option "include system folder" selected
1114
|| (m_includeSystem // AND export folder is a system folder
1115
&& resourcename.startsWith(CmsWorkplace.VFS_PATH_SYSTEM)));
1116    }
1117
1118    /**
1119     * Exports one single file with all its data and content.<p>
1120     *
1121     * @param file the file to be exported
1122     * @throws CmsImportExportException if something goes wrong
1123     * @throws SAXException if something goes wrong procesing the manifest.xml
1124     * @throws CmsLoaderException if an "old style" XML page could be exported
1125     * @throws IOException if the ZIP entry for the file could be appended to the ZIP archive
1126     */

1127    private void exportFile(CmsFile file)
1128    throws CmsImportExportException, SAXException JavaDoc, CmsLoaderException, IOException JavaDoc {
1129
1130        String JavaDoc source = trimResourceName(getCms().getSitePath(file));
1131        I_CmsReport report = getReport();
1132        m_exportCount++;
1133        report.print(org.opencms.report.Messages.get().container(
1134            org.opencms.report.Messages.RPT_SUCCESSION_1,
1135            String.valueOf(m_exportCount)), I_CmsReport.FORMAT_NOTE);
1136        report.print(Messages.get().container(Messages.RPT_EXPORT_0), I_CmsReport.FORMAT_NOTE);
1137        report.print(org.opencms.report.Messages.get().container(
1138            org.opencms.report.Messages.RPT_ARGUMENT_1,
1139            getCms().getSitePath(file)));
1140        report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0));
1141
1142        // store content in zip-file
1143
// check if the content of this resource was not already exported
1144
if (!m_exportedResources.contains(file.getResourceId())) {
1145            ZipEntry JavaDoc entry = new ZipEntry JavaDoc(source);
1146            // save the time of the last modification in the zip
1147
entry.setTime(file.getDateLastModified());
1148            getExportZipStream().putNextEntry(entry);
1149            getExportZipStream().write(file.getContents());
1150            getExportZipStream().closeEntry();
1151            // add the resource id to the storage to mark that this resource was already exported
1152
m_exportedResources.add(file.getResourceId());
1153            // create the manifest-entrys
1154
appendResourceToManifest(file, true);
1155        } else {
1156            // only create the manifest-entrys
1157
appendResourceToManifest(file, false);
1158        }
1159        // check if the resource is a page of the old style. if so, export the body as well
1160
if (OpenCms.getResourceManager().getResourceType(file.getTypeId()).getTypeName().equals("page")) {
1161            m_exportedPageFiles.add("/" + source);
1162        }
1163
1164        if (LOG.isInfoEnabled()) {
1165            LOG.info(Messages.get().getBundle().key(Messages.LOG_EXPORTING_OK_2, String.valueOf(m_exportCount), source));
1166        }
1167        report.println(
1168            org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0),
1169            I_CmsReport.FORMAT_OK);
1170    }
1171
1172    /**
1173     * Exports one single group with all it's data.<p>
1174     *
1175     * @param parent the parent node to add the groups to
1176     * @param group the group to be exported
1177     * @throws CmsImportExportException if something goes wrong
1178     * @throws SAXException if something goes wrong procesing the manifest.xml
1179     */

1180    private void exportGroup(Element parent, CmsGroup group) throws CmsImportExportException, SAXException JavaDoc {
1181
1182        try {
1183            String JavaDoc parentgroup;
1184            if (group.getParentId().isNullUUID()) {
1185                parentgroup = "";
1186            } else {
1187                parentgroup = getCms().getParent(group.getName()).getName();
1188            }
1189
1190            Element e = parent.addElement(CmsImportExportManager.N_GROUPDATA);
1191            e.addElement(CmsImportExportManager.N_NAME).addText(group.getName());
1192            e.addElement(CmsImportExportManager.N_DESCRIPTION).addCDATA(group.getDescription());
1193            e.addElement(CmsImportExportManager.N_FLAGS).addText(Integer.toString(group.getFlags()));
1194            e.addElement(CmsImportExportManager.N_PARENTGROUP).addText(parentgroup);
1195
1196            // write the XML
1197
digestElement(parent, e);
1198        } catch (CmsException e) {
1199
1200            CmsMessageContainer message = org.opencms.db.Messages.get().container(
1201                org.opencms.db.Messages.ERR_GET_PARENT_GROUP_1,
1202                group.getName());
1203            if (LOG.isDebugEnabled()) {
1204                LOG.debug(message.key(), e);
1205            }
1206
1207            throw new CmsImportExportException(message, e);
1208        }
1209    }
1210
1211    /**
1212     * Exports all groups with all data.<p>
1213     *
1214     * @param parent the parent node to add the groups to
1215     * @throws CmsImportExportException if something goes wrong
1216     * @throws SAXException if something goes wrong procesing the manifest.xml
1217     */

1218    private void exportGroups(Element parent) throws CmsImportExportException, SAXException JavaDoc {
1219
1220        try {
1221            I_CmsReport report = getReport();
1222            List JavaDoc allGroups = getCms().getGroups();
1223            for (int i = 0, l = allGroups.size(); i < l; i++) {
1224                CmsGroup group = (CmsGroup)allGroups.get(i);
1225                report.print(org.opencms.report.Messages.get().container(
1226                    org.opencms.report.Messages.RPT_SUCCESSION_2,
1227                    String.valueOf(i + 1),
1228                    String.valueOf(l)), I_CmsReport.FORMAT_NOTE);
1229                report.print(Messages.get().container(Messages.RPT_EXPORT_GROUP_0), I_CmsReport.FORMAT_NOTE);
1230                report.print(org.opencms.report.Messages.get().container(
1231                    org.opencms.report.Messages.RPT_ARGUMENT_1,
1232                    group.getName()));
1233                report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0));
1234                exportGroup(parent, group);
1235                report.println(
1236                    org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0),
1237                    I_CmsReport.FORMAT_OK);
1238            }
1239        } catch (CmsImportExportException e) {
1240
1241            throw e;
1242        } catch (CmsException e) {
1243
1244            CmsMessageContainer message = org.opencms.db.Messages.get().container(
1245                org.opencms.db.Messages.ERR_GET_GROUPS_0);
1246            if (LOG.isDebugEnabled()) {
1247                LOG.debug(message.key(), e);
1248            }
1249
1250            throw new CmsImportExportException(message, e);
1251        }
1252    }
1253
1254    /**
1255     * Exports one single user with all its data.<p>
1256     *
1257     * @param parent the parent node to add the users to
1258     * @param user the user to be exported
1259     * @throws CmsImportExportException if something goes wrong
1260     * @throws SAXException if something goes wrong procesing the manifest.xml
1261     */

1262    private void exportUser(Element parent, CmsUser user) throws CmsImportExportException, SAXException JavaDoc {
1263
1264        try {
1265            // add user node to the manifest.xml
1266
Element e = parent.addElement(CmsImportExportManager.N_USERDATA);
1267            e.addElement(CmsImportExportManager.N_NAME).addText(user.getName());
1268            // encode the password, using a base 64 decoder
1269
String JavaDoc passwd = new String JavaDoc(Base64.encodeBase64(user.getPassword().getBytes()));
1270            e.addElement(CmsImportExportManager.N_PASSWORD).addCDATA(passwd);
1271            e.addElement(CmsImportExportManager.N_DESCRIPTION).addCDATA(user.getDescription());
1272            e.addElement(CmsImportExportManager.N_FIRSTNAME).addText(user.getFirstname());
1273            e.addElement(CmsImportExportManager.N_LASTNAME).addText(user.getLastname());
1274            e.addElement(CmsImportExportManager.N_EMAIL).addText(user.getEmail());
1275            e.addElement(CmsImportExportManager.N_FLAGS).addText(Integer.toString(user.getFlags()));
1276            e.addElement(CmsImportExportManager.N_TAG_ADDRESS).addCDATA(user.getAddress());
1277            e.addElement(CmsImportExportManager.N_TYPE).addText(Integer.toString(user.getType()));
1278            // serialize the user info and write it into a file
1279
try {
1280                String JavaDoc datfileName = "/~" + CmsImportExportManager.N_USERINFO + "/" + user.getName() + ".dat";
1281                // create tag for userinfo
1282
e.addElement(CmsImportExportManager.N_USERINFO).addText(datfileName);
1283                ByteArrayOutputStream JavaDoc bout = new ByteArrayOutputStream JavaDoc();
1284                ObjectOutputStream JavaDoc oout = new ObjectOutputStream JavaDoc(bout);
1285                oout.writeObject(user.getAdditionalInfo());
1286                oout.close();
1287                byte[] serializedInfo = bout.toByteArray();
1288                // store the serialized user info in the zip-file
1289
ZipEntry JavaDoc entry = new ZipEntry JavaDoc(datfileName);
1290                getExportZipStream().putNextEntry(entry);
1291                getExportZipStream().write(serializedInfo);
1292                getExportZipStream().closeEntry();
1293            } catch (IOException JavaDoc ioe) {
1294                getReport().println(ioe);
1295
1296                if (LOG.isErrorEnabled()) {
1297                    LOG.error(Messages.get().getBundle().key(
1298                        Messages.ERR_IMPORTEXPORT_ERROR_EXPORTING_USER_1,
1299                        user.getName()), ioe);
1300                }
1301            }
1302            // append the node for groups of user
1303
List JavaDoc userGroups = getCms().getDirectGroupsOfUser(user.getName());
1304            Element g = e.addElement(CmsImportExportManager.N_USERGROUPS);
1305            for (int i = 0; i < userGroups.size(); i++) {
1306                String JavaDoc groupName = ((CmsGroup)userGroups.get(i)).getName();
1307                g.addElement(CmsImportExportManager.N_GROUPNAME).addElement(CmsImportExportManager.N_NAME).addText(
1308                    groupName);
1309            }
1310            // write the XML
1311
digestElement(parent, e);
1312        } catch (CmsException e) {
1313
1314            CmsMessageContainer message = org.opencms.db.Messages.get().container(
1315                org.opencms.db.Messages.ERR_GET_GROUPS_OF_USER_1,
1316                user.getName());
1317            if (LOG.isDebugEnabled()) {
1318                LOG.debug(message.key(), e);
1319            }
1320
1321            throw new CmsImportExportException(message, e);
1322        }
1323    }
1324
1325    /**
1326     * Exports all users with all data.<p>
1327     *
1328     * @param parent the parent node to add the users to
1329     * @throws CmsImportExportException if something goes wrong
1330     * @throws SAXException if something goes wrong procesing the manifest.xml
1331     */

1332    private void exportUsers(Element parent) throws CmsImportExportException, SAXException JavaDoc {
1333
1334        try {
1335            I_CmsReport report = getReport();
1336            List JavaDoc allUsers = new ArrayList JavaDoc();
1337            if (m_exportUserdata) {
1338                // add system users
1339
allUsers.addAll(getCms().getUsers());
1340            }
1341            if (m_exportWebusers) {
1342                // add webusers
1343
allUsers.addAll(getCms().getUsers(CmsUser.USER_TYPE_WEBUSER));
1344            }
1345            for (int i = 0, l = allUsers.size(); i < l; i++) {
1346                CmsUser user = (CmsUser)allUsers.get(i);
1347                report.print(org.opencms.report.Messages.get().container(
1348                    org.opencms.report.Messages.RPT_SUCCESSION_2,
1349                    String.valueOf(i + 1),
1350                    String.valueOf(l)), I_CmsReport.FORMAT_NOTE);
1351                report.print(Messages.get().container(Messages.RPT_EXPORT_USER_0), I_CmsReport.FORMAT_NOTE);
1352                report.print(org.opencms.report.Messages.get().container(
1353                    org.opencms.report.Messages.RPT_ARGUMENT_1,
1354                    user.getName()));
1355                report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0));
1356                exportUser(parent, user);
1357                report.println(
1358                    org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0),
1359                    I_CmsReport.FORMAT_OK);
1360            }
1361        } catch (CmsImportExportException e) {
1362
1363            throw e;
1364        } catch (CmsException e) {
1365
1366            CmsMessageContainer message = org.opencms.db.Messages.get().container(
1367                org.opencms.db.Messages.ERR_GET_USERS_0);
1368            if (LOG.isDebugEnabled()) {
1369                LOG.debug(message.key(), e);
1370            }
1371
1372            throw new CmsImportExportException(message, e);
1373        }
1374    }
1375
1376    /**
1377     * Cuts leading and trailing '/' from the given resource name.<p>
1378     *
1379     * @param resourceName the absolute path of a resource
1380     * @return the trimmed resource name
1381     */

1382    private String JavaDoc trimResourceName(String JavaDoc resourceName) {
1383
1384        if (resourceName.startsWith("/")) {
1385            resourceName = resourceName.substring(1);
1386        }
1387        if (resourceName.endsWith("/")) {
1388            resourceName = resourceName.substring(0, resourceName.length() - 1);
1389        }
1390        return resourceName;
1391    }
1392}
1393
Popular Tags