KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opencms > legacy > CmsImportVersion1


1 /*
2  * File : $Source: /usr/local/cvs/opencms/src-modules/com/opencms/legacy/CmsImportVersion1.java,v $
3  * Date : $Date: 2005/06/27 23:27:46 $
4  * Version: $Revision: 1.8 $
5  *
6  * This library is part of OpenCms -
7  * the Open Source Content Mananagement System
8  *
9  * Copyright (C) 2002 Alkacon Software (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, 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 com.opencms.legacy;
33
34 import org.opencms.importexport.CmsCompatibleCheck;
35 import org.opencms.importexport.CmsImportVersion2;
36 import org.opencms.main.CmsException;
37 import org.opencms.main.OpenCms;
38 import org.opencms.report.I_CmsReport;
39 import org.opencms.util.CmsStringUtil;
40 import org.opencms.xml.CmsXmlException;
41 import org.opencms.xml.CmsXmlUtils;
42
43 import com.opencms.template.*;
44
45 import java.io.ByteArrayInputStream JavaDoc;
46 import java.io.InputStream JavaDoc;
47 import java.io.UnsupportedEncodingException JavaDoc;
48 import java.util.Enumeration JavaDoc;
49 import java.util.Hashtable JavaDoc;
50 import java.util.List JavaDoc;
51
52 import org.dom4j.Attribute;
53 import org.dom4j.Document;
54 import org.dom4j.DocumentHelper;
55 import org.dom4j.Element;
56 import org.xml.sax.InputSource JavaDoc;
57
58 /**
59  * Implementation of the OpenCms Import Interface ({@link org.opencms.importexport.I_CmsImport}) for
60  * the import version 1.<p>
61  *
62  * This import format was used in OpenCms 4.3.23 - 5.0.0.<p>
63  *
64  * This import class has similar funktions to CmsImportVersion2, but because of the need for a
65  * single import class for each import version, a new, inherited class must be used, returning
66  * the correct import version.<p>
67  *
68  * @author Michael Emmerich (m.emmerich@alkacon.com)
69  * @author Thomas Weckert (t.weckert@alkacon.com)
70  *
71  * @see org.opencms.importexport.A_CmsImport
72  *
73  * @deprecated Will not be supported past the OpenCms 6 release.
74  */

75 public class CmsImportVersion1 extends CmsImportVersion2 {
76
77     /** The version number of this import implementation. */
78     private static final int C_IMPORT_VERSION = 1;
79
80     /** The path to the bodies in OpenCms 4.x. */
81     private static final String JavaDoc C_VFS_PATH_OLD_BODIES = "/content/bodys/";
82
83     /**
84      * @see org.opencms.importexport.I_CmsImport#getVersion()
85      */

86     public int getVersion() {
87
88         return CmsImportVersion1.C_IMPORT_VERSION;
89     }
90
91     /**
92      * Converts the content of a file from OpenCms 4.x versions.<p>
93      *
94      * @param filename the name of the file to convert
95      * @param byteContent the content of the file
96      * @return the converted filecontent
97      */

98     private byte[] convertFile(String JavaDoc filename, byte[] byteContent) {
99
100         byte[] returnValue = byteContent;
101         if (!filename.startsWith("/")) {
102             filename = "/" + filename;
103         }
104
105         String JavaDoc fileContent = new String JavaDoc(byteContent);
106         String JavaDoc encoding = getEncoding(fileContent);
107         if (!"".equals(encoding)) {
108             // encoding found, ensure that the String is correct
109
try {
110                 // get content of the file and store it in String with the correct encoding
111
fileContent = new String JavaDoc(byteContent, encoding);
112             } catch (UnsupportedEncodingException JavaDoc e) {
113                 // encoding not supported, we use the default and hope we are lucky
114
if (DEBUG > 0) {
115                     System.err.println("["
116                         + this.getClass().getName()
117                         + ".convertFile()]: Encoding not supported, using default encoding.");
118                 }
119             }
120         } else {
121             // encoding not found, set encoding of xml files to default
122
if (DEBUG > 0) {
123                 System.err.println("["
124                     + this.getClass().getName()
125                     + ".convertFile()]: Encoding not set, using default encoding and setting it in <?xml...?>.");
126             }
127             encoding = OpenCms.getSystemInfo().getDefaultEncoding();
128             fileContent = setEncoding(fileContent, encoding);
129         }
130         // check the frametemplates
131
if (filename.indexOf("frametemplates") != -1) {
132             fileContent = scanFrameTemplate(fileContent);
133         }
134         // scan content/bodys
135
if (filename.indexOf(C_VFS_PATH_OLD_BODIES) != -1 || filename.indexOf(CmsCompatibleCheck.VFS_PATH_BODIES) != -1) {
136             if (DEBUG > 0) {
137                 System.err.println("[" + this.getClass().getName() + ".convertFile()]: Starting scan of body page.");
138             }
139             fileContent = convertPageBody(fileContent, filename);
140         }
141         // translate OpenCms 4.x paths to the new directory structure
142
fileContent = setDirectories(fileContent, m_cms.getRequestContext().getDirectoryTranslator().getTranslations());
143
144         // create output ByteArray
145
try {
146             returnValue = fileContent.getBytes(encoding);
147         } catch (UnsupportedEncodingException JavaDoc e) {
148             // encoding not supported, we use the default and hope we are lucky
149
returnValue = fileContent.getBytes();
150         }
151         return returnValue;
152     }
153
154     /**
155      * Searches for the webapps String and replaces it with a macro which is needed for the WYSIWYG editor,
156      * also creates missing &lt;edittemplate&gt; tags for exports of older OpenCms 4.x versions.<p>
157      *
158      * @param content the filecontent
159      * @param fileName the name of the file
160      * @return String the modified filecontent
161      */

162
163     private String JavaDoc convertPageBody(String JavaDoc content, String JavaDoc fileName) {
164
165         String JavaDoc nodeName = null;
166
167         // variables needed for the creation of <template> elements
168
boolean createTemplateTags = false;
169         Hashtable JavaDoc templateElements = new Hashtable JavaDoc();
170
171         // first check if any contextpaths are in the content String
172
boolean found = false;
173         for (int i = 0; i < m_webAppNames.size(); i++) {
174             if (content.indexOf((String JavaDoc)m_webAppNames.get(i)) != -1) {
175                 found = true;
176             }
177         }
178         // check if edittemplates are in the content string
179
if (content.indexOf("<edittemplate>") != -1 || content.indexOf("<EDITTEMPLATE>") != -1) {
180             found = true;
181         }
182
183         // only build document when some paths were found or <edittemplate> is missing!
184
if (found) {
185             InputStream JavaDoc in = new ByteArrayInputStream JavaDoc(content.getBytes());
186             String JavaDoc editString, templateString;
187             try {
188                 // create DOM document
189
InputSource JavaDoc source = new InputSource JavaDoc(in);
190                 Document doc = CmsXmlUtils.unmarshalHelper(source, null);
191
192                 // get all <edittemplate> nodes to check their content
193
nodeName = "edittemplate";
194                 Element root = doc.getRootElement();
195                 List JavaDoc editNodes = root.elements(nodeName.toLowerCase());
196                 editNodes.addAll(root.elements(nodeName.toUpperCase()));
197                 // no <edittemplate> tags present, create them!
198
if (editNodes.size() < 1) {
199                     if (DEBUG > 0) {
200                         System.err.println("["
201                             + this.getClass().getName()
202                             + ".convertPageBody()]: No <edittemplate> found, creating it.");
203                     }
204
205                     createTemplateTags = true;
206
207                     nodeName = "TEMPLATE";
208                     List JavaDoc templateNodes = root.elements(nodeName.toLowerCase());
209                     List JavaDoc attributes;
210                     templateNodes.addAll(root.elements(nodeName.toUpperCase()));
211
212                     // create an <edittemplate> tag for each <template> tag
213
Element templateTag;
214                     for (int i = 0; i < templateNodes.size(); i++) {
215
216                         // get the CDATA content of the <template> tags
217
templateTag = (Element)templateNodes.get(i);
218                         editString = templateTag.getText();
219                         templateString = editString;
220
221                         // substitute the links in the <template> tag String
222
try {
223                             templateString = CmsXmlTemplateLinkConverter.convertFromImport(
224                                 templateString,
225                                 m_webappUrl,
226                                 fileName);
227                         } catch (CmsException e) {
228                             throw new CmsLegacyException("["
229                                 + this.getClass().getName()
230                                 + ".convertPageBody()] can't parse the content: ", e);
231                         }
232
233                         // look for the "name" attribute of the <template> tag
234
attributes = ((Element)templateNodes.get(i)).attributes();
235
236                         String JavaDoc templateName = "";
237
238                         if (attributes.size() > 0) {
239                             templateName = ((Attribute)attributes.get(0)).getName();
240                         }
241
242                         // create the new <edittemplate> node
243
nodeName = "edittemplate";
244                         Element newNode = DocumentHelper.createElement(nodeName.toLowerCase());
245                         if (newNode == null) {
246                             newNode = root.addElement(nodeName.toUpperCase());
247                         }
248                         newNode.addCDATA(editString);
249                         // set the "name" attribute, if necessary
250
attributes = newNode.attributes();
251                         if (!templateName.equals("")) {
252                             newNode.addAttribute("name", templateName);
253                         }
254
255                         // append the new edittemplate node to the document
256
((Element)root.elements("XMLTEMPLATE").get(0)).add(newNode);
257                         // store modified <template> node Strings in Hashtable
258
if (templateName.equals("")) {
259                             templateName = "noNameKey";
260                         }
261                         templateElements.put(templateName, templateString);
262                     }
263                     // finally, delete old <TEMPLATE> tags from document
264
while (templateNodes.size() > 0) {
265                         ((Element)root.elements("XMLTEMPLATE").get(0)).remove((Element)templateNodes.get(0));
266                     }
267
268                 }
269                 // check the content of the <edittemplate> nodes
270
Element editTemplate;
271                 for (int i = 0; i < editNodes.size(); i++) {
272                     // editString = editNodes.item(i).getFirstChild().getNodeValue();
273
editTemplate = (Element)editNodes.get(i);
274                     editString = editTemplate.getText();
275                     for (int k = 0; k < m_webAppNames.size(); k++) {
276                         editString = CmsStringUtil.substitute(
277                             editString,
278                             (String JavaDoc)m_webAppNames.get(k),
279                             CmsStringUtil.MACRO_OPENCMS_CONTEXT + "/");
280                     }
281
282                     // There is a setText(String) but no corresponding setCDATA in dom4j.
283
editTemplate.clearContent();
284                     editTemplate.addCDATA(editString);
285
286                 }
287                 // convert XML document back to String
288

289                 content = CmsXmlUtils.marshal(doc, OpenCms.getSystemInfo().getDefaultEncoding());
290                 // rebuild the template tags in the document!
291
if (createTemplateTags) {
292                     content = content.substring(0, content.lastIndexOf("</XMLTEMPLATE>"));
293                     // get the keys
294
Enumeration JavaDoc en = templateElements.keys();
295                     while (en.hasMoreElements()) {
296                         String JavaDoc key = (String JavaDoc)en.nextElement();
297                         String JavaDoc value = (String JavaDoc)templateElements.get(key);
298                         // create the default template
299
if (key.equals("noNameKey")) {
300                             content += "\n<TEMPLATE><![CDATA[" + value;
301                         } else {
302                             // create template with "name" attribute
303
content += "\n<TEMPLATE name=\"" + key + "\"><![CDATA[" + value;
304                         }
305                         content += "]]></TEMPLATE>\n";
306                     }
307                     content += "\n</XMLTEMPLATE>";
308                 }
309
310             } catch (Exception JavaDoc exc) {
311                 // ignore
312
}
313         }
314         return content;
315     }
316
317     /**
318      * Scans the given content of a frametemplate and returns the result.<p>
319      *
320      * @param content the filecontent
321      * @return modified content
322      */

323     private String JavaDoc scanFrameTemplate(String JavaDoc content) {
324
325         // no Meta-Tag present, insert it!
326
if (content.toLowerCase().indexOf("http-equiv=\"content-type\"") == -1) {
327             content = CmsStringUtil
328                 .substitute(
329                     content,
330                     "</head>",
331                     "<meta http-equiv=\"content-type\" content=\"text/html; charset=]]><method name=\"getEncoding\"/><![CDATA[\">\n</head>");
332         } else {
333             // Meta-Tag present
334
if (content.toLowerCase().indexOf("charset=]]><method name=\"getencoding\"/>") == -1) {
335                 String JavaDoc fileStart = content.substring(0, content.toLowerCase().indexOf("charset=") + 8);
336                 String JavaDoc editContent = content.substring(content.toLowerCase().indexOf("charset="));
337                 editContent = editContent.substring(editContent.indexOf("\""));
338                 String JavaDoc newEncoding = "]]><method name=\"getEncoding\"/><![CDATA[";
339                 content = fileStart + newEncoding + editContent;
340             }
341         }
342         return content;
343     }
344
345     /**
346      * Performs all required pre-import steps.<p>
347      *
348      * The content *IS* changed in the implementation of this class (edittemplate/displaytemplate,
349      * links, paths including the webapps name etc.).<p>
350      *
351      * @see org.opencms.importexport.CmsImportVersion2#convertContent(java.lang.String, java.lang.String, byte[], java.lang.String)
352      */

353     protected byte[] convertContent(String JavaDoc source, String JavaDoc destination, byte[] content, String JavaDoc resType) {
354
355         // check and convert old import files
356
if (getVersion() < 2) {
357             // convert content from pre 5.x must be activated
358
if ("page".equals(resType) || ("plain".equals(resType)) || ("XMLTemplate".equals(resType))) {
359                 if (DEBUG > 0) {
360                     System.err.println("#########################");
361                     System.err.println("["
362                         + this.getClass().getName()
363                         + ".convertContent()]: starting conversion of \""
364                         + resType
365                         + "\" resource "
366                         + source
367                         + ".");
368                 }
369                 // change the filecontent for encoding if necessary
370
content = convertFile(source, content);
371             }
372             // only check the file type if the version of the export is 0
373
if (getVersion() == 0) {
374                 // ok, a (very) old system exported this, check if the file is ok
375
if (!(new CmsCompatibleCheck()).isTemplateCompatible(m_importPath + destination, content, resType)) {
376                     resType = CmsResourceTypeCompatiblePlain.getStaticTypeName();
377                     m_report.print(Messages.get().container(Messages.RPT_MUST_SET_TO_1, resType), I_CmsReport.FORMAT_WARNING);
378                 }
379             }
380         }
381
382         // drag the content also through the conversion method in the super class
383
return super.convertContent(source, destination, content, resType);
384     }
385
386     /**
387      * Creates a dom4j document out of a specified stream.<p>
388      *
389      * @param stream the stream
390      * @return a dom4j document
391      * @throws CmsXmlException if something goes wrong
392      */

393     public static Document getXmlDocument(InputStream JavaDoc stream) throws CmsXmlException {
394
395         return CmsXmlUtils.unmarshalHelper(new InputSource JavaDoc(stream), null);
396     }
397
398 }
399
Popular Tags