KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opencms > workplace > tools > content > CmsElementRename


1 /*
2  * File : $Source: /usr/local/cvs/opencms/src-modules/org/opencms/workplace/tools/content/CmsElementRename.java,v $
3  * Date : $Date: 2006/03/31 13:59:16 $
4  * Version: $Revision: 1.15 $
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.workplace.tools.content;
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.types.CmsResourceTypeXmlPage;
41 import org.opencms.i18n.CmsLocaleManager;
42 import org.opencms.i18n.CmsMessages;
43 import org.opencms.jsp.CmsJspActionElement;
44 import org.opencms.lock.CmsLock;
45 import org.opencms.main.CmsException;
46 import org.opencms.main.CmsLog;
47 import org.opencms.main.OpenCms;
48 import org.opencms.report.I_CmsReport;
49 import org.opencms.util.CmsStringUtil;
50 import org.opencms.workplace.CmsReport;
51 import org.opencms.workplace.CmsWorkplace;
52 import org.opencms.workplace.CmsWorkplaceSettings;
53 import org.opencms.workplace.editors.CmsDialogElement;
54 import org.opencms.workplace.explorer.CmsNewResourceXmlPage;
55 import org.opencms.xml.CmsXmlException;
56 import org.opencms.xml.page.CmsXmlPage;
57 import org.opencms.xml.page.CmsXmlPageFactory;
58 import org.opencms.xml.types.CmsXmlHtmlValue;
59
60 import java.util.ArrayList JavaDoc;
61 import java.util.HashSet JavaDoc;
62 import java.util.Iterator JavaDoc;
63 import java.util.List JavaDoc;
64 import java.util.Locale JavaDoc;
65 import java.util.Set JavaDoc;
66 import java.util.StringTokenizer JavaDoc;
67 import java.util.TreeMap JavaDoc;
68
69 import javax.servlet.http.HttpServletRequest JavaDoc;
70 import javax.servlet.http.HttpServletResponse JavaDoc;
71 import javax.servlet.jsp.JspException JavaDoc;
72 import javax.servlet.jsp.PageContext JavaDoc;
73
74 import org.apache.commons.logging.Log;
75
76 /**
77  * Provides methods for the change page element name dialog.<p>
78  *
79  * @author Armen Markarian
80  *
81  * @version $Revision: 1.15 $
82  *
83  * @since 6.0.0
84  */

85 public class CmsElementRename extends CmsReport {
86
87     /** A constant representing the select option all templates. */
88     public static final String JavaDoc ALL = "ALL";
89
90     /** The dialog type. */
91     public static final String JavaDoc DIALOG_TYPE = "renameelement";
92
93     /** Request parameter name for the locale. */
94     public static final String JavaDoc PARAM_LOCALE = "locale";
95
96     /** Request parameter name for the new element name. */
97     public static final String JavaDoc PARAM_NEW_ELEMENT = "newelement";
98
99     /** Request parameter name for the old element name. */
100     public static final String JavaDoc PARAM_OLD_ELEMENT = "oldelement";
101
102     /** Request parameter name for the recursive search. */
103     public static final String JavaDoc PARAM_RECURSIVE = "recursive";
104
105     /** Request parameter name for the remove empty elements. */
106     public static final String JavaDoc PARAM_REMOVE_EMPTYELEMENTS = "removeemptyelements";
107
108     /** Request parameter name for the template. */
109     public static final String JavaDoc PARAM_TEMPLATE = "template";
110
111     /** Request parameter name for the validate new element. */
112     public static final String JavaDoc PARAM_VALIDATE_NEW_ELEMENT = "validatenewelement";
113
114     /** The log object for this class. */
115     private static final Log LOG = CmsLog.getLog(CmsElementRename.class);
116
117     /** the cms object. */
118     private CmsObject m_cms;
119     /** the error message. */
120     private String JavaDoc m_errorMessage;
121     /** the locale use for content definition. */
122     private String JavaDoc m_paramLocale;
123     /** The new page element name. */
124     private String JavaDoc m_paramNewElement;
125     /** The old page element name. */
126     private String JavaDoc m_paramOldElement;
127     /** The recursive parameter. */
128     private String JavaDoc m_paramRecursive;
129     /** the flag indicating to remove empty elements. */
130     private String JavaDoc m_paramRemoveEmptyElements;
131     /** the template use for all pages (optional). */
132     private String JavaDoc m_paramTemplate;
133     /** the flag indicating to remove empty elements. */
134     private String JavaDoc m_paramValidateNewElement;
135     /** the report for the output. */
136     private I_CmsReport m_report;
137
138     /**
139      * Public constructor with JSP action element.<p>
140      *
141      * @param jsp an initialized JSP action element
142      */

143     public CmsElementRename(CmsJspActionElement jsp) {
144
145         super(jsp);
146     }
147
148     /**
149      * Public constructor for testcase using.<p>
150      *
151      * @param jsp an initialized JSP action element
152      * @param cms the cms object
153      * @param resource the resource path
154      * @param recursive if true then do read recursive from the folder
155      * @param template the template
156      * @param locale the locale
157      * @param oldElement the old element name
158      * @param newElement the new element name
159      * @param removeEmptyElements if true then remove all invalid elements with no content
160      * @param validateNewElement if true then validate the new element before renaming
161      */

162     public CmsElementRename(
163         CmsJspActionElement jsp,
164         CmsObject cms,
165         String JavaDoc resource,
166         String JavaDoc recursive,
167         String JavaDoc template,
168         String JavaDoc locale,
169         String JavaDoc oldElement,
170         String JavaDoc newElement,
171         String JavaDoc removeEmptyElements,
172         String JavaDoc validateNewElement) {
173
174         super(jsp);
175         m_cms = cms;
176         setParamResource(resource);
177         setParamRecursive(recursive);
178         setParamTemplate(template);
179         setParamLocale(locale);
180         setParamOldElement(oldElement);
181         setParamNewElement(newElement);
182         setParamRemoveEmptyElements(removeEmptyElements);
183         setParamValidateNewElement(validateNewElement);
184     }
185
186     /**
187      * Public constructor with JSP variables.<p>
188      *
189      * @param context the JSP page context
190      * @param req the JSP request
191      * @param res the JSP response
192      */

193     public CmsElementRename(PageContext JavaDoc context, HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res) {
194
195         this(new CmsJspActionElement(context, req, res));
196     }
197
198     /**
199      * Renames the element name on the specified resources.<p>
200      *
201      * @param report the cms report
202      */

203     public void actionRename(I_CmsReport report) {
204
205         m_report = report;
206         List JavaDoc locales = OpenCms.getLocaleManager().getAvailableLocales();
207         List JavaDoc xmlPages = getXmlPages();
208         if (ALL.equals(getParamLocale())) {
209             Iterator JavaDoc i = locales.iterator();
210             while (i.hasNext()) {
211                 Locale JavaDoc locale = (Locale JavaDoc)i.next();
212                 performRenameOperation(xmlPages, locale);
213             }
214         } else {
215             performRenameOperation(xmlPages, CmsLocaleManager.getLocale(getParamLocale()));
216         }
217     }
218
219     /**
220      * Performs the move report, will be called by the JSP page.<p>
221      *
222      * @throws JspException if problems including sub-elements occur
223      */

224     public void actionReport() throws JspException JavaDoc {
225
226         // save initialized instance of this class in request attribute for included sub-elements
227
getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, this);
228         switch (getAction()) {
229             case ACTION_REPORT_END:
230                 actionCloseDialog();
231                 break;
232             case ACTION_REPORT_UPDATE:
233                 setParamAction(REPORT_UPDATE);
234                 getJsp().include(FILE_REPORT_OUTPUT);
235                 break;
236             case ACTION_REPORT_BEGIN:
237             case ACTION_CONFIRMED:
238             default:
239                 CmsElementRenameThread thread = new CmsElementRenameThread(getCms(), this);
240                 setParamAction(REPORT_BEGIN);
241                 setParamThread(thread.getUUID().toString());
242                 getJsp().include(FILE_REPORT_OUTPUT);
243                 break;
244         }
245     }
246
247     /**
248      * Builds the html for the available locales select box.<p>
249      *
250      * @param attributes optional attributes for the &lt;select&gt; tag
251      *
252      * @return the html for the available locales select box
253      */

254     public String JavaDoc buildSelectLocales(String JavaDoc attributes) {
255
256         List JavaDoc options = new ArrayList JavaDoc();
257         List JavaDoc values = new ArrayList JavaDoc();
258         List JavaDoc locales = OpenCms.getLocaleManager().getAvailableLocales();
259         int selectedIndex = -1;
260         if (locales == null) {
261             // no locales found, return empty String
262
return "";
263         } else {
264             // locales found, create option and value lists
265
CmsMessages messages = Messages.get().getBundle(getLocale());
266             options.add(messages.key(Messages.GUI_PLEASE_SELECT_0));
267             values.add("");
268             options.add(messages.key(Messages.GUI_BUTTON_ALL_0));
269             values.add(ALL);
270             if (ALL.equals(getParamLocale())) {
271                 selectedIndex = 1;
272             }
273             Iterator JavaDoc i = locales.iterator();
274             int counter = 2;
275             while (i.hasNext()) {
276                 Locale JavaDoc locale = (Locale JavaDoc)i.next();
277                 String JavaDoc language = locale.getLanguage();
278                 String JavaDoc displayLanguage = locale.getDisplayLanguage();
279                 if (language.equals(getParamLocale())) {
280                     selectedIndex = counter;
281                 }
282                 options.add(displayLanguage);
283                 values.add(language);
284                 counter++;
285             }
286         }
287
288         return CmsWorkplace.buildSelect(attributes, options, values, selectedIndex, false);
289     }
290
291     /**
292      * Builds the html for the template select box.<p>
293      *
294      * @param attributes optional attributes for the &lt;select&gt; tag
295      * @return the html for the template select box
296      */

297     public String JavaDoc buildSelectTemplates(String JavaDoc attributes) {
298
299         List JavaDoc options = new ArrayList JavaDoc();
300         List JavaDoc values = new ArrayList JavaDoc();
301         TreeMap JavaDoc templates = null;
302         int selectedIndex = -1;
303         try {
304             // get all available templates
305
templates = CmsNewResourceXmlPage.getTemplates(getCms(), null);
306         } catch (CmsException e) {
307             // can usually be ignored
308
if (LOG.isInfoEnabled()) {
309                 LOG.info(e);
310             }
311         }
312         if (templates == null) {
313             // no templates found, return empty String
314
return "";
315         } else {
316             // templates found, create option and value lists
317
CmsMessages messages = Messages.get().getBundle(getLocale());
318             options.add(messages.key(Messages.GUI_PLEASE_SELECT_0));
319             values.add("");
320             options.add(messages.key(Messages.GUI_BUTTON_ALL_0));
321             values.add(ALL);
322             if (ALL.equals(getParamTemplate())) {
323                 selectedIndex = 1;
324             }
325             Iterator JavaDoc i = templates.keySet().iterator();
326             int counter = 2;
327             while (i.hasNext()) {
328                 String JavaDoc key = (String JavaDoc)i.next();
329                 String JavaDoc path = (String JavaDoc)templates.get(key);
330                 if (path.equals(getParamTemplate())) {
331                     selectedIndex = counter;
332                 }
333                 options.add(key);
334                 values.add(path);
335                 counter++;
336             }
337         }
338         return buildSelect(attributes, options, values, selectedIndex, false);
339     }
340
341     /**
342      * @see org.opencms.workplace.CmsWorkplace#getCms()
343      */

344     public CmsObject getCms() {
345
346         if (m_cms == null) {
347             return super.getCms();
348         }
349
350         return m_cms;
351     }
352
353     /**
354      * Returns the errorMessage.<p>
355      *
356      * @return the errorMessage
357      */

358     public String JavaDoc getErrorMessage() {
359
360         if (CmsStringUtil.isEmpty(m_errorMessage)) {
361             return "";
362         }
363
364         return m_errorMessage;
365     }
366
367     /**
368      * Returns the paramLocale.<p>
369      *
370      * @return the paramLocale
371      */

372     public String JavaDoc getParamLocale() {
373
374         return m_paramLocale;
375     }
376
377     /**
378      * Returns the value of the newvalue parameter.<p>
379      *
380      * @return the value of the newvalue parameter
381      */

382     public String JavaDoc getParamNewElement() {
383
384         return m_paramNewElement;
385     }
386
387     /**
388      * Returns the value of the oldvalue parametere.<p>
389      *
390      * @return the value of the oldvalue parameter
391      */

392     public String JavaDoc getParamOldElement() {
393
394         return m_paramOldElement;
395     }
396
397     /**
398      * Returns the value of the recursive parameter.<p>
399      *
400      * @return the value of the recursive parameter
401      */

402     public String JavaDoc getParamRecursive() {
403
404         return m_paramRecursive;
405     }
406
407     /**
408      * Returns true if the user has set remove empty elements parameter; otherwise false.<p>
409      *
410      * @return true if the user has set remove empty elements parameter; otherwise false
411      */

412     public String JavaDoc getParamRemoveEmptyElements() {
413
414         return m_paramRemoveEmptyElements;
415     }
416
417     /**
418      * Returns the template.<p>
419      *
420      * @return the template
421      */

422     public String JavaDoc getParamTemplate() {
423
424         return m_paramTemplate;
425     }
426
427     /**
428      * Returns true if the user has set validate new element parameter; otherwise false.<p>.<p>
429      *
430      * @return true if the user has set validate new element parameter; otherwise false
431      */

432     public String JavaDoc getParamValidateNewElement() {
433
434         return m_paramValidateNewElement;
435     }
436
437     /**
438      * Sets the errorMessage.<p>
439      *
440      * @param errorMessage the errorMessage to set
441      */

442     public void setErrorMessage(String JavaDoc errorMessage) {
443
444         m_errorMessage = errorMessage;
445     }
446
447     /**
448      * Sets the locale.<p>
449      *
450      * @param paramLocale the locale to set
451      */

452     public void setParamLocale(String JavaDoc paramLocale) {
453
454         m_paramLocale = paramLocale;
455     }
456
457     /**
458      * Sets the value of the newvalue parameter.<p>
459      *
460      * @param paramNewValue the value of the newvalue parameter
461      */

462     public void setParamNewElement(String JavaDoc paramNewValue) {
463
464         m_paramNewElement = paramNewValue;
465     }
466
467     /**
468      * Sets the value of the oldvalue parameter.<p>
469      *
470      * @param paramOldValue the value of the oldvalue parameter
471      */

472     public void setParamOldElement(String JavaDoc paramOldValue) {
473
474         m_paramOldElement = paramOldValue;
475     }
476
477     /**
478      * Sets the value of the recursive parameter.<p>
479      *
480      * @param paramRecursive the value of the recursive parameter
481      */

482     public void setParamRecursive(String JavaDoc paramRecursive) {
483
484         m_paramRecursive = paramRecursive;
485     }
486
487     /**
488      * Sets the remove empty elements parameter to true or false.<p>
489      *
490      * @param paramRemoveEmptyElements the remove empty elements parameter to set
491      */

492     public void setParamRemoveEmptyElements(String JavaDoc paramRemoveEmptyElements) {
493
494         m_paramRemoveEmptyElements = paramRemoveEmptyElements;
495     }
496
497     /**
498      * Sets the param Template.<p>
499      *
500      * @param paramTemplate the template name to set
501      */

502     public void setParamTemplate(String JavaDoc paramTemplate) {
503
504         m_paramTemplate = paramTemplate;
505     }
506
507     /**
508      * Sets the paramValidateNewElement.<p>
509      *
510      * @param paramValidateNewElement the validate new element parameter to set
511      */

512     public void setParamValidateNewElement(String JavaDoc paramValidateNewElement) {
513
514         m_paramValidateNewElement = paramValidateNewElement;
515     }
516
517     /**
518      * Does validate the request parameters and returns a buffer with error messages.<p>
519      *
520      * If there were no error messages, the buffer is empty.<p>
521      */

522     public void validateParameters() {
523
524         // localisation
525
CmsMessages messages = Messages.get().getBundle(getLocale());
526
527         StringBuffer JavaDoc validationErrors = new StringBuffer JavaDoc();
528         if (CmsStringUtil.isEmpty(getParamResource())) {
529             validationErrors.append(messages.key(Messages.GUI_ELEM_RENAME_VALIDATE_RESOURCE_FOLDER_0)).append("<br>");
530         }
531         if (CmsStringUtil.isEmpty(getParamTemplate())) {
532             validationErrors.append(messages.key(Messages.GUI_ELEM_RENAME_VALIDATE_SELECT_TEMPLATE_0)).append("<br>");
533         }
534         if (CmsStringUtil.isEmpty(getParamLocale())) {
535             validationErrors.append(messages.key(Messages.GUI_ELEM_RENAME_VALIDATE_SELECT_LANGUAGE_0)).append("<br>");
536         }
537         if (CmsStringUtil.isEmpty(getParamOldElement())) {
538             validationErrors.append(messages.key(Messages.GUI_ELEM_RENAME_VALIDATE_ENTER_OLD_ELEM_0)).append("<br>");
539         }
540         if (CmsStringUtil.isEmpty(getParamNewElement())) {
541             validationErrors.append(messages.key(Messages.GUI_ELEM_RENAME_VALIDATE_ENTER_NEW_ELEM_0)).append("<br>");
542         }
543         if (!isValidElement(getParamNewElement())) {
544             validationErrors.append(
545                 messages.key(
546                     Messages.GUI_ELEM_RENAME_VALIDATE_INVALID_NEW_ELEM_2,
547                     getParamNewElement(),
548                     getParamTemplate())).append("<br>");
549         }
550
551         setErrorMessage(validationErrors.toString());
552     }
553
554     /**
555      * @see org.opencms.workplace.CmsWorkplace#initWorkplaceRequestValues(org.opencms.workplace.CmsWorkplaceSettings, javax.servlet.http.HttpServletRequest)
556      */

557     protected void initWorkplaceRequestValues(CmsWorkplaceSettings settings, HttpServletRequest JavaDoc request) {
558
559         // fill the parameter values in the get/set methods
560
fillParamValues(request);
561         // set the dialog type
562
setParamDialogtype(DIALOG_TYPE);
563         // set the action for the JSP switch
564
// set the action for the JSP switch
565
if (DIALOG_CONFIRMED.equals(getParamAction())) {
566             setAction(ACTION_CONFIRMED);
567         } else if (DIALOG_OK.equals(getParamAction())) {
568             setAction(ACTION_OK);
569         } else if (DIALOG_CANCEL.equals(getParamAction())) {
570             setAction(ACTION_CANCEL);
571         } else if (REPORT_UPDATE.equals(getParamAction())) {
572             setAction(ACTION_REPORT_UPDATE);
573         } else if (REPORT_BEGIN.equals(getParamAction())) {
574             setAction(ACTION_REPORT_BEGIN);
575         } else if (REPORT_END.equals(getParamAction())) {
576             setAction(ACTION_REPORT_END);
577         } else {
578             setAction(ACTION_DEFAULT);
579             // add the title for the dialog
580
setParamTitle(key("title.renameelement"));
581         }
582     }
583
584     /**
585      * Returns a retained list of xml pages that belongs to the specified template.<p>
586      *
587      * @param xmlPages a list of all xml pages
588      * @return a retained list of xml pages that belongs to the specified template
589      */

590     private List JavaDoc getRetainedPagesWithTemplate(List JavaDoc xmlPages) {
591
592         // list of resources belongs to the selected template
593
List JavaDoc resourcesWithTemplate = new ArrayList JavaDoc();
594         TreeMap JavaDoc templates = null;
595         try {
596             templates = CmsNewResourceXmlPage.getTemplates(getCms(), null);
597         } catch (CmsException e) {
598             if (LOG.isErrorEnabled()) {
599                 LOG.error(e);
600             }
601         }
602         // check if the users selected template is valid.
603
if (templates != null && templates.containsValue(getParamTemplate())) {
604             // iterate the xmlPages list and add all resources with the specified template to the resourcesWithTemplate list
605
Iterator JavaDoc i = xmlPages.iterator();
606             while (i.hasNext()) {
607                 CmsResource currentPage = (CmsResource)i.next();
608                 // read the template property
609
CmsProperty templateProperty;
610                 try {
611                     templateProperty = getCms().readPropertyObject(
612                         getCms().getSitePath(currentPage),
613                         CmsPropertyDefinition.PROPERTY_TEMPLATE,
614                         false);
615                 } catch (CmsException e2) {
616                     if (LOG.isErrorEnabled()) {
617                         LOG.error(e2);
618                     }
619                     continue;
620                 }
621                 // add currentResource if the template property value is the same as the given template
622
if (getParamTemplate().equals(templateProperty.getValue())) {
623                     resourcesWithTemplate.add(currentPage);
624                 }
625             }
626             // retain the list of pages against the list with template
627
xmlPages.retainAll(resourcesWithTemplate);
628         }
629
630         return xmlPages;
631     }
632
633     /**
634      * Returns a set of elements stored in the given template property.<p>
635      *
636      * The elements are stored in the property I_CmsConstants.C_PROPERTY_TEMPLATE_ELEMENTS.<p>
637      *
638      * @param currentTemplate the path of the template to look in
639      * @return a set of elements stored in the given template path
640      */

641     private Set JavaDoc getTemplateElements(String JavaDoc currentTemplate) {
642
643         Set JavaDoc templateElements = new HashSet JavaDoc();
644
645         if (currentTemplate != null && currentTemplate.length() > 0) {
646             // template found, check template-elements property
647
String JavaDoc elements = null;
648             try {
649                 // read the property from the template file
650
elements = getCms().readPropertyObject(
651                     currentTemplate,
652                     CmsPropertyDefinition.PROPERTY_TEMPLATE_ELEMENTS,
653                     false).getValue(null);
654             } catch (CmsException e) {
655                 if (LOG.isWarnEnabled()) {
656                     LOG.warn(e.getLocalizedMessage());
657                 }
658             }
659             if (elements != null) {
660                 // elements are defined on template file, merge with available elements
661
StringTokenizer JavaDoc T = new StringTokenizer JavaDoc(elements, ",");
662                 while (T.hasMoreTokens()) {
663                     String JavaDoc currentElement = T.nextToken();
664                     String JavaDoc niceName = null;
665                     boolean mandatory = false;
666                     int sepIndex = currentElement.indexOf("|");
667                     if (sepIndex != -1) {
668                         // nice name found for current element, extract it
669
niceName = currentElement.substring(sepIndex + 1);
670                         currentElement = currentElement.substring(0, sepIndex);
671                     }
672                     if (currentElement.endsWith("*")) {
673                         // element is mandatory
674
mandatory = true;
675                         currentElement = currentElement.substring(0, currentElement.length() - 1);
676                     }
677
678                     CmsDialogElement element = new CmsDialogElement(currentElement, niceName, mandatory, true, false);
679                     templateElements.add(element);
680                 }
681             }
682         }
683
684         return templateElements;
685     }
686
687     /**
688      * Returns a list of xml pages from the specified folder.<p>
689      *
690      * @return a list of xml pages from the specified folder
691      */

692     private List JavaDoc getXmlPages() {
693
694         boolean isRecursive = Boolean.valueOf(getParamRecursive()).booleanValue();
695         // filterdefinition to read only the required resources
696
CmsResourceFilter filter = CmsResourceFilter.IGNORE_EXPIRATION.addRequireType(CmsResourceTypeXmlPage.getStaticTypeId());
697         // trying to read the resources
698
List JavaDoc xmlPages = null;
699
700         try {
701             xmlPages = getCms().readResources(getParamResource(), filter, isRecursive);
702         } catch (CmsException e) {
703             if (LOG.isErrorEnabled()) {
704                 LOG.error(e);
705             }
706         }
707
708         return xmlPages;
709     }
710
711     /**
712      * Checks if the specified element/locale of the given page has a content.<p>
713      *
714      * @param page the xml page
715      * @param element the element name
716      * @param locale the locale
717      * @return false if the specified element/locale of the given page has a content; otherwise true
718      */

719     private boolean isEmptyElement(CmsXmlPage page, String JavaDoc element, Locale JavaDoc locale) {
720
721         CmsXmlHtmlValue xmlHtmlValue = (CmsXmlHtmlValue)page.getValue(element, locale);
722         if (CmsStringUtil.isNotEmpty(xmlHtmlValue.getPlainText(getCms()))) {
723             return false;
724         }
725
726         return true;
727     }
728
729     /**
730      * Checks if the selected new element is valid for the selected template.<p>
731      *
732      * @param page the xml page
733      * @param element the element name
734      *
735      * @return true if ALL_TEMPLATES selected or the element is valid for the selected template; otherwise false
736      */

737     private boolean isValidElement(CmsXmlPage page, String JavaDoc element) {
738
739         CmsFile file = page.getFile();
740         String JavaDoc template;
741         try {
742             template = getCms().readPropertyObject(
743                 getCms().getSitePath(file),
744                 CmsPropertyDefinition.PROPERTY_TEMPLATE,
745                 true).getValue(null);
746         } catch (CmsException e) {
747             return false;
748         }
749
750         return isValidTemplateElement(template, element);
751     }
752
753     /**
754      * Checks if the selected new element is valid for the selected template.<p>
755      *
756      * @param element the element name
757      *
758      * @return true if ALL_TEMPLATES selected or the element is valid for the selected template; otherwise false
759      */

760     private boolean isValidElement(String JavaDoc element) {
761
762         boolean validateNewElement = Boolean.valueOf(getParamValidateNewElement()).booleanValue();
763         if (ALL.equals(getParamTemplate()) || !validateNewElement) {
764             return true;
765         }
766
767         return isValidTemplateElement(getParamTemplate(), element);
768     }
769
770     /**
771      * Check if the given template includes the specified element.<p>
772      *
773      * @param template the template
774      * @param element the element name
775      * @return true if the template includes the given element
776      */

777     private boolean isValidTemplateElement(String JavaDoc template, String JavaDoc element) {
778
779         List JavaDoc elements = new ArrayList JavaDoc(getTemplateElements(template));
780         if (elements != null) {
781             Iterator JavaDoc i = elements.iterator();
782             while (i.hasNext()) {
783                 CmsDialogElement currElement = (CmsDialogElement)i.next();
784                 if (element.equals(currElement.getName())) {
785                     return true;
786                 }
787             }
788         }
789
790         return false;
791     }
792
793     /**
794      * Performs the main element rename operation on the filtered resources.<p>
795      *
796      * @param xmlPages the list of xml pages
797      * @param locale the locale specifying the xmlpage node to perform the operation on
798      */

799     private void performRenameOperation(List JavaDoc xmlPages, Locale JavaDoc locale) {
800
801         // partial localized (stopped due to low prio).
802
boolean removeEmptyElements = Boolean.valueOf(getParamRemoveEmptyElements()).booleanValue();
803         boolean validateNewElement = Boolean.valueOf(getParamValidateNewElement()).booleanValue();
804         // the list including at least one resource
805
if (xmlPages != null && xmlPages.size() > 0) {
806             m_report.println(
807                 Messages.get().container(Messages.RPT_RENAME_LANG_1, locale.getLanguage()),
808                 I_CmsReport.FORMAT_HEADLINE);
809             // if user has not selected ALL templates, then retain pages with specified template
810
if (!ALL.equals(getParamTemplate())) {
811                 xmlPages = getRetainedPagesWithTemplate(xmlPages);
812             }
813             int m = 0;
814             int n = xmlPages.size();
815             // loop over remained pages
816
Iterator JavaDoc i = xmlPages.iterator();
817             while (i.hasNext()) {
818                 m++;
819                 CmsXmlPage page = null;
820                 try {
821                     // next file from the list
822
CmsResource res = (CmsResource)i.next();
823                     CmsFile file;
824
825                     m_report.print(org.opencms.report.Messages.get().container(
826                         org.opencms.report.Messages.RPT_SUCCESSION_2,
827                         String.valueOf(m),
828                         String.valueOf(n)), I_CmsReport.FORMAT_NOTE);
829                     m_report.print(Messages.get().container(Messages.RPT_PROCESSING_PAGE_0), I_CmsReport.FORMAT_NOTE);
830                     m_report.print(org.opencms.report.Messages.get().container(
831                         org.opencms.report.Messages.RPT_ARGUMENT_1,
832                         getCms().getSitePath(res)));
833                     m_report.println(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0));
834
835                     try {
836                         file = getCms().readFile(getCms().getSitePath(res), CmsResourceFilter.IGNORE_EXPIRATION);
837                     } catch (CmsException e2) {
838                         if (LOG.isErrorEnabled()) {
839                             LOG.error(e2);
840                         }
841                         m_report.println(e2);
842                         continue;
843                     }
844                     // try unmarshaling to xml page
845
try {
846                         page = CmsXmlPageFactory.unmarshal(getCms(), file);
847                     } catch (CmsXmlException e) {
848                         m_report.println(e);
849                         continue;
850                     }
851
852                     // check if the source element exists in the page
853
if (!page.hasValue(getParamOldElement(), locale)) {
854                         m_report.println(
855                             Messages.get().container(Messages.RPT_NONEXISTANT_ELEM_1, getParamOldElement()),
856                             I_CmsReport.FORMAT_NOTE);
857                         continue;
858                     }
859
860                     // check if the target element already exists in the page
861
if (page.hasValue(getParamNewElement(), locale)) {
862                         // the page contains already the new element with speicific content.
863
// renaming the old will invalid the xml page
864
m_report.println(
865                             Messages.get().container(Messages.RPT_NEW_ELEM_EXISTS_0),
866                             I_CmsReport.FORMAT_NOTE);
867                         continue;
868                     }
869
870                     if (validateNewElement) {
871                         // check if the target element is valid for the template
872
if (!isValidElement(page, getParamNewElement())) {
873                             m_report.println(Messages.get().container(
874                                 Messages.RPT_INVALID_ARGUMENT_1,
875                                 getParamNewElement()), I_CmsReport.FORMAT_NOTE);
876                             continue;
877                         }
878                     }
879
880                     try {
881                         // rename the element from the old value to the new
882
page.renameValue(getParamOldElement(), getParamNewElement(), locale);
883                         // write the page with the new content
884
writePageAndReport(page, true);
885                     } catch (Throwable JavaDoc t) {
886                         LOG.error(t);
887                         m_report.println(t);
888                         continue;
889                     }
890
891                 } catch (Throwable JavaDoc t) {
892                     LOG.error(t);
893                     m_report.println(t);
894                 } finally {
895                     // finally do remove empty elements of the page
896
// the remove operation is executed if the user has checked the specified checkbox and selected a template (NOT ALL)
897
if (removeEmptyElements) {
898                         removeInValidElements(page, locale);
899                     }
900                 }
901             }
902         }
903     }
904
905     /**
906      * Analyzes xml page and removes any element if this is not valid for the specified template and has no content.<p>
907      *
908      * @param page a xml page
909      * @param locale the locale
910      */

911     private void removeInValidElements(CmsXmlPage page, Locale JavaDoc locale) {
912
913         if (page == null) {
914             return;
915         }
916
917         if (ALL.equals(getParamTemplate())) {
918             return;
919         }
920
921         // get all elements of this page
922
List JavaDoc pageElements = page.getNames(locale);
923         if (pageElements != null) {
924             Iterator JavaDoc i = pageElements.iterator();
925             while (i.hasNext()) {
926                 String JavaDoc currElement = (String JavaDoc)i.next();
927                 // remove current element only is invalid and has no content
928
if (!isValidElement(currElement) && isEmptyElement(page, currElement, locale)) {
929                     page.removeValue(currElement, locale);
930                     try {
931                         writePageAndReport(page, false);
932                         m_report.println(
933                             Messages.get().container(Messages.RPT_REMOVE_INVALID_EMPTY_ELEM_1, currElement),
934                             I_CmsReport.FORMAT_NOTE);
935                     } catch (CmsException e) {
936                         // ignore
937
}
938                 }
939             }
940         }
941     }
942
943     /**
944      * Writes the given xml page by reporting the result.<p>
945      *
946      * @param page the xml page
947      * @param report if true then some output will be written to the report
948      * @throws CmsException if operation failed
949      */

950     private void writePageAndReport(CmsXmlPage page, boolean report) throws CmsException {
951
952         CmsFile file = page.getFile();
953         byte[] content = page.marshal();
954         file.setContents(content);
955         // check lock
956
CmsLock lock = getCms().getLock(file);
957         if (lock.isNullLock() || lock.getUserId().equals(getCms().getRequestContext().currentUser().getId())) {
958             // lock the page
959
checkLock(getCms().getSitePath(file));
960             // write the file with the new content
961
getCms().writeFile(file);
962             // unlock the page
963
getCms().unlockResource(getCms().getSitePath(file));
964             if (report) {
965                 m_report.println(Messages.get().container(
966                     Messages.RPT_ELEM_RENAME_2,
967                     getParamOldElement(),
968                     getParamNewElement()), I_CmsReport.FORMAT_OK);
969             }
970         }
971     }
972 }
Popular Tags