Example usage for org.w3c.dom Document importNode

List of usage examples for org.w3c.dom Document importNode

Introduction

In this page you can find the example usage for org.w3c.dom Document importNode.

Prototype

public Node importNode(Node importedNode, boolean deep) throws DOMException;

Source Link

Document

Imports a node from another document to this document, without altering or removing the source node from the original document; this method creates a new copy of the source node.

Usage

From source file:com.enonic.vertical.adminweb.handlers.SimpleContentHandlerServlet.java

protected DOMSource buildXSL(HttpSession session, AdminService admin, int contentTypeKey)
        throws VerticalAdminException {

    DOMSource result = null;//w w w. j av a  2  s .  co  m
    try {
        Document sourceDoc = XMLTool.domparse(admin.getContentTypeModuleData(contentTypeKey));

        // Set whether fields are indexed or not
        Document indexDoc = XMLTool.domparse(admin.getIndexingParametersXML(contentTypeKey));
        Element[] indexingParams = XMLTool.getElements(indexDoc.getDocumentElement(), "index");

        Element browseElem = XMLTool.getElement(sourceDoc.getDocumentElement(), "browse");
        Element[] fields = XMLTool.getElements(browseElem, "field");
        for (Element field : fields) {
            String xpath = XMLTool.getElementText(XMLTool.getElement(field, "xpath"));
            boolean indexed = false;

            // Check whether this xpath is in the index doc
            if (xpath != null) {
                for (Element indexingParam : indexingParams) {
                    if ((xpath).equals(indexingParam.getAttribute("xpath"))) {
                        indexed = true;
                    }
                }
            }

            field.setAttribute("indexed", String.valueOf(indexed));
        }

        Element rootElement = sourceDoc.getDocumentElement();

        // check for xsl:
        boolean enablePreview = false;
        Element previewXSLElement = XMLTool.getElement(rootElement, "previewxsl");
        if (previewXSLElement != null) {
            String cdata = XMLTool.getElementText(previewXSLElement);
            if (cdata.length() > 0) {
                enablePreview = true;
            }
        }

        // extract module xml:
        Element moduleElement = XMLTool.getElement(rootElement, "config");
        sourceDoc = XMLTool.createDocument();
        sourceDoc.appendChild(sourceDoc.importNode(moduleElement, true));

        StringWriter swriter = new StringWriter();
        Map<String, Object> xslParams = new HashMap<String, Object>();

        xslParams.put("xsl_prefix", "");

        xslParams.put("enablepreview", String.valueOf(enablePreview));
        Source xslFile = AdminStore.getStylesheet(session, FORM_TEMPLATE);
        transformXML(session, swriter, new DOMSource(sourceDoc), xslFile, xslParams);

        result = new DOMSource(XMLTool.domparse(swriter.toString()));
        result.setSystemId(xslFile.getSystemId());
    } catch (TransformerConfigurationException e) {
        VerticalAdminLogger.errorAdmin(this.getClass(), 50, "XSLT error: %t", e);
    } catch (TransformerException e) {
        VerticalAdminLogger.errorAdmin(this.getClass(), 50, "XSLT error: %t", e);
    }

    return result;
}

From source file:com.portfolio.data.attachment.XSLService.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    /**//from  ww w . j ava2 s.  c  om
     * Format demand:
     * <convert>
     *   <portfolioid>{uuid}</portfolioid>
     *   <portfolioid>{uuid}</portfolioid>
     *   <nodeid>{uuid}</nodeid>
     *   <nodeid>{uuid}</nodeid>
     *   <documentid>{uuid}</documentid>
     *   <xsl>{rpertoire}{fichier}</xsl>
     *   <format>[pdf rtf xml ...]</format>
     *   <parameters>
     *     <maVar1>lala</maVar1>
     *     ...
     *   </parameters>
     * </convert>
     */
    try {
        //On initialise le dataProvider
        Connection c = null;
        //On initialise le dataProvider
        if (ds == null) // Case where we can't deploy context.xml
        {
            c = getConnection();
        } else {
            c = ds.getConnection();
        }
        dataProvider.setConnection(c);
        credential = new Credential(c);
    } catch (Exception e) {
        e.printStackTrace();
    }

    String origin = request.getRequestURL().toString();

    /// Variable stuff
    int userId = 0;
    int groupId = 0;
    String user = "";
    HttpSession session = request.getSession(true);
    if (session != null) {
        Integer val = (Integer) session.getAttribute("uid");
        if (val != null)
            userId = val;
        val = (Integer) session.getAttribute("gid");
        if (val != null)
            groupId = val;
        user = (String) session.getAttribute("user");
    }

    /// TODO: A voire si un form get ne ferait pas l'affaire aussi

    /// On lis le xml
    /*
    BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while( (line = rd.readLine()) != null )
       sb.append(line);
            
    DocumentBuilderFactory documentBuilderFactory =DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = null;
    Document doc=null;
    try
    {
       documentBuilder = documentBuilderFactory.newDocumentBuilder();
       doc = documentBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes("UTF-8")));
    }
    catch( Exception e )
    {
       e.printStackTrace();
    }
            
    /// On lit les paramtres
    NodeList portfolioNode = doc.getElementsByTagName("portfolioid");
    NodeList nodeNode = doc.getElementsByTagName("nodeid");
    NodeList documentNode = doc.getElementsByTagName("documentid");
    NodeList xslNode = doc.getElementsByTagName("xsl");
    NodeList formatNode = doc.getElementsByTagName("format");
    NodeList parametersNode = doc.getElementsByTagName("parameters");
    //*/
    //      String xslfile = xslNode.item(0).getTextContent();
    String xslfile = request.getParameter("xsl");
    String format = request.getParameter("format");
    //      String format = formatNode.item(0).getTextContent();
    String parameters = request.getParameter("parameters");
    String documentid = request.getParameter("documentid");
    String portfolios = request.getParameter("portfolioids");
    String[] portfolioid = null;
    if (portfolios != null)
        portfolioid = portfolios.split(";");
    String nodes = request.getParameter("nodeids");
    String[] nodeid = null;
    if (nodes != null)
        nodeid = nodes.split(";");

    System.out.println("PARAMETERS: ");
    System.out.println("xsl: " + xslfile);
    System.out.println("format: " + format);
    System.out.println("user: " + userId);
    System.out.println("portfolioids: " + portfolios);
    System.out.println("nodeids: " + nodes);
    System.out.println("parameters: " + parameters);

    boolean redirectDoc = false;
    if (documentid != null) {
        redirectDoc = true;
        System.out.println("documentid @ " + documentid);
    }

    boolean usefop = false;
    String ext = "";
    if (MimeConstants.MIME_PDF.equals(format)) {
        usefop = true;
        ext = ".pdf";
    } else if (MimeConstants.MIME_RTF.equals(format)) {
        usefop = true;
        ext = ".rtf";
    }
    //// Paramtre portfolio-uuid et file-xsl
    //      String uuid = request.getParameter("uuid");
    //      String xslfile = request.getParameter("xsl");

    StringBuilder aggregate = new StringBuilder();
    try {
        int portcount = 0;
        int nodecount = 0;
        // On aggrge les donnes
        if (portfolioid != null) {
            portcount = portfolioid.length;
            for (int i = 0; i < portfolioid.length; ++i) {
                String p = portfolioid[i];
                String portfolioxml = dataProvider
                        .getPortfolio(new MimeType("text/xml"), p, userId, groupId, "", null, null, 0)
                        .toString();
                aggregate.append(portfolioxml);
            }
        }

        if (nodeid != null) {
            nodecount = nodeid.length;
            for (int i = 0; i < nodeid.length; ++i) {
                String n = nodeid[i];
                String nodexml = dataProvider.getNode(new MimeType("text/xml"), n, true, userId, groupId, "")
                        .toString();
                aggregate.append(nodexml);
            }
        }

        // Est-ce qu'on a eu besoin d'aggrger les donnes?
        String input = aggregate.toString();
        String pattern = "<\\?xml[^>]*>"; // Purge previous xml declaration

        input = input.replaceAll(pattern, "");

        input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<!DOCTYPE xsl:stylesheet ["
                + "<!ENTITY % lat1 PUBLIC \"-//W3C//ENTITIES Latin 1 for XHTML//EN\" \"" + servletDir
                + "xhtml-lat1.ent\">" + "<!ENTITY % symbol PUBLIC \"-//W3C//ENTITIES Symbols for XHTML//EN\" \""
                + servletDir + "xhtml-symbol.ent\">"
                + "<!ENTITY % special PUBLIC \"-//W3C//ENTITIES Special for XHTML//EN\" \"" + servletDir
                + "xhtml-special.ent\">" + "%lat1;" + "%symbol;" + "%special;" + "]>" + // For the pesky special characters
                "<root>" + input + "</root>";

        //         System.out.println("INPUT WITH PROXY:"+ input);

        /// Rsolution des proxys
        DocumentBuilder documentBuilder;
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(input));
        Document doc = documentBuilder.parse(is);

        /// Proxy stuff
        XPath xPath = XPathFactory.newInstance().newXPath();
        String filterRes = "//asmResource[@xsi_type='Proxy']";
        String filterCode = "./code/text()";
        NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);

        XPathExpression codeFilter = xPath.compile(filterCode);

        for (int i = 0; i < nodelist.getLength(); ++i) {
            Node res = nodelist.item(i);
            Node gp = res.getParentNode(); // resource -> context -> container
            Node ggp = gp.getParentNode();
            Node uuid = (Node) codeFilter.evaluate(res, XPathConstants.NODE);

            /// Fetch node we want to replace
            String returnValue = dataProvider
                    .getNode(new MimeType("text/xml"), uuid.getTextContent(), true, userId, groupId, "")
                    .toString();

            Document rep = documentBuilder.parse(new InputSource(new StringReader(returnValue)));
            Element repNode = rep.getDocumentElement();
            Node proxyNode = repNode.getFirstChild();
            proxyNode = doc.importNode(proxyNode, true); // adoptNode have some weird side effect. To be banned
            //            doc.replaceChild(proxyNode, gp);
            ggp.insertBefore(proxyNode, gp); // replaceChild doesn't work.
            ggp.removeChild(gp);
        }

        try // Convert XML document to string
        {
            DOMSource domSource = new DOMSource(doc);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.transform(domSource, result);
            writer.flush();
            input = writer.toString();
        } catch (TransformerException ex) {
            ex.printStackTrace();
        }

        //         System.out.println("INPUT DATA:"+ input);

        // Setup a buffer to obtain the content length
        ByteArrayOutputStream stageout = new ByteArrayOutputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        //// Setup Transformer (1st stage)
        /// Base path
        String basepath = xslfile.substring(0, xslfile.indexOf(File.separator));
        String firstStage = baseDir + File.separator + basepath + File.separator + "karuta" + File.separator
                + "xsl" + File.separator + "html2xml.xsl";
        System.out.println("FIRST: " + firstStage);
        Source xsltSrc1 = new StreamSource(new File(firstStage));
        Transformer transformer1 = transFactory.newTransformer(xsltSrc1);
        StreamSource stageSource = new StreamSource(new ByteArrayInputStream(input.getBytes()));
        Result stageRes = new StreamResult(stageout);
        transformer1.transform(stageSource, stageRes);

        // Setup Transformer (2nd stage)
        String secondStage = baseDir + File.separator + xslfile;
        Source xsltSrc2 = new StreamSource(new File(secondStage));
        Transformer transformer2 = transFactory.newTransformer(xsltSrc2);

        // Configure parameter from xml
        String[] table = parameters.split(";");
        for (int i = 0; i < table.length; ++i) {
            String line = table[i];
            int var = line.indexOf(":");
            String par = line.substring(0, var);
            String val = line.substring(var + 1);
            transformer2.setParameter(par, val);
        }

        // Setup input
        StreamSource xmlSource = new StreamSource(new ByteArrayInputStream(stageout.toString().getBytes()));
        //         StreamSource xmlSource = new StreamSource(new File(baseDir+origin, "projectteam.xml") );

        Result res = null;
        if (usefop) {
            /// FIXME: Might need to include the entity for html stuff?
            //Setup FOP
            //Make sure the XSL transformation's result is piped through to FOP
            Fop fop = fopFactory.newFop(format, out);

            res = new SAXResult(fop.getDefaultHandler());

            //Start the transformation and rendering process
            transformer2.transform(xmlSource, res);
        } else {
            res = new StreamResult(out);

            //Start the transformation and rendering process
            transformer2.transform(xmlSource, res);
        }

        if (redirectDoc) {

            // /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]]
            String urlTarget = "http://" + server + "/resources/resource/file/" + documentid;
            System.out.println("Redirect @ " + urlTarget);

            HttpClientBuilder clientbuilder = HttpClientBuilder.create();
            CloseableHttpClient client = clientbuilder.build();

            HttpPost post = new HttpPost(urlTarget);
            post.addHeader("referer", origin);
            String sessionid = request.getSession().getId();
            System.out.println("Session: " + sessionid);
            post.addHeader("Cookie", "JSESSIONID=" + sessionid);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            ByteArrayBody body = new ByteArrayBody(out.toByteArray(), "generated" + ext);

            builder.addPart("uploadfile", body);

            HttpEntity entity = builder.build();
            post.setEntity(entity);
            HttpResponse ret = client.execute(post);
            String stringret = new BasicResponseHandler().handleResponse(ret);

            int code = ret.getStatusLine().getStatusCode();
            response.setStatus(code);
            ServletOutputStream output = response.getOutputStream();
            output.write(stringret.getBytes(), 0, stringret.length());
            output.close();
            client.close();

            /*
            HttpURLConnection connection = CreateConnection( urlTarget, request );
                    
            /// Helping construct Json
            connection.setRequestProperty("referer", origin);
                    
            /// Send post data
            ServletInputStream inputData = request.getInputStream();
            DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
                    
            byte[] buffer = new byte[1024];
            int dataSize;
            while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 )
            {
               writer.write(buffer, 0, dataSize);
            }
            inputData.close();
            writer.close();
                    
            RetrieveAnswer(connection, response, origin);
            //*/
        } else {
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=generated" + ext);
            response.setContentType(format);
            response.setContentLength(out.size());
            response.getOutputStream().write(out.toByteArray());
            response.getOutputStream().flush();
        }
    } catch (Exception e) {
        String message = e.getMessage();
        response.setStatus(500);
        response.getOutputStream().write(message.getBytes());
        response.getOutputStream().close();

        e.printStackTrace();
    } finally {
        dataProvider.disconnect();
    }
}

From source file:org.apache.manifoldcf.crawler.connectors.meridio.meridiowrapper.MeridioWrapper.java

/** Given the SOAP response received by AXIS on the successful call to a Meridio
* Web Service, this helper method returns a castor RMDataSet object which represents
* the XML/* w  ww. j  ava2  s .  co m*/
*
* This makes it much easier to subsequently manipulate the data that has been
* returned from the web service, and ensures that the Meridio wrapper implementation
* is as close to native .NET code as we can get.
*/
protected RMDataSet getRMDataSet(MessageElement[] messageElement) throws MeridioDataSetException {
    if (oLog != null)
        oLog.debug("Meridio: Entered getRMDataSet method.");

    try {
        if (messageElement.length != 2) {
            if (oLog != null)
                oLog.warn("Meridio: SOAP Message not of expected length");
            if (oLog != null)
                oLog.debug("Meridio: Exiting getRMDataSet method with null.");
            return null;
        }

        /*
        for (int i = 0; i < messageElement.length; i++)
        {
          oLog.debug("Meridio: Message Part: " + i + " " + messageElement[i]);
        }
        */

        Document document = messageElement[1].getAsDocument();
        NodeList nl = document.getElementsByTagName("RMDataSet");

        NodeList errors = document.getElementsByTagName("diffgr:errors");
        if (errors.getLength() != 0) {
            String errorXML = "";

            if (oLog != null)
                oLog.error("Found <" + errors.getLength() + "> errors in returned data set");
            for (int i = 0; i < errors.getLength(); i++) {

                Element e = (Element) errors.item(i);

                Document resultDocument = new DocumentImpl();
                Node node = resultDocument.importNode(e, true);

                resultDocument.appendChild(node);

                DOMImplementation domImpl = DOMImplementationImpl.getDOMImplementation();
                DOMImplementationLS implLS = (DOMImplementationLS) domImpl;
                LSSerializer writer = implLS.createLSSerializer();
                errorXML += writer.writeToString(resultDocument) + "\n";

                if (oLog != null)
                    oLog.warn("..." + errorXML);
            }
            throw new MeridioDataSetException(errorXML);
        }

        if (nl.getLength() != 1) {
            if (oLog != null)
                oLog.warn("Meridio: Returning null - could not find RMDataSet in SOAP Message");
            if (oLog != null)
                oLog.debug("Meridio: Exiting getRMDataSet method with null.");
            return null;
        }

        Element e = (Element) nl.item(0);
        Document resultDocument = new DocumentImpl();
        Node node = resultDocument.importNode(e, true);

        resultDocument.appendChild(node);

        DOMImplementation domImpl = DOMImplementationImpl.getDOMImplementation();
        DOMImplementationLS implLS = (DOMImplementationLS) domImpl;
        LSSerializer writer = implLS.createLSSerializer();
        String documentXML = writer.writeToString(resultDocument);

        StringReader sr = new StringReader(documentXML);
        RMDataSet dsRM = new RMDataSet();
        dsRM = RMDataSet.unmarshal(sr);
        if (oLog != null)
            oLog.debug("Meridio: Exiting getRMDataSet method.");
        return dsRM;
    } catch (ClassNotFoundException classNotFoundException) {
        throw new MeridioDataSetException(
                "Could not find the DOM Parser class when unmarshalling the Meridio Dataset",
                classNotFoundException);
    } catch (InstantiationException instantiationException) {
        throw new MeridioDataSetException(
                "Error instantiating the DOM Parser when unmarshalling the Meridio Dataset",
                instantiationException);
    } catch (IllegalAccessException illegalAccessException) {
        throw new MeridioDataSetException("DOM Parser illegal access when unmarshalling the Meridio Dataset",
                illegalAccessException);
    } catch (MarshalException marshalException) {
        throw new MeridioDataSetException("Castor error in marshalling the XML from the Meridio Dataset",
                marshalException);
    } catch (ValidationException validationException) {
        throw new MeridioDataSetException("Castor error in validating the XML from the Meridio Dataset",
                validationException);
    } catch (Exception ex) // from messageElement[1].getAsDocument();
    {
        throw new MeridioDataSetException("Error retrieving the XML Document from the Web Service response",
                ex);
    }
}

From source file:org.apache.manifoldcf.crawler.connectors.meridio.meridiowrapper.MeridioWrapper.java

/** Given the SOAP response received by AXIS on the successful call to a Meridio
* Web Service, this helper method returns a castor DMDataSet object which represents
* the XML/*from  w w w  . ja  v  a 2 s  .c o m*/
*
* This makes it much easier to subsequently manipulate the data that has been
* returned from the web service, and ensures that the Meridio wrapper implementation
* is as close to native .NET code as we can get.
*/
protected DMDataSet getDMDataSet(MessageElement[] messageElement) throws MeridioDataSetException {
    if (oLog != null)
        oLog.debug("Meridio: Entered getDMDataSet method.");

    try {
        if (messageElement.length != 2) {
            if (oLog != null)
                oLog.warn("Meridio: SOAP Message not of expected length");
            if (oLog != null)
                oLog.debug("Meridio: Exiting getDMDataSet method with null.");
            return null;
        }

        /*
        for (int i = 0; i < messageElement.length; i++)
        {
          oLog.debug("Meridio: Message Part: " + i + " " + messageElement[i]);
        }
        */

        Document document = messageElement[1].getAsDocument();
        NodeList nl = document.getElementsByTagName("DMDataSet");

        NodeList errors = document.getElementsByTagName("diffgr:errors");
        if (errors.getLength() != 0) {
            String errorXML = "";

            if (oLog != null)
                oLog.error("Found <" + errors.getLength() + "> errors in returned data set");
            for (int i = 0; i < errors.getLength(); i++) {

                Element e = (Element) errors.item(i);

                Document resultDocument = new DocumentImpl();
                Node node = resultDocument.importNode(e, true);

                resultDocument.appendChild(node);

                DOMImplementation domImpl = DOMImplementationImpl.getDOMImplementation();
                DOMImplementationLS implLS = (DOMImplementationLS) domImpl;
                LSSerializer writer = implLS.createLSSerializer();
                errorXML += writer.writeToString(resultDocument) + "\n";

                if (oLog != null)
                    oLog.warn("..." + errorXML);
            }
            throw new MeridioDataSetException(errorXML);
        }

        if (nl.getLength() != 1) {
            if (oLog != null)
                oLog.warn("Meridio: Returning null - could not find DMDataSet in SOAP Message");
            if (oLog != null)
                oLog.debug("Meridio: Exiting getDMDataSet method with null.");
            return null;
        }

        Element e = (Element) nl.item(0);
        Document resultDocument = new DocumentImpl();
        Node node = resultDocument.importNode(e, true);

        resultDocument.appendChild(node);

        DOMImplementation domImpl = DOMImplementationImpl.getDOMImplementation();
        DOMImplementationLS implLS = (DOMImplementationLS) domImpl;
        LSSerializer writer = implLS.createLSSerializer();
        String documentXML = writer.writeToString(resultDocument);

        //oLog.debug("Meridio: Result: " + documentXML);

        StringReader sr = new StringReader(documentXML);
        DMDataSet dsDM = new DMDataSet();
        dsDM = DMDataSet.unmarshal(sr);

        if (oLog != null)
            oLog.debug("Meridio: Exiting getDMDataSet method.");

        return dsDM;
    } catch (ClassNotFoundException classNotFoundException) {
        throw new MeridioDataSetException(
                "Could not find the DOM Parser class when unmarshalling the Meridio Dataset",
                classNotFoundException);
    } catch (InstantiationException instantiationException) {
        throw new MeridioDataSetException(
                "Error instantiating the DOM Parser when unmarshalling the Meridio Dataset",
                instantiationException);
    } catch (IllegalAccessException illegalAccessException) {
        throw new MeridioDataSetException("DOM Parser illegal access when unmarshalling the Meridio Dataset",
                illegalAccessException);
    } catch (MarshalException marshalException) {
        throw new MeridioDataSetException("Castor error in marshalling the XML from the Meridio Dataset",
                marshalException);
    } catch (ValidationException validationException) {
        throw new MeridioDataSetException("Castor error in validating the XML from the Meridio Dataset",
                validationException);
    } catch (Exception ex) // from messageElement[1].getAsDocument();
    {
        throw new MeridioDataSetException("Error retrieving the XML Document from the Web Service response",
                ex);
    }
}

From source file:de.mpg.mpdl.inge.transformation.Util.java

/**
 * Queries CoNE service and returns the result as DOM node. The returned XML has the following
 * structure: <cone> <author> <familyname>Buxtehude-Mlln</familyname>
 * <givenname>Heribert</givenname> <prefix>von und zu</prefix> <title>Knig</title> </author>
 * <author> <familyname>Mller</familyname> <givenname>Peter</givenname> </author> </authors>
 * /* w w  w.  ja  va  2 s.  c  o  m*/
 * @param authors
 * @return
 */
public static Node queryCone(String model, String query) {
    DocumentBuilder documentBuilder;
    String queryUrl = null;
    try {
        logger.info("queryCone: " + model + " query: " + query);

        documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder();

        Document document = documentBuilder.newDocument();
        Element element = document.createElement("cone");
        document.appendChild(element);

        queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&q="
                + URLEncoder.encode(query, "UTF-8");
        String detailsUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/resource/$1?format=rdf";
        HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        GetMethod method = new GetMethod(queryUrl);

        String coneSession = getConeSession();

        if (coneSession != null) {
            method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
        }
        ProxyHelper.executeMethod(client, method);

        if (method.getStatusCode() == 200) {
            String[] results = method.getResponseBodyAsString().split("\n");
            for (String result : results) {
                if (!"".equals(result.trim())) {
                    String id = result.split("\\|")[1];
                    // TODO "&redirect=true" must be reinserted again
                    GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle="
                            + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8")));
                    detailMethod.setFollowRedirects(true);

                    if (coneSession != null) {
                        detailMethod.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
                    }
                    ProxyHelper.executeMethod(client, detailMethod);
                    logger.info("CoNE query: " + id + "?format=rdf&eSciDocUserHandle="
                            + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8")) + " returned "
                            + detailMethod.getResponseBodyAsString());

                    if (detailMethod.getStatusCode() == 200) {
                        Document details = documentBuilder.parse(detailMethod.getResponseBodyAsStream());
                        element.appendChild(document.importNode(details.getFirstChild(), true));
                    } else {
                        logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n"
                                + detailMethod.getResponseBodyAsString());
                    }
                }
            }
        } else {
            logger.error("Error querying CoNE: Status " + method.getStatusCode() + "\n"
                    + method.getResponseBodyAsString());
        }

        return document;
    } catch (Exception e) {
        logger.error("Error querying CoNE service. This is normal during unit tests. (" + queryUrl
                + ") .Otherwise it should be clarified if any measures have to be taken.", e);
        logger.debug("Stacktrace", e);
        return null;
        // throw new RuntimeException(e);
    }
}

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

@Override
public synchronized String listElementsByPath(String path, final String originalXml, boolean inList,
        boolean includeChildren) throws XPathExpressionException, SAXException, IOException {

    Assert.hasText(path);//from   ww  w .  j a  va  2s. c o m
    Assert.hasText(originalXml);

    Document originalDom = parse(originalXml);

    XPath xPath = getXPathInstance();

    logger.debug("xpath: " + path);
    NodeList nodeList = (NodeList) (xPath.evaluate(path, originalDom, XPathConstants.NODESET));
    Assert.notNull(nodeList);

    Document finalDom = documentBuilder.newDocument();
    Element root = null;
    if (inList) {
        root = finalDom.createElement("list");
    } else {
        root = finalDom.createElement(originalDom.getFirstChild().getNodeName());
    }
    int l = nodeList.getLength();

    logger.trace("find: " + l);
    Node currentNode = null;
    for (int i = 0; i < l; i++) {
        currentNode = nodeList.item(i);
        logger.trace("find: " + currentNode.getNodeName());
        root.appendChild(finalDom.importNode(currentNode, includeChildren));
    }

    return DomUtils.elementToString(root);
}

From source file:com.enonic.vertical.engine.handlers.PageTemplateHandler.java

private Document getPageTemplateCO(PageTemplateEntity pageTemplate) {
    Document doc = XMLTool.createDocument();
    Element root = XMLTool.createRootElement(doc, "contentobjects");

    final List<PageTemplatePortletEntity> objects = pageTemplate.getPortlets();
    for (PageTemplatePortletEntity pageTemplateObject : objects) {
        final PortletEntity portlet = pageTemplateObject.getPortlet();
        final PageTemplateRegionEntity pageTemplateParam = pageTemplateObject.getPageTemplateRegion();

        Element elem = XMLTool.createElement(doc, root, "contentobject");
        elem.setAttribute("pagetemplatekey", String.valueOf(pageTemplate.getKey()));
        elem.setAttribute("conobjkey", String.valueOf(portlet.getKey()));

        elem.setAttribute("parameterkey", String.valueOf(pageTemplateParam.getKey()));

        // element: contentobjectdata
        Document contentdata = XMLDocumentFactory.create(portlet.getXmlDataAsJDOMDocument()).getAsDOMDocument();
        Node xmldata_root = doc.importNode(contentdata.getDocumentElement(), true);
        elem.appendChild(xmldata_root);//ww  w .ja v  a  2s  .  c  o m

        // sub-elements
        XMLTool.createElement(doc, elem, "order", String.valueOf(pageTemplateObject.getOrder()));
        XMLTool.createElement(doc, elem, "name", portlet.getName());
        XMLTool.createElement(doc, elem, "separator", pageTemplateParam.getSeparator());
        elem = XMLTool.createElement(doc, elem, "parametername", pageTemplateParam.getName());
        elem.setAttribute("multiple", String.valueOf(pageTemplateParam.isMultiple() ? "1" : "0"));
        elem.setAttribute("override", String.valueOf(pageTemplateParam.isOverride() ? "1" : "0"));
    }

    return doc;
}

From source file:com.enonic.vertical.adminweb.ContentObjectHandlerServlet.java

public void handlerForm(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        AdminService admin, ExtendedMap formItems) throws VerticalAdminException {

    User user = securityService.getLoggedInAdminConsoleUser();
    boolean createContentObject = false;
    String xmlData = null;/*from w  w  w. j  a  va 2 s .c  o  m*/
    Document doc;
    String queryParam = "";
    String script = "";

    int menuKey = formItems.getInt("menukey");

    if (request.getParameter("key") == null || request.getParameter("key").equals("")) {
        // Blank form, make dummy document
        doc = XMLTool.createDocument("contentobjects");
        createContentObject = true;
    } else {
        int cobKey = Integer.parseInt(request.getParameter("key"));

        xmlData = admin.getContentObject(cobKey);

        doc = XMLTool.domparse(xmlData);

        NodeList coNodes = doc.getElementsByTagName("contentobject");
        Element contentobject = (Element) coNodes.item(0);
        String contentKeyStr = contentobject.getAttribute("contentkey");
        if (contentKeyStr != null && contentKeyStr.length() > 0) {
            int contentKey = Integer.parseInt(contentKeyStr);

            String contentXML = admin.getContent(user, contentKey, 0, 0, 0);
            Document contentDoc = XMLTool.domparse(contentXML);
            NodeList contentNodes = contentDoc.getElementsByTagName("content");
            Element content = (Element) contentNodes.item(0);
            content = (Element) doc.importNode(content, true);
            contentobject.appendChild(content);
        }

        String menuItemsXML;
        menuItemsXML = admin.getMenuItemsByContentObject(user, cobKey);
        Document menuItemsDoc = XMLTool.domparse(menuItemsXML);
        contentobject.appendChild(doc.importNode(menuItemsDoc.getDocumentElement(), true));

        // Henter ut pagetemplates/frameworks som bruker dette contentobject
        String pageTemplatesXML = admin.getPageTemplatesByContentObject(cobKey);
        Document pageTemplatesDoc = XMLTool.domparse(pageTemplatesXML);
        contentobject.appendChild(doc.importNode(pageTemplatesDoc.getDocumentElement(), true));

        Element objectstylesheetElem = XMLTool.getElement(contentobject, "objectstylesheet");
        ResourceKey objectStyleSheetKey = new ResourceKey(objectstylesheetElem.getAttribute("key"));

        ResourceFile res = resourceService.getResourceFile(objectStyleSheetKey);
        objectstylesheetElem.setAttribute("exist", res == null ? "false" : "true");

        if (res != null) {
            try {
                Document styleSheetDoc = res.getDataAsXml().getAsDOMDocument();
                objectstylesheetElem.setAttribute("valid", "true");

                Element styleSheetRoot = styleSheetDoc.getDocumentElement();
                String attr = styleSheetRoot.getAttribute("xmlns:xsl");
                styleSheetRoot.removeAttribute("xmlns:xsl");
                styleSheetRoot.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsl", attr);
                Element elem = XMLTool.createElement(doc, contentobject, "objectstylesheet_xsl");
                elem.appendChild(doc.importNode(styleSheetRoot, true));
            } catch (XMLException e) {
                objectstylesheetElem.setAttribute("valid", "false");
            }
        }

        Element borderstylesheetElem = XMLTool.getElement(contentobject, "borderstylesheet");
        if (borderstylesheetElem != null) {
            ResourceKey borderStyleSheetKey = ResourceKey.parse(borderstylesheetElem.getAttribute("key"));
            if (borderStyleSheetKey != null) {
                res = resourceService.getResourceFile(borderStyleSheetKey);
                borderstylesheetElem.setAttribute("exist", res == null ? "false" : "true");
                if (res != null) {
                    try {
                        Document borderStyleSheetDoc = res.getDataAsXml().getAsDOMDocument();
                        borderstylesheetElem.setAttribute("valid", "true");

                        Element styleSheetRoot = borderStyleSheetDoc.getDocumentElement();
                        String attr = styleSheetRoot.getAttribute("xmlns:xsl");
                        styleSheetRoot.removeAttribute("xmlns:xsl");
                        styleSheetRoot.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsl", attr);
                        Element elem = XMLTool.createElement(doc, contentobject, "borderstylesheet_xsl");
                        elem.appendChild(doc.importNode(styleSheetRoot, true));
                    } catch (XMLException e) {
                        borderstylesheetElem.setAttribute("valid", "false");
                    }
                }
            }
        }
    }

    if (xmlData != null) {
        Map subelems = XMLTool.filterElements(doc.getDocumentElement().getChildNodes());
        if (subelems.get("contentobject") != null) {
            Element tempElem = (Element) subelems.get("contentobject");
            Map contentobjectmap = XMLTool.filterElements(tempElem.getChildNodes());

            Element contentobjectdata = (Element) contentobjectmap.get("contentobjectdata");
            Map queryparammap = XMLTool.filterElements(contentobjectdata.getChildNodes());
            tempElem = (Element) queryparammap.get("datasources");

            Document queryParamDoc = XMLTool.createDocument();
            tempElem = (Element) queryParamDoc.importNode(tempElem, true);
            queryParamDoc.appendChild(tempElem);

            StringWriter sw = new StringWriter();
            queryParamDoc.normalize();
            XMLTool.printDocument(sw, queryParamDoc, 0);
            queryParam = sw.toString();

            // Find the script data
            Element scriptElem = (Element) queryparammap.get("script");
            if (scriptElem != null) {
                script = XMLTool.getElementText(scriptElem);
            }

            Element[] paramElems = XMLTool.getElements(contentobjectdata, "stylesheetparam");
            for (Element paramElem1 : paramElems) {
                String type = paramElem1.getAttribute("type");
                if ("page".equals(type)) {
                    String menuItemKeyStr = XMLTool.getElementText(paramElem1);
                    int menuItemKey = Integer.parseInt(menuItemKeyStr);
                    String name = admin.getMenuItemName(menuItemKey);
                    paramElem1.setAttribute("valuename", name);
                } else if ("category".equals(type)) {
                    String categoryKeyStr = XMLTool.getElementText(paramElem1);
                    int categoryKey = Integer.parseInt(categoryKeyStr);
                    String name = admin.getMenuItemName(categoryKey);
                    paramElem1.setAttribute("valuename", name);
                }
            }

            paramElems = XMLTool.getElements(contentobjectdata, "borderparam");
            for (Element paramElem : paramElems) {
                String type = paramElem.getAttribute("type");
                if ("page".equals(type)) {
                    String menuItemKeyStr = XMLTool.getElementText(paramElem);
                    int menuItemKey = Integer.parseInt(menuItemKeyStr);
                    String name = admin.getMenuItemName(menuItemKey);
                    paramElem.setAttribute("valuename", name);
                } else if ("category".equals(type)) {
                    String categoryKeyStr = XMLTool.getElementText(paramElem);
                    int categoryKey = Integer.parseInt(categoryKeyStr);
                    String name = admin.getMenuItemName(categoryKey);
                    paramElem.setAttribute("valuename", name);
                }
            }
        }
    }

    ExtendedMap parameters = new ExtendedMap();

    // Get default css if present
    ResourceKey defaultCSS = admin.getDefaultCSSByMenu(menuKey);
    if (defaultCSS != null) {
        parameters.put("defaultcsskey", defaultCSS.toString());
        parameters.put("defaultcsskeyExist",
                resourceService.getResourceFile(defaultCSS) == null ? "false" : "true");
    }

    VerticalAdminLogger.debug(this.getClass(), 0, doc);

    addCommonParameters(admin, user, request, parameters, -1, menuKey);

    if (createContentObject) {
        parameters.put("create", "1");
        parameters.put("queryparam", "<?xml version=\"1.0\" ?>\n<datasources/>");
    } else {
        parameters.put("create", "0");
        queryParam = StringUtil.formatXML(queryParam, 2);
        parameters.put("queryparam", queryParam);
    }

    parameters.put("menukey", String.valueOf(menuKey));

    parameters.put("page", String.valueOf(request.getParameter("page")));

    String subop = formItems.getString("subop", "");
    if ("popup".equals(subop)) {
        URL redirectURL = new URL("adminpage");
        redirectURL.setParameter("op", "callback");
        redirectURL.setParameter("callback", formItems.getString("callback"));
        redirectURL.setParameter("page", 991);
        redirectURL.setParameter("key", Integer.parseInt(request.getParameter("key")));
        redirectURL.setParameter("fieldname", formItems.getString("fieldname"));
        redirectURL.setParameter("fieldrow", formItems.getString("fieldrow"));
        parameters.put("referer", redirectURL.toString());
        parameters.put("subop", "popup");
    } else {
        parameters.put("referer", request.getHeader("referer"));
    }

    parameters.put("subop", subop);
    parameters.put("fieldname", formItems.getString("fieldname", null));
    parameters.put("fieldrow", formItems.getString("fieldrow", null));
    parameters.put("script", script);

    addAccessLevelParameters(user, parameters);

    UserEntity defaultRunAsUser = siteDao.findByKey(menuKey).resolveDefaultRunAsUser();
    String defaultRunAsUserName = "NA";
    if (defaultRunAsUser != null) {
        defaultRunAsUserName = defaultRunAsUser.getDisplayName();
    }
    parameters.put("defaultRunAsUser", defaultRunAsUserName);

    transformXML(request, response, doc, "contentobject_form.xsl", parameters);
}

From source file:de.mpg.escidoc.services.transformation.Util.java

/**
 * Queries CoNE service and returns the result as DOM node.
 * The returned XML has the following structure:
 * <cone>//from  www . j a va2 s.  c o m
 *   <author>
 *     <familyname>Buxtehude-Mlln</familyname>
 *     <givenname>Heribert</givenname>
 *     <prefix>von und zu</prefix>
 *     <title>Knig</title>
 *   </author>
 *   <author>
 *     <familyname>Mller</familyname>
 *     <givenname>Peter</givenname>
 *   </author>
 * </authors>
 * 
 * @param authors
 * @return 
 */
public static Node queryCone(String model, String query) {
    DocumentBuilder documentBuilder;
    String queryUrl = null;
    try {
        logger.info("queryCone: " + model + " query: " + query);

        documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder();

        Document document = documentBuilder.newDocument();
        Element element = document.createElement("cone");
        document.appendChild(element);

        queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&q="
                + URLEncoder.encode(query, "UTF-8");
        String detailsUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/resource/$1?format=rdf";
        HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        GetMethod method = new GetMethod(queryUrl);

        String coneSession = getConeSession();

        if (coneSession != null) {
            method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
        }
        ProxyHelper.executeMethod(client, method);

        if (method.getStatusCode() == 200) {
            String[] results = method.getResponseBodyAsString().split("\n");
            for (String result : results) {
                if (!"".equals(result.trim())) {
                    String id = result.split("\\|")[1];
                    // TODO "&redirect=true" must be reinserted again
                    GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle="
                            + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8")));
                    detailMethod.setFollowRedirects(true);

                    if (coneSession != null) {
                        detailMethod.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
                    }
                    ProxyHelper.executeMethod(client, detailMethod);
                    if (logger.isDebugEnabled()) {
                        logger.debug("CoNE query: " + id + "?format=rdf&eSciDocUserHandle="
                                + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8"))
                                + " returned " + detailMethod.getResponseBodyAsString());
                    }

                    if (detailMethod.getStatusCode() == 200) {
                        Document details = documentBuilder.parse(detailMethod.getResponseBodyAsStream());
                        element.appendChild(document.importNode(details.getFirstChild(), true));
                    } else {
                        logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n"
                                + detailMethod.getResponseBodyAsString());
                    }
                }
            }
        } else {
            logger.error("Error querying CoNE: Status " + method.getStatusCode() + "\n"
                    + method.getResponseBodyAsString());
        }

        return document;
    } catch (Exception e) {
        logger.error("Error querying CoNE service. This is normal during unit tests. (" + queryUrl
                + ") .Otherwise it should be clarified if any measures have to be taken.", e);
        logger.debug("Stacktrace", e);
        return null;
        //throw new RuntimeException(e);
    }
}

From source file:com.mirth.connect.model.util.ImportConverter.java

public static Document convertServerConfiguration(String serverConfiguration) throws Exception {
    serverConfiguration = convertPackageNames(serverConfiguration);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Document document;
    DocumentBuilder builder;/*ww w .  j  a  va  2 s.c  om*/

    builder = factory.newDocumentBuilder();
    document = builder.parse(new InputSource(new StringReader(serverConfiguration)));

    // Remove users from the server configuration file if they were there.
    Element documentElement = document.getDocumentElement();
    NodeList users = documentElement.getElementsByTagName("users");
    if (users != null && users.getLength() > 0) {
        documentElement.removeChild(users.item(0));
    }

    Element channelsRoot = (Element) document.getElementsByTagName("channels").item(0);
    NodeList channels = getElements(document, "channel", "com.mirth.connect.model.Channel");
    List<Element> channelList = new ArrayList<Element>();
    int length = channels.getLength();

    for (int i = 0; i < length; i++) {
        // Must get node 0 because the first channel is removed each
        // iteration
        Element channel = (Element) channels.item(0);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer trans = tf.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        StringWriter sw = new StringWriter();
        trans.transform(new DOMSource(channel), new StreamResult(sw));
        String channelDocXML = sw.toString();

        channelList.add(new DonkeyElement(convertChannelString(channelDocXML)).getElement());
        channelsRoot.removeChild(channel);
    }

    for (Element channel : channelList) {
        channelsRoot.appendChild(document.importNode(channel, true));
    }

    NodeList codeTemplates = documentElement.getElementsByTagName("codeTemplates");
    int codeTemplateCount = codeTemplates.getLength();

    for (int i = 0; i < codeTemplateCount; i++) {
        Element codeTemplate = (Element) codeTemplates.item(i);
        Element convertedCodeTemplate = convertCodeTemplates(new DonkeyElement(codeTemplate).toXml())
                .getDocumentElement();
        documentElement.replaceChild(document.importNode(convertedCodeTemplate, true), codeTemplate);
    }

    return document;
}