KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opencms > template > CmsXmlTemplateFile


1 /*
2 * File : $Source: /usr/local/cvs/opencms/src-modules/com/opencms/template/CmsXmlTemplateFile.java,v $
3 * Date : $Date: 2005/05/31 15:51:19 $
4 * Version: $Revision: 1.3 $
5 *
6 * This library is part of OpenCms -
7 * the Open Source Content Mananagement System
8 *
9 * Copyright (C) 2001 The OpenCms Group
10 *
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
15 *
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
20 *
21 * For further information about OpenCms, please see the
22 * OpenCms Website: http://www.opencms.org
23 *
24 * You should have received a copy of the GNU Lesser General Public
25 * License along with this library; if not, write to the Free Software
26 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
27 */

28
29
30 package com.opencms.template;
31
32 import org.opencms.file.CmsFile;
33 import org.opencms.file.CmsObject;
34 import org.opencms.main.CmsException;
35 import org.opencms.main.CmsLog;
36 import org.opencms.main.OpenCms;
37 import org.opencms.util.CmsStringUtil;
38
39 import com.opencms.core.I_CmsRequest;
40 import com.opencms.legacy.CmsLegacyException;
41 import com.opencms.legacy.CmsXmlTemplateLoader;
42 import com.opencms.template.cache.CmsElementLink;
43 import com.opencms.template.cache.CmsElementVariant;
44 import com.opencms.template.cache.CmsMethodLink;
45
46 import java.io.OutputStream JavaDoc;
47 import java.io.StringReader JavaDoc;
48 import java.io.StringWriter JavaDoc;
49 import java.util.Hashtable JavaDoc;
50 import java.util.Vector JavaDoc;
51
52 import org.w3c.dom.Document JavaDoc;
53 import org.w3c.dom.Element JavaDoc;
54 import org.w3c.dom.Node JavaDoc;
55 import org.w3c.dom.NodeList JavaDoc;
56
57 /**
58  * Content definition for XML template files.
59  *
60  * @author Alexander Lucas
61  * @version $Revision: 1.3 $ $Date: 2005/05/31 15:51:19 $
62  *
63  * @deprecated Will not be supported past the OpenCms 6 release.
64  */

65 public class CmsXmlTemplateFile extends A_CmsXmlContent {
66
67     /** Name of the tag for the editable templates */
68     public static final String JavaDoc C_EDIT_TEMPLATE = "edittemplate";
69
70     /** Name of the tag for the templates */
71     public static final String JavaDoc C_TEMPLATE = "template";
72
73     /**
74      * Default constructor.
75      */

76     public CmsXmlTemplateFile() throws CmsException {
77         if(CmsXmlTemplateLoader.getOnlineElementCache() == null){
78             registerTag("ELEMENT", CmsXmlTemplateFile.class, "handleElementTag", C_REGISTER_MAIN_RUN);
79         }
80     }
81
82     /**
83      * Constructor for creating a new object containing the content
84      * of the given filename.
85      *
86      * @param cms CmsObject object for accessing system resources.
87      * @param filename Name of the body file that shoul be read.
88      */

89     public CmsXmlTemplateFile(CmsObject cms, CmsFile file) throws CmsException {
90         super();
91         if(!CmsXmlTemplateLoader.isElementCacheEnabled()) {
92             registerMyTags();
93         }
94         init(cms, file);
95     }
96
97     /**
98      * Constructor for creating a new object containing the content
99      * of the given filename.
100      *
101      * @param cms CmsObject object for accessing system resources.
102      * @param filename Name of the body file that shoul be read.
103      */

104     public CmsXmlTemplateFile(CmsObject cms, String JavaDoc filename) throws CmsException {
105         super();
106         if(!CmsXmlTemplateLoader.isElementCacheEnabled()) {
107             registerMyTags();
108         }
109         init(cms, filename);
110     }
111     
112     public CmsXmlTemplateFile(CmsObject cms, String JavaDoc filename, String JavaDoc content) throws CmsException {
113         super();
114         if(!CmsXmlTemplateLoader.isElementCacheEnabled()) {
115             registerMyTags();
116         }
117         init(cms, filename, content);
118     }
119         
120     
121     public int createNewSection(String JavaDoc sectionName) {
122         int loop = 2;
123         String JavaDoc tempName = sectionName + loop;
124         while(hasData("template." + tempName)) {
125             tempName = sectionName + (++loop);
126         }
127         Element JavaDoc newData = getXmlDocument().createElement("template");
128         newData.setAttribute("name", tempName);
129         setData("template." + tempName, newData);
130         // and now create the section for the editor
131
Element JavaDoc newEditData = getXmlDocument().createElement(C_EDIT_TEMPLATE);
132         newEditData.setAttribute("name", tempName);
133         setData(C_EDIT_TEMPLATE + "."+ tempName, newEditData);
134         return loop;
135     }
136     public Vector JavaDoc getAllSections() throws CmsException {
137         NodeList JavaDoc nl = getXmlDocument().getDocumentElement().getChildNodes();
138         return getNamesFromNodeList(nl, "TEMPLATE", true);
139     }
140
141     /**
142      * This method is used by the linkmanagement. It returns a Vector with all
143      * link tag values in all TEMPLATE sections of the document.
144      */

145     public Vector JavaDoc getAllLinkTagValues()throws CmsException{
146         Vector JavaDoc retValue = new Vector JavaDoc();
147         NodeList JavaDoc list = getXmlDocument().getDocumentElement().getChildNodes();
148         int numElements = list.getLength();
149         for(int i=0; i < numElements; i++){
150             Node JavaDoc n = list.item(i);
151             // we only search in the template tags
152
if(n.getNodeType() == Node.ELEMENT_NODE && n.getNodeName().toLowerCase().equals(C_TEMPLATE)){
153                 NodeList JavaDoc subList = n.getChildNodes();
154                 for(int j=0; j<subList.getLength(); j++){
155                     Node JavaDoc subNode = subList.item(j);
156                     if(subNode.getNodeType()==Node.ELEMENT_NODE && subNode.getNodeName().equalsIgnoreCase("link")){
157                         // TODO: check firstChild null?
158
String JavaDoc value = subNode.getFirstChild().getNodeValue();
159                         if(!retValue.contains(value)){
160                             retValue.add(value);
161                         }
162                     }
163                 }
164             }
165         }
166
167         return retValue;
168     }
169
170     /**
171      * Gets an enumeration of all used subelements in all sections of
172      * of this template file.
173      * @return Vector of all subtemplate names.
174      * @throws CmsException
175      */

176     public Vector JavaDoc getAllSubElements() throws CmsException {
177         NodeList JavaDoc nl = getXmlDocument().getDocumentElement().getElementsByTagName("*");
178         return getNamesFromNodeList(nl, "ELEMENT", false);
179     }
180
181     /**
182      * Gets an enumeration of all subelements defined in all sections of
183      * of this template file.
184      * @return Vector of all subtemplate names.
185      * @throws CmsException
186      */

187     public Vector JavaDoc getAllSubElementDefinitions() throws CmsException {
188         NodeList JavaDoc nl = getXmlDocument().getDocumentElement().getElementsByTagName("*");
189         return getNamesFromNodeList(nl, "ELEMENTDEF", false);
190     }
191
192     /**
193      * Gets an enumeration of all used subelements in the given section
194      * of a template file.
195      * @param selector Section to be scanned for subelements
196      * @return Vector of all subtemplate names.
197      * @throws CmsException
198      */

199     public Vector JavaDoc getAllSubElements(String JavaDoc selector) throws CmsException {
200         String JavaDoc templateDatablockName = getTemplateDatablockName(selector);
201         Element JavaDoc templateElement = getData(templateDatablockName);
202         NodeList JavaDoc nl = templateElement.getChildNodes();
203         return getNamesFromNodeList(nl, "ELEMENT", false);
204     }
205     public Element JavaDoc getBodyTag() throws CmsException {
206         Element JavaDoc result = null;
207         if(hasData("bodyTag")) {
208             result = getData("bodytag");
209         }
210         else {
211             if(CmsLog.getLog(this).isDebugEnabled() ) {
212                 CmsLog.getLog(this).debug("Cannot find \"bodytag\" tag in XML template file " + getFilename());
213             }
214         }
215         return result;
216     }
217
218     /**
219      * Gets a description of this content type.
220      * @return Content type description.
221      */

222     public String JavaDoc getContentDescription() {
223         return "OpenCms XML template file";
224     }
225
226     /**
227      * Gets a complete datablock from the datablock hashtable.
228      *
229      * @param tag Key for the datablocks hashtable.
230      * @return Complete DOM element of the datablock for the given key
231      * or null if no datablock is found for this key.
232      */

233     public Element JavaDoc getData(String JavaDoc tag) throws CmsException {
234         return super.getData(tag);
235     }
236
237     /**
238      * Gets the text and CDATA content of a datablock from the
239      * datablock hashtable.
240      *
241      * @param tag Key for the datablocks hashtable.
242      * @return Datablock content for the given key or null if no datablock
243      * is found for this key.
244      */

245     public String JavaDoc getDataValue(String JavaDoc tag) throws CmsException {
246         return super.getDataValue(tag);
247     }
248
249     public String JavaDoc getEditableTemplateContent(Object JavaDoc callingObject, Hashtable JavaDoc parameters, String JavaDoc templateSelector, boolean html, String JavaDoc style) throws CmsException {
250         Vector JavaDoc cdatas = new Vector JavaDoc();
251         String JavaDoc editDatablockName = this.getEditTemplateDatablockName(templateSelector);
252         String JavaDoc datablockName = null;
253         String JavaDoc testValue = getDataValue(editDatablockName);
254         // if the editDatablock is empty (or not there) this seems to be an old template,
255
// so we use the original file
256
if(testValue == null || "".equals(testValue)){
257             datablockName = this.getTemplateDatablockName(templateSelector);
258         }else{
259             datablockName = editDatablockName;
260         }
261         Element JavaDoc data = getData(datablockName);
262         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
263         if(style == null) {
264             style = "";
265         }
266         Document JavaDoc tempDoc = (Document JavaDoc)getXmlDocument().cloneNode(true);
267         Element JavaDoc rootElem = tempDoc.getDocumentElement();
268         while(rootElem.hasChildNodes()) {
269             rootElem.removeChild(rootElem.getFirstChild());
270         }
271         data = (Element JavaDoc)getXmlParser().importNode(tempDoc, data);
272         rootElem.appendChild(data);
273         if(html) {
274             // Scan for cdatas
275
Node JavaDoc n = data;
276             while(n != null) {
277                 if(n.getNodeType() == Node.CDATA_SECTION_NODE) {
278                     cdatas.addElement(n.getNodeValue());
279                     n.setNodeValue("");
280                 }
281                 n = treeWalker(rootElem, n);
282             }
283         }
284         StringWriter JavaDoc out = new StringWriter JavaDoc();
285         getXmlParser().getXmlText(tempDoc, out);
286         String JavaDoc xmlString = out.toString();
287         int endOpeningXmlTag = xmlString.indexOf(">");
288         int endOpeningDocTag = xmlString.indexOf(">", endOpeningXmlTag + 1);
289         int endOpeningBodyTag = xmlString.indexOf(">", endOpeningDocTag + 1) + 1;
290         int startClosingDocTag = xmlString.lastIndexOf("<");
291         int startClosingBodyTag = xmlString.lastIndexOf("<", startClosingDocTag - 1);
292         if(startClosingBodyTag <= endOpeningBodyTag) {
293             xmlString = "";
294         }else {
295             xmlString = xmlString.substring(endOpeningBodyTag, startClosingBodyTag);
296             xmlString = xmlString.trim();
297         }
298         if(html) {
299             int cdataStart = xmlString.indexOf("<![CDATA[");
300             int currentPos = 0;
301             int loop = 0;
302             result.append("<HTML>\n<HEAD>\n");
303             result.append("<link rel=stylesheet type=\"text/css\" HREF=\"" + style + "\">\n");
304             result.append("</HEAD>\n");
305             result.append("<BASE HREF=\"");
306             I_CmsRequest req = CmsXmlTemplateLoader.getRequest(m_cms.getRequestContext());
307             result.append(req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getServletUrl() + (String JavaDoc)parameters.get("file"));
308             result.append("\"></BASE>");
309             result.append("<BODY " + getProcessedDataValue("bodytag", callingObject, parameters) + ">\n");
310             while(cdataStart != -1) {
311                 String JavaDoc tempString = xmlString.substring(currentPos, cdataStart);
312                 tempString = replaceBack(tempString);
313                 //result.append(xmlString.substring(currentPos, cdataStart).replace('<', '[').replace('>', ']'));
314
result.append(tempString);
315                 result.append((String JavaDoc)cdatas.elementAt(loop++));
316                 cdataStart = xmlString.indexOf("<![CDATA[", cdataStart + 1);
317                 currentPos = xmlString.indexOf("]]>", currentPos + 1) + 3;
318             }
319             String JavaDoc tempString = xmlString.substring(currentPos);
320             tempString = replaceBack(tempString);
321             //result.append(xmlString.substring(currentPos).replace('<', '[').replace('>', ']'));
322
result.append(tempString);
323             result.append("\n</BODY>\n</HTML>");
324             xmlString = result.toString();
325         }else {
326             // We are in text mode.
327
// Check, if there is any content in this body.
328
// Otherwise, set empty CDATA blocks.
329
if(xmlString.trim().equals("")) {
330                 xmlString = "<![CDATA[\n]]>";
331             }
332         }
333         return xmlString;
334     }
335
336     /**
337      * Internal utility method to extract the values of the "name" attribute
338      * from defined nodes of a given nodelist.
339      * @param nl NodeList to extract.
340      * @param tag Name of the tag whose "name" attribute should be extracted
341      * @param unnamedAllowed Indicates if unnamed tags are allowed or an exception should
342      * be thrown.
343      * @return Enumeration of all "name" attributes.
344      * @throws CmsException
345      */

346     private Vector JavaDoc getNamesFromNodeList(NodeList JavaDoc nl, String JavaDoc tag, boolean unnamedAllowed) throws CmsException {
347         int numElements = nl.getLength();
348         Vector JavaDoc collectNames = new Vector JavaDoc();
349         for(int i = 0;i < numElements;i++) {
350             Node JavaDoc n = nl.item(i);
351             if(n.getNodeType() == Node.ELEMENT_NODE && n.getNodeName().toLowerCase().equals(tag.toLowerCase())) {
352                 String JavaDoc name = ((Element JavaDoc)n).getAttribute("name");
353                 if(name == null || "".equals(name)) {
354                     // unnamed element found.
355
if(unnamedAllowed) {
356                         name = "(default)";
357                     }else {
358                         if(CmsLog.getLog(this).isErrorEnabled() ) {
359                             CmsLog.getLog(this).error("Unnamed <" + n.getNodeName() + "> found in OpenCms control file " + getAbsoluteFilename());
360                         }
361                         throw new CmsLegacyException("Unnamed \"" + n.getNodeName() + "\" found in OpenCms control file " + getAbsoluteFilename(), CmsLegacyException.C_XML_TAG_MISSING);
362                     }
363                 }
364                 collectNames.addElement(name);
365             }
366         }
367         return collectNames;
368     }
369
370     /**
371      * Gets the value of a single parameter of a given subelement definition.
372      * @param elementName Name of the subelement.
373      * @param parameterName Name of the requested parameter.
374      */

375     public String JavaDoc getParameter(String JavaDoc elementName, String JavaDoc parameterName) throws CmsException {
376         return getDataValue("ELEMENTDEF." + elementName + ".PARAMETER." + parameterName);
377     }
378
379     /**
380      * Gets an enumeration of all parameter names of a given subelement definition.
381      * @param elementName Name of the subelement.
382      * @return Vector of all names.
383      * @throws CmsException
384      */

385     public Vector JavaDoc getParameterNames(String JavaDoc elementName) throws CmsException {
386         if(hasData("elementdef." + elementName)) {
387             Element JavaDoc elementDefinition = getData("elementdef." + elementName);
388             NodeList JavaDoc parameterTags = elementDefinition.getChildNodes();
389             return getNamesFromNodeList(parameterTags, "PARAMETER", false);
390         }
391         else {
392             return null;
393         }
394     }
395
396     /**
397      * Get a hashtable containing all parameters and thies values of a given subelement definition.
398      * @param elementName Name of the subelement.
399      * @return Enumeration of all names.
400      * @throws CmsException
401      */

402     public Hashtable JavaDoc getParameters(String JavaDoc elementName) throws CmsException {
403         Hashtable JavaDoc result = new Hashtable JavaDoc();
404         if(hasData("elementdef." + elementName)) {
405             Element JavaDoc elementDefinition = getData("elementdef." + elementName);
406             NodeList JavaDoc parameterTags = elementDefinition.getChildNodes();
407
408             int numElements = parameterTags.getLength();
409             for(int i = 0;i < numElements;i++) {
410                 Node JavaDoc n = parameterTags.item(i);
411                 if(n.getNodeType() == Node.ELEMENT_NODE && n.getNodeName().toLowerCase().equals("parameter")) {
412                     String JavaDoc name = ((Element JavaDoc)n).getAttribute("name");
413                     if(name != null && !"".equals(name)) {
414                         result.put(name, getTagValue((Element JavaDoc)n));
415                     }
416                 }
417             }
418         }
419         return result;
420     }
421
422     /**
423      * Gets a processed datablock from the datablock hashtable.
424      *
425      * @param tag Key for the datablocks hashtable.
426      * @return Processed datablock for the given key.
427      * @throws CmsException
428      */

429     public Element JavaDoc getProcessedData(String JavaDoc tag) throws CmsException {
430         return super.getProcessedData(tag);
431     }
432
433     /**
434      * Gets a processed datablock from the datablock hashtable.
435      *
436      * @param tag Key for the datablocks hashtable.
437      * @param callingObject Object that should be used to look up user methods.
438      * @return Processed datablock for the given key.
439      * @throws CmsException
440      */

441     public Element JavaDoc getProcessedData(String JavaDoc tag, Object JavaDoc callingObject) throws CmsException {
442         return super.getProcessedData(tag, callingObject);
443     }
444
445     /**
446      * Gets a processed datablock from the datablock hashtable.
447      * <P>
448      * The userObj Object is passed to all called user methods.
449      * By using this, the initiating class can pass customized data to its methods.
450      *
451      * @param tag Key for the datablocks hashtable.
452      * @param callingObject Object that should be used to look up user methods.
453      * @param userObj any object that should be passed to user methods
454      * @return Processed datablock for the given key.
455      * @throws CmsException
456      */

457     public Element JavaDoc getProcessedData(String JavaDoc tag, Object JavaDoc callingObject, Object JavaDoc userObj) throws CmsException {
458         return super.getProcessedData(tag, callingObject, userObj);
459     }
460
461     /**
462      * Gets the text and CDATA content of a processed datablock from the
463      * datablock hashtable.
464      *
465      * @param tag Key for the datablocks hashtable.
466      * @return Processed datablock for the given key.
467      * @throws CmsException
468      */

469     public String JavaDoc getProcessedDataValue(String JavaDoc tag) throws CmsException {
470         return super.getProcessedDataValue(tag);
471     }
472
473     /**
474      * Gets the text and CDATA content of a processed datablock from the
475      * datablock hashtable.
476      *
477      * @param tag Key for the datablocks hashtable.
478      * @param callingObject Object that should be used to look up user methods.
479      * @return Processed datablock for the given key.
480      * @throws CmsException
481      */

482     public String JavaDoc getProcessedDataValue(String JavaDoc tag, Object JavaDoc callingObject) throws CmsException {
483         return super.getProcessedDataValue(tag, callingObject);
484     }
485
486     /**
487      * Gets the text and CDATA content of a processed datablock from the
488      * datablock hashtable.
489      * <P>
490      * The userObj Object is passed to all called user methods.
491      * By using this, the initiating class can pass customized data to its methods.
492      *
493      * @param tag Key for the datablocks hashtable.
494      * @param callingObject Object that should be used to look up user methods.
495      * @param userObj any object that should be passed to user methods
496      * @return Processed datablock for the given key.
497      * @throws CmsException
498      */

499     public String JavaDoc getProcessedDataValue(String JavaDoc tag, Object JavaDoc callingObject, Object JavaDoc userObj) throws CmsException {
500         return super.getProcessedDataValue(tag, callingObject, userObj);
501     }
502
503     /**
504      * Gets the text and CDATA content of a processed datablock from the
505      * datablock hashtable. An eventually given output stream is user for streaming
506      * the generated result directly to the response output stream while processing.
507      * <P>
508      * The userObj Object is passed to all called user methods.
509      * By using this, the initiating class can pass customized data to its methods.
510      *
511      * @param tag Key for the datablocks hashtable.
512      * @param callingObject Object that should be used to look up user methods.
513      * @param userObj any object that should be passed to user methods
514      * @param stream OutputStream that may be used for directly streaming the results or null.
515      * @return Processed datablock for the given key.
516      * @throws CmsException
517      */

518     public String JavaDoc getProcessedDataValue(String JavaDoc tag, Object JavaDoc callingObject, Object JavaDoc userObj, OutputStream JavaDoc stream) throws CmsException {
519         return super.getProcessedDataValue(tag, callingObject, userObj, stream);
520     }
521
522     /**
523      * Gets the processed data of the default <code>&lt;TEMPLATE&gt;</code> section of
524      * this workplace template file.
525      * <P>
526      * The correct datablock name for the template datablock will be taken
527      * from <code>getTemplateDatablockName</code>.
528      *
529      * @param callingObject reference to the calling object. Used to look up user methods while processing.
530      * @param parameters hashtable containing all user parameters.
531      * @return Processed template data.
532      * @throws CmsException
533      */

534     public String JavaDoc getProcessedTemplateContent(Object JavaDoc callingObject, Hashtable JavaDoc parameters) throws CmsException {
535         return getProcessedTemplateContent(callingObject, parameters, null);
536     }
537
538     /**
539      * Gets the processed data of the appropriate <code>&lt;TEMPLATE&gt;</code> section of
540      * this workplace template file.
541      * <P>
542      * The correct datablock name for the template datablock will be taken
543      * from <code>getTemplateDatablockName</code>.
544      *
545      * @param callingObject reference to the calling object. Used to look up user methods while processing.
546      * @param parameters hashtable containing all user parameters.
547      * @param templateSelector Name of the template section or null if the default section is requested.
548      * @return Processed template data.
549      * @throws CmsException
550      */

551     public String JavaDoc getProcessedTemplateContent(Object JavaDoc callingObject, Hashtable JavaDoc parameters, String JavaDoc templateSelector) throws CmsException {
552         OutputStream JavaDoc os = null;
553
554         String JavaDoc datablockName = this.getTemplateDatablockName(templateSelector);
555         if(datablockName == null && (templateSelector.toLowerCase().equals("script"))) {
556             return "";
557         }
558
559         if (CmsLog.getLog(this).isDebugEnabled()) {
560             CmsLog.getLog(this).debug("TemplateSelector is " + templateSelector);
561         }
562         return getProcessedDataValue(datablockName, callingObject, parameters, os);
563     }
564
565     /**
566      * Gets the processed data of the appropriate <code>&lt;TEMPLATE&gt;</code> section of
567      * this workplace template file.
568      * <P>
569      * In contrast to <code>getProcessedElementContent()</code> the <code>&lt;ELEMENT&gt;</code>
570      * tags will NOT be resolved during this loop. Instead, a new element cache variant
571      * containing links to these elements will be created.
572      *
573      * @param callingObject reference to the calling object. Used to look up user methods while processing.
574      * @param parameters hashtable containing all user parameters.
575      * @param elementName Element name of this template in our parent template.
576      * @param templateSelector Name of the template section or null if the default section is requested.
577      * @return New variant for the element cache.
578      * @throws CmsException
579      */

580     public CmsElementVariant generateElementCacheVariant(Object JavaDoc callingObject, Hashtable JavaDoc parameters, String JavaDoc elementName, String JavaDoc templateSelector) throws CmsException {
581         CmsElementVariant result = new CmsElementVariant();
582
583         String JavaDoc datablockName = this.getTemplateDatablockName(templateSelector);
584         if(datablockName == null && (templateSelector.toLowerCase().equals("script"))) {
585             return result;
586         }
587
588         Element JavaDoc domEl = getProcessedData(datablockName, callingObject, parameters, null);
589         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
590         for(Node JavaDoc n = domEl.getFirstChild(); n != null; n = treeWalker(domEl, n)) {
591             if(n.getNodeType() == Node.ELEMENT_NODE && "element".equalsIgnoreCase(n.getNodeName())) {
592                 // This is an <ELEMENT> tag. First get the name of this element
593
String JavaDoc elName = ((Element JavaDoc)n).getAttribute("name");
594
595                 if(elName != null && !"".equalsIgnoreCase(elName)) {
596                     // If there is something in the string buffer, store is now!
597
if(buf.length() > 0) {
598                         result.add(buf.toString());
599                         buf = new StringBuffer JavaDoc();
600
601                     }
602
603                     // Create new CmsElementLink
604
CmsElementLink link = new CmsElementLink(elName);
605                     result.add(link);
606                 }
607             } else if (n.getNodeType() == Node.ELEMENT_NODE && "method".equalsIgnoreCase(n.getNodeName())) {
608                 // this is a left over <METHOD> tag.
609
String JavaDoc methodName = ((Element JavaDoc)n).getAttribute("name");
610                 String JavaDoc tagcontent = getTagValue((Element JavaDoc)n);
611                 if(methodName != null && !"".equals(methodName)){
612                     //if there is something in the buffer store it now
613
if(buf.length() > 0) {
614                         result.add(buf.toString());
615                         buf = new StringBuffer JavaDoc();
616                     }
617                     // create the new methode link
618
CmsMethodLink methodLink = new CmsMethodLink(methodName, tagcontent);
619                     result.add(methodLink);
620                     // remove the tagcontent if necessary
621
if(tagcontent != null && !"".equals(tagcontent)){
622                         n = treeWalker(domEl, n);
623                     }
624                 }
625             } else if (n.getNodeType() == Node.TEXT_NODE || n.getNodeType() == Node.CDATA_SECTION_NODE) {
626                 buf.append(n.getNodeValue());
627             }
628         }
629
630         // Store pending buffer content
631
if(buf.length() > 0) {
632             result.add(buf.toString());
633         }
634         return result;
635     }
636
637     public String JavaDoc getSectionTitle(String JavaDoc sectionName) throws CmsException {
638         String JavaDoc datablockName = getTemplateDatablockName(sectionName);
639         String JavaDoc result = null;
640         try {
641             Element JavaDoc data = getData(datablockName);
642             result = data.getAttribute("title");
643         }
644         catch(Exception JavaDoc e) {
645
646             // The given section doesn't exist. Ignore.
647
result = "";
648         }
649         return result;
650     }
651
652     /**
653      * Gets the template class of a given subelement definition.
654      * @param elementName Name of the subelement.
655      * @return Name of the template class.
656      */

657     public String JavaDoc getSubtemplateClass(String JavaDoc name) throws CmsException {
658         String JavaDoc className = getDataValue("ELEMENTDEF." + name + ".CLASS");
659         return className;
660     }
661
662     /**
663      * Gets the filename of the master template file of a given subelement definition.
664      * @param elementName Name of the subelement.
665      * @return Filename of the template file.
666      */

667     public String JavaDoc getSubtemplateFilename(String JavaDoc name) throws CmsException {
668         String JavaDoc className = getDataValue("ELEMENTDEF." + name + ".TEMPLATE");
669         return className;
670     }
671
672     /**
673      * Gets the template selector of the master template file of a given subelement definition.
674      * @param elementName Name of the subelement.
675      * @return Filename of the template file.
676      */

677     public String JavaDoc getSubtemplateSelector(String JavaDoc name) throws CmsException {
678         String JavaDoc templateSelector = getDataValue("ELEMENTDEF." + name + ".TEMPLATESELECTOR");
679         return templateSelector;
680     }
681
682     /**
683      * Gets the data of the appropriate <code>&lt;TEMPLATE&gt;</code> section of
684      * this workplace template file.
685      * <P>
686      * The correct datablock name for the template datablock will be taken
687      * from <code>getTemplateDatablockName</code>.
688      *
689      * @param callingObject reference to the calling object. Used to look up user methods while processing.
690      * @param parameters hashtable containing all user parameters.
691      * @param templateSelector Name of the template section or null if the default section is requested.
692      * @return Processed template data.
693      * @throws CmsException
694      */

695     public String JavaDoc getTemplateContent(Object JavaDoc callingObject, Hashtable JavaDoc parameters, String JavaDoc templateSelector) throws CmsException {
696         String JavaDoc datablockName = this.getTemplateDatablockName(templateSelector);
697         return getDataValue(datablockName);
698     }
699
700     /**
701      * Utility method to get the correct datablock name for a given selector.<BR>
702      * If no selector is given or the selected section is not found, the template section
703      * with no name will be returned. If even this is not found the section named "default"
704      * will be returned.
705      *
706      * @param templateSelector Name of the template section or null if the default section is requested.
707      * @return Appropriate name of the template datablock.
708      * @throws CmsException
709      */

710     private String JavaDoc getTemplateDatablockName(String JavaDoc templateSelector) throws CmsException {
711         String JavaDoc templateDatablockName = null;
712         if(templateSelector != null && !"".equals(templateSelector)) {
713             if(hasData("template." + templateSelector)) {
714                 templateDatablockName = "template." + templateSelector;
715             }else {
716                 if(CmsLog.getLog(this).isDebugEnabled() && (!"script".equals(templateSelector))) {
717                     CmsLog.getLog(this).debug("Cannot load selected template file section " + templateSelector + " in template file " + getFilename() + ", fallback to default section");
718                 }
719             }
720         }
721         if(templateDatablockName == null && (!"script".equals(templateSelector))) {
722             if(hasData("TEMPLATE")) {
723                 templateDatablockName = "TEMPLATE";
724             }else {
725                 if(hasData("TEMPLATE.default")) {
726                     templateDatablockName = "TEMPLATE.default";
727                 }else {
728                     if(CmsLog.getLog(this).isErrorEnabled() ) {
729                         CmsLog.getLog(this).error("Template definition file " + getAbsoluteFilename() + " is corrupt, cannot find default section");
730                     }
731                     throw new CmsLegacyException("Corrupt template file " + getAbsoluteFilename() + ", cannot find default section", CmsLegacyException.C_XML_TAG_MISSING);
732                 }
733             }
734         }
735         return templateDatablockName;
736     }
737
738     /**
739      * Utility method to get the correct edit-datablock name for a given selector.<BR>
740      * If no selector is given or the selected section is not found, the template section
741      * with no name will be returned. If even this is not found the section named "default"
742      * will be returned.
743      *
744      * @param templateSelector Name of the template section or null if the default section is requested.
745      * @return Appropriate name of the template datablock.
746      * @throws CmsException
747      */

748     private String JavaDoc getEditTemplateDatablockName(String JavaDoc templateSelector) throws CmsException {
749         String JavaDoc templateDatablockName = null;
750         if(templateSelector != null && !"".equals(templateSelector)) {
751             if(hasData(C_EDIT_TEMPLATE + "." + templateSelector)) {
752                 templateDatablockName = C_EDIT_TEMPLATE + "." + templateSelector;
753             }else {
754                 if(CmsLog.getLog(this).isDebugEnabled() && (!"script".equals(templateSelector))) {
755                     CmsLog.getLog(this).debug("Cannot load selected template file section " + templateSelector + " in template file " + getFilename() + ", fallback to default section");
756                 }
757             }
758         }
759         if(templateDatablockName == null && (!"script".equals(templateSelector))) {
760             if(hasData(C_EDIT_TEMPLATE)) {
761                 templateDatablockName = C_EDIT_TEMPLATE;
762             }else {
763                 if(hasData(C_EDIT_TEMPLATE + ".default")) {
764                     templateDatablockName = C_EDIT_TEMPLATE + ".default";
765                 }else{
766                     // no default section. file seems to be an old one without the edittemplate section
767
// so create it.
768
setData(C_EDIT_TEMPLATE , (String JavaDoc)null);
769                     templateDatablockName = C_EDIT_TEMPLATE;
770                 }
771            }
772         }
773         return templateDatablockName;
774     }
775
776     /**
777      * Gets the expected tagname for the XML documents of this content type
778      * @return Expected XML tagname.
779      */

780     public String JavaDoc getXmlDocumentTagName() {
781         return "XMLTEMPLATE";
782     }
783
784     /**
785      * Handling of the <CODE>&lt;ELEMENT&gt;</CODE> tags.
786      * Calls the user method <code>elementTag</code> that has to be
787      * defined in the XML template class.
788      *
789      * @param n XML element containing the <code>&lt;PROCESS&gt;</code> tag.
790      * @param callingObject Reference to the object requesting the node processing.
791      * @param userObj Customizable user object that will be passed through to handling and user methods.
792      * @return Result of user method <code>templateElement()</code>.
793      * @throws CmsException
794      */

795     public Object JavaDoc handleElementTag(Element JavaDoc n, Object JavaDoc callingObject, Object JavaDoc userObj) throws CmsException {
796         String JavaDoc tagcontent = n.getAttribute("name");
797         return callUserMethod("templateElement", tagcontent, callingObject, userObj, false);
798     }
799
800     /**
801      * Checks if this Template owns a datablock with the given key.
802      * @param key Datablock key to be checked.
803      * @return true if a datablock is found, false otherwise.
804      */

805     public boolean hasData(String JavaDoc key) {
806         return super.hasData(key);
807     }
808
809     /**
810      * Checks if the section with the given name is defined
811      * in this XML template file.
812      * @param name Name of the requested section.
813      * @return <code>true</code> if a section exists, <code>false</code> otherwise.
814      */

815     public boolean hasSection(String JavaDoc name) {
816         return hasData("template." + name);
817     }
818
819     /**
820      * Check if there is the template class of a given subelement defined.
821      * @param elementName Name of the subelement.
822      * @return <code>true</code>, if defined, <code>false</code> otherwise
823      */

824     public boolean hasSubtemplateClass(String JavaDoc name) throws CmsException {
825         return hasData("ELEMENTDEF." + name + ".CLASS");
826     }
827
828     /**
829      * Check if there is the template filename of a given subelement defined.
830      * @param elementName Name of the subelement.
831      * @return <code>true</code>, if defined, <code>false</code> otherwise
832      */

833     public boolean hasSubtemplateFilename(String JavaDoc name) throws CmsException {
834         return hasData("ELEMENTDEF." + name + ".TEMPLATE");
835     }
836
837     /**
838      * Checks if there is a template selector defined in the subelement definition of
839      * this template file.
840      * @param elementName Name of the subelement.
841      * @return <code>true</code>, if there exists a template selector, <code>false</code> otherwise.
842      */

843     public boolean hasSubtemplateSelector(String JavaDoc name) throws CmsException {
844         return hasData("ELEMENTDEF." + name + ".TEMPLATESELECTOR");
845     }
846     private int min(int a, int b) {
847         if(a == -1) {
848             return b;
849         }
850         if(b == -1) {
851             return a;
852         }
853         return a < b ? a : b;
854     }
855     private String JavaDoc replaceBack(String JavaDoc s) {
856         StringBuffer JavaDoc tempContent = new StringBuffer JavaDoc();
857
858         //int index = s.indexOf(search);
859
int index = min(s.indexOf("<"), s.indexOf(">"));
860         index = min(index, s.indexOf("\""));
861         int lastindex = 0;
862         while(index != -1) {
863             String JavaDoc sub = s.substring(lastindex, index);
864             tempContent.append(sub);
865             if(s.charAt(index) == '>') {
866
867                 //tempContent.append("]</CODE>");
868
tempContent.append("]]");
869                 lastindex = index + 1;
870             }
871             else {
872                 if(s.charAt(index) == '<') {
873
874                     //tempContent.append("<CODE>[");
875
tempContent.append("[[");
876                     lastindex = index + 1;
877                 }
878                 else {
879                     tempContent.append("&quot;");
880                     lastindex = index + 1;
881                 }
882             }
883
884             //index = s.indexOf(search, index+1);
885

886             //index = min(s.indexOf("<", index+1), s.indexOf(">", index+1));
887
index = min(s.indexOf("<", index + 1), min(s.indexOf(">", index + 1), s.indexOf("\"", index + 1)));
888         }
889         tempContent.append(s.substring(lastindex));
890         return new String JavaDoc(tempContent);
891     }
892
893     /**
894      * Registers the special tag <CODE>&lt;ELEMENT&gt;</CODE> for processing with
895      * processNode().
896      */

897     private void registerMyTags() {
898         registerTag("ELEMENT", CmsXmlTemplateFile.class, "handleElementTag", C_REGISTER_MAIN_RUN);
899     }
900
901     /**
902      * Remove a datablock from the internal hashtable and
903      * from the XML document
904      * @param tag Key of the datablock to delete.
905      */

906     public void removeData(String JavaDoc tag) {
907         super.removeData(tag);
908     }
909     public void renameSection(String JavaDoc oldName, String JavaDoc newName) throws CmsException {
910         if(!hasData("template." + newName)) {
911             if(CmsLog.getLog(this).isInfoEnabled() ) {
912                 CmsLog.getLog(this).info("Datablock TEMPLATE." + newName + " not found, creating it");
913             }
914             Element JavaDoc newData = (Element JavaDoc)getData("template." + oldName).cloneNode(true);
915             newData.setAttribute("name", newName);
916             setData("template." + newName, newData);
917             removeData("template." + oldName);
918             // now for the editor copy
919
if(hasData(C_EDIT_TEMPLATE +"."+oldName)){
920                 Element JavaDoc newEditData = (Element JavaDoc)getData(C_EDIT_TEMPLATE +"."+oldName).cloneNode(true);
921                 newEditData.setAttribute("name", newName);
922                 setData(C_EDIT_TEMPLATE +"."+newName, newEditData);
923                 removeData(C_EDIT_TEMPLATE +"."+oldName);
924             }
925         }else {
926             throw new CmsLegacyException("Section already exists: " + newName, CmsLegacyException.C_BAD_NAME);
927         }
928     }
929     /* parameters search and replace are ignored.*/
930     private String JavaDoc replace(String JavaDoc s, String JavaDoc search, String JavaDoc replace) {
931         StringBuffer JavaDoc tempContent = new StringBuffer JavaDoc();
932
933         //int index = s.indexOf(search);
934
int index = min(s.indexOf("[["), s.indexOf("]]"));
935         index = min(index, s.indexOf("&quot;"));
936         int lastindex = 0;
937         while(index != -1) {
938             String JavaDoc sub = s.substring(lastindex, index);
939             tempContent.append(sub);
940             if(s.charAt(index) == ']') {
941                 tempContent.append("><![CDATA[");
942                 lastindex = index + 2;
943             }
944             else {
945                 if(s.charAt(index) == '[') {
946                     tempContent.append("]]><");
947                     lastindex = index + 2;
948                 }
949                 else {
950                     tempContent.append("\"");
951                     lastindex = index + 6;
952                 }
953             }
954
955             //index = s.indexOf(search, index+1);
956
index = min(s.indexOf("[[", index + 1), min(s.indexOf("]]", index + 1), s.indexOf("&quot;", index + 1)));
957         }
958         tempContent.append(s.substring(lastindex));
959         return new String JavaDoc(tempContent);
960     }
961     public void setBodyTag(Element JavaDoc data) throws CmsException {
962         setData("bodytag", data);
963     }
964
965     /**
966      * Creates a datablock consisting of a single TextNode containing
967      * data and stores this block into the datablock-hashtable.
968      *
969      * @param tag Key for this datablock.
970      * @param data String to be put in the datablock.
971      */

972     public void setData(String JavaDoc tag, String JavaDoc data) {
973         super.setData(tag, data);
974     }
975
976     /**
977      * Stores a given datablock element in the datablock hashtable.
978      *
979      * @param tag Key for this datablock.
980      * @param data DOM element node for this datablock.
981      */

982     public void setData(String JavaDoc tag, Element JavaDoc data) {
983         super.setData(tag, data);
984     }
985
986     /**
987      * Creates a datablock element by parsing the data string
988      * and stores this block into the datablock-hashtable.
989      *
990      * @param tag Key for this datablock.
991      * @param data String to be put in the datablock.
992      */

993     public void setParsedData(String JavaDoc tag, String JavaDoc data) throws CmsException {
994         super.setParsedData(tag, data);
995     }
996
997     public void setEditedTemplateContent(CmsObject cms, String JavaDoc content, String JavaDoc templateSelector, boolean html, String JavaDoc filePath, String JavaDoc relativeRoot) throws CmsException {
998         //first the original only used by the editor
999
String JavaDoc editDatablockName = getEditTemplateDatablockName(templateSelector);
1000        String JavaDoc copyOfContent = content;
1001        if(html) {
1002            
1003            int startIndex = content.indexOf("<body");
1004            if (startIndex < 0) startIndex = content.indexOf("<BODY");
1005            startIndex = content.indexOf(">", startIndex + 1) + 1;
1006            int endIndex = content.lastIndexOf("</body>");
1007            if (endIndex < 0) endIndex = content.lastIndexOf("</BODY>");
1008            if(startIndex > 0) {
1009                content = content.substring(startIndex, endIndex);
1010            }
1011        }
1012        
1013        // substitute contextpath with variable
1014
content = CmsStringUtil.substituteContextPath(content, OpenCms.getSystemInfo().getOpenCmsContext() + "/");
1015                
1016        StringBuffer JavaDoc tempXmlString = new StringBuffer JavaDoc();
1017        tempXmlString.append("<?xml version=\"1.0\"?>\n");
1018        tempXmlString.append("<" + getXmlDocumentTagName() + ">");
1019        tempXmlString.append("<"+C_EDIT_TEMPLATE +">\n");
1020        if(html) {
1021            tempXmlString.append("<![CDATA[");
1022            content = replace(content, "[", "]]><");
1023            tempXmlString.append(content.trim());
1024            tempXmlString.append("]]>");
1025        }else {
1026            tempXmlString.append(content);
1027        }
1028        tempXmlString.append("</"+C_EDIT_TEMPLATE +">\n");
1029        tempXmlString.append("</" + getXmlDocumentTagName() + ">\n");
1030        I_CmsXmlParser parser = getXmlParser();
1031        StringReader JavaDoc parserReader = new StringReader JavaDoc(tempXmlString.toString());
1032        Document JavaDoc tempDoc = null;
1033        try {
1034            tempDoc = parser.parse(parserReader);
1035        }catch(Exception JavaDoc e) {
1036            throwException("PARSING ERROR!", CmsLegacyException.C_XML_PARSING_ERROR);
1037        }
1038        Element JavaDoc templateNode = (Element JavaDoc)tempDoc.getDocumentElement().getFirstChild();
1039        setData(editDatablockName, templateNode);
1040
1041        // now the parsed content for the templatemechanism
1042
String JavaDoc datablockName = this.getTemplateDatablockName(templateSelector);
1043        if(!html){
1044            // we have to prepare the content for the tidy
1045
copyOfContent = "<HTML><HEAD></HEAD><body>" + copyOfContent.substring(9, copyOfContent.lastIndexOf("]]>")) + "</body></HTML>";
1046        }else{
1047            copyOfContent = replace(copyOfContent, "", "");
1048        }
1049        // now we have something for the tidy
1050
try{
1051            copyOfContent = CmsXmlTemplateLinkConverter.convertFromEditor(cms, copyOfContent, filePath, relativeRoot);
1052        }catch(CmsException e){
1053            throw new CmsLegacyException("["+this.getClass().getName()+"] cant parse the content:", e);
1054        }
1055        int startIndex = copyOfContent.indexOf("<body");
1056        startIndex = copyOfContent.indexOf(">", startIndex + 1) + 1;
1057        int endIndex = copyOfContent.lastIndexOf("</body>");
1058        if(startIndex > 0) {
1059            copyOfContent = copyOfContent.substring(startIndex, endIndex);
1060        }
1061        tempXmlString = new StringBuffer JavaDoc();
1062        tempXmlString.append("<?xml version=\"1.0\"?>\n");
1063        tempXmlString.append("<" + getXmlDocumentTagName() + ">");
1064        tempXmlString.append("<template>\n");
1065        tempXmlString.append("<![CDATA[");
1066        tempXmlString.append(copyOfContent.trim());
1067        tempXmlString.append("]]>");
1068        tempXmlString.append("</template>\n");
1069        tempXmlString.append("</" + getXmlDocumentTagName() + ">\n");
1070        I_CmsXmlParser parser2 = getXmlParser();
1071        StringReader JavaDoc parserReader2 = new StringReader JavaDoc(tempXmlString.toString());
1072        Document JavaDoc tempDoc2 = null;
1073        try {
1074            tempDoc2 = parser2.parse(parserReader2);
1075        }
1076        catch(Exception JavaDoc e) {
1077            throwException("PARSING ERROR!", CmsLegacyException.C_XML_PARSING_ERROR);
1078        }
1079        Element JavaDoc templateNode2 = (Element JavaDoc)tempDoc2.getDocumentElement().getFirstChild();
1080        setData(datablockName, templateNode2);
1081
1082    }
1083
1084    public void setSectionTitle(String JavaDoc sectionName, String JavaDoc title) throws CmsException {
1085        String JavaDoc datablockName = getTemplateDatablockName(sectionName);
1086        Element JavaDoc data = null;
1087        try {
1088            data = getData(datablockName);
1089        }
1090        catch(Exception JavaDoc e) {
1091
1092            // The given section doesn't exist. Ignore.
1093
if(CmsLog.getLog(this).isWarnEnabled() ) {
1094                CmsLog.getLog(this).warn("Cannot set title for template section \"" + sectionName + "\" in file " + getAbsoluteFilename() + ", section doesn't exist");
1095            }
1096            return ;
1097        }
1098        data.setAttribute("title", title);
1099    }
1100}
1101
Popular Tags