Example usage for org.dom4j.io DocumentResult DocumentResult

List of usage examples for org.dom4j.io DocumentResult DocumentResult

Introduction

In this page you can find the example usage for org.dom4j.io DocumentResult DocumentResult.

Prototype

public DocumentResult() 

Source Link

Usage

From source file:de.ingrid.mdek.servlets.HelpServlet.java

License:EUPL

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    HttpSession session = request.getSession();
    Enumeration<String> enumeration = request.getParameterNames();

    while (enumeration.hasMoreElements()) {
        String parameterName = enumeration.nextElement();
        String parameter = (String) request.getParameter(parameterName);
        log.debug("parameter name: " + parameterName);
        log.debug("parameter value: " + parameter);
    }/*from  w w  w .j  ava 2 s .  c  om*/

    String fileName = baseHelpFileName.substring(0, baseHelpFileName.lastIndexOf(".xml")) + "_"
            + request.getSession().getAttribute("currLang") + ".xml";

    response.setContentType("text/html");
    response.setCharacterEncoding("UTF8");

    PrintWriter out = null;
    try {
        out = response.getWriter();

    } catch (IOException e) {
        log.error("Could not open PrintWriter.", e);
        throw new ServletException(e);
    }

    // read help resource
    SAXReader xmlReader = new SAXReader();
    Document doc = null;
    try {
        doc = xmlReader.read(getServletContext().getResourceAsStream(fileName));

    } catch (Exception e) {
        //            log.error("Error reading help source file!", e);
    }

    // If the doc could not be found, use the base help filename
    if (doc == null) {
        try {
            doc = xmlReader.read(getServletContext().getResourceAsStream(baseHelpFileName));

        } catch (Exception e) {
            log.error("Error reading help source file!", e);
            throw new ServletException(e);
        }
    }

    // get the help chapter
    String helpKey = request.getParameter("hkey");
    if (helpKey == null) {
        helpKey = "index";
    }
    Object chapterObj = doc.selectSingleNode("//section[@help-key='" + helpKey + "']/ancestor::chapter");

    // transform the xml content to valid html using xslt
    if (chapterObj == null) {
        //           context.put("help_content", "<p>help key (" + helpKey + ") not found!</p>");
        out.print("<p>help key (" + helpKey + ") not found!</p>");

    } else {
        TransformerFactory factory;
        try {
            factory = TransformerFactory.newInstance();
        } catch (Throwable t) {
            System.setProperty("javax.xml.transform.TransformerFactory",
                    "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");
            factory = TransformerFactory.newInstance();
        }

        try {
            StreamSource stylesheet = new StreamSource(getServletContext().getResourceAsStream(xslFileName));
            Transformer transformer = factory.newTransformer(stylesheet);
            DocumentResult result = new DocumentResult();
            String subtree = ((DefaultElement) chapterObj).asXML();
            DocumentSource source = new DocumentSource(DocumentHelper.parseText(subtree));

            transformer.transform(source, result);
            String helpContent = result.getDocument().asXML();
            //                context.put("help_content", helpContent);
            out.print(helpContent);

        } catch (Exception e) {
            log.error("Error processing help entry!", e);
        }
    }
}

From source file:de.ingrid.portal.portlets.HelpPortlet.java

License:EUPL

/**
 * @see org.apache.portals.bridges.velocity.GenericVelocityPortlet#doView(javax.portlet.RenderRequest, javax.portlet.RenderResponse)
 *///from w w  w  .j  av  a 2  s  .  c o  m
public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
    Context context = getContext(request);

    IngridResourceBundle messages = new IngridResourceBundle(
            getPortletConfig().getResourceBundle(request.getLocale()), request.getLocale());
    context.put("MESSAGES", messages);

    // find help file according to the language
    String lang = Utils.checkSupportedLanguage(request.getLocale().getLanguage());
    String fileName = "ingrid-portal-help_" + lang + ".xml";
    String filePath = null;
    try {
        filePath = Utils.getResourceAsStream(fileName);
    } catch (Exception e1) {
        log.warn(fileName + " not found!");
    }
    if (filePath == null) {
        try {
            filePath = Utils.getResourceAsStream("ingrid-portal-help.xml");
        } catch (Exception e) {
            log.error("ingrid-portal-help.xml not found!");
        }
    }

    // read help resource
    SAXReader xmlReader = new SAXReader();
    Document doc = null;
    try {
        doc = xmlReader.read(filePath);
    } catch (Exception e) {
        log.error("Error reading help source file: " + filePath, e);
    }

    // get the help chapter
    String helpKey = request.getParameter("hkey");
    if (helpKey == null) {
        helpKey = "index";
    }

    // read help chapter
    Object chapterObj = null;
    String myPath = "//section[@help-key='" + helpKey + "']/ancestor::chapter";
    try {
        chapterObj = doc.selectSingleNode(myPath);
    } catch (Throwable t) {
        log.error("Error reading '" + myPath + "' from help source file: " + filePath, t);
    }

    // transform the xml content to valid html using xslt
    if (chapterObj == null) {
        context.put("help_content", "<p>help key (" + helpKey + ") not found!</p>");
    } else {
        TransformerFactory factory;
        try {
            factory = TransformerFactory.newInstance();
        } catch (Throwable t) {
            System.setProperty("javax.xml.transform.TransformerFactory",
                    "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");
            factory = TransformerFactory.newInstance();
        }

        try {
            StreamSource stylesheet = new StreamSource(Utils.getResourceAsStream("ingrid-portal-help.xsl"));
            Transformer transformer = factory.newTransformer(stylesheet);
            DocumentResult result = new DocumentResult();
            String subtree = ((DefaultElement) chapterObj).asXML();
            DocumentSource source = new DocumentSource(DocumentHelper.parseText(subtree));

            transformer.transform(source, result);
            String helpContent = result.getDocument().asXML();
            context.put("help_content", helpContent);
        } catch (Exception e) {
            log.error("Error processing help entry!", e);
        }
    }

    super.doView(request, response);
}

From source file:dk.nsi.stamdata.replication.webservice.AtomFeedWriter.java

License:Mozilla Public License

protected void writeEntry(Element feed, String path, View record, Marshaller marshaller) throws JAXBException {
    Element entry = feed.addElement("atom:entry", ATOM_NS);

    entry.addElement("atom:id", ATOM_NS).addText(TAG_PREFIX + path + "/" + record.getOffset());
    entry.addElement("atom:title", ATOM_NS); // Empty, but required by ATOM for human redability.
    entry.addElement("atom:updated", ATOM_NS).addText(AtomDate.toString(record.getUpdated()));

    // Write the actual entity inside the content tag.

    Element content = entry.addElement("atom:content", ATOM_NS).addAttribute("type", "application/xml");

    DocumentResult dr = new DocumentResult();
    marshaller.marshal(record, dr);/*from w  ww .  j av  a 2 s.com*/
    content.add(dr.getDocument().getRootElement());
}

From source file:gov.nih.nci.ispy.web.xml.Transformer.java

License:BSD License

/**
 * Transform the input document//from   w  ww.  j a  v a  2  s. c  o  m
 * @param xml The input xml
 * @return The rendered HTML
 * @throws IOException
 */
public Document transform(Document document) throws IOException {

    String renderedHTML = "";

    javax.xml.transform.Transformer transformer;

    Document transformedDoc = null;

    try {

        transformer = m_template.newTransformer();
        assignParameters(transformer, m_params);
        DocumentSource fileSource = new DocumentSource(document);
        //Source fileSource = new StreamSource(xml);
        //Result result = new StreamResult(renderedHTML);
        DocumentResult result = new DocumentResult();

        transformer.transform(fileSource, result);

        transformedDoc = result.getDocument();

    } catch (TransformerConfigurationException e) {
        throw new IOException(e.getMessage());
    } catch (TransformerException e) {
        throw new IOException(e.getMessage());
    }

    return transformedDoc;
}

From source file:gov.nih.nci.rembrandt.web.xml.Transformer.java

License:BSD License

/**
 * Transform the input document/*from   ww w.ja va 2s . c o m*/
 * @param xml The input xml
 * @return The rendered HTML
 * @throws IOException
 */
public Document transform(Document document) throws IOException {

    String renderedHTML = "";
    javax.xml.transform.Transformer transformer;
    Document transformedDoc = null;

    try {

        transformer = m_template.newTransformer();
        assignParameters(transformer, m_params);
        DocumentSource fileSource = new DocumentSource(document);

        //Source fileSource = new StreamSource(xml);
        //Result result = new StreamResult(renderedHTML);
        DocumentResult result = new DocumentResult();
        transformer.transform(fileSource, result);
        transformedDoc = result.getDocument();

    } catch (TransformerConfigurationException e) {
        throw new IOException(e.getMessage());
    } catch (TransformerException e) {
        throw new IOException(e.getMessage());
    }

    return transformedDoc;
}

From source file:gov.nih.nci.system.web.util.SDKRESTContentHandler.java

License:BSD License

private void handleCollection(CollectionBean collectionObj, OutputStreamWriter writer, Class type,
        MetadataCache mCache) throws XMLUtilityException, IOException, IllegalArgumentException,
        IllegalAccessException, InvocationTargetException, JDOMException {

    String collectionType = collectionObj.getType();
    gov.nih.nci.system.client.proxy.ListProxy proxy = null;
    String getMethod = "get"
            + collectionType.substring(collectionType.lastIndexOf(".") + 1, collectionType.length()) + "s";

    try {//from  w w w . j av a 2  s . co  m
        Method method = collectionObj.getClass().getDeclaredMethod(getMethod, (Class<?>[]) null);
        proxy = (gov.nih.nci.system.client.proxy.ListProxy) method.invoke(collectionObj, null);
    } catch (NoSuchMethodException e) {
        log.error("ERROR: ", e);
    }

    boolean includeAssociations = true;
    List results = new ArrayList();
    String targetClassName = proxy.getTargetClassName();
    int counter = proxy.size();
    String packageName = "";
    boolean isFirst = true;
    StringBuffer outputStr = new StringBuffer();

    Object obj = proxy.get(0);

    if (obj == null)
        return;

    String collectionFullName = obj.getClass().getName();
    String namespace = "gme://caCORE.caCORE/4.5/";
    try {
        Class klass = obj.getClass();
        Method method = klass.getDeclaredMethod("getNamespacePrefix", (Class[]) null);
        namespace = (String) method.invoke(obj, null);
    } catch (NoSuchMethodException e) {
        log.error("ERROR: ", e);
    }

    String collectionName = collectionFullName.substring(collectionFullName.lastIndexOf(".") + 1,
            collectionFullName.lastIndexOf("Bean")) + "s";
    String className = type.getName().substring(0, type.getName().length() - 1);
    org.jdom.Element httpQuery = new org.jdom.Element(collectionName, namespace);
    Collection<ResourceLink> collectionLinks = collectionObj.getLinks();
    if (collectionLinks != null) {
        for (ResourceLink link : collectionLinks) {
            Element linkElement = new Element("link", namespace);
            linkElement.setAttribute("ref", link.getRelationship());
            linkElement.setAttribute("type", link.getType());
            linkElement.setAttribute("href", link.getHref());
            httpQuery.addContent(linkElement);
        }
    }

    for (int i = 0; i < counter; i++) {
        obj = proxy.get(i);
        if (obj instanceof ResourceLink) {
            ResourceLink link = (ResourceLink) obj;
            Element linkElement = new Element("link", namespace);
            linkElement.setAttribute("ref", link.getRelationship());
            linkElement.setAttribute("type", link.getType());
            linkElement.setAttribute("href", link.getHref());
            httpQuery.addContent(linkElement);
            continue;
        }

        Marshaller marshaller = new JAXBMarshaller(false, packageName, namespace);

        List<ResourceLink> links = null;
        try {
            Method method = obj.getClass().getDeclaredMethod("getLinks", (Class[]) null);
            links = (List) method.invoke(obj, null);
        } catch (NoSuchMethodException e) {
            log.error("ERROR: ", e);
        }

        Object convertedObj = XMLUtility.convertFromProxy(obj, false);
        packageName = convertedObj.getClass().getPackage().getName();
        if (isFirst) {
            try {
                Method method = convertedObj.getClass().getDeclaredMethod("getNamespacePrefix",
                        (Class<?>[]) null);
                namespace = (String) method.invoke(convertedObj, null);
            } catch (NoSuchMethodException e) {
                log.error("ERROR: ", e);
            }
            isFirst = false;
        }
        StringWriter strWriter = null;
        Reader in = null;
        try {
            strWriter = new StringWriter();
            DocumentResult dr = new DocumentResult();
            marshaller.toXML(convertedObj, strWriter);
            in = new StringReader(strWriter.toString());
            SAXBuilder builder = new SAXBuilder();
            Document doc = builder.build(in);
            if (mCache.hasMetadata(caDSRMetadata.CONTEXT_NAME, className))
                doc = MetadataInjector.injectMetadata(mCache, caDSRMetadata.CONTEXT_NAME, doc, className);
            Element rootEle = (Element) doc.getRootElement().clone();
            if (links != null) {
                for (ResourceLink link : links) {
                    Element linkElement = new Element("link", rootEle.getNamespace());
                    linkElement.setAttribute("ref", link.getRelationship());
                    linkElement.setAttribute("type", link.getType());
                    linkElement.setAttribute("href", link.getHref());
                    rootEle.addContent(linkElement);
                }
            }
            httpQuery.addContent(rootEle);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (strWriter != null) {
                strWriter.close();
                strWriter = null;
            }
            if (in != null) {
                in.close();
                in = null;
            }
        }
    }
    org.jdom.Document xmlDoc = new org.jdom.Document(httpQuery);
    XMLOutputter outputter = new XMLOutputter();
    outputter.output(xmlDoc, writer);
}

From source file:gr.abiss.calipso.util.XmlUtils.java

License:Open Source License

public static Document transform(Document source, Document stylesheet) {
    TransformerFactory factory = TransformerFactory.newInstance();
    try {/*  w  w  w  . j  av a 2  s  .  co  m*/
        Transformer transformer = factory.newTransformer(new DocumentSource(stylesheet));
        DocumentResult result = new DocumentResult();
        transformer.transform(new DocumentSource(source), result);
        return result.getDocument();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:hk.hku.cecid.ebms.pkg.PKISignatureImpl.java

License:Open Source License

void sign(String alias, char[] password, String keyStoreLocation, String algo, String digestAlgo,
        boolean signEnvelopeOnly) throws SignatureException {
    try {// w ww. j  av a  2  s.com
        final SOAPPart soapPart = ebxmlMessage.getSOAPMessage().getSOAPPart();
        DocumentResult docResult = new DocumentResult();
        TransformerFactory.newInstance().newTransformer().transform(soapPart.getContent(), docResult);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        (new XMLWriter(baos)).write(docResult.getDocument());
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        // soapPartDocument is a DOM equivilance of soapPart
        final Document soapPartDocument = factory.newDocumentBuilder()
                .parse(new ByteArrayInputStream(baos.toByteArray()));
        final String soapHeaderName = soapPart.getEnvelope().getHeader().getElementName().getLocalName();
        final Element soapHeader = (Element) soapPartDocument
                .getElementsByTagNameNS(NAMESPACE_URI_SOAP_ENVELOPE, soapHeaderName).item(0);
        ApacheXMLDSigner signature = new ApacheXMLDSigner();
        CompositeKeyStore ks = new CompositeKeyStore();
        ks.addKeyStoreFile(keyStoreLocation, null, password);
        PrivateKey pk = (PrivateKey) ks.getKey(alias, password);
        /* 
         * To reduce the complexity of the exception message,
         * the exception can be catch on the final catch block.
         *  
         try {
        pk = (PrivateKey) ks.getKey(alias, password);
        if(pk ==null){
           String message ="Cannot retrieve key from keystore["+keyStoreLocation+"]" +"\n"+
              "KeyStore Type: " + ks.getKeyStore().getType() +"\n"+
              "Key Provider: " + ks.getKeyStore().getProvider().getInfo();
           throw new NullPointerException(message);
        }
        }
        catch (Exception e) {
        String err = "Cannot get private key: " + alias + " - "
            + e.getMessage();
           logger.warn(err);
        throw new SignException(err);
        }*/

        if (algo != null) {
            if (!isAlgorithmMatchedWithKey(pk, algo)) {
                throw new SignException("Signing algorithm not matched with key algorithm, "
                        + "actual key algorithum:" + pk.getAlgorithm() + "\t" + "expect algorithum: " + algo);
            }
            if (digestAlgo == null) {
                signature.setEnvelope(soapPartDocument, algo);
            } else {
                signature.setEnvelope(soapPartDocument, algo, digestAlgo);
            }
        } else {
            String keyAlgo = getAlgorithmFromPrivateKey(pk);
            signature.setEnvelope(soapPartDocument, keyAlgo);
        }
        /*
        if (algo == null) {
        // use default algorithm, i.e. dsa-sha1
        signature.setEnvelope(soapPartDocument);
        }
        else {
        // use user-defined algorithm, only support dsa-sha1 and 
        // rsa-sha1
        if (digestAlgo == null) {
            signature.setEnvelope(soapPartDocument, algo);
        } else {
            signature.setEnvelope(soapPartDocument, algo, digestAlgo);
        }
        }
        */

        // important, if not, the transformation will fail
        soapHeader.appendChild(signature.getElement());

        if (!signEnvelopeOnly) {
            Iterator i = ebxmlMessage.getPayloadContainers();
            while (i.hasNext()) {
                PayloadContainer pc = (PayloadContainer) i.next();
                signature.addDocument(pc.getHref(), pc.getDataHandler().getInputStream(), pc.getContentType());
            }
        }

        signature.sign(ks, alias, password);

        domToSoap(signature.getElement(), this);

        Iterator childElements = getChildElements(SignatureReference.SIGNATURE_REFERENCE);
        if (childElements.hasNext()) {
            while (childElements.hasNext()) {
                references.add(new SignatureReference(soapEnvelope, (SOAPElement) childElements.next()));
            }
        } else {
            throw new SOAPValidationException(SOAPValidationException.SOAP_FAULT_CLIENT,
                    "<" + NAMESPACE_PREFIX_DS + ":" + SignatureReference.SIGNATURE_REFERENCE
                            + "> is not found in <" + NAMESPACE_PREFIX_DS + ":" + ELEMENT_SIGNATURE + ">!");
        }

        childElements = getChildElements(ELEMENT_SIGNATURE_VALUE);
        if (childElements.hasNext()) {
            signatureValue = ((SOAPElement) childElements.next()).getValue();
        } else {
            throw new SOAPValidationException(SOAPValidationException.SOAP_FAULT_CLIENT,
                    "<" + NAMESPACE_PREFIX_DS + ":" + ELEMENT_SIGNATURE_VALUE + "> is not found in <"
                            + NAMESPACE_PREFIX_DS + ":" + ELEMENT_SIGNATURE + ">!");
        }
    } catch (Exception e) {
        String err = ErrorMessages.getMessage(ErrorMessages.ERR_PKI_CANNOT_SIGN, e);
        err += "\n" + "Try to retreive key alias[" + alias + "] from keystore[" + keyStoreLocation + "]";
        throw new SignatureException(err, e);
    }
}

From source file:hk.hku.cecid.ebms.pkg.PKISignatureImpl.java

License:Open Source License

boolean verify(char[] password, String keyStoreLocation, CertResolver certResolver, DataSource dataSource)
        throws SignatureException {
    try {/*  w ww .  j  ava 2s. c om*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        String fileName = ebxmlMessage.getFileName();
        String persistenceName = ebxmlMessage.getPersistenceName();
        byte[] soapEnvelopeBytes = ebxmlMessage.getSoapEnvelopeBytes();
        if (soapEnvelopeBytes != null) {
            baos.write(soapEnvelopeBytes);
        } else if (persistenceName != null) {
            if (dataSource == null) {
                throw new SignatureException("Inconsistence persistence data for : " + persistenceName);
            }
            InputStream istream = dataSource.getInputStream();
            try {
                soapEnvelopeBytes = EbxmlMessage.getSoapEnvelopeBytesFromStream(istream);
            } catch (SOAPException e) {
                throw e;
            } finally {
                istream.close();
            }
        } else if (fileName != null) {
            InputStream istream = null;
            try {
                istream = new FileInputStream(fileName);
                soapEnvelopeBytes = EbxmlMessage.getSoapEnvelopeBytesFromStream(istream);
            } catch (IOException e) {
                throw e;
            } catch (SOAPException e) {
                throw e;
            } finally {
                if (istream != null) {
                    istream.close();
                }
            }
        } else {
            final SOAPPart soapPart = ebxmlMessage.getSOAPMessage().getSOAPPart();
            DocumentResult docResult = new DocumentResult();
            TransformerFactory.newInstance().newTransformer().transform(soapPart.getContent(), docResult);
            (new XMLWriter(baos)).write(docResult.getDocument());
        }
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        // soapPartDocument is a DOM equivilance of soapPart
        final Document soapPartDocument = factory.newDocumentBuilder()
                .parse(new ByteArrayInputStream(baos.toByteArray()));

        ApacheXMLDSigner signature = new ApacheXMLDSigner();
        signature.setEnvelope(soapPartDocument);

        for (Iterator i = ebxmlMessage.getPayloadContainers(); i.hasNext();) {
            PayloadContainer pc = (PayloadContainer) i.next();
            signature.addDocument(pc.getHref(), pc.getDataHandler().getInputStream(), pc.getContentType());
        }

        if (keyStoreLocation != null) {
            CompositeKeyStore ks = new CompositeKeyStore();
            ks.addKeyStoreFile(keyStoreLocation, null, password);
            signature.setTrustAnchor(ks);
        }
        signature.addCertResolver(certResolver, ebxmlMessage);

        return signature.verify();
    } catch (VerifyException e) {
        throw new SignatureException(e.getMessage(), e);
    } catch (Exception e) {
        String err = ErrorMessages.getMessage(ErrorMessages.ERR_PKI_UNKNOWN_ERROR, e);
        throw new SignatureException(err, e);
    }
}

From source file:itensil.io.xml.XMLTransform.java

License:Open Source License

public Document transform(Document srcDoc) throws TransformerException {
    DocumentSource source = new DocumentSource(srcDoc);
    DocumentResult result = new DocumentResult();
    transformer.transform(source, result);
    return result.getDocument();
}