001    /*
002     * 
003     * $Revision: 15604 $ $Date: 2009-07-24 09:48:26 +0200 (Fri, 24 Jul 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    package org.mycore.frontend.servlets;
025    
026    import java.io.File;
027    import java.io.FileOutputStream;
028    import java.io.FilenameFilter;
029    import java.io.IOException;
030    import java.lang.reflect.Method;
031    import java.net.HttpURLConnection;
032    import java.net.URL;
033    import java.net.URLEncoder;
034    import java.util.ArrayList;
035    import java.util.Collection;
036    import java.util.Enumeration;
037    import java.util.HashMap;
038    import java.util.List;
039    import java.util.Map;
040    import java.util.Properties;
041    
042    import javax.servlet.ServletException;
043    
044    import org.apache.log4j.Logger;
045    
046    import org.mycore.access.MCRAccessInterface;
047    import org.mycore.access.MCRAccessManager;
048    import org.mycore.common.MCRConfiguration;
049    import org.mycore.common.MCRException;
050    import org.mycore.common.MCRMailer;
051    import org.mycore.common.MCRSession;
052    import org.mycore.common.MCRSessionMgr;
053    import org.mycore.common.MCRUtils;
054    import org.mycore.datamodel.common.MCRActiveLinkException;
055    import org.mycore.datamodel.ifs.MCRDirectory;
056    import org.mycore.datamodel.metadata.MCRDerivate;
057    import org.mycore.datamodel.metadata.MCRMetaElement;
058    import org.mycore.datamodel.metadata.MCRMetaInterface;
059    import org.mycore.datamodel.metadata.MCRMetaNBN;
060    import org.mycore.datamodel.metadata.MCRObject;
061    import org.mycore.datamodel.metadata.MCRObjectID;
062    import org.mycore.datamodel.metadata.MCRObjectService;
063    import org.mycore.frontend.MCRWebsiteWriteProtection;
064    import org.mycore.frontend.fileupload.MCRSWFUploadHandlerIFS;
065    import org.mycore.frontend.fileupload.MCRSWFUploadHandlerMyCoRe;
066    import org.mycore.frontend.workflow.MCRSimpleWorkflowManager;
067    import org.mycore.services.urn.MCRURNManager;
068    
069    /**
070     * The servlet start the MyCoRe editor session or other workflow actions with
071     * some parameters from a HTML form. The parameters are: <br />
072     * <li>type - the MCRObjectID type like schrift, text ...</li> <br />
073     * <li>step - the name of the step like author, editor ...</li> <br />
074     * <li>layout - the name of the layout like firststep, secondstep ...</li> <br />
075     * <li>todo - the mode of the editor start like new or edit or change or delete</li>
076     * <br />
077     * <li>tf_mcrid - the MCRObjectID of the data they came from a input field</li> <br />
078     * <li>se_mcrid - the MCRObjectID of the data they came from a select field</li> <br />
079     * <li>re_mcrid - the MCRObjectID of the data they is in relation to
080     * tf_mcrid/se_mcrid</li> <br />
081     * 
082     * @author Jens Kupferschmidt
083     * @version $Revision: 15604 $ $Date: 2009-01-26 12:02:59 +0100 (Mo, 26. Jan
084     *          2009) $
085     */
086    public class MCRStartEditorServlet extends MCRServlet {
087    
088        private static final long serialVersionUID = 1L;
089    
090        // The configuration
091        protected static Logger LOGGER = Logger.getLogger(MCRStartEditorServlet.class);
092    
093        // The workflow manager
094        protected static MCRSimpleWorkflowManager WFM = null;
095    
096        // The file slash
097        protected static String SLASH = System.getProperty("file.separator");;
098    
099        // the access system
100        private static final MCRAccessInterface AI = MCRAccessManager.getAccessImpl();
101    
102        // static pages
103        protected static String pagedir = MCRConfiguration.instance().getString("MCR.SWF.PageDir", "");
104    
105        protected static String cancelpage = pagedir + MCRConfiguration.instance().getString("MCR.SWF.PageCancel", "editor_cancel.xml");
106    
107        protected static String deletepage = pagedir + MCRConfiguration.instance().getString("MCR.SWF.PageDelete", "editor_delete.xml");
108    
109        protected static String usererrorpage = pagedir
110                + MCRConfiguration.instance().getString("MCR.SWF.PageErrorUser", "editor_error_user.xml");
111    
112        protected static String mcriderrorpage = pagedir
113                + MCRConfiguration.instance().getString("MCR.SWF.PageErrorMcrid", "editor_error_mcrid.xml");
114    
115        protected static String storeerrorpage = pagedir
116                + MCRConfiguration.instance().getString("MCR.SWF.PageErrorStore", "editor_error_store.xml");
117    
118        protected static String deleteerrorpage = pagedir
119                + MCRConfiguration.instance().getString("MCR.SWF.PageErrorDelete", "editor_error_delete.xml");
120    
121        // common data
122        protected static class CommonData {
123            protected String mystep = null; // the special step for todo
124    
125            protected String myproject = null; // the project part
126    
127            protected String mytype = null; // the metadata type
128    
129            protected String myfile = null; // the formular file to be called
130    
131            protected MCRObjectID mytfmcrid = null; // the metadata ID (textfield)
132    
133            protected MCRObjectID mysemcrid = null; // the metadata ID (selected)
134    
135            protected MCRObjectID myremcrid = null; // the metadata ID (redirect)
136    
137            protected String extparm = null; // the extra parameter
138        }
139    
140        /** Initialisation of the servlet */
141        public void init() throws ServletException {
142            super.init();
143            WFM = MCRSimpleWorkflowManager.instance();
144        }
145    
146        /**
147         * This method overrides doGetPost of MCRServlet. <br />
148         * <br />
149         * The <b>todo </b> value corresponds with <b>tf_mcrid</b> or
150         * <b>se_mcridor</b> value and with the type of the data model for the
151         * permissions that the user need. For some actions you need a third value
152         * of <b>re_mcrid</b> for relations (object - derivate). <br />
153         * 
154         * <li>If the permission is not correct it calls
155         * <em>editor_error_user.xml</em>.</li> <br />
156         * <li>If the MCRObjectID is not correct it calls
157         * <em>editor_error_mcrid.xml</em>.</li> <br />
158         * <li>If a store error is occurred it calls <em>editor_error_store.xml</em>
159         * .</li> <br />
160         * <li>If <b>CANCEL </b> was pressed it calls <em>editor_cancel.xml</em>.</li>
161         * <br />
162         * <li>If the permission is correct it starts the file editor_form_
163         * <em>step-type</em> .xml.</li> <br />
164         */
165        public void doGetPost(MCRServletJob job) throws Exception {
166    
167            if (MCRWebsiteWriteProtection.printInfoPageIfNoAccess(job.getRequest(), job.getResponse(), getBaseURL()))
168                return;
169    
170            // get the MCRSession object for the current thread from the session
171            // manager.
172            MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
173            CommonData cd = new CommonData();
174    
175            // get the current language
176            String mylang = mcrSession.getCurrentLanguage();
177            LOGGER.debug("LANG = " + mylang);
178    
179            // read the parameter
180            // get the step
181            cd.mystep = getProperty(job.getRequest(), "step");
182            if (cd.mystep == null) {
183                cd.mystep = "";
184            }
185            LOGGER.debug("STEP = " + cd.mystep);
186    
187            // get the layout
188            String mylayout = getProperty(job.getRequest(), "layout");
189            if (mylayout == null) {
190                mylayout = "";
191            }
192            LOGGER.debug("LAYOUT = " + mylayout);
193    
194            // get what is to do
195            String mytodo = getProperty(job.getRequest(), "todo");
196            if ((mytodo == null) || ((mytodo = mytodo.trim()).length() == 0)) {
197                mytodo = "wrongtodo";
198            }
199            LOGGER.debug("TODO = " + mytodo);
200    
201            // get the MCRObjectID from the select field (SE)
202            String mysemcrid = getProperty(job.getRequest(), "se_mcrid");
203            if ((mysemcrid == null) || ((mysemcrid = mysemcrid.trim()).length() == 0)) {
204                cd.mysemcrid = new MCRObjectID();
205            } else {
206                try {
207                    cd.mysemcrid = new MCRObjectID(mysemcrid);
208                    cd.myproject = cd.mysemcrid.getProjectId();
209                    cd.mytype = cd.mysemcrid.getTypeId();
210                } catch (Exception e) {
211                    cd.mysemcrid = new MCRObjectID();
212                }
213            }
214            LOGGER.debug("MCRID (SE) = " + cd.mysemcrid.getId());
215    
216            String base = getProperty(job.getRequest(), "base");
217            if ((base != null) && (base.length() != 0)) {
218                MCRObjectID objid = new MCRObjectID();
219                objid.setNextFreeId(base);
220                cd.mytype = objid.getTypeId();
221                cd.myproject = objid.getProjectId();
222            }
223    
224            // get the type
225            if ((cd.mytype == null) || (cd.mytype.length() == 0)) {
226                cd.mytype = getProperty(job.getRequest(), "type");
227            }
228            LOGGER.debug("TYPE = " + cd.mytype);
229    
230            // get the project name
231            if ((cd.myproject == null) || (cd.myproject.length() == 0)) {
232                cd.myproject = getProperty(job.getRequest(), "project");
233            }
234            LOGGER.info("Project = " + cd.myproject);
235    
236            // get the MCRObjectID from the text filed (TF)
237            String mytfmcrid = getProperty(job.getRequest(), "tf_mcrid");
238            try {
239                cd.mytfmcrid = new MCRObjectID(mytfmcrid);
240            } catch (Exception e) {
241                cd.mytfmcrid = new MCRObjectID();
242            }
243            if ((mytfmcrid == null) || ((mytfmcrid = mytfmcrid.trim()).length() == 0)) {
244                cd.mytfmcrid = new MCRObjectID(getNextMCRTFID(cd.myproject, cd.mytype));
245            }
246            LOGGER.debug("MCRID (TF) = " + cd.mytfmcrid.getId());
247    
248            // get the MCRObjectID from the relation field (RE)
249            String myremcrid = getProperty(job.getRequest(), "re_mcrid");
250            if ((myremcrid == null) || ((myremcrid = myremcrid.trim()).length() == 0)) {
251                cd.myremcrid = new MCRObjectID();
252            } else {
253                try {
254                    cd.myremcrid = new MCRObjectID(myremcrid);
255                } catch (Exception e) {
256                    cd.myremcrid = new MCRObjectID();
257                }
258            }
259            LOGGER.debug("MCRID (RE) = " + cd.myremcrid.getId());
260    
261            // appending parameter
262            cd.extparm = getProperty(job.getRequest(), "extparm");
263            LOGGER.info("EXTPARM = " + cd.extparm);
264    
265            LOGGER.debug("Base URL : " + getBaseURL());
266    
267            // set the pages
268            StringBuffer sb = new StringBuffer();
269            sb.append(pagedir).append("editor_form_").append(cd.mystep).append('-').append(cd.mytype);
270            if (mylayout.length() != 0) {
271                sb.append('-').append(mylayout);
272            }
273            cd.myfile = sb.append(".xml").toString();
274    
275            // call method named like todo
276            Method meth[] = this.getClass().getMethods();
277            for (int i = 0; i < meth.length; i++) {
278                LOGGER.debug("Methods for SWF " + meth[i].getName());
279            }
280            try {
281                Method method = this.getClass().getMethod(mytodo, new Class[] { job.getClass(), cd.getClass() });
282                method.invoke(this, new Object[] { job, cd });
283                return;
284            } catch (Exception e) {
285                LOGGER.error("Error while execution of method " + mytodo);
286                e.printStackTrace();
287            }
288    
289            sb = new StringBuffer();
290            sb.append(getBaseURL()).append("index.html");
291            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(sb.toString()));
292        }
293    
294        /**
295         * This method return a next new MCRObjectID for the given type and project
296         * ID.
297         * 
298         * @param projectid
299         *            The MCRObjectID project ID
300         * @type type The MCRObjectID type
301         * @return the next free MCRObject for the given parameter
302         */
303        protected final String getNextMCRTFID(String myproject, String mytype) {
304            if ((mytype == null) || (mytype.trim().length() == 0) || (mytype.equals("MCR"))) {
305                mytype = "dummy";
306            }
307            if ((myproject == null) || (myproject.trim().length() == 0) || (myproject.equals("MCR"))) {
308                if (mytype.equals("dummy")) {
309                    myproject = MCRConfiguration.instance().getString("MCR.SWF.Project.ID", "MCR");
310                } else {
311                    myproject = MCRConfiguration.instance().getString("MCR.SWF.Project.ID." + mytype, "MCR");
312                }
313            }
314    
315            final String mytypeString = "_" + mytype + "_";
316            final String project = myproject;
317            File workdir = MCRSimpleWorkflowManager.instance().getDirectoryPath(myproject + "_" + mytype);
318            String max = mytypeString + "0.xml";
319            for (String file : workdir.list(new FilenameFilter() {
320                public boolean accept(File dir, String name) {
321                    return name.startsWith(project) && name.contains(mytypeString) && name.endsWith(".xml");
322                }
323            })) {
324                if (file.compareTo(max) > 0)
325                    max = file;
326            }
327            int maxIDinWorkflow = Integer.parseInt( max.substring( max.lastIndexOf( "_" ) + 1, max.length() - 4 ) );  
328                
329            MCRObjectID mcridnext = new MCRObjectID();
330            mcridnext.setNextFreeId(myproject + "_" + mytype, maxIDinWorkflow );
331            return mcridnext.getId();
332        }
333    
334        /**
335         * The method start the editor add a file to a derivate object that is
336         * stored in the server. The method use the input parameter:
337         * <b>type</b>,<b>step</b> <b>se_mcrid</b> and <b>re_mcrid</b>. Access
338         * rights must be 'writedb'.
339         * 
340         * @param job
341         *            the MCRServletJob instance
342         */
343        public void saddfile(MCRServletJob job, CommonData cd) throws IOException {
344            if (!MCRAccessManager.checkPermission(cd.myremcrid.getId(), "writedb")) {
345                job.getResponse().sendRedirect(getBaseURL() + usererrorpage);
346                return;
347            }
348    
349            StringBuffer sb = new StringBuffer(getBaseURL()).append("receive/").append(cd.myremcrid.getId());
350            MCRSWFUploadHandlerIFS fuh = new MCRSWFUploadHandlerIFS(cd.myremcrid.getId(), cd.mysemcrid.getId(), sb.toString());
351            String fuhid = fuh.getID();
352            cd.myfile = pagedir + "fileupload_commit.xml";
353    
354            String base = getBaseURL() + cd.myfile;
355            Properties params = new Properties();
356            params.put("XSL.UploadID", fuhid);
357            params.put("cancelUrl", getReferer(job));
358            params.put("XSL.target.param.1", "method=formBasedUpload");
359            params.put("XSL.target.param.2", "uploadId=" + fuhid);
360            params.put("mcrid", cd.mysemcrid.getId());
361            params.put("type", cd.mytype);
362            params.put("step", cd.mystep);
363            params.put("remcrid", cd.myremcrid.getId());
364            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(buildRedirectURL(base, params)));
365        }
366    
367        /**
368         * The method add a new NBN to the dataset with type <b>document</b> or
369         * <b>disshab</b>. The access right is writedb.
370         * 
371         * @param job
372         *            the MCRServletJob instance
373         */
374        public void saddnbn(MCRServletJob job, CommonData cd) throws Exception {
375            // access right
376            if (!MCRAccessManager.checkPermission(cd.mysemcrid, "writedb")) {
377                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + usererrorpage));
378                return;
379            }
380            if (!cd.mysemcrid.isValid()) {
381                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + mcriderrorpage));
382                return;
383            }
384            // check type
385            if (cd.mytype.equals("document") || cd.mytype.equals("disshab")) {
386                MCRObject obj = new MCRObject();
387                obj.receiveFromDatastore(cd.mysemcrid);
388                MCRMetaElement elm = obj.getMetadataElement("nbns");
389                if (elm == null) {
390                    String urn = MCRURNManager.buildURN("UBL");
391                    MCRMetaNBN nbn = new MCRMetaNBN("metadata", "nbn", 0, urn);
392                    ArrayList<MCRMetaInterface> list = new ArrayList<MCRMetaInterface>();
393                    elm = new MCRMetaElement("de", "MCRMetaNBN", "nbns", true, false, list);
394                    elm.addMetaObject(nbn);
395                    obj.getMetadata().setMetadataElement(elm, "nbns");
396                    try {
397                        obj.updateInDatastore();
398                        MCRURNManager.assignURN(urn, obj.getId().toString());
399                    } catch (MCRActiveLinkException e) {
400                        LOGGER.warn("Can't store NBN for " + cd.mysemcrid);
401                        e.printStackTrace();
402                    }
403                    LOGGER.info("Add the NBN " + urn);
404                } else {
405                    LOGGER.warn("The NBN already exists for " + cd.mysemcrid);
406                }
407    
408            }
409            // back to the metadata view
410            StringBuffer sb = new StringBuffer();
411            sb.append(getBaseURL()).append("receive/").append(cd.mysemcrid);
412            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(sb.toString()));
413        }
414    
415        /**
416         * The method delete a derivate object that is stored in the server. The
417         * method use the input parameter: <b>type</b>,<b>step</b> and
418         * <b>tf_mcrid</b>. Access rights must be 'writedb'.
419         * 
420         * @param job
421         *            the MCRServletJob instance
422         */
423        public void sdelder(MCRServletJob job, CommonData cd) throws IOException {
424            if (!MCRAccessManager.checkPermission(cd.myremcrid.getId(), "deletedb")) {
425                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + usererrorpage));
426                return;
427            }
428            if (!cd.mysemcrid.isValid()) {
429                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + mcriderrorpage));
430                return;
431            }
432    
433            MCRDerivate der = new MCRDerivate();
434    
435            try {
436                der.deleteFromDatastore(cd.mysemcrid.getId());
437                StringBuffer sb = new StringBuffer();
438                sb.append("receive/").append(cd.myremcrid.getId());
439                cd.myfile = sb.toString();
440            } catch (Exception e) {
441                cd.myfile = deleteerrorpage;
442            }
443    
444            List<String> addr = WFM.getMailAddress(cd.myproject + "_" + cd.mytype, "sdelder");
445            if (addr.size() == 0) {
446                addr = WFM.getMailAddress(cd.mytype, "sdelder");
447            }
448    
449            if (addr.size() != 0) {
450                String sender = WFM.getMailSender();
451                String appl = MCRConfiguration.instance().getString("MCR.SWF.Mail.ApplicationID", "DocPortal");
452                String subject = "Automatically generated message from " + appl;
453                StringBuffer text = new StringBuffer();
454                text.append("The derivate with ID ").append(cd.mysemcrid).append(" from the object with ID ").append(cd.mysemcrid).append(
455                        " was removed from server.");
456                LOGGER.info(text.toString());
457    
458                try {
459                    MCRMailer.send(sender, addr, subject, text.toString(), false);
460                } catch (Exception ex) {
461                    LOGGER.error("Can't send a mail to " + addr);
462                }
463            }
464            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + cd.myfile));
465        }
466    
467        /**
468         * The method delete a file from a derivate object that is stored in the
469         * server. The method use the input parameter: <b>type</b>,<b>step</b>
470         * <b>se_mcrid</b> and <b>re_mcrid</b>. Access rights must be 'deletedb'.
471         * 
472         * @param job
473         *            the MCRServletJob instance
474         */
475        public void sdelfile(MCRServletJob job, CommonData cd) throws IOException {
476            if (!MCRAccessManager.checkPermission(cd.myremcrid.getId(), "deletedb")) {
477                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + usererrorpage));
478                return;
479            }
480            if (!cd.mysemcrid.isValid()) {
481                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + mcriderrorpage));
482                return;
483            }
484    
485            int all = 0;
486    
487            int i = cd.extparm.indexOf("####nrall####");
488            int j = 0;
489    
490            if (i != -1) {
491                j = cd.extparm.indexOf("####", i + 13);
492                all = Integer.parseInt(cd.extparm.substring(i + 13, j));
493            }
494    
495            i = cd.extparm.indexOf("####nrthe####");
496    
497            if (i != -1) {
498                j = cd.extparm.indexOf("####", i + 13);
499                Integer.parseInt(cd.extparm.substring(i + 13, j));
500            }
501    
502            if (all > 1) {
503                i = cd.extparm.indexOf("####filename####");
504    
505                if (i != -1) {
506                    String filename = cd.extparm.substring(i + 16, cd.extparm.length());
507    
508                    try {
509                        MCRDirectory rootdir = MCRDirectory.getRootDirectory(cd.mysemcrid.getId());
510                        rootdir.getChildByPath(filename).delete();
511                    } catch (Exception ex) {
512                        LOGGER.warn("Can't remove file " + filename, ex);
513                    }
514                }
515            }
516    
517            StringBuffer sb = new StringBuffer();
518            sb.append(getBaseURL()).append("servlets/MCRFileNodeServlet/").append(cd.mysemcrid).append("/?hosts=local");
519            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(sb.toString()));
520        }
521    
522        /**
523         * The method delete a metadata object that is stored in the server. The
524         * method use the input parameter: <b>type</b>,<b>step</b> and
525         * <b>tf_mcrid</b>. Access rights must be 'writedb'.
526         * 
527         * @param job
528         *            the MCRServletJob instance
529         */
530        public void sdelobj(MCRServletJob job, CommonData cd) throws IOException {
531            if (!MCRAccessManager.checkPermission(cd.mytfmcrid, "deletedb")) {
532                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + usererrorpage));
533                return;
534            }
535            if (!cd.mytfmcrid.isValid()) {
536                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + mcriderrorpage));
537                return;
538            }
539    
540            MCRObject obj = new MCRObject();
541    
542            try {
543                obj.deleteFromDatastore(cd.mytfmcrid.getId());
544                cd.myfile = deletepage;
545            } catch (Exception e) {
546                if (LOGGER.isDebugEnabled()) {
547                    e.printStackTrace();
548                } else {
549                    LOGGER.error(e.getMessage());
550                }
551                cd.myfile = deleteerrorpage;
552            }
553    
554            List<String> addr = WFM.getMailAddress(cd.myproject + "_" + cd.mytype, "sdelobj");
555            if (addr.size() == 0) {
556                addr = WFM.getMailAddress(cd.mytype, "sdelobj");
557            }
558    
559            if (addr.size() != 0) {
560                String sender = WFM.getMailSender();
561                String appl = MCRConfiguration.instance().getString("MCR.SWF.Mail.ApplicationID", "DocPortal");
562                String subject = "Automaticaly message from " + appl;
563                StringBuffer text = new StringBuffer();
564                text.append("The object with type ").append(cd.mytype).append(" with ID ").append(cd.mytfmcrid).append(
565                        " was removed from server.");
566                LOGGER.info(text.toString());
567    
568                try {
569                    MCRMailer.send(sender, addr, subject, text.toString(), false);
570                } catch (Exception ex) {
571                    LOGGER.error("Can't send a mail to " + addr);
572                }
573            }
574            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + cd.myfile));
575        }
576    
577        /**
578         * The method start the editor to modify ACL of a metadata object that is
579         * stored in the server. The method use the input parameter:
580         * <b>type</b>,<b>step</b> and <b>tf_mcrid</b>. Access rights must be
581         * 'writedb'.
582         * 
583         * @param job
584         *            the MCRServletJob instance
585         */
586        public void seditacl(MCRServletJob job, CommonData cd) throws IOException {
587            if (!MCRAccessManager.checkPermission(cd.mysemcrid, "writedb")) {
588                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + usererrorpage));
589                return;
590            }
591            if (!cd.mysemcrid.isValid()) {
592                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + mcriderrorpage));
593                return;
594            }
595    
596            // read object
597            MCRObjectService service = new MCRObjectService();
598            Collection<String> permlist = MCRAccessManager.getPermissionsForID(cd.mysemcrid.getId());
599            for (String permission : permlist) {
600                org.jdom.Element ruleelm = AI.getRule(cd.mysemcrid.getId(), permission);
601                ruleelm = normalizeACLforSWF(ruleelm);
602                service.addRule(permission, ruleelm);
603            }
604            org.jdom.Element serviceelm = service.createXML();
605            if (LOGGER.isDebugEnabled()) {
606                org.jdom.Document dof = new org.jdom.Document();
607                dof.addContent(serviceelm);
608                byte[] xml = MCRUtils.getByteArray(dof);
609                System.out.println(new String(xml));
610            }
611    
612            StringBuffer sb = new StringBuffer();
613            sb.append(pagedir).append("editor_form_").append(cd.mystep).append("-acl.xml");
614            MCRSession session = MCRSessionMgr.getCurrentSession();
615            session.put("service", serviceelm);
616            String base = getBaseURL() + sb.toString();
617            Properties params = new Properties();
618            params.put("sourceUri", "session:service");
619            params.put("cancelUrl", getReferer(job));
620            params.put("mcrid", cd.mysemcrid.getId());
621            params.put("type", "acl");
622            params.put("step", cd.mystep);
623            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(buildRedirectURL(base, params)));
624        }
625    
626        /**
627         * Normalize the ACL to use in the SWF ACL editor. Some single conditions
628         * are one step to high in the hierarchy of the condition tree. This method
629         * move it down and normalized the output.
630         * 
631         * @param ruleelm
632         *            The XML access condition from the ACL system
633         */
634        @SuppressWarnings("unchecked")
635        private final org.jdom.Element normalizeACLforSWF(org.jdom.Element ruleelm) {
636            if (LOGGER.isDebugEnabled()) {
637                try {
638                    MCRUtils.writeElementToSysout(ruleelm);
639                } catch (Exception e) {
640                    LOGGER.warn("Can't write ACL Element input for SWF.");
641                }
642            }
643            // build new condition element
644            org.jdom.Element newcondition = new org.jdom.Element("condition");
645            newcondition.setAttribute("format", "xml");
646            // build new boolean AND element
647            org.jdom.Element newwrapperand = new org.jdom.Element("boolean");
648            newwrapperand.setAttribute("operator", "and");
649            newcondition.addContent(newwrapperand);
650            // build new boolean TRUE element
651            org.jdom.Element newtrue = new org.jdom.Element("boolean");
652            newtrue.setAttribute("operator", "true");
653            // check rule
654            if (ruleelm == null) {
655                LOGGER.warn("Rule element is null.");
656                return newcondition;
657            }
658            try {
659                // check of boolean AND element
660                org.jdom.Element oldwrapperand = ruleelm.getChild("boolean");
661                if (oldwrapperand == null) {
662                    return newcondition;
663                }
664    
665                org.jdom.Element newuser = (org.jdom.Element) newtrue.clone();
666                newuser.detach();
667                org.jdom.Element newdate = (org.jdom.Element) newtrue.clone();
668                newdate.detach();
669                org.jdom.Element newip = (org.jdom.Element) newtrue.clone();
670                newip.detach();
671                org.jdom.Element newelm = null;
672    
673                List<org.jdom.Element> parts = oldwrapperand.getChildren();
674                for (int i = 0; i < parts.size(); i++) {
675                    if (i > 2)
676                        break;
677                    org.jdom.Element oldelm = (org.jdom.Element) parts.get(i).detach();
678                    // if (oldelm.getChildren().size() == 0)
679                    // continue;
680                    if (oldelm.getName().equals("condition")) {
681                        org.jdom.Element newwrapper = new org.jdom.Element("boolean");
682                        newwrapper.setAttribute("operator", "or");
683                        newwrapper.addContent(oldelm);
684                        newelm = newwrapper;
685                    } else {
686                        newelm = oldelm;
687                    }
688                    String testfield = "";
689                    List<org.jdom.Element> innercond = newelm.getChildren();
690                    for (int j = 0; j < innercond.size(); j++) {
691                        org.jdom.Element cond = (org.jdom.Element) innercond.get(j);
692                        if (cond.getName().equals("condition")) {
693                            testfield = cond.getAttributeValue("field");
694                        }
695                    }
696                    if (testfield.equals("user") || testfield.equals("group")) {
697                        newuser = newelm;
698                    }
699                    if (testfield.equals("date")) {
700                        newdate = newelm;
701                    }
702                    if (testfield.equals("ip")) {
703                        newip = newelm;
704                    }
705                }
706                newwrapperand.addContent(newuser.detach());
707                newwrapperand.addContent(newdate.detach());
708                newwrapperand.addContent(newip.detach());
709            } catch (Exception e) {
710                e.printStackTrace();
711            }
712            if (LOGGER.isDebugEnabled()) {
713                try {
714                    MCRUtils.writeElementToSysout(newcondition);
715                } catch (Exception e) {
716                    LOGGER.warn("Can't write ACL Element output for SWF.");
717                }
718            }
719            return newcondition;
720        }
721    
722        /**
723         * The method start the editor to modify a derivate object that is stored in
724         * the server. The method use the input parameter: <b>type</b>,<b>step</b>
725         * <b>se_mcrid</b> and <b>se_mcrid</b>. Access rights must be 'writedb'.
726         * 
727         * @param job
728         *            the MCRServletJob instance
729         */
730        public void seditder(MCRServletJob job, CommonData cd) throws IOException {
731            if (!MCRAccessManager.checkPermission(cd.myremcrid.getId(), "writedb")) {
732                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + usererrorpage));
733                return;
734            }
735            if (!cd.mysemcrid.isValid()) {
736                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + mcriderrorpage));
737                return;
738            }
739    
740            StringBuffer sb = new StringBuffer();
741            Properties params = new Properties();
742            sb.append("request:receive/").append(cd.mysemcrid).append("?XSL.Style=editor");
743            params.put("sourceUri", sb.toString());
744            sb = new StringBuffer();
745            sb.append(getBaseURL()).append("receive/").append(cd.myremcrid.getId());
746            params.put("cancelUrl", sb.toString());
747            params.put("se_mcrid", cd.mysemcrid.getId());
748            params.put("re_mcrid", cd.myremcrid.getId());
749            params.put("type", cd.mytype);
750            params.put("step", cd.mystep);
751            sb = new StringBuffer();
752            sb.append(getBaseURL()).append(pagedir).append("editor_form_commit-derivate.xml");
753            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(buildRedirectURL(sb.toString(), params)));
754        }
755    
756        /**      
757         * The method start the editor to modify a derivate object that is stored in    
758         * the server. The method use the input parameter: <b>type</b>,<b>step</b>      
759         * <b>se_mcrid</b> and <b>se_mcrid</b>. Access rights must be 'writedb'.    
760         *      
761         * @param job   
762         *            the MCRServletJob instance    
763         */     
764        public void deleteDedivate(MCRServletJob job, CommonData cd) throws IOException {   
765            if (!MCRAccessManager.checkPermission(cd.myremcrid.getId(), "writedb")) {   
766                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + usererrorpage));      
767                return;     
768            }   
769            if (!cd.mysemcrid.isValid()) {      
770                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + mcriderrorpage));     
771                return;     
772            }   
773        
774            StringBuffer sb = new StringBuffer();   
775            Properties params = new Properties();   
776            sb.append("request:receive/").append(cd.mysemcrid).append("?XSL.Style=editor");     
777            params.put("sourceUri", sb.toString());     
778            sb = new StringBuffer();    
779            sb.append(getBaseURL()).append("receive/").append(cd.myremcrid.getId());    
780        
781            params.put("cancelUrl", sb.toString());     
782            params.put("XSL.se_mcrid", cd.mysemcrid.getId());   
783            params.put("XSL.re_mcrid", cd.myremcrid.getId());   
784            params.put("XSL.tf_mcrid", cd.mytfmcrid.getId());   
785            params.put("type", cd.mytype);      
786            params.put("step", cd.mystep);      
787            sb = new StringBuffer();    
788            sb.append(getBaseURL()).append(pagedir).append("deleteDerivate.xml");   
789            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(buildRedirectURL(sb.toString(), params)));   
790        }   
791        
792        /**     
793         * The method start the editor to modify a derivate object that is stored in    
794         * the server. The method use the input parameter: <b>type</b>,<b>step</b>      
795         * <b>se_mcrid</b> and <b>se_mcrid</b>. Access rights must be 'writedb'.    
796         *      
797         * @param job   
798         *            the MCRServletJob instance    
799         */     
800        public void deleteObject(MCRServletJob job, CommonData cd) throws IOException {     
801            if (!MCRAccessManager.checkPermission(cd.myremcrid.getId(), "writedb")) {   
802                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + usererrorpage));      
803                return;     
804            }   
805            if (!cd.mysemcrid.isValid()) {      
806                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + mcriderrorpage));     
807                return;     
808            }   
809        
810            StringBuffer sb = new StringBuffer();   
811            Properties params = new Properties();   
812            sb.append("request:receive/").append(cd.mysemcrid).append("?XSL.Style=editor");     
813            params.put("sourceUri", sb.toString());     
814            sb = new StringBuffer();    
815            sb.append(getBaseURL()).append("receive/").append(cd.myremcrid.getId());    
816        
817            params.put("cancelUrl", sb.toString());     
818            params.put("XSL.se_mcrid", cd.mysemcrid.getId());   
819            params.put("XSL.re_mcrid", cd.myremcrid.getId());   
820            params.put("XSL.tf_mcrid", cd.mytfmcrid.getId());   
821            params.put("type", cd.mytype);      
822            params.put("step", cd.mystep);      
823            sb = new StringBuffer();    
824            sb.append(getBaseURL()).append(pagedir).append("deleteObject.xml");     
825            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(buildRedirectURL(sb.toString(), params)));   
826        }   
827    
828        /**
829         * The method start the editor to modify a metadata object that is stored in
830         * the server. The method use the input parameter: <b>type</b>,<b>step</b>
831         * and <b>tf_mcrid</b>. Access rights must be 'writedb'.
832         * 
833         * @param job
834         *            the MCRServletJob instance
835         */
836        public void seditobj(MCRServletJob job, CommonData cd) throws IOException {
837            if (!MCRAccessManager.checkPermission(cd.mytfmcrid, "writedb")) {
838                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + usererrorpage));
839                return;
840            }
841            if (!cd.mytfmcrid.isValid()) {
842                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + mcriderrorpage));
843                return;
844            }
845    
846            StringBuffer sb = new StringBuffer();
847            // TODO: should transform mcrobject and use "session:" to save roundtrip
848            Properties params = new Properties();
849            sb.append("request:receive/").append(cd.mytfmcrid).append("?XSL.Style=editor");
850            params.put("sourceUri", sb.toString());
851            sb = new StringBuffer();
852            sb.append(getBaseURL()).append("receive/").append(cd.mytfmcrid);
853            params.put("cancelUrl", sb.toString());
854            params.put("mcrid", cd.mytfmcrid.getId());
855            params.put("type", cd.mytype);
856            params.put("step", cd.mystep);
857            String base = getBaseURL() + cd.myfile;
858            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(buildRedirectURL(base, params)));
859        }
860    
861        /**
862         * The method set a new derivate object that is stored in the server. The
863         * method use the input parameter: <b>type</b>,<b>step</b> <b>se_mcrid</b>
864         * and <b>re_mcrid</b>. Access rights must be 'writedb'.
865         * 
866         * @param job
867         *            the MCRServletJob instance
868         */
869        public void snewder(MCRServletJob job, CommonData cd) throws IOException {
870            if (!MCRAccessManager.checkPermission(cd.myremcrid.getId(), "writedb")) {
871                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + usererrorpage));
872                return;
873            }
874            cd.mystep = "addfile";
875            cd.mysemcrid = WFM.getNextDrivateID(cd.myremcrid);
876            saddfile(job, cd);
877        }
878    
879        /**
880         * The method set the main file of a derivate object that is stored in the
881         * server. The method use the input parameter: <b>type</b>,<b>step</b>
882         * <b>se_mcrid</b> and <b>re_mcrid</b>. Access rights must be 'writedb'.
883         * 
884         * @param job
885         *            the MCRServletJob instance
886         */
887        public void ssetfile(MCRServletJob job, CommonData cd) throws IOException {
888            if (!MCRAccessManager.checkPermission(cd.myremcrid.getId(), "writedb")) {
889                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + usererrorpage));
890                return;
891            }
892            if (!cd.mysemcrid.isValid()) {
893                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + mcriderrorpage));
894                return;
895            }
896    
897            MCRDerivate der = new MCRDerivate();
898            der.receiveFromDatastore(cd.mysemcrid);
899            der.getDerivate().getInternals().setMainDoc(cd.extparm);
900    
901            try {
902                der.updateXMLInDatastore();
903            } catch (MCRException ex) {
904                LOGGER.error("Exception while store to derivate " + cd.mysemcrid);
905            }
906    
907            StringBuffer sb = new StringBuffer();
908            sb.append(getBaseURL()).append("servlets/MCRFileNodeServlet/").append(cd.mysemcrid).append("/?hosts=local");
909            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(sb.toString()));
910        }
911    
912        /**
913         * The method start the file upload to add to the metadata object that is
914         * stored in the workflow. The method use the input parameter: <b>type</b>,
915         * <b>step</b>, <b>re_mcrid</b> and <b>se_mcrid</b>. Access rights must be
916         * 'create-'type.
917         * 
918         * @param job
919         *            the MCRServletJob instance
920         */
921        public void waddfile(MCRServletJob job, CommonData cd) throws IOException {
922            if (!MCRAccessManager.checkPermission("create-" + cd.myremcrid.getTypeId())) {
923                job.getResponse().sendRedirect(getBaseURL() + usererrorpage);
924                return;
925            }
926    
927            StringBuffer sb = new StringBuffer(pagedir);
928            sb.append("editor_").append(cd.myremcrid.getTypeId()).append("_editor.xml");
929    
930            String fuhid = new MCRSWFUploadHandlerMyCoRe(cd.myremcrid.getId(), cd.mysemcrid.getId(), "new", getBaseURL() + sb.toString())
931                    .getID();
932            cd.myfile = pagedir + "fileupload_new.xml";
933    
934            String base = getBaseURL() + cd.myfile;
935            Properties params = new Properties();
936            params.put("XSL.UploadID", fuhid);
937            params.put("cancelUrl", getReferer(job));
938            params.put("XSL.target.param.1", "method=formBasedUpload");
939            params.put("XSL.target.param.2", "uploadId=" + fuhid);
940            params.put("mcrid", cd.mysemcrid.getId());
941            params.put("type", cd.mytype);
942            params.put("step", cd.mystep);
943            params.put("remcrid", cd.myremcrid.getId());
944            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(buildRedirectURL(base, params)));
945        }
946    
947        /**
948         * The method commit a object including all derivates that is stored in the
949         * workflow to the server. The method use the input parameter:
950         * <b>type</b>,<b>step</b> and <b>se_mcrid</b>. Access rights must be
951         * 'writedb'.
952         * 
953         * @param job
954         *            the MCRServletJob instance
955         */
956        public void wcommit(MCRServletJob job, CommonData cd) throws IOException {
957            org.jdom.Element rule = WFM.getRuleFromFile(cd.mysemcrid, "writedb");
958            if (rule != null && !AI.checkPermission(rule)) {
959                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + usererrorpage));
960                return;
961            }
962            if (!cd.mysemcrid.isValid()) {
963                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + mcriderrorpage));
964                return;
965            }
966    
967            try {
968                if (WFM.commitMetadataObject(cd.mysemcrid)) {
969                    WFM.deleteMetadataObject(cd.mysemcrid);
970    
971                    List<String> addr = WFM.getMailAddress(cd.myproject + "_" + cd.mytype, "wcommit");
972                    if (addr.size() == 0) {
973                        addr = WFM.getMailAddress(cd.mytype, "wcommit");
974                    }
975    
976                    if (addr.size() != 0) {
977                        String sender = WFM.getMailSender();
978                        String appl = MCRConfiguration.instance().getString("MCR.SWF.Mail.ApplicationID", "DocPortal");
979                        String subject = "Automaticaly message from " + appl;
980                        StringBuffer text = new StringBuffer();
981                        text.append("The object of type ").append(cd.mytype).append(" with ID ").append(cd.mysemcrid).append(
982                                " was commited from workflow to the server.");
983                        LOGGER.info(text.toString());
984    
985                        try {
986                            MCRMailer.send(sender, addr, subject, text.toString(), false);
987                        } catch (Exception ex) {
988                            LOGGER.error("Can't send a mail to " + addr);
989                        }
990                    }
991    
992                    StringBuffer sb = new StringBuffer("receive/").append(cd.mysemcrid);
993                    cd.myfile = sb.toString();
994                } else {
995                    cd.myfile = storeerrorpage;
996                }
997            } catch (MCRActiveLinkException e) {
998                try {
999                    generateActiveLinkErrorpage(job.getRequest(), job.getResponse(), "Error while commiting work to the server.", e);
1000                    return;
1001                } catch (Exception se) {
1002                    LOGGER.error(se.getMessage(), se);
1003                    cd.myfile = storeerrorpage;
1004                }
1005            } catch (MCRException e) {
1006                LOGGER.error(e.getMessage(), e);
1007                cd.myfile = storeerrorpage;
1008            }
1009            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + cd.myfile));
1010        }
1011    
1012        /**
1013         * The method delete a derivate from an object that is stored in the
1014         * workflow. The method use the input parameter: <b>type</b>,<b>step</b>
1015         * <b>se_mcrid</b> and <b>re_mcrid</b>. Access rights must be 'deletewf'.
1016         * 
1017         * @param job
1018         *            the MCRServletJob instance
1019         */
1020        public void wdelder(MCRServletJob job, CommonData cd) throws IOException {
1021            org.jdom.Element rule = WFM.getRuleFromFile(cd.myremcrid, "deletewf");
1022            if (rule != null && !AI.checkPermission(rule)) {
1023                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + usererrorpage));
1024                return;
1025            }
1026            if (!cd.mysemcrid.isValid()) {
1027                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + mcriderrorpage));
1028                return;
1029            }
1030    
1031            StringBuffer sb = new StringBuffer(pagedir);
1032            sb.append("editor_").append(cd.myremcrid.getTypeId()).append("_editor.xml");
1033    
1034            WFM.deleteDerivateObject(cd.myremcrid, cd.mysemcrid);
1035    
1036            List<String> addr = WFM.getMailAddress(cd.myproject + "_" + cd.mytype, "wdelder");
1037            if (addr.size() == 0) {
1038                addr = WFM.getMailAddress(cd.mytype, "wdelder");
1039            }
1040    
1041            if (addr.size() != 0) {
1042                String sender = WFM.getMailSender();
1043                String appl = MCRConfiguration.instance().getString("MCR.SWF.Mail.ApplicationID", "DocPortal");
1044                String subject = "Automaticaly message from " + appl;
1045                StringBuffer text = new StringBuffer();
1046                text.append("The derivate with ID ").append(cd.mysemcrid).append(" was removed from workflow.");
1047                LOGGER.info(text.toString());
1048    
1049                try {
1050                    MCRMailer.send(sender, addr, subject, text.toString(), false);
1051                } catch (Exception ex) {
1052                    LOGGER.error("Can't send a mail to " + addr);
1053                }
1054            }
1055            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + sb.toString()));
1056        }
1057    
1058        /**
1059         * The method delete a file from the derivate object that is stored in the
1060         * workflow. The method use the input parameter: <b>type</b>,<b>step</b>
1061         * <b>se_mcrid</b> and <b>re_mcrid</b>. Access rights must be 'deletewf'.
1062         * 
1063         * @param job
1064         *            the MCRServletJob instance
1065         */
1066        public void wdelfile(MCRServletJob job, CommonData cd) throws IOException {
1067            org.jdom.Element rule = WFM.getRuleFromFile(cd.myremcrid, "deletewf");
1068            if (rule != null && !AI.checkPermission(rule)) {
1069                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + usererrorpage));
1070                return;
1071            }
1072            if (!cd.mysemcrid.isValid()) {
1073                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + mcriderrorpage));
1074                return;
1075            }
1076    
1077            int all = 0;
1078    
1079            int i = cd.extparm.indexOf("####nrall####");
1080            int j = 0;
1081    
1082            if (i != -1) {
1083                j = cd.extparm.indexOf("####", i + 13);
1084                all = Integer.parseInt(cd.extparm.substring(i + 13, j));
1085            }
1086    
1087            i = cd.extparm.indexOf("####nrthe####");
1088    
1089            if (i != -1) {
1090                j = cd.extparm.indexOf("####", i + 13);
1091                Integer.parseInt(cd.extparm.substring(i + 13, j));
1092            }
1093    
1094            if (all > 1) {
1095                File derpath = WFM.getDirectoryPath(cd.myproject + "_" + cd.mytype);
1096                i = cd.extparm.indexOf("####filename####");
1097    
1098                if (i != -1) {
1099                    String filename = cd.extparm.substring(i + 16, cd.extparm.length());
1100    
1101                    try {
1102                        File fi = new File(derpath, filename);
1103                        fi.delete();
1104                    } catch (Exception ex) {
1105                        LOGGER.warn("Can't remove file " + filename);
1106                    }
1107                }
1108            }
1109    
1110            StringBuffer sb = new StringBuffer();
1111            sb.append(getBaseURL()).append(pagedir).append("editor_").append(cd.myremcrid.getTypeId()).append("_editor.xml");
1112            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(sb.toString()));
1113        }
1114    
1115        /**
1116         * The method delete a metadata object that is stored in the workflow. The
1117         * method use the input parameter: <b>type</b>,<b>step</b> and
1118         * <b>se_mcrid</b>. Access rights must be 'deletewf'.
1119         * 
1120         * @param job
1121         *            the MCRServletJob instance
1122         */
1123        public void wdelobj(MCRServletJob job, CommonData cd) throws IOException {
1124            org.jdom.Element rule = WFM.getRuleFromFile(cd.mysemcrid, "deletewf");
1125            if (rule != null && !AI.checkPermission(rule)) {
1126                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + usererrorpage));
1127                return;
1128            }
1129            if (!cd.mysemcrid.isValid()) {
1130                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + mcriderrorpage));
1131                return;
1132            }
1133    
1134            String wfurl = getWorkflowFile(pagedir, cd);
1135    
1136            WFM.deleteMetadataObject(cd.mysemcrid);
1137    
1138            List<String> addr = WFM.getMailAddress(cd.myproject + "_" + cd.mytype, "wdelobj");
1139            if (addr.size() == 0) {
1140                addr = WFM.getMailAddress(cd.mytype, "wdelobj");
1141            }
1142    
1143            if (addr.size() != 0) {
1144                String sender = WFM.getMailSender();
1145                String appl = MCRConfiguration.instance().getString("MCR.SWF.Mail.ApplicationID", "MyCoRe");
1146                String subject = "Automaticaly message from " + appl;
1147                StringBuffer text = new StringBuffer();
1148                text.append("The object of type ").append(cd.mytype).append(" with ID ").append(cd.mysemcrid).append(
1149                        " was removed from the workflow.");
1150                LOGGER.info(text.toString());
1151    
1152                try {
1153                    MCRMailer.send(sender, addr, subject, text.toString(), false);
1154                } catch (Exception ex) {
1155                    LOGGER.error("Can't send a mail to " + addr);
1156                }
1157            }
1158            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + wfurl));
1159        }
1160    
1161        private final String getWorkflowFile(String pagedir, CommonData cd) {
1162            StringBuffer sb = new StringBuffer();
1163            sb.append(pagedir).append("editor_").append(cd.myproject).append('_').append(cd.mytype).append("_editor.xml");
1164            URL url = null;
1165            HttpURLConnection http = null;
1166            try {
1167                url = new URL(getBaseURL() + sb.toString());
1168                http = (HttpURLConnection) url.openConnection();
1169                if (http.getResponseCode() != 200) {
1170                    sb = new StringBuffer();
1171                    sb.append(pagedir).append("editor_").append(cd.mytype).append("_editor.xml");
1172                    url = new URL(getBaseURL() + sb.toString());
1173                    http = (HttpURLConnection) url.openConnection();
1174                    if (http.getResponseCode() != 200) {
1175                        sb = new StringBuffer("");
1176                    } else {
1177                        http.disconnect();
1178                    }
1179                } else {
1180                    http.disconnect();
1181                }
1182            } catch (Exception eu) {
1183                sb = new StringBuffer("");
1184            }
1185    
1186            return sb.toString();
1187        }
1188    
1189        /**
1190         * The method start the editor to modify the metadata object ACL that is
1191         * stored in the workflow. The method use the input parameter:
1192         * <b>type</b>,<b>step</b> and <b>se_mcrid</b>. Access rights must be
1193         * 'writewf'.
1194         * 
1195         * @param job
1196         *            the MCRServletJob instance
1197         */
1198        public void weditacl(MCRServletJob job, CommonData cd) throws IOException {
1199            org.jdom.Element rule = WFM.getRuleFromFile(cd.mysemcrid, "writewf");
1200            if (rule != null && !AI.checkPermission(rule)) {
1201                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + usererrorpage));
1202                return;
1203            }
1204            if (!cd.mysemcrid.isValid()) {
1205                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + mcriderrorpage));
1206                return;
1207            }
1208    
1209            // read file
1210            File path = WFM.getDirectoryPath(cd.mysemcrid.getBase());
1211            File fi = new File(path, cd.mysemcrid + ".xml");
1212            org.jdom.Element service = null;
1213            try {
1214                if (fi.isFile() && fi.canRead()) {
1215                    MCRObject obj = new MCRObject();
1216                    obj.setFromURI(fi.toURI());
1217                    service = obj.getService().createXML();
1218                } else {
1219                    LOGGER.error("Can't read file " + fi.getAbsolutePath());
1220                }
1221            } catch (Exception ex) {
1222                ex.printStackTrace();
1223                LOGGER.error("Can't read file " + fi.getAbsolutePath());
1224            }
1225    
1226            StringBuilder sb = new StringBuilder();
1227            sb.append(pagedir).append("editor_form_").append(cd.mystep).append("-acl.xml");
1228            MCRSession session = MCRSessionMgr.getCurrentSession();
1229            session.put("service", service);
1230            String base = getBaseURL() + sb.toString();
1231            Properties params = new Properties();
1232            params.put("sourceUri", "session:service");
1233            params.put("cancelUrl", getReferer(job));
1234            params.put("mcrid", cd.mysemcrid.getId());
1235            params.put("type", "acl");
1236            params.put("step", cd.mystep);
1237            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(buildRedirectURL(base, params)));
1238        }
1239    
1240        /**
1241         * The method start the editor modify derivate metadata that is stored in
1242         * the workflow. The method use the input parameter: <b>type</b>,<b>step</b>
1243         * <b>re_mcrid</b> and <b>se_mcrid</b>. Access rights must be 'writewf'.
1244         * 
1245         * @param job
1246         *            the MCRServletJob instance
1247         */
1248        public void weditder(MCRServletJob job, CommonData cd) throws IOException {
1249            org.jdom.Element rule = WFM.getRuleFromFile(cd.myremcrid, "writewf");
1250            if (rule != null && !AI.checkPermission(rule)) {
1251                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + usererrorpage));
1252                return;
1253            }
1254            if (!cd.mysemcrid.isValid()) {
1255                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + mcriderrorpage));
1256                return;
1257            }
1258    
1259            Properties params = new Properties();
1260            StringBuffer sb = new StringBuffer();
1261            sb.append("file://").append(WFM.getDirectoryPath(cd.myproject + "_" + cd.mytype)).append(SLASH).append(cd.mysemcrid).append(".xml");
1262            params.put("sourceUri", sb.toString());
1263            params.put("cancelUrl", getReferer(job));
1264            params.put("se_mcrid", cd.mysemcrid.getId());
1265            params.put("re_mcrid", cd.myremcrid.getId());
1266            params.put("type", cd.mytype);
1267            params.put("step", cd.mystep);
1268            sb = new StringBuffer();
1269            sb.append(getBaseURL()).append(pagedir).append("editor_form_editor-derivate.xml");
1270            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(buildRedirectURL(sb.toString(), params)));
1271        }
1272    
1273        /**
1274         * The method copy a object in the workflow with a a new MCRObjectID.
1275         * 
1276         * @param cd
1277         *            the common data stack
1278         * @param job
1279         *            the MCRServletJob instance
1280         */
1281        public void wcopyobj(MCRServletJob job, CommonData cd) throws IOException {
1282            org.jdom.Element rule = WFM.getRuleFromFile(cd.mysemcrid, "writewf");
1283            if (rule != null && !AI.checkPermission(rule)) {
1284                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + usererrorpage));
1285                return;
1286            }
1287            if (!cd.mysemcrid.isValid()) {
1288                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + mcriderrorpage));
1289                return;
1290            }
1291    
1292            cd.mytfmcrid = new MCRObjectID(getNextMCRTFID(cd.myproject, cd.mytype));
1293            LOGGER.debug("MCRID (TF) = " + cd.mytfmcrid.getId());
1294            File outFile = new File(WFM.getDirectoryPath(cd.mytfmcrid.getBase()), cd.mytfmcrid + ".xml");
1295            MCRObject copyobj = new MCRObject();
1296            File inFile = new File(WFM.getDirectoryPath(cd.mysemcrid.getBase()), cd.mysemcrid + ".xml");
1297            copyobj.setFromURI(inFile.toURI());
1298            copyobj.setId(cd.mytfmcrid);
1299            copyobj.setLabel(cd.mytfmcrid.getId());
1300            MCRUtils.writeJDOMToFile(copyobj.createXML(), outFile);
1301    
1302            String base = WFM.getWorkflowFile(pagedir, cd.mytfmcrid.getBase());
1303            Properties params = new Properties();
1304            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(buildRedirectURL(getBaseURL() + base, params)));
1305        }
1306    
1307        /**
1308         * The method start the editor to modify a metadata object that is stored in
1309         * the workflow. The method use the input parameter: <b>type</b>,<b>step</b>
1310         * and <b>se_mcrid</b>. Access rights must be 'writewf'.
1311         * 
1312         * @param job
1313         *            the MCRServletJob instance
1314         */
1315        public void weditobj(MCRServletJob job, CommonData cd) throws IOException {
1316            org.jdom.Element rule = WFM.getRuleFromFile(cd.mysemcrid, "writewf");
1317            if (rule != null && !AI.checkPermission(rule)) {
1318                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + usererrorpage));
1319                return;
1320            }
1321            if (!cd.mysemcrid.isValid()) {
1322                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + mcriderrorpage));
1323                return;
1324            }
1325    
1326            File wfFile = new File(WFM.getDirectoryPath(cd.mysemcrid.getBase()), cd.mysemcrid + ".xml");
1327            String base = getBaseURL() + cd.myfile;
1328            Properties params = new Properties();
1329            params.put("sourceUri", wfFile.toURI().toString());
1330            params.put("cancelUrl", getReferer(job));
1331            params.put("mcrid", cd.mysemcrid.getId());
1332            params.put("type", cd.mytype);
1333            params.put("step", cd.mystep);
1334            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(buildRedirectURL(base, params)));
1335        }
1336    
1337        /**
1338         * The method build a new derivate and start the file upload to add to the
1339         * metadata object that is stored in the workflow. The method use the input
1340         * parameter: <b>type</b>, <b>step</b>, <b>re_mcrid</b> and <b>se_mcrid</b>.
1341         * Access rights must be 'create-'type.
1342         * 
1343         * @param job
1344         *            the MCRServletJob instance
1345         */
1346        public void wnewder(MCRServletJob job, CommonData cd) throws IOException {
1347            if (!MCRAccessManager.checkPermission("create-" + cd.mytype)) {
1348                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + usererrorpage));
1349                return;
1350            }
1351    
1352            cd.myremcrid = cd.mysemcrid;
1353            cd.mysemcrid = WFM.getNextDrivateID(cd.myremcrid);
1354            waddfile(job, cd);
1355        }
1356    
1357        /**
1358         * The method start the editor to create new metadata object that will be
1359         * stored in the workflow. The method use the input parameter:
1360         * <b>type</b>,<b>step</b> and <b>tf_mcrid</b>. Access rights must be
1361         * 'create-'type.
1362         * 
1363         * @param job
1364         *            the MCRServletJob instance
1365         */
1366        public void wnewobj(MCRServletJob job, CommonData cd) throws IOException {
1367            if ((!AI.checkPermission("create-" + cd.mytfmcrid.getBase())) && (!MCRAccessManager.checkPermission("create-" + cd.mytype))) {
1368                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + usererrorpage));
1369                return;
1370            }
1371    
1372            String base = getBaseURL() + cd.myfile;
1373            Properties params = new Properties();
1374    
1375            // start changes for submitting xml templates
1376            LOGGER.debug("calling buildXMLTemplate...");
1377            Enumeration<?> e = job.getRequest().getParameterNames();
1378            HashMap<String, String> templatePairs = new HashMap<String, String>();
1379            while (e.hasMoreElements()) {
1380                String name = (String) (e.nextElement());
1381                String value = job.getRequest().getParameter(name);
1382                if (name.startsWith("_xml_")) {
1383                    templatePairs.put(URLEncoder.encode(name.substring(5), "UTF-8"), URLEncoder.encode(value, "UTF-8"));
1384                } else {
1385                    params.put(name, value);
1386    
1387                }
1388            }
1389            if (templatePairs.size() > 0) {
1390                StringBuilder sb = new StringBuilder("buildxml:_rootName_=mycoreobject");
1391                for (Map.Entry<String, String> entry : templatePairs.entrySet()) {
1392                    sb.append('&').append(entry.getKey()).append('=').append(entry.getValue());
1393                }
1394                params.put("sourceUri", sb.toString());
1395            } else {
1396                LOGGER.debug("XMLTemplate is empty");
1397            }
1398            // end changes
1399    
1400            params.put("cancelUrl", getReferer(job));
1401            params.put("mcrid", cd.mytfmcrid.getId());
1402            params.put("type", cd.mytype);
1403            params.put("step", cd.mystep);
1404            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(buildRedirectURL(base, params)));
1405        }
1406    
1407        /**
1408         * The method start the editor to modify a derivate object that is stored in
1409         * the workflow. The method use the input parameter: <b>type</b>,<b>step</b>
1410         * <b>re_mcrid</b> and <b>se_mcrid</b>. Access rights must be 'writewf'.
1411         * 
1412         * @param job
1413         *            the MCRServletJob instance
1414         */
1415        public void wsetfile(MCRServletJob job, CommonData cd) throws IOException {
1416            org.jdom.Element rule = WFM.getRuleFromFile(cd.myremcrid, "writewf");
1417            if (rule != null && !AI.checkPermission(rule)) {
1418                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + usererrorpage));
1419                return;
1420            }
1421            if (!cd.mysemcrid.isValid()) {
1422                job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + mcriderrorpage));
1423                return;
1424            }
1425    
1426            File impex = new File(WFM.getDirectoryPath(cd.myproject + "_" + cd.mytype), cd.mysemcrid + ".xml");
1427    
1428            MCRDerivate der = new MCRDerivate();
1429            der.setFromURI(impex.toURI());
1430    
1431            if (cd.extparm.startsWith("####main####")) {
1432                der.getDerivate().getInternals().setMainDoc(cd.extparm.substring(cd.mysemcrid.getId().length() + 1 + 12, cd.extparm.length()));
1433            }
1434    
1435            byte[] outxml = MCRUtils.getByteArray(der.createXML());
1436    
1437            FileOutputStream out = new FileOutputStream(impex);
1438            try {
1439                out.write(outxml);
1440                out.flush();
1441            } catch (IOException ex) {
1442                LOGGER.error("Exception while store to file " + impex);
1443            } finally {
1444                out.close();
1445            }
1446    
1447            StringBuilder sb = new StringBuilder();
1448            sb.append(pagedir).append("editor_").append(cd.myremcrid.getTypeId()).append("_editor.xml");
1449            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + sb.toString()));
1450        }
1451    
1452        /**
1453         * This method implements the error exit to <em>index.xml</em> if the action
1454         * method was not found or has an error. It implements the TODO 'wrongtodo'.
1455         * 
1456         * @param job
1457         *            the MCRServletJob instance
1458         */
1459        public void wrongtodo(MCRServletJob job, CommonData cd) throws IOException {
1460            StringBuffer sb = new StringBuffer();
1461            sb.append(getBaseURL()).append("index.html");
1462            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(sb.toString()));
1463        }
1464    
1465        private String getReferer(MCRServletJob job) {
1466            String referer = job.getRequest().getHeader("Referer");
1467            if (referer == null || referer.equals("")) {
1468                referer = getBaseURL() + cancelpage;
1469            }
1470            LOGGER.debug("Referer: " + referer);
1471            return referer;
1472        }
1473    }