KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opencms > db > CmsImportFolder


1 /*
2  * File : $Source: /usr/local/cvs/opencms/src/org/opencms/db/CmsImportFolder.java,v $
3  * Date : $Date: 2006/10/19 15:08:20 $
4  * Version: $Revision: 1.35 $
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.db;
33
34 import org.opencms.file.CmsFile;
35 import org.opencms.file.CmsObject;
36 import org.opencms.file.CmsProperty;
37 import org.opencms.file.CmsPropertyDefinition;
38 import org.opencms.file.CmsResource;
39 import org.opencms.file.CmsResourceFilter;
40 import org.opencms.file.CmsVfsException;
41 import org.opencms.file.types.CmsResourceTypeFolder;
42 import org.opencms.main.CmsEvent;
43 import org.opencms.main.CmsException;
44 import org.opencms.main.I_CmsEventListener;
45 import org.opencms.main.OpenCms;
46 import org.opencms.util.CmsFileUtil;
47
48 import java.io.ByteArrayInputStream JavaDoc;
49 import java.io.File JavaDoc;
50 import java.io.FileInputStream JavaDoc;
51 import java.io.IOException JavaDoc;
52 import java.util.ArrayList JavaDoc;
53 import java.util.Collections JavaDoc;
54 import java.util.List JavaDoc;
55 import java.util.StringTokenizer JavaDoc;
56 import java.util.zip.ZipEntry JavaDoc;
57 import java.util.zip.ZipInputStream JavaDoc;
58
59 /**
60  * Allows to import resources from the filesystem or a ZIP file into the OpenCms VFS.<p>
61  *
62  * @author Alexander Kandzior
63  *
64  * @version $Revision: 1.35 $
65  *
66  * @since 6.0.0
67  */

68 public class CmsImportFolder {
69
70     /** The OpenCms context object that provides the permissions. */
71     private CmsObject m_cms;
72
73     /** The name of the import folder to load resources from. */
74     private String JavaDoc m_importFolderName;
75
76     /** The import path in the OpenCms VFS. */
77     private String JavaDoc m_importPath;
78
79     /** The resource (folder or ZIP file) to import from in the real file system. */
80     private File m_importResource;
81
82     /** Will be true if the import resource is a valid ZIP file. */
83     private boolean m_validZipFile;
84
85     /** The import resource ZIP stream to load resources from. */
86     private ZipInputStream JavaDoc m_zipStreamIn;
87
88     /**
89      * Constructor for a new CmsImportFolder that will read from a ZIP file.<p>
90      *
91      * @param content the zip file to import
92      * @param importPath the path to the OpenCms VFS to import to
93      * @param cms a OpenCms context to provide the permissions
94      * @param noSubFolder if false no sub folder will be created
95      * @throws CmsException if something goes wrong
96      */

97     public CmsImportFolder(byte[] content, String JavaDoc importPath, CmsObject cms, boolean noSubFolder)
98     throws CmsException {
99
100         m_importPath = importPath;
101         m_cms = cms;
102         try {
103             // open the import resource
104
m_zipStreamIn = new ZipInputStream JavaDoc(new ByteArrayInputStream JavaDoc(content));
105             m_cms.readFolder(importPath, CmsResourceFilter.IGNORE_EXPIRATION);
106             // import the resources
107
importZipResource(m_zipStreamIn, m_importPath, noSubFolder);
108         } catch (Exception JavaDoc e) {
109             throw new CmsVfsException(Messages.get().container(Messages.ERR_IMPORT_FOLDER_1, importPath), e);
110         }
111     }
112
113     /**
114      * Constructor for a new CmsImportFolder that will read from the real file system.<p>
115      *
116      * @param importFolderName the folder to import
117      * @param importPath the path to the OpenCms VFS to import to
118      * @param cms a OpenCms context to provide the permissions
119      * @throws CmsException if something goes wrong
120      */

121     public CmsImportFolder(String JavaDoc importFolderName, String JavaDoc importPath, CmsObject cms)
122     throws CmsException {
123
124         try {
125             m_importFolderName = importFolderName;
126             m_importPath = importPath;
127             m_cms = cms;
128             // open the import resource
129
getImportResource();
130             // first lock the destination path
131
m_cms.lockResource(m_importPath);
132             // import the resources
133
if (m_zipStreamIn == null) {
134                 importResources(m_importResource, m_importPath);
135             } else {
136                 importZipResource(m_zipStreamIn, m_importPath, false);
137             }
138             // all is done, unlock the resources
139
m_cms.unlockResource(m_importPath);
140         } catch (Exception JavaDoc e) {
141             throw new CmsVfsException(Messages.get().container(
142                 Messages.ERR_IMPORT_FOLDER_2,
143                 importFolderName,
144                 importPath), e);
145         }
146     }
147
148     /**
149      * Returns true if a valid ZIP file was imported.<p>
150      *
151      * @return true if a valid ZIP file was imported
152      */

153     public boolean isValidZipFile() {
154
155         return m_validZipFile;
156     }
157
158     /**
159      * Stores the import resource in an Object member variable.<p>
160      * @throws CmsVfsException if the file to import is no valid zipfile
161      */

162     private void getImportResource() throws CmsVfsException {
163
164         // get the import resource
165
m_importResource = new File(m_importFolderName);
166         // check if this is a folder or a ZIP file
167
if (m_importResource.isFile()) {
168             try {
169                 m_zipStreamIn = new ZipInputStream JavaDoc(new FileInputStream JavaDoc(m_importResource));
170             } catch (IOException JavaDoc e) {
171                 // if file but no ZIP file throw an exception
172
throw new CmsVfsException(Messages.get().container(
173                     Messages.ERR_NO_ZIPFILE_1,
174                     m_importResource.getName()), e);
175             }
176         }
177     }
178
179     /**
180      * Imports the resources from the folder in the real file system to the OpenCms VFS.<p>
181      *
182      * @param folder the folder to import from
183      * @param importPath the OpenCms VFS import path to import to
184      * @throws Exception if something goes wrong during file IO
185      */

186     private void importResources(File folder, String JavaDoc importPath) throws Exception JavaDoc {
187
188         String JavaDoc[] diskFiles = folder.list();
189         File currentFile;
190
191         for (int i = 0; i < diskFiles.length; i++) {
192             currentFile = new File(folder, diskFiles[i]);
193
194             if (currentFile.isDirectory()) {
195                 // create directory in cms
196
m_cms.createResource(importPath + currentFile.getName(), CmsResourceTypeFolder.RESOURCE_TYPE_ID);
197                 importResources(currentFile, importPath + currentFile.getName() + "/");
198             } else {
199                 // import file into cms
200
int type = OpenCms.getResourceManager().getDefaultTypeForName(currentFile.getName()).getTypeId();
201                 byte[] content = CmsFileUtil.readFile(currentFile);
202                 // create the file
203
m_cms.createResource(importPath + currentFile.getName(), type, content, null);
204                 content = null;
205             }
206         }
207     }
208
209     /**
210      * Imports the resources from a ZIP file in the real file system to the OpenCms VFS.<p>
211      *
212      * @param zipStreamIn the input Stream
213      * @param importPath the path in the vfs
214      * @param noSubFolder create subFolders or not
215      * @throws Exception if something goes wrong during file IO
216      */

217     private void importZipResource(ZipInputStream JavaDoc zipStreamIn, String JavaDoc importPath, boolean noSubFolder) throws Exception JavaDoc {
218
219         int todo = 0;
220         // TODO: this method looks very crude, it should be re-written sometime...
221

222         boolean isFolder = false;
223         int j, r, stop, size;
224         int entries = 0;
225         byte[] buffer = null;
226         boolean resourceExists;
227
228         while (true) {
229             // handle the single entries ...
230
j = 0;
231             stop = 0;
232             // open the entry ...
233
ZipEntry JavaDoc entry = zipStreamIn.getNextEntry();
234             if (entry == null) {
235                 break;
236             }
237             entries++; // count number of entries in zip
238
String JavaDoc actImportPath = importPath;
239             String JavaDoc title = CmsResource.getName(entry.getName());
240             String JavaDoc filename = m_cms.getRequestContext().getFileTranslator().translateResource(entry.getName());
241             // separate path in directories and file name ...
242
StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(filename, "/\\");
243             int count = st.countTokens();
244             String JavaDoc[] path = new String JavaDoc[count];
245
246             if (filename.endsWith("\\") || filename.endsWith("/")) {
247                 isFolder = true; // last entry is a folder
248
} else {
249                 isFolder = false; // last entry is a file
250
}
251             while (st.hasMoreTokens()) {
252                 // store the files and folder names in array ...
253
path[j] = st.nextToken();
254                 j++;
255             }
256             stop = isFolder ? path.length : (path.length - 1);
257
258             if (noSubFolder) {
259                 stop = 0;
260             }
261             // now write the folders ...
262
for (r = 0; r < stop; r++) {
263                 try {
264                     m_cms.createResource(actImportPath + path[r], CmsResourceTypeFolder.RESOURCE_TYPE_ID);
265                 } catch (CmsException e) {
266                     // of course some folders did already exist!
267
}
268                 actImportPath += path[r];
269                 actImportPath += "/";
270             }
271             if (!isFolder) {
272                 // import file into cms
273
int type = OpenCms.getResourceManager().getDefaultTypeForName(path[path.length - 1]).getTypeId();
274                 size = new Long JavaDoc(entry.getSize()).intValue();
275                 if (size == -1) {
276                     buffer = CmsFileUtil.readFully(zipStreamIn, false);
277                 } else {
278                     buffer = CmsFileUtil.readFully(zipStreamIn, size, false);
279                 }
280                 filename = actImportPath + path[path.length - 1];
281
282                 try {
283                     m_cms.lockResource(filename);
284
285                     m_cms.readResource(filename);
286                     resourceExists = true;
287                 } catch (CmsException e) {
288                     resourceExists = false;
289                 }
290
291                 if (resourceExists) {
292                     CmsResource res = m_cms.readResource(filename, CmsResourceFilter.ALL);
293                     CmsFile file = CmsFile.upgrade(res, m_cms);
294                     byte[] contents = file.getContents();
295                     try {
296                         m_cms.replaceResource(filename, res.getTypeId(), buffer, Collections.EMPTY_LIST);
297                     } catch (CmsDbSqlException sqlExc) {
298                         // SQL error, probably the file is too large for the database settings, restore content
299
file.setContents(contents);
300                         m_cms.writeFile(file);
301                         throw sqlExc;
302                     }
303
304                     OpenCms.fireCmsEvent(new CmsEvent(
305                         I_CmsEventListener.EVENT_RESOURCE_AND_PROPERTIES_MODIFIED,
306                         Collections.singletonMap("resource", res)));
307                 } else {
308                     String JavaDoc newResName = actImportPath + path[path.length - 1];
309                     if (title.lastIndexOf('.') != -1) {
310                         title = title.substring(0, title.lastIndexOf('.'));
311                     }
312                     List JavaDoc properties = new ArrayList JavaDoc(1);
313                     CmsProperty titleProp = new CmsProperty();
314                     titleProp.setName(CmsPropertyDefinition.PROPERTY_TITLE);
315                     if (OpenCms.getWorkplaceManager().isDefaultPropertiesOnStructure()) {
316                         titleProp.setStructureValue(title);
317                     } else {
318                         titleProp.setResourceValue(title);
319                     }
320                     properties.add(titleProp);
321                     try {
322                         m_cms.createResource(newResName, type, buffer, properties);
323                     } catch (CmsDbSqlException sqlExc) {
324                         // SQL error, probably the file is too large for the database settings, delete file
325
m_cms.lockResource(newResName);
326                         m_cms.deleteResource(newResName, CmsResource.DELETE_PRESERVE_SIBLINGS);
327                         throw sqlExc;
328                     }
329                 }
330             }
331
332             // close the entry ...
333
zipStreamIn.closeEntry();
334         }
335         zipStreamIn.close();
336         if (entries > 0) {
337             // at least one entry, got a valid zip file ...
338
m_validZipFile = true;
339         }
340     }
341 }
342
Popular Tags