001    /*
002     * 
003     * $Revision: 15202 $ $Date: 2009-05-15 17:00:44 +0200 (Fri, 15 May 2009) $
004     *
005     * This file is part of ***  M y C o R e  ***
006     * See http://www.mycore.de/ for details.
007     *
008     * This program is free software; you can use it, redistribute it
009     * and / or modify it under the terms of the GNU General Public License
010     * (GPL) as published by the Free Software Foundation; either version 2
011     * of the License or (at your option) any later version.
012     *
013     * This program is distributed in the hope that it will be useful, but
014     * WITHOUT ANY WARRANTY; without even the implied warranty of
015     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
016     * GNU General Public License for more details.
017     *
018     * You should have received a copy of the GNU General Public License
019     * along with this program, in a file called gpl.txt or license.txt.
020     * If not, write to the Free Software Foundation Inc.,
021     * 59 Temple Place - Suite 330, Boston, MA  02111-1307 USA
022     */
023    
024    /*
025     * WCMSActionServlet.java
026     *
027     * Created on 22. September 2003, 16:09
028     */
029    package org.mycore.frontend.wcms;
030    
031    import java.io.BufferedInputStream;
032    import java.io.BufferedOutputStream;
033    import java.io.ByteArrayInputStream;
034    import java.io.ByteArrayOutputStream;
035    import java.io.File;
036    import java.io.FileInputStream;
037    import java.io.FileNotFoundException;
038    import java.io.FileOutputStream;
039    import java.io.IOException;
040    import java.io.InputStream;
041    import java.io.PrintWriter;
042    import java.io.SequenceInputStream;
043    import java.io.StringReader;
044    import java.io.StringWriter;
045    import java.io.UnsupportedEncodingException;
046    import java.net.URL;
047    import java.text.SimpleDateFormat;
048    import java.util.Calendar;
049    import java.util.GregorianCalendar;
050    import java.util.Iterator;
051    import java.util.List;
052    
053    import javax.servlet.http.HttpServletRequest;
054    import javax.servlet.http.HttpServletResponse;
055    
056    import org.apache.log4j.Logger;
057    import org.jdom.Document;
058    import org.jdom.Element;
059    import org.jdom.JDOMException;
060    import org.jdom.Namespace;
061    import org.jdom.input.SAXBuilder;
062    import org.jdom.output.XMLOutputter;
063    import org.mycore.common.MCRConfiguration;
064    import org.mycore.common.MCRSession;
065    import org.mycore.common.MCRSessionMgr;
066    import org.mycore.common.MCRUtils;
067    import org.w3c.tidy.Tidy;
068    import org.xml.sax.EntityResolver;
069    import org.xml.sax.InputSource;
070    
071    /**
072     * 
073     * @author m5brmi-sh, Thomas Scheffler (yagee)
074     * @version
075     */
076    public class MCRWCMSActionServlet extends MCRWCMSServlet {
077    
078        private static final long serialVersionUID = 1L;
079    
080        private static final Namespace ns = Namespace.XML_NAMESPACE;
081    
082        /* Session, userDB */
083        private String userID = null; // UserID of the current user
084    
085        private String userRealName = null; // Name of the current user
086    
087        private String userClass = null; // Class which a current user belongs to
088    
089        // {sysadmin, admin, editor, author}
090        private List rootNodes = null; // List of nodes under wich the current user
091    
092        // can perform actions like add, edit and
093        // delete
094    
095        /* Session, WCMSChooseServlet */
096        private String href = null;
097    
098        private String action = null;
099    
100        private String mode = null;
101    
102        private String dir = null;
103    
104        private String currentLang = null;
105    
106        private String defaultLang = null;
107    
108        private String currentLangLabel = null;
109    
110        /* Request */
111        private String target = null; // Target where to open the current file
112    
113        // adding(editing) {_blank, _self}
114        private String style = null; // Font style showing the element in the
115    
116        // navigation {bold, normal}
117        private String label = null; // Label showing the element in the
118    
119        // navigation
120    
121        private String content = null; // Content saved as xml file
122    
123        private String contentCurrentLang = null; // Translated content of the
124    
125        // current Language saved as xml
126        // file
127        private String link = null; // Representing an url linking to the current
128    
129        // element
130        private String changeInfo = null; // Contains changes made during edit
131    
132        // (like
133    
134        // commit in cvs)
135        private String realyDel = null; // Marks a flag for confirmation security
136    
137        // request on the delete action
138        private String labelPath = null; // Complete path of labels on the
139    
140        // acestor
141    
142        // axis to the current element
143        private String replaceMenu = null; // Representing a Parameter, allowing an
144    
145        // navigation element to replace the
146        // previous navigation structure only
147        // with its subelements. Can be "true" or
148        // "false".
149        private String constrainPopUp = null; // 
150    
151        private String masterTemplate = null; // Represents the action of
152    
153        // templates
154    
155        private String selfTemplate = null; // Represents the action of
156    
157        // templates
158    
159        // (set, change, remove)
160        private String fileName = null; // href attribut for the new element and
161    
162        // posiition where the element is saved on
163        // the server in case of mode = intern
164        private String contentFileBackup = null; // Path for content backup
165    
166        // (should
167    
168        // be data type File)
169        private String naviFileBackup = null; // Path for navigation.xml backup
170    
171        // (should be data type File)
172        private String error = null; // Errors, such as "empty form fields" aso
173    
174        private String attribute = null;
175    
176        private String avalue = null;
177    
178        private String usedParser = null; // Parser that is used for content code
179    
180        // validation (xhtml|xml|none);
181        private boolean dcbActionAdd = false;
182    
183        private String dcbValueAdd = null;
184    
185        private boolean dcbActionDelete = false;
186    
187        private String dcbValueDelete = null;
188    
189        private String sessionParam = null;
190    
191        private String addAtPosition = null;
192    
193        private boolean back;
194    
195        private String backaddr = null;
196    
197        private File naviFile = new File(MCRConfiguration.instance().getString("MCR.navigationFile").replace('/', File.separatorChar));
198    
199        private HttpServletRequest request;
200    
201        private HttpServletResponse response;
202    
203        char fs = File.separatorChar;
204    
205        String[] imageList;
206    
207        String[] documentList;
208    
209        File hrefFile;
210    
211        Element actElem;
212    
213        File[] masterTemplates;
214    
215        static Logger logger = Logger.getLogger(MCRWCMSActionServlet.class);
216    
217        MCRSession mcrSession = null;
218    
219        /**
220         * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
221         * 
222         * @param request
223         *            servlet request
224         * @param response
225         *            servlet response
226         */
227        protected void processRequest(HttpServletRequest request, HttpServletResponse response) {
228    
229            logger.debug("procReq");
230    
231            mcrSession = MCRSessionMgr.getCurrentSession();
232    
233            setReq(request);
234            setResp(response);
235            setback();
236            setBackAddress();
237            initParam(getReq());
238    
239            if (!realyDel.equals("false")) {
240                doItAll(request, hrefFile, action, mode, addAtPosition);
241            } else {
242                sessionParam = "choose";
243                generateOutput(error, label, fileName);
244            }
245        }
246    
247        public void generateOutput(String error, String label, String fileName) {
248            try {
249                // MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
250                Document doc = getXMLAsJDOM(naviFile);
251    
252                // Document doc = builder.build(naviFile);
253                Element root = doc.getRootElement();
254                if (!MCRSessionMgr.getCurrentSession().get("mode").toString().equals("extern"))
255                    validate(root);
256    
257                Element rootOut = new Element("cms");
258                Document jdom = new Document(rootOut);
259                rootOut.addContent(new Element("session").setText(sessionParam));
260                rootOut.addContent(new Element("href").setText(fileName));
261                rootOut.addContent(new Element("label").setText(label));
262                rootOut.addContent(new Element("target").setText(target));
263                rootOut.addContent(new Element("style").setText(style));
264                rootOut.addContent(new Element("usedParser").setText(usedParser));
265                rootOut.addContent(new Element("addAtPosition").setText(addAtPosition));
266                rootOut.addContent(new Element("action").setAttribute("mode", mode).setText(action));
267                rootOut.addContent(new Element("sessionID").setText(mcrSession.getID()));
268                rootOut.addContent(new Element("userID").setText(userID));
269                rootOut.addContent(new Element("userClass").setText(userClass));
270    
271                // rootNodes Iterator used in case of action==delete &&
272                // realyDel==false
273                Iterator rootNodesIterator = rootNodes.iterator();
274                while (rootNodesIterator.hasNext()) {
275                    Element rootNode = (Element) rootNodesIterator.next();
276                    rootOut.addContent(new Element("rootNode").setAttribute("href", rootNode.getAttributeValue("href")).setText(rootNode.getTextTrim()));
277                }
278    
279                if (action.equals("delete")) {
280                    File[] contentTemplates = new File((MCRConfiguration.instance().getString("MCR.templatePath") + "content/").replace('/', File.separatorChar)).listFiles();
281                    Element templates = new Element("templates");
282                    Element contentTemp = new Element("content");
283    
284                    for (int i = 0; i < contentTemplates.length; i++) {
285                        if (!contentTemplates[i].isDirectory()) {
286                            contentTemp.addContent(new Element("template").setText(contentTemplates[i].getName()));
287                        }
288                    }
289    
290                    templates.addContent(contentTemp);
291                    rootOut.addContent(templates);
292                } else {
293                    imageList = null;
294                    documentList = null;
295    
296                    Element images = new Element("images");
297                    rootOut.addContent(images);
298                    imageList = (new File(MCRConfiguration.instance().getString("MCR.WCMS.imagePath").replace('/', File.separatorChar))).list();
299    
300                    for (int i = 0; i < imageList.length; i++) {
301                        images.addContent(new Element("image").setText(MCRConfiguration.instance().getString("MCR.WCMS.imagePath") + imageList[i]));
302                    }
303    
304                    Element documents = new Element("documents");
305                    rootOut.addContent(documents);
306                    documentList = (new File(MCRConfiguration.instance().getString("MCR.WCMS.documentPath").replace('/', File.separatorChar))).list();
307    
308                    for (int i = 0; i < documentList.length; i++) {
309                        documents.addContent(new Element("document").setText(MCRConfiguration.instance().getString("MCR.WCMS.imagePath") + documentList[i]));
310                    }
311    
312                    Element templates = new Element("templates");
313                    Element master = new Element("master");
314    
315                    for (int i = 0; i < masterTemplates.length; i++) {
316                        if (masterTemplates[i].isDirectory() && (masterTemplates[i].getName().compareToIgnoreCase("cvs") != 0)) {
317                            master.addContent(new Element("template").setText(masterTemplates[i].getName()));
318                        }
319                    }
320    
321                    templates.addContent(master);
322                    rootOut.addContent(templates);
323                }
324    
325                if (error != null) {
326                    SAXBuilder saxb = new SAXBuilder();
327                    saxb.setEntityResolver(new ResolveDTD());
328                    Document saxDoc = new Document();
329    
330                    if (!action.equals("translate")) {
331                        try {
332                            saxDoc = saxb.build(new StringReader(content));
333                            Element html = saxDoc.getRootElement();
334                            html.detach();
335                            Element contentElem = new Element("section");
336                            contentElem.addContent(html);
337                            rootOut.addContent(contentElem);
338                            rootOut.addContent(new Element("error").setText(error));
339                        } catch (JDOMException jex) {
340                            try {
341                                String contentTmp = "<section>" + content + "</section>";
342                                saxDoc = saxb.build(new StringReader(contentTmp));
343                                Element html = saxDoc.getRootElement();
344                                html.detach();
345                                Element contentElem = new Element("section");
346                                contentElem.setContent(html);
347                                rootOut.addContent(contentElem);
348                                rootOut.addContent(new Element("error").setText(error));
349                            } catch (Exception e) {
350                                rootOut.addContent(new Element("error").setText(error));
351                            }
352                        }
353                    } else {
354                        try {
355                            saxDoc = saxb.build(new StringReader(contentCurrentLang));
356                            Element html = saxDoc.getRootElement();
357                            html.detach();
358                            Element contentElem = new Element("section");
359                            contentElem.addContent(html);
360                            rootOut.addContent(contentElem);
361                            rootOut.addContent(new Element("error").setText(error));
362                        } catch (JDOMException jex) {
363                            try {
364                                String contentCurrentLangTmp = "<section>" + contentCurrentLang + "</section>";
365                                saxDoc = saxb.build(new StringReader(contentCurrentLangTmp));
366                                Element html = saxDoc.getRootElement();
367                                html.detach();
368                                Element contentElem = new Element("section");
369                                contentElem.setContent(html);
370                                rootOut.addContent(contentElem);
371                                rootOut.addContent(new Element("error").setText(error));
372                            } catch (Exception e) {
373                                rootOut.addContent(new Element("error").setText(error));
374                            }
375                        }
376                    }
377                }
378    
379                String jump = null;
380                int filepos = 0;
381                String help = null;
382    
383                // if you used the edittool
384                if (getback()) {
385                    if (error == null) {
386                        // if new intern child, predecossor or successor created, go
387                        // to it
388                        if (action.equals("add") && mode.equals("intern")) {
389                            if (addAtPosition.equals("child")) {
390                                int length = getBackAddress().length();
391                                help = getBackAddress().substring(0, (length - 4));
392                                filepos = fileName.lastIndexOf("/");
393                                jump = help.concat(fileName.substring(filepos));
394                            } else {
395                                filepos = fileName.lastIndexOf("/");
396                                int neighbarpos = getBackAddress().lastIndexOf("/");
397                                help = getBackAddress().substring(0, neighbarpos);
398                                jump = help.concat(fileName.substring(filepos));
399                            }
400                        }
401                        // on edit or external link go back to initiator address
402                        else {
403                            jump = getBackAddress();
404                        }
405                        response.sendRedirect(jump);
406                    } else {
407                        getLayoutService().doLayout(request, response, jdom);
408                    }
409                } else {
410                    getLayoutService().doLayout(request, response, jdom);
411                }
412            } catch (Exception e) {
413                e.printStackTrace();
414                error = e.getMessage();
415            }
416        }
417    
418        public void updateFooterFile() {
419            try {
420                File footer = new File(MCRConfiguration.instance().getString("MCR.WCMS.footer").replace('/', File.separatorChar));
421                Document doc = new Document();
422    
423                if (!footer.exists())
424                    footer.getParentFile().mkdirs();
425                doc = getXMLAsJDOM(footer);
426                Element root = doc.getRootElement();
427                root.setAttribute("date", getDate()).setAttribute("time", getTime()).setAttribute("labelPath", labelPath).setAttribute("lastEditor", userRealName);
428                writeJDOMDocumentToFile(doc, footer);
429    
430                /*
431                 * XMLOutputter xmlout = new XMLOutputter(Format.getRawFormat().setTextMode(Format.TextMode.PRESERVE).setEncoding("UTF-8")); xmlout.output(doc, new
432                 * FileOutputStream(footer));
433                 */
434            } catch (Exception e) {
435                e.printStackTrace();
436    
437                // System.out.println(e.getMessage());
438            }
439        }
440    
441        public void addLastModifiedToContent(File hrefFile) {
442            try {
443                Document doc = getXMLAsJDOM(hrefFile);
444                Element root = doc.getRootElement();
445    
446                if (root.getChild("meta") != null) {
447                    if (root.getChild("meta").getChild("log") != null) {
448                        root.getChild("meta").getChild("log").setAttribute("date", getDate()).setAttribute("time", getTime()).setAttribute("labelPath", labelPath)
449                                        .setAttribute("lastEditor", userRealName);
450                    } else {
451                        root.getChild("meta").addContent(
452                                        new Element("log").setAttribute("date", getDate()).setAttribute("time", getTime()).setAttribute("labelPath", labelPath)
453                                                        .setAttribute("lastEditor", userRealName));
454                    }
455                } else {
456                    Element meta = new Element("meta");
457                    meta.addContent(new Element("log").setAttribute("date", getDate()).setAttribute("time", getTime()).setAttribute("labelPath", labelPath)
458                                    .setAttribute("lastEditor", userRealName));
459                    root.addContent(meta);
460                }
461    
462                writeJDOMDocumentToFile(doc, hrefFile);
463    
464                /*
465                 * XMLOutputter xmlout = new XMLOutputter(Format.getRawFormat().setTextMode(Format.TextMode.PRESERVE).setEncoding("UTF-8")); xmlout.output(doc, new
466                 * FileOutputStream(hrefFile));
467                 */
468            } catch (Exception e) {
469                e.printStackTrace();
470    
471                // System.out.println(e.getMessage());
472            }
473        }
474    
475        public void writeToLogFile(String action, String contentFileBackup) {
476            try {
477                File logFile = new File(MCRConfiguration.instance().getString("MCR.WCMS.logFile").replace('/', File.separatorChar));
478                Document doc;
479    
480                if (!logFile.exists()) {
481                    logFile.getParentFile().mkdirs();
482                    logFile.createNewFile();
483                    doc = new Document(new Element("loggings"));
484    
485                    // System.out.println("Logfile wurde
486                    // unter"+logFile.toString()+"angelegt.");
487                } else {
488                    doc = getXMLAsJDOM(logFile);
489                }
490    
491                Element root = doc.getRootElement();
492    
493                if (contentFileBackup == null) {
494    
495                    contentFileBackup = MCRConfiguration.instance().getString("MCR.WCMS.backupPath").replace('/', File.separatorChar) + fileName.substring(1);
496                }
497    
498                if (changeInfo == null) {
499                    root.addContent(new Element("log").setAttribute("date", getDate()).setAttribute("time", getTime()).setAttribute("userRealName", userRealName)
500                                    .setAttribute("labelPath", labelPath).setAttribute("doneAction", action).setAttribute("backupContentFile", contentFileBackup)
501                                    .setAttribute("backupNavigationFile", naviFileBackup));
502                } else {
503                    Element log = new Element("log");
504                    log.setAttribute("date", getDate()).setAttribute("time", getTime()).setAttribute("userRealName", userRealName).setAttribute("labelPath",
505                                    labelPath).setAttribute("doneAction", action).setAttribute("backupContentFile", contentFileBackup).setAttribute(
506                                    "backupNavigationFile", naviFileBackup).addContent(new Element("note").setText(changeInfo));
507    
508                    root.addContent(log);
509                }
510    
511                writeJDOMDocumentToFile(doc, logFile);
512    
513                /*
514                 * XMLOutputter xmlout = new XMLOutputter(Format.getRawFormat().setTextMode(Format.TextMode.PRESERVE).setEncoding("UTF-8")); xmlout.output(doc, new
515                 * FileOutputStream(logFile));
516                 */
517            } catch (Exception e) {
518                e.printStackTrace();
519    
520                // System.out.println(e.getMessage());
521            }
522        }
523    
524        public String getDate() {
525            Calendar gregCal = GregorianCalendar.getInstance();
526            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
527            String date = sdf.format(gregCal.getTime());
528    
529            return date;
530        }
531    
532        public String getTime() {
533            Calendar gregCal = GregorianCalendar.getInstance();
534            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
535            String time = sdf.format(gregCal.getTime());
536    
537            return time;
538        }
539    
540        public void validate(Element element) {
541            List elements = element.getChildren();
542            Iterator elementIterator = elements.iterator();
543    
544            while (elementIterator.hasNext()) {
545                Element child = (Element) elementIterator.next();
546    
547                if (child.getAttribute("href") != null) {
548                    if (child.getAttributeValue("href").equals(href)) {
549                        mode = child.getAttributeValue("type");
550    
551                        while (((Element) child.getParent()).getChild("label") != null) {
552                            child = (Element) child.getParent();
553                        }
554    
555                        return;
556                    }
557    
558                    validate(child);
559                }
560            }
561        }
562    
563        public Element findActElem(Element element, String attr, String value) {
564            List elements = element.getChildren();
565            Iterator elementIterator = elements.iterator();
566            Element tempresult;
567    
568            while (elementIterator.hasNext()) {
569                Element child = (Element) elementIterator.next();
570    
571                if ((child.getAttribute(attr) != null) && child.getAttribute(attr).getValue().equals(value)) {
572                    return child;
573                }
574    
575                tempresult = findActElem(child, attr, value);
576    
577                if (tempresult != null) {
578                    return tempresult;
579                }
580            }
581    
582            return null;
583        }
584    
585        public Element findActElem(Element element, String attr, String value, Namespace ns) {
586            List elements = element.getChildren();
587            Iterator elementIterator = elements.iterator();
588            Element tempresult;
589    
590            while (elementIterator.hasNext()) {
591                Element child = (Element) elementIterator.next();
592    
593                if ((child.getAttribute(attr, ns) != null) && child.getAttributeValue(attr, ns).equals(value)) {
594                    return child;
595                }
596    
597                tempresult = findActElem(child, attr, value, ns);
598    
599                if (tempresult != null) {
600                    return tempresult;
601                }
602            }
603    
604            return null;
605        }
606    
607        public int countChildren(Element actElem) {
608            List children = actElem.getChildren();
609            Iterator elementIterator = children.iterator();
610            int counter = 0;
611    
612            while (elementIterator.hasNext()) {
613                counter++;
614                elementIterator.next();
615            }
616    
617            return counter;
618        }
619    
620        public String makeBackup(File inputFile) {
621            File backupFile = null;
622    
623            if (inputFile.toString().endsWith(fs + "navigation.xml")) {
624                backupFile = new File(MCRConfiguration.instance().getString("MCR.WCMS.backupPath").replace('/', File.separatorChar) + fs + "navi" + fs + "navigation.xml");
625            } else {
626                backupFile = new File(MCRConfiguration.instance().getString("MCR.WCMS.backupPath").replace('/', File.separatorChar) + href.replace('/', File.separatorChar));
627            }
628    
629            if (inputFile.exists()) {
630                try {
631                    BufferedInputStream bi = new BufferedInputStream(new FileInputStream(inputFile));
632    
633                    if (backupFile.exists()) {
634                        int version = 1;
635                        String backupPath = backupFile.toString();
636    
637                        while (backupFile.exists()) {
638                            backupFile = new File(backupPath + "." + String.valueOf(version));
639                            version++;
640                        }
641                    } else {
642                        backupFile.getParentFile().mkdirs();
643    
644                        // backupFile.createNewFile();
645                    }
646    
647                    BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(backupFile));
648                    MCRUtils.copyStream(bi, bo);
649                    bi.close();
650                    bo.close();
651                } catch (FileNotFoundException fnfe) {
652                    fnfe.printStackTrace();
653                    error = fnfe.getMessage();
654                } catch (IOException ioe) {
655                    ioe.printStackTrace();
656                    error = ioe.getMessage();
657                }
658            }
659    
660            return backupFile.toString();
661        }
662    
663        public void modifyNavi(File inputFile) {
664            if (action.equals("add")) {
665                try {
666                    Document doc = getXMLAsJDOM(inputFile);
667                    Element root = doc.getRootElement();
668    
669                    // Bug work around. When a page as neighboor of a link shall be created, the mode will changed
670                    // by a sub method (valitate) of getParentAttribute. This behaviour is not correct.
671                    // So, the mode will be kept as set before.
672                    String modeBefore = new String(mode);
673    
674                    if (!mcrSession.get("mode").toString().equals("extern"))
675                        validate(root);
676    
677                    // Bug work around. When a page as neighboor of a link shall be created, the mode will changed
678                    // by a sub method (valitate) of getParentAttribute. This behaviour is not correct.
679                    // So, the mode will be kept as set before.
680                    if (!mode.equals(modeBefore))
681                        mode = modeBefore;
682    
683                    Element actElem = findActElem(root, attribute, avalue);
684                    List neighbors = ((Element) actElem.getParent()).getChildren();
685    
686                    int position = neighbors.indexOf(actElem);
687    
688                    if (addAtPosition.equals("predecessor") || addAtPosition.equals("successor")) {
689                        if (addAtPosition.equals("successor")) {
690                            position += 1;
691                        }
692    
693                        if ((0 <= position) && (position <= neighbors.size())) {
694                            if (!masterTemplate.equals("delete") && !masterTemplate.equals("noAction")) {
695                                neighbors.add(position, new Element("item").setAttribute("href", fileName).setAttribute("type", mode)
696                                                .setAttribute("target", target).setAttribute("style", style).setAttribute("replaceMenu", replaceMenu).setAttribute(
697                                                                "constrainPopUp", constrainPopUp).setAttribute("template", masterTemplate).addContent(
698                                                                new Element("label").setAttribute("lang", defaultLang, ns).setText(label)));
699                            } else {
700                                neighbors.add(position, new Element("item").setAttribute("href", fileName).setAttribute("type", mode)
701                                                .setAttribute("target", target).setAttribute("style", style).setAttribute("replaceMenu", replaceMenu).setAttribute(
702                                                                "constrainPopUp", constrainPopUp).addContent(
703                                                                new Element("label").setAttribute("lang", defaultLang, ns).setText(label)));
704                            }
705                        }
706                    }
707    
708                    if (addAtPosition.equals("child")) {
709                        if (!masterTemplate.equals("delete") && !masterTemplate.equals("noAction")) {
710                            Element itemElement = new Element("item").setAttribute("href", fileName).setAttribute("type", mode).setAttribute("target", target)
711                                            .setAttribute("style", style).setAttribute("replaceMenu", replaceMenu).setAttribute("constrainPopUp", constrainPopUp)
712                                            .setAttribute("template", masterTemplate);
713                            itemElement.addContent(new Element("label").setAttribute("lang", defaultLang, ns).setText(label));
714                            actElem.addContent(itemElement);
715                        } else {
716                            Element itemElement = new Element("item").setAttribute("href", fileName).setAttribute("type", mode).setAttribute("target", target)
717                                            .setAttribute("style", style).setAttribute("replaceMenu", replaceMenu).setAttribute("constrainPopUp", constrainPopUp);
718                            itemElement.addContent(new Element("label").setAttribute("lang", defaultLang, ns).setText(label));
719                            actElem.addContent(itemElement);
720                        }
721                    }
722    
723                    /* dynamic content binding */
724                    /* set */
725                    if (dcbActionAdd == true) {
726                        Element addedChildElement = findActElem(root, "href", fileName);
727                        Element dcb = new Element("dynamicContentBinding");
728                        dcb.addContent(new Element("rootTag").setText(dcbValueAdd));
729                        addedChildElement.addContent(dcb);
730                    }
731    
732                    /* END OF: set */
733                    /* END OF: dynamic content binding */
734                    writeJDOMDocumentToFile(doc, inputFile);
735    
736                    /*
737                     * XMLOutputter xmlout = new XMLOutputter(Format.getRawFormat().setTextMode(Format.TextMode.PRESERVE).setEncoding("UTF-8")); xmlout.output(doc,
738                     * new FileOutputStream(inputFile));
739                     */
740                } catch (Exception e) {
741                }
742            }
743    
744            if (action.equals("edit")) {
745                try {
746                    Document doc = getXMLAsJDOM(inputFile);
747                    Element root = doc.getRootElement();
748                    validate(root);
749                    actElem = findActElem(root, attribute, avalue);
750    
751                    List labels = actElem.getChildren("label");
752                    Iterator li = labels.iterator();
753    
754                    while (li.hasNext()) {
755                        Element lie = (Element) li.next();
756    
757                        if (lie.getAttributeValue("lang", ns).equals(defaultLang)) {
758                            lie.setText(label);
759                        }
760                    }
761    
762                    actElem.setAttribute("target", target).setAttribute("style", style);
763    
764                    if (mode.equals("extern") && (link != null)) {
765                        actElem.setAttribute("href", fileName);
766    
767                        if (!masterTemplate.equals("noAction")) {
768                            if (masterTemplate.equals("delete")) {
769                                actElem.removeAttribute("template");
770                            } else {
771                                actElem.setAttribute("template", masterTemplate);
772                            }
773                        }
774    
775                        // fileName = link;
776                    } else {
777                        actElem.setAttribute("replaceMenu", replaceMenu);
778                        actElem.setAttribute("constrainPopUp", constrainPopUp);
779    
780                        if (!masterTemplate.equals("noAction")) {
781                            if (masterTemplate.equals("delete")) {
782                                actElem.removeAttribute("template");
783                            } else {
784                                actElem.setAttribute("template", masterTemplate);
785                            }
786                        }
787    
788                        // fileName = href;
789                    }
790    
791                    /* dynamic content binding */
792                    /* set */
793                    if (dcbActionAdd == true) {
794                        if (actElem.getChild("dynamicContentBinding") == null) {
795                            Element dcb = new Element("dynamicContentBinding");
796                            dcb.addContent(new Element("rootTag").setText(dcbValueAdd));
797                            actElem.addContent(dcb);
798                        } else {
799                            actElem.getChild("dynamicContentBinding").addContent(new Element("rootTag").setText(dcbValueAdd));
800                        }
801                    }
802    
803                    /* END OF: set */
804                    /* remove */
805                    if (dcbActionDelete == true) {
806                        List dcbChildren = actElem.getChild("dynamicContentBinding").getChildren();
807                        Iterator elementIterator = dcbChildren.iterator();
808                        boolean childrenRemoved = false;
809    
810                        while (childrenRemoved != true) {
811                            Element child = (Element) elementIterator.next();
812    
813                            if (child.getValue().equals(dcbValueDelete)) {
814                                child.detach();
815                                childrenRemoved = true;
816                            }
817                        }
818    
819                        if (countChildren(actElem.getChild("dynamicContentBinding")) == 0) {
820                            actElem.getChild("dynamicContentBinding").detach();
821                        }
822                    }
823    
824                    /* END OF: remove */
825                    /* END OF: dynamic content binding */
826                    writeJDOMDocumentToFile(doc, inputFile);
827    
828                    /*
829                     * XMLOutputter outputter = new XMLOutputter(Format.getRawFormat().setTextMode(Format.TextMode.PRESERVE).setEncoding("UTF-8"));
830                     * outputter.output(doc, new FileOutputStream(inputFile));
831                     */
832                } catch (Exception e) {
833                }
834            }
835    
836            if (action.equals("delete")) {
837                try {
838                    Document doc = getXMLAsJDOM(inputFile);
839                    Element root = doc.getRootElement();
840                    validate(root);
841                    actElem = findActElem(root, attribute, avalue);
842                    fileName = ((Element) actElem.getParent()).getAttributeValue("href");
843                    label = actElem.getChildText("label");
844                    actElem.detach();
845                    writeJDOMDocumentToFile(doc, inputFile);
846    
847                    /*
848                     * XMLOutputter outputter = new XMLOutputter(Format.getRawFormat().setTextMode(Format.TextMode.PRESERVE).setEncoding("UTF-8"));
849                     * outputter.output(doc, new FileOutputStream(inputFile));
850                     */
851                } catch (Exception e) {
852                }
853            }
854    
855            if (action.equals("translate")) {
856                try {
857                    Document doc = getXMLAsJDOM(inputFile);
858                    Element root = doc.getRootElement();
859                    validate(root);
860                    actElem = findActElem(root, attribute, avalue);
861    
862                    List labels = actElem.getChildren("label");
863                    Iterator li = labels.iterator();
864                    boolean newEntry = true;
865    
866                    while (li.hasNext()) {
867                        Element lie = (Element) li.next();
868    
869                        if (lie.getAttributeValue("lang", ns).equals(currentLang)) {
870                            lie.setText(label);
871                            newEntry = false;
872                        }
873                    }
874    
875                    if (newEntry) {
876                        actElem.addContent(new Element("label").setAttribute("lang", currentLang, ns).setText(label));
877                    }
878    
879                    writeJDOMDocumentToFile(doc, inputFile);
880    
881                    /*
882                     * XMLOutputter xmlout = new XMLOutputter(Format.getRawFormat().setTextMode(Format.TextMode.PRESERVE).setEncoding("UTF-8")); xmlout.output(doc,
883                     * new FileOutputStream(inputFile));
884                     */
885                } catch (Exception e) {
886                }
887            }
888        }
889    
890        public boolean validXHTML(File htmlFile) {
891            boolean validXHTML = true;
892    
893            /* just to be implemented */
894            return validXHTML;
895        }
896    
897        public String getParentAttribute(File inputFile, String attribute, String avalue, String parentAttribute, String altParentAttribute) {
898            /*
899             * builds a jdom document from inputFile searches for Element with given attribute and value returns value of attribut of parent or alternative value if
900             * previous one dosen't exist
901             */
902            String reval = "";
903    
904            try {
905                Document doc = getXMLAsJDOM(inputFile);
906                Element root = doc.getRootElement();
907                validate(root);
908                actElem = findActElem(root, attribute, avalue);
909    
910                // check if parent element is not <item>, because it has an @dir
911                if (((Element) actElem.getParent()).getAttributeValue(altParentAttribute) != null) {
912                    reval = ((Element) actElem.getParent()).getAttributeValue(altParentAttribute) + reval;
913                    actElem = (Element) actElem.getParent();
914                } else {
915                    reval = ((Element) actElem.getParent()).getAttributeValue(parentAttribute);
916                }
917            } catch (Exception e) {
918                e.printStackTrace();
919                reval = "error";
920            }
921    
922            return reval;
923        }
924    
925        public void makeAction(String action) {
926            try {
927                Document html2BeStored = new Document();
928    
929                if (action.equals("add")) {
930                    if (mode.equals("intern")) {
931                        if (!hrefFile.exists()) {
932                            hrefFile.getParentFile().mkdir();
933                            StringBuffer contentHead = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n").append("<!DOCTYPE MyCoReWebPage>\n")
934                                            .append("<MyCoReWebPage>\n").append("\t<section xml:lang=\"" + defaultLang + "\" title=\"" + label + "\">\n");
935                            StringBuffer contentBody = new StringBuffer(content);
936                            StringBuffer contentTail = new StringBuffer("\t</section>\n").append("</MyCoReWebPage>\n");
937                            BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(((contentHead).append(contentBody).append(contentTail))
938                                            .toString().getBytes("UTF-8")));
939                            html2BeStored = getXMLAsJDOM(bis);
940                            bis.close();
941                        } else {
942                            error = "Unter diesem Pfad existiert bereits ein File mit diesem Filename!";
943                            return;
944                        }
945                    } else {
946                        return;
947                    }
948                }
949    
950                if (action.equals("edit")) {
951                    if (mode.equals("intern")) {
952                        try {
953                            Element formHTML = getXMLAsJDOM(content).getRootElement();
954    
955                            html2BeStored = getXMLAsJDOM(hrefFile);
956    
957                            Element storedHTMLRoot = html2BeStored.getRootElement();
958                            validate(storedHTMLRoot);
959    
960                            Element contentSection = findActElem(storedHTMLRoot, "lang", defaultLang, ns);
961                            contentSection.setAttribute("title", label);
962                            if (formHTML.getName().equals("dummyRoot")) {
963                                contentSection.setContent(formHTML.cloneContent());
964                            } else
965                                contentSection.setContent((Element) formHTML.clone());
966                        } catch (Exception ex) {
967                            error = "Error while updating document, update rejected.";
968                            return;
969                        }
970                    } else {
971                        return;
972                    }
973                }
974    
975                if (action.equals("translate") && mode.equals("intern")) {
976                    try {
977    
978                        Element formHTML = getXMLAsJDOM(contentCurrentLang).getRootElement();
979    
980                        html2BeStored = getXMLAsJDOM(hrefFile);
981    
982                        Element storedHTMLRoot = html2BeStored.getRootElement();
983                        validate(storedHTMLRoot);
984    
985                        Element contentSection = findActElem(storedHTMLRoot, "lang", currentLang, ns);
986    
987                        if (contentSection == null) {
988                            storedHTMLRoot.addContent(new Element("section").setAttribute("lang", currentLang, ns).setAttribute("title", label));
989                        }
990    
991                        contentSection = findActElem(storedHTMLRoot, "lang", currentLang, ns);
992                        contentSection.setAttribute("title", label);
993                        contentSection.setContent(formHTML.cloneContent());
994                    } catch (Exception e) {
995                        e.printStackTrace();
996                    }
997                }
998    
999                // management of prepared content jdom
1000                if (action.equals("delete")) {
1001                    if (realyDel.equals("true")) {
1002                        if (mode.equals("intern")) {
1003                            // if (storeTypMycore) {
1004                            hrefFile.delete();
1005                            File testFile = hrefFile;
1006                            while (testFile.getParentFile().listFiles().length < 1) {
1007                                testFile.getParentFile().delete();
1008                                testFile = testFile.getParentFile();
1009                            }
1010                        }
1011                    } else
1012                        sessionParam = "choose";
1013                    return;
1014                }
1015    
1016                writeJDOMDocumentToFile(html2BeStored, hrefFile);
1017    
1018            } catch (FileNotFoundException e) {
1019                error = "File not found. For further information look at the System Output.";
1020                e.printStackTrace();
1021            } catch (UnsupportedEncodingException e) {
1022                error = "Unsupportet Encoding found. For further information look at the System Output.";
1023                e.printStackTrace();
1024            } catch (IOException e) {
1025                error = "IO Error. For further information look at the System Output.";
1026                e.printStackTrace();
1027            }
1028        }
1029    
1030        public boolean validInput(HttpServletRequest request) {
1031            // page valid xhtml ?
1032            boolean contentValid = getXMLAsJDOM(request.getParameter("content")) != null;
1033            if (!contentValid) {
1034                error = "invalidXHTML";
1035                return false;
1036            }
1037            // no file name or page title provided
1038            if (!action.equals("delete") && (((fileName == null) || fileName.equals("")) || ((label == null) || label.equals("")))) {
1039                error = "emptyFormField";
1040                return false;
1041            }
1042            return true;
1043        }
1044    
1045        public void doItAll(HttpServletRequest request, File hrefFile, String action, String mode, String addAtPosition) {
1046    
1047            // verify if html form was filled in correctly
1048            if (!validInput(request)) {
1049                sessionParam = "action";
1050                generateOutput(error, label, fileName);
1051                return;
1052            }
1053    
1054            // do backups
1055            if (!action.equals("add") && mode.equals("intern")) {
1056                contentFileBackup = makeBackup(hrefFile);
1057            }
1058    
1059            naviFileBackup = makeBackup(naviFile);
1060    
1061            // update navigation base
1062            modifyNavi(naviFile);
1063    
1064            // update content page
1065            makeAction(action);
1066    
1067            // update footer with
1068            if (!action.equals("delete") && mode.equals("intern")) {
1069                addLastModifiedToContent(hrefFile);
1070            }
1071    
1072            updateFooterFile();
1073    
1074            // update log file
1075            writeToLogFile(action, contentFileBackup);
1076    
1077            // prepare xml container for MCRLayoutService
1078            generateOutput(error, label, fileName);
1079        }
1080    
1081        public void codeValidation(String validator) {
1082            logger.debug("validator (" + validator + ") will never be used."); // FIXME:
1083            // use
1084            // or
1085            // remove
1086            // validator
1087            try {
1088                String contentTmp = content;
1089                String contentCurrentLangTmp = contentCurrentLang;
1090                StringWriter sw = new StringWriter();
1091                PrintWriter pw = new PrintWriter(sw);
1092                logger.debug("Trying XHTML code validation using " + VALIDATOR);
1093    
1094                // JTidy Configuration
1095                Tidy tidy = new Tidy();
1096                tidy.setXHTML(true);
1097                tidy.setInputEncoding(OUTPUT_ENCODING);
1098                tidy.setOutputEncoding(OUTPUT_ENCODING);
1099                tidy.setWord2000(true);
1100                tidy.setPrintBodyOnly(true);
1101                tidy.setIndentContent(true);
1102                tidy.setForceOutput(true);
1103                tidy.setMakeClean(true);
1104                tidy.setMakeBare(true);
1105                tidy.setQuoteAmpersand(true);
1106                tidy.setQuoteMarks(true);
1107                tidy.setQuoteNbsp(true);
1108                tidy.setErrout(pw);
1109                tidy.setNumEntities(true);
1110    
1111                if (content != null) {
1112                    ByteArrayInputStream bais = new ByteArrayInputStream(contentTmp.getBytes(OUTPUT_ENCODING));
1113                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
1114                    tidy.parse(bais, baos);
1115                    contentTmp = baos.toString(OUTPUT_ENCODING);
1116                    baos.flush();
1117                    baos.close();
1118                    bais.close();
1119                }
1120    
1121                if (contentCurrentLang != null) {
1122                    ByteArrayInputStream bais = new ByteArrayInputStream(contentCurrentLangTmp.getBytes(OUTPUT_ENCODING));
1123                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
1124                    tidy.parse(bais, baos);
1125                    contentCurrentLangTmp = baos.toString(OUTPUT_ENCODING);
1126                    baos.flush();
1127                    baos.close();
1128                    bais.close();
1129                }
1130    
1131                pw.flush();
1132                pw.close();
1133    
1134                if (sw.toString().indexOf("Warning: discarding unexpected") != -1) {
1135                    logger.debug("Jumping to XML code validation because content contains at least one non-valid XHTML Element.");
1136    
1137                    Tidy tidyXML = new Tidy();
1138    
1139                    tidyXML.setXmlOut(true);
1140                    tidyXML.setInputEncoding("UTF-8");
1141                    tidyXML.setOutputEncoding("UTF-8");
1142                    tidyXML.setWord2000(true);
1143                    tidyXML.setIndentContent(true);
1144                    tidyXML.setForceOutput(true);
1145                    tidyXML.setMakeClean(true);
1146                    tidyXML.setMakeBare(true);
1147                    tidyXML.setQuoteAmpersand(true);
1148                    tidyXML.setQuoteMarks(true);
1149                    tidyXML.setQuoteNbsp(true);
1150                    tidyXML.setXmlTags(true);
1151    
1152                    if (content != null) {
1153                        contentTmp = "<dummyroot>" + content + "</dummyroot>";
1154    
1155                        // logger.debug("content vor parsing= "+content);
1156                        ByteArrayInputStream bais = new ByteArrayInputStream(contentTmp.getBytes("UTF-8"));
1157                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
1158                        tidyXML.parse(bais, baos);
1159                        contentTmp = baos.toString("UTF-8");
1160                        contentTmp = contentTmp.substring(contentTmp.indexOf(">") + 1, contentTmp.lastIndexOf("<"));
1161    
1162                        // logger.debug("content nach parsing= "+content);
1163                        bais.close();
1164                        baos.flush();
1165                        baos.close();
1166                    }
1167    
1168                    if (contentCurrentLang != null) {
1169                        contentCurrentLangTmp = "<dummyroot>" + contentCurrentLangTmp + "</dummyroot>";
1170    
1171                        ByteArrayInputStream baisc = new ByteArrayInputStream(contentCurrentLangTmp.getBytes("UTF-8"));
1172                        ByteArrayOutputStream baosc = new ByteArrayOutputStream();
1173                        tidyXML.parse(baisc, baosc);
1174                        contentCurrentLangTmp = baosc.toString("UTF-8");
1175                        contentCurrentLangTmp = contentCurrentLangTmp.substring(contentCurrentLangTmp.indexOf(">") + 1, contentCurrentLangTmp.lastIndexOf("<"));
1176                        baisc.close();
1177                        baosc.flush();
1178                        baosc.close();
1179                    }
1180    
1181                    usedParser = "xml";
1182                    logger.debug("XML code validation successfully done.");
1183                } else {
1184                    usedParser = "xhtml";
1185                    logger.debug("XHTML code validation successfully done.");
1186                }
1187    
1188                content = contentTmp;
1189                contentCurrentLang = contentCurrentLangTmp;
1190            } catch (UnsupportedEncodingException e) {
1191                logger.debug("XHTML/XML code validation unsuccessfully.");
1192                e.printStackTrace();
1193            } catch (IOException e) {
1194                logger.debug("XHTML/XML code validation unsuccessfully.");
1195                e.printStackTrace();
1196            }
1197        }
1198    
1199        /**
1200         * Returns a short description of the servlet.
1201         */
1202        public String getServletInfo() {
1203            return "Short description";
1204        }
1205    
1206        /**
1207         * @param req
1208         */
1209        public void setReq(HttpServletRequest req) {
1210            this.request = req;
1211        }
1212    
1213        public HttpServletRequest getReq() {
1214            return request;
1215        }
1216    
1217        public void setResp(HttpServletResponse resp) {
1218            this.response = resp;
1219        }
1220    
1221        public HttpServletResponse getResp() {
1222            return response;
1223        }
1224    
1225        /* new methods */
1226    
1227        // --------------
1228        public File getFile(String fileName) throws IOException, FileNotFoundException {
1229            File loadFile = new File(fileName);
1230    
1231            if (!loadFile.exists()) {
1232                logger.debug("File \"" + fileName + "\" don't exist.");
1233                setFile(fileName);
1234    
1235                // or maybe better loadFile = setFile(fileName);
1236                // and setting return type of setFile method to File
1237                // ???
1238                getFile(fileName);
1239            } else {
1240                if (!loadFile.isFile()) {
1241                    logger.debug("File \"" + fileName + "\" is no valid File.");
1242                } else {
1243                    if (!loadFile.canRead()) {
1244                        logger.debug("File \"" + fileName + "\" can't be read.");
1245                    }
1246    
1247                    if (!loadFile.canWrite()) {
1248                        logger.debug("File \"" + fileName + "\" can't be written to.");
1249                    }
1250                }
1251            }
1252    
1253            return loadFile;
1254        }
1255    
1256        /**
1257         * @param fileName
1258         * @throws IOException
1259         */
1260        public void setFile(String fileName) throws IOException {
1261            File newFile = new File(fileName);
1262            newFile.createNewFile();
1263            logger.debug("New file \"" + fileName + "\" created.");
1264        }
1265    
1266        /**
1267         * @param xmlSource -
1268         *            any source that contains xml-valid content
1269         * @return JDOM Document
1270         */
1271        public Document getXMLAsJDOM(Object xmlSource) {
1272            logger.debug("inside getXMLAsJDOM(Object xmlSource)");
1273            SAXBuilder builder = new SAXBuilder();
1274            Document jdomDoc = new Document();
1275    
1276            try {
1277                if (xmlSource instanceof String) {
1278                    logger.debug("instanceof String=" + xmlSource);
1279                    jdomDoc = builder.build(new ByteArrayInputStream(((String) xmlSource).getBytes("UTF-8")));
1280                }
1281                if (xmlSource instanceof File) {
1282                    logger.debug("instanceof File=" + xmlSource);
1283                    jdomDoc = builder.build((File) xmlSource);
1284                }
1285                if (xmlSource instanceof InputStream) {
1286                    logger.debug("instanceof InputStream=" + xmlSource);
1287                    jdomDoc = builder.build((InputStream) xmlSource);
1288                }
1289                if (xmlSource instanceof URL) {
1290                    logger.debug("instanceof URL=" + xmlSource);
1291                    jdomDoc = builder.build((URL) xmlSource);
1292                }
1293            } catch (JDOMException e) {
1294                // no root element ?
1295                String extendedXML = addRootElement((String) xmlSource);
1296                try {
1297                    logger.debug("JDOMException occurred -> adding root tag =" + extendedXML);
1298                    jdomDoc = builder.build(new ByteArrayInputStream((extendedXML).getBytes("UTF-8")));
1299                } catch (UnsupportedEncodingException e1) {
1300                    e1.printStackTrace();
1301                } catch (JDOMException e1) {
1302                    try {
1303                        logger.debug("JDOMException after root tag added occurred -> using JTidy");
1304                        jdomDoc = validateSource(xmlSource);
1305                    } catch (Exception e2) {
1306                        jdomDoc = null;
1307                        logger.error("XHTML-Content could not be transformed with JTidyto into valid XHTML");
1308                    }
1309                    e1.printStackTrace();
1310                } catch (IOException e1) {
1311                    e1.printStackTrace();
1312                }
1313            } catch (IOException e) {
1314                logger.debug("IO error: File \"" + xmlSource + "\" can't be parsed as JDOM.");
1315                e.printStackTrace();
1316            }
1317            return jdomDoc;
1318        }
1319    
1320        public String addRootElement(String xml) {
1321            return "<dummyRoot>" + xml + "</dummyRoot>";
1322        }
1323    
1324        public Document validateSource(Object xmlSource) {
1325            logger.debug("Trying to build a valid XHTML/XML Document from Source using JTidy.");
1326    
1327            StringWriter sw = new StringWriter();
1328            PrintWriter pw = new PrintWriter(sw);
1329    
1330            /*
1331             * Construct a new JTidy object and get Configuration | ---------------------------------------------------+ At first, allways try to parse the Document
1332             * as XHTML. Only if an unknown Element is found and JTidy wants to discard it, the Output format is set to XML.
1333             */
1334            Tidy tidy = new Tidy();
1335            tidy = getTidyConfig(tidy, "xhtml");
1336            // tidy.setErrout(pw);
1337            tidy.setInputEncoding(OUTPUT_ENCODING);
1338            tidy.setOutputEncoding(OUTPUT_ENCODING);
1339            tidy.setWord2000(true);
1340            tidy.setPrintBodyOnly(true);
1341            tidy.setIndentContent(true);
1342            tidy.setForceOutput(true);
1343            tidy.setMakeClean(true);
1344            tidy.setMakeBare(true);
1345            tidy.setQuoteAmpersand(true);
1346            tidy.setQuoteMarks(true);
1347            tidy.setQuoteNbsp(true);
1348            tidy.setNumEntities(true);
1349            tidy.setErrout(pw);
1350    
1351            BufferedInputStream bis = null;
1352            ByteArrayInputStream beginTag = new ByteArrayInputStream("<dummyRoot>".getBytes());
1353            ByteArrayInputStream endTag = new ByteArrayInputStream("</dummyRoot>".getBytes());
1354            ByteArrayInputStream bais = null;
1355            Document jdomDoc = null;
1356    
1357            try {
1358                if (xmlSource != null) {
1359                    if (xmlSource instanceof String) {
1360                        System.out.println("String");
1361                        bais = new ByteArrayInputStream(((String) xmlSource).getBytes("UTF-8"));
1362                    }
1363    
1364                    if (xmlSource instanceof File) {
1365                        System.out.println("File");
1366                        bis = new BufferedInputStream(new FileInputStream((File) xmlSource));
1367                    }
1368    
1369                    if (xmlSource instanceof InputStream) { //
1370                        System.out.println("InputStream");
1371                        bis = new BufferedInputStream((InputStream) xmlSource);
1372                    }
1373    
1374                }
1375    
1376                SequenceInputStream sis = new SequenceInputStream(new SequenceInputStream(beginTag, bais), endTag);
1377                System.out.println("---begin parsing---");
1378    
1379                ByteArrayOutputStream baisCopy = new ByteArrayOutputStream();
1380                ByteArrayOutputStream baos = new ByteArrayOutputStream();
1381    
1382                if (bis == null) {
1383                    MCRUtils.copyStream(sis, baisCopy);
1384                    bais.close();
1385                    sis.close();
1386                } else {
1387                    MCRUtils.copyStream(bis, baisCopy);
1388                    bis.close();
1389                }
1390    
1391                tidy.parse(new ByteArrayInputStream(baisCopy.toByteArray()), baos);
1392                pw.flush();
1393                pw.close();
1394                System.out.println(pw);
1395    
1396                if ((sw.toString().indexOf("is not recognized!") != -1) && (sw.toString().indexOf("Warning: discarding unexpected") != -1)) {
1397                    System.out.println("Parsing Document as XML");
1398                    tidy = new Tidy();
1399                    tidy = getTidyConfig(tidy, "xml");
1400                    baos.reset();
1401                    tidy.parse(new ByteArrayInputStream(baisCopy.toByteArray()), baos);
1402                }
1403    
1404                SAXBuilder builder = new SAXBuilder();
1405                baos.flush();
1406                System.out.println("jdom = " + baos.toByteArray().toString());
1407                jdomDoc = builder.build(new ByteArrayInputStream(baos.toByteArray()));
1408                baos.flush();
1409                baos.close();
1410                System.out.println("---parsing ended---");
1411            } catch (UnsupportedEncodingException e) {
1412                // TODO Auto-generated catch block
1413                e.printStackTrace();
1414            } catch (FileNotFoundException e) {
1415                // TODO Auto-generated catch block
1416                e.printStackTrace();
1417            } catch (IOException e) {
1418                // TODO Auto-generated catch block
1419                e.printStackTrace();
1420            } catch (JDOMException e) {
1421                // TODO Auto-generated catch block
1422                e.printStackTrace();
1423            }
1424    
1425            System.out.println("jdomDoc erzeugt");
1426    
1427            return jdomDoc;
1428        }
1429    
1430        public Tidy getTidyConfig(Tidy tidy, String outputFormat) {
1431            if (outputFormat.equals("xhtml")) {
1432                logger.debug("Parsing Document using JTidy. Output as XHTML.");
1433                tidy.setXHTML(true);
1434                tidy.setPrintBodyOnly(true);
1435            } else {
1436                logger.debug("Parsing Document using JTidy. Output as well-formed XML.");
1437                tidy.setXmlOut(true);
1438                tidy.setXmlTags(true);
1439            }
1440    
1441            tidy.setInputEncoding(OUTPUT_ENCODING);
1442            tidy.setOutputEncoding(OUTPUT_ENCODING);
1443            tidy.setWord2000(true);
1444            tidy.setIndentContent(true);
1445            tidy.setForceOutput(true);
1446            tidy.setMakeClean(true);
1447            tidy.setMakeBare(true);
1448            tidy.setQuoteAmpersand(true);
1449            tidy.setQuoteMarks(true);
1450            tidy.setQuoteNbsp(true);
1451    
1452            return tidy;
1453        }
1454    
1455        /**
1456         * @param request
1457         */
1458        public void initParam(HttpServletRequest request) {
1459            usedParser = "none";
1460            sessionParam = "final";
1461            contentFileBackup = null;
1462            naviFileBackup = null;
1463            hrefFile = null;
1464            error = href = labelPath = content = label = link = dir = null;
1465            changeInfo = null;
1466            masterTemplates = new File(MCRConfiguration.instance().getString("MCR.templatePath") + "master/".replace('/', File.separatorChar)).listFiles();
1467            userID = (String) mcrSession.get("userID");
1468            userClass = (String) mcrSession.get("userClass");
1469            userRealName = (String) mcrSession.get("userRealName");
1470            rootNodes = (List) mcrSession.get("rootNodes");
1471            action = (String) mcrSession.get("action");
1472            mode = (String) mcrSession.get("mode");
1473            href = (String) mcrSession.get("href");
1474            dir = (String) mcrSession.get("dir");
1475            currentLang = (String) mcrSession.get("currentLang");
1476            defaultLang = (String) mcrSession.get("defaultLang");
1477    
1478            if (mcrSession.get("addAtPosition") != null) {
1479                addAtPosition = (String) mcrSession.get("addAtPosition");
1480            }
1481    
1482            target = request.getParameter("target");
1483            style = request.getParameter("style");
1484            label = request.getParameter("label");
1485            content = request.getParameter("content");
1486            contentCurrentLang = request.getParameter("content_currentLang");
1487    
1488            /* code validation by JTidy */
1489            if (request.getParameter("codeValidationDisable") == null) {
1490                // logger.debug("Code validation using" + VALIDATOR);
1491                // codeValidation(VALIDATOR);
1492            }
1493    
1494            /* END: code validation by JTidy */
1495            currentLangLabel = request.getParameter("label_currentLang");
1496    
1497            /*
1498             * if (content != null ) { if ( content.endsWith("\n") ) content = content.substring(0, content.length() - 2); }
1499             */
1500            /* check for dynamic content bindings */
1501            /* add */
1502            if ((request.getParameter("dcbActionAdd") != null) && !request.getParameter("dcbActionAdd").equals("") && (request.getParameter("dcbValueAdd") != null)
1503                            && !request.getParameter("dcbValueAdd").equals("")) {
1504                dcbActionAdd = true;
1505                dcbValueAdd = request.getParameter("dcbValueAdd");
1506            } else {
1507                dcbActionAdd = false;
1508            }
1509    
1510            /* remove */
1511            if ((request.getParameter("dcbActionDelete") != null) && !request.getParameter("dcbActionDelete").equals("")
1512                            && (request.getParameter("dcbValueDelete") != null) && !request.getParameter("dcbValueDelete").equals("")) {
1513                dcbActionDelete = true;
1514                dcbValueDelete = request.getParameter("dcbValueDelete");
1515            } else {
1516                dcbActionDelete = false;
1517            }
1518    
1519            /* END OF: check for dynamic content bindings */
1520            if (request.getParameter("href") != null) {
1521                link = request.getParameter("href"); // .toLowerCase();
1522            }
1523    
1524            changeInfo = request.getParameter("changeInfo");
1525    
1526            if (request.getParameter("delete") != null) {
1527                realyDel = request.getParameter("delete");
1528            } else {
1529                realyDel = "";
1530            }
1531    
1532            labelPath = request.getParameter("labelPath");
1533            replaceMenu = request.getParameter("replaceMenu");
1534            constrainPopUp = request.getParameter("constrainPopUp");
1535    
1536            if (replaceMenu == null) {
1537                replaceMenu = "false";
1538            }
1539    
1540            if (constrainPopUp == null) {
1541                constrainPopUp = "false";
1542            }
1543    
1544            masterTemplate = request.getParameter("masterTemplate");
1545            selfTemplate = request.getParameter("selfTemplate");
1546    
1547            if (selfTemplate != "") {
1548                masterTemplate = selfTemplate;
1549            }
1550    
1551            fileName = href;
1552    
1553            /* -------------------------------------------------------------------- */
1554            if (action.equals("add") && mode.equals("intern")) {
1555                if ((link != null) && !link.toLowerCase().endsWith(".xml") && !link.toLowerCase().endsWith(".html")) {
1556                    link = link + ".xml";
1557                }
1558    
1559                fileName = href + link;
1560    
1561                if (addAtPosition.equals("child")) {
1562                    // implement here (add, intern, child)3
1563                    labelPath = labelPath + '/' + label;
1564    
1565                    if (href.toLowerCase().endsWith(".xml") || href.toLowerCase().endsWith(".html")) {
1566                        fileName = href.substring(0, href.lastIndexOf('.')) + '/' + link;
1567                    }
1568                } else {
1569                    // implement here (add, intern, predecessor, successor)1
1570                    labelPath = labelPath.substring(0, labelPath.indexOf('/') + 1) + label;
1571    
1572                    // Bug work around. When a page as neighboor of a link shall be created, the mode will changed
1573                    // by a sub method (valitate) of getParentAttribute. This behaviour is not correct.
1574                    // So, the mode will be kept as set before.
1575                    String modeBefore = new String(mode);
1576    
1577                    href = getParentAttribute(naviFile, "href", href, "href", "dir");
1578    
1579                    // Bug work around. When a page as neighboor of a link shall be created, the mode will changed
1580                    // by a sub method (valitate) of getParentAttribute. This behaviour is not correct.
1581                    // So, the mode will be kept as set before.
1582                    if (!mode.equals(modeBefore))
1583                        mode = modeBefore;
1584    
1585                    // not a root item (direct child of a menu node )
1586                    if (href.toLowerCase().endsWith(".xml") || href.toLowerCase().endsWith(".html")) {
1587                        fileName = href.substring(0, href.lastIndexOf('.')) + '/' + link;
1588                    }
1589                    // a root item shall be created
1590                    else {
1591                        String nameOfFile = link.trim();
1592                        String pathToFile = href.trim();
1593                        if (!pathToFile.endsWith(Character.toString(fs)))
1594                            pathToFile = pathToFile + fs;
1595                        fileName = pathToFile + nameOfFile;
1596                    }
1597    
1598                    href = (String) mcrSession.get("href");
1599                }
1600            }
1601    
1602            if (action.equals("add") && mode.equals("extern")) {
1603                fileName = link;
1604    
1605                if (!(link.toLowerCase().startsWith("http") || link.toLowerCase().startsWith("ftp:") || link.toLowerCase().startsWith("mailto:"))) {
1606                    // fileName = "http://" + link;
1607                    fileName = link;
1608                }
1609    
1610                if (addAtPosition.equals("child")) {
1611                    // implement here (add, extern, child)4
1612                    labelPath = labelPath + '/' + label;
1613                } else {
1614                    // implement here (add, extern, predecessor, successor)2
1615                    labelPath = labelPath.substring(0, labelPath.indexOf('/') + 1) + label;
1616                }
1617            }
1618    
1619            if (action.equals("edit") && mode.equals("intern")) {
1620                // implement here (edit, intern)5
1621            }
1622    
1623            if (action.equals("edit") && mode.equals("extern")) {
1624                // implement here (edit, extern)6
1625                fileName = link;
1626    
1627                if (!(link.toLowerCase().startsWith("http") || link.toLowerCase().startsWith("ftp:") || link.toLowerCase().startsWith("mailto:"))) {
1628                    // fileName = "http://" + link;
1629                    fileName = link;
1630                }
1631            }
1632    
1633            if (action.equals("delete")) {
1634                // implement here (delete)7
1635            }
1636    
1637            if (action.equals("translate")) {
1638                label = currentLangLabel;
1639            }
1640    
1641            /*-------------------------------------------------------------------*/
1642            if (!dir.equals("false")) {
1643                attribute = "dir";
1644                avalue = (String) mcrSession.get("dir");
1645            } else {
1646                attribute = "href";
1647                avalue = href;
1648            }
1649            hrefFile = new File(getServletContext().getRealPath("") + fileName.replace('/', fs));
1650        }
1651    
1652        /**
1653         * @param jdomDoc -
1654         *            JDOM Document
1655         * @param xmlFile -
1656         *            File the Document is written to.
1657         */
1658        public void writeJDOMDocumentToFile(Document jdomDoc, File xmlFile) throws IOException, FileNotFoundException {
1659            XMLOutputter xmlOut = new XMLOutputter();
1660            xmlOut.output(jdomDoc, new FileOutputStream(xmlFile));
1661            MCRConfiguration.instance().systemModified();
1662        }
1663    
1664        /**
1665         * 
1666         */
1667        public void test() throws IOException, FileNotFoundException {
1668            Document jdomDoc = getXMLAsJDOM(content);
1669    
1670            // Document jdomDoc2 = getXMLAsJDOM(getFile("c:\\test.xml"));
1671            // Document jdomDoc3 = getXMLAsJDOM(new
1672            // URL("http://java.sun.com/j2se/1.3/docs/api/java/net/URL.html"));
1673            writeJDOMDocumentToFile(jdomDoc, getFile("C:\\test_string.xml"));
1674    
1675            // writeJDOMDocumentToFile(jdomDoc2, getFile("C:\\test_file.xml"));
1676            // writeJDOMDocumentToFile(jdomDoc3, getFile("C:\\test_url.xml"));
1677        }
1678    
1679        // -----------------------
1680    
1681        /* END OF: new methods */
1682    
1683        /**
1684         * @author m5brmi-s
1685         * 
1686         * TODO To change the template for this generated type comment go to Window - Preferences - Java - Code Style - Code Templates
1687         */
1688        public static class ResolveDTD implements EntityResolver {
1689            public InputSource resolveEntity(String publicId, String systemId) {
1690                return new InputSource(new StringReader(" "));
1691            }
1692        }
1693    
1694        public boolean getback() {
1695            return this.back;
1696        }
1697    
1698        public void setback() {
1699            if (request.getParameter("back") != null && request.getParameter("back").equals("true")) {
1700                this.back = true;
1701            } else {
1702                this.back = false;
1703            }
1704        }
1705    
1706        public String getBackAddress() {
1707            return this.backaddr;
1708        }
1709    
1710        public void setBackAddress() {
1711            this.backaddr = request.getParameter("address");
1712        }
1713    }