001    /*
002     * 
003     * $Revision: 15291 $ $Date: 2009-05-28 12:49:38 +0200 (Thu, 28 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    package org.mycore.frontend.servlets;
025    
026    import static org.jdom.Namespace.XML_NAMESPACE;
027    import static org.mycore.common.MCRConstants.XLINK_NAMESPACE;
028    import static org.mycore.common.MCRConstants.XSI_NAMESPACE;
029    
030    import java.util.List;
031    
032    import org.apache.log4j.Logger;
033    import org.jdom.Document;
034    import org.jdom.Element;
035    import org.jdom.xpath.XPath;
036    import org.mycore.access.MCRAccessManager;
037    import org.mycore.common.MCRConfiguration;
038    import org.mycore.common.MCRMailer;
039    import org.mycore.common.MCRUtils;
040    import org.mycore.datamodel.common.MCRActiveLinkException;
041    import org.mycore.datamodel.metadata.MCRDerivate;
042    import org.mycore.datamodel.metadata.MCRMetaLinkID;
043    import org.mycore.datamodel.metadata.MCRObject;
044    import org.mycore.datamodel.metadata.MCRObjectID;
045    import org.mycore.frontend.editor.MCREditorSubmission;
046    
047    /**
048     * The servlet store the MCREditorServlet output XML in a file of a MCR type
049     * dependencies directory, check it dependence of the MCR type and store the XML
050     * in a file in this directory or if an error was occured start the editor again
051     * with <b>todo </b> <em>repair</em>.
052     * 
053     * @author Jens Kupferschmidt
054     * @version $Revision: 15291 $ $Date: 2009-05-28 12:49:38 +0200 (Thu, 28 May 2009) $
055     */
056    public class MCRCheckCommitDerivateServlet extends MCRCheckBase {
057    
058        private static final long serialVersionUID = 1L;
059        private static Logger LOGGER = Logger.getLogger(MCRCheckCommitDerivateServlet.class);
060    
061        /**
062         * This method overrides doGetPost of MCRServlet. <br />
063         */
064        public void doGetPost(MCRServletJob job) throws Exception {
065            // read the XML data
066            MCREditorSubmission sub = (MCREditorSubmission) (job.getRequest().getAttribute("MCREditorSubmission"));
067            Document indoc = sub.getXML();
068            if (LOGGER.isDebugEnabled()) {
069                MCRUtils.writeJDOMToSysout(indoc);
070            }
071    
072            // create a metadata object and prepare it
073            MCRObjectID derID = null;
074            boolean okay = false;
075            String url = getNextURL(derID, okay);
076            try {
077                Element root = indoc.getRootElement();
078                derID = new MCRObjectID(root.getAttributeValue("ID"));
079                root.setAttribute("noNamespaceSchemaLocation", "datamodel-derivate.xsd", XSI_NAMESPACE);
080                root.addNamespaceDeclaration(XLINK_NAMESPACE);
081                root.addNamespaceDeclaration(XSI_NAMESPACE);
082                XPath titles = XPath.newInstance("/mycorederivate/derivate/titles/title");
083                for (Object node : titles.selectNodes(indoc)) {
084                    Element e = (Element) node;
085                    if (e.getAttribute("lang") != null) {
086                        e.getAttribute("lang").setNamespace(XML_NAMESPACE);
087                    }
088                }
089                XPath linkmetas = XPath.newInstance("/mycorederivate/derivate/linkmetas/linkmeta");
090                for (Object node : linkmetas.selectNodes(indoc)) {
091                    Element e = (Element) node;
092                    if (e.getAttribute("href") != null) {
093                        e.getAttribute("href").setNamespace(XLINK_NAMESPACE);
094                    }
095                    if (e.getAttribute("title") != null) {
096                        e.getAttribute("title").setNamespace(XLINK_NAMESPACE);
097                    }
098                    if (e.getAttribute("type") != null) {
099                        e.getAttribute("type").setNamespace(XLINK_NAMESPACE);
100                    }
101                }
102                if (LOGGER.isDebugEnabled()) {
103                    MCRUtils.writeJDOMToSysout(indoc);
104                }
105                byte[] xml = MCRUtils.getByteArray(indoc);
106    
107                // read data
108                MCRDerivate der = new MCRDerivate();
109                der.setFromXML(xml, true);
110                MCRObjectID objID = der.getDerivate().getMetaLink().getXLinkHrefID();
111                
112                // check access
113                if (!checkAccess(objID)) {
114                    job.getResponse().sendRedirect(getBaseURL() + usererrorpage);
115                    return;
116                }
117    
118                // update data
119                der.updateXMLInDatastore();
120                String label = der.getLabel();
121                String href = der.getDerivate().getMetaLink().getXLinkHref();
122                MCRObject obj = new MCRObject();
123                obj.receiveFromDatastore(href);
124                int size = obj.getStructure().getDerivateSize();
125                boolean isset = false;
126                for (int i = 0; i < size; i++) {
127                    MCRMetaLinkID link = obj.getStructure().getDerivate(i);
128                    if (link.getXLinkHref().equals(der.getId().getId())) {
129                        String oldlabel = link.getXLinkLabel();
130                        if ((oldlabel != null) && (!oldlabel.trim().equals(label))) {
131                            obj.getStructure().getDerivate(i).setXLinkLabel(label);
132                            isset = true;
133                        }
134                        break;
135                    }
136                }
137                // update mycoreobject
138                if (isset) {
139                    obj.updateThisInDatastore();
140                    LOGGER.info("Synchronized " + der.getId().getId());
141                }
142    
143                // go back
144                okay = true;
145                url = getNextURL(objID, okay);
146                sendMail(derID);
147            } catch (Exception e) {
148                e.printStackTrace();
149            }
150            // return
151            job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(getBaseURL() + url));
152        }
153    
154        /**
155         * The method is a dummy and return an URL with the next working step.
156         * 
157         * @param ID
158         *            the MCRObjectID of the MCRObject
159         * @param okay
160         *            the return value of the store operation
161         * @return the next URL as String
162         */
163        public final String getNextURL(MCRObjectID ID, boolean okay) throws MCRActiveLinkException {
164            StringBuffer sb = new StringBuffer();
165            if (okay) {
166                // return all is ready
167                sb.append("receive/").append(ID.getId());
168            } else {
169                sb.append(MCRConfiguration.instance().getString("MCR.SWF.PageDir", "")).append(MCRConfiguration.instance().getString("MCR.SWF.PageErrorStore", "editor_error_store.xml"));
170            }
171            return sb.toString();
172        }
173    
174        /**
175         * The method send a message to the mail address for the MCRObjectType.
176         * 
177         * @param ID
178         *            the MCRObjectID of the MCRObject
179         */
180        public final void sendMail(MCRObjectID ID) {
181            List<String> addr = WFM.getMailAddress(ID.getTypeId(), "seditder");
182            if (addr.size() == 0) {
183                return;
184            }
185            String sender = WFM.getMailSender();
186            String appl = MCRConfiguration.instance().getString("MCR.SWF.Mail.ApplicationID", "MyCoRe");
187            String subject = "Automatically generated message from " + appl;
188            StringBuffer text = new StringBuffer();
189            text.append("The title of the derivate with the ID ").append(ID.getId()).append(" was changed in the server.");
190            LOGGER.info(text.toString());
191            try {
192                MCRMailer.send(sender, addr, subject, text.toString(), false);
193            } catch (Exception ex) {
194                LOGGER.error("Can't send a mail to " + addr);
195            }
196        }
197    
198        /**
199         * check the access permission
200         * @param ID the mycore ID
201         * @return true if the access is set
202         */
203        protected boolean checkAccess(MCRObjectID ID) {
204            if (MCRAccessManager.checkPermission(ID, "writedb")) {
205                return true;
206            }
207            return false;
208        }
209    
210    }