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:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

/**
 * inList para force to create a <list></list> wrap the result
 *///from   ww  w. j av  a 2 s.  c o m
@Override
public List<String> listElementDomStringsByPaths(Set<String> paths, final String xmlData,
        boolean includeChildren) throws SAXException, IOException, XPathExpressionException {
    Assert.hasText(xmlData);

    Document originalDom = parse(xmlData);

    Document finalDom = documentBuilder.newDocument();

    List<String> nodes = Lists.newArrayList();
    // Element lastChild = null;

    for (String path : paths) {

        // create the node structure first. and return the last child of the
        // path... the right most node...
        // lastChild = createElementStructureByPath(root, path);
        XPath xPath = getXPathInstance();
        NodeList nodeList = (NodeList) (xPath.evaluate(path, originalDom, XPathConstants.NODESET));

        int l = nodeList.getLength();
        logger.trace("find: " + l);

        Node currentNode = null;
        for (int i = 0; i < l; i++) {
            currentNode = nodeList.item(i);

            Node importedNode = finalDom.importNode(currentNode, includeChildren);
            nodes.add(DomUtils.elementToString(importedNode));

        }

    }

    return nodes;

}

From source file:com.twinsoft.convertigo.beans.transactions.XmlHttpTransaction.java

@Override
public void makeDocument(byte[] httpData) throws Exception {
    Engine.logBeans.trace("makeDocument : " + getEncodingCharSet());

    Charset charset = XMLUtils.getEncoding(httpData, Charset.forName(xmlEncoding));

    String sdata = new String(httpData, charset);
    sdata = sdata.replaceFirst("[\\d\\D]*?<", "<");
    Engine.logBeans.trace("makeDocument afternewString: " + sdata);

    Document xmlHttpDocument = requester.parseDOM(sdata);
    if (Engine.logBeans.isTraceEnabled())
        Engine.logBeans.trace("makeDocument after parseDom: " + XMLUtils.prettyPrintDOM(xmlHttpDocument));

    // Replace SOAP fault by an c8o error element
    if (isErrorOnSoapFault()) {
        Element soapFaultElement = null;
        soapFaultElement = getSoapFaultElement(xmlHttpDocument);
        if (soapFaultElement != null) {
            String sfm = getSoapFaultMessage(soapFaultElement);
            ConvertigoException ex = new ConvertigoException("The Web Service returned a SOAP Fault",
                    new SOAPException(sfm));
            ConvertigoError err = ConvertigoError.initError(ErrorType.Project, ex);
            Document errDocument = err.buildErrorDocument(getRequester(), context);
            Node error = context.outputDocument.importNode(errDocument.getDocumentElement().getFirstChild(),
                    true);//from   w w  w.ja  v  a  2 s .c  om
            context.outputDocument.getDocumentElement().appendChild(error);
            return;
        }
    }

    if (getAllowDownloadAttachment()) {
        Element attachmentInfo = (Element) XPathAPI.selectSingleNode(context.outputDocument,
                "/document/AttachmentInfo");

        if (attachmentInfo != null) {
            NodeList nl = XPathAPI.selectNodeList(attachmentInfo, "attachment");

            for (int i = 0; i < nl.getLength(); i++) {
                Element attachment = (Element) nl.item(i);
                String cid = attachment.getAttribute("cid");

                if (StringUtils.isNotBlank(cid)) {
                    Element include = (Element) XPathAPI.selectSingleNode(xmlHttpDocument,
                            "//*[local-name()='Include' and @href='" + cid + "']");

                    if (include != null) {
                        include.appendChild(xmlHttpDocument.importNode(attachment, true));
                        XMLUtils.removeNode(attachment);
                    }
                }
            }

            if (XPathAPI.selectSingleNode(attachmentInfo, "attachment") == null) {
                XMLUtils.removeNode(attachmentInfo);
            }
        }
    }

    // Removes soap elements if needed
    if (isIgnoreSoapEnveloppe()) {
        Element soapBodyResponseElement = null;
        soapBodyResponseElement = getSoapBodyResponseElement(xmlHttpDocument.getDocumentElement());
        if (soapBodyResponseElement != null) {
            NamedNodeMap attributes = ((Element) soapBodyResponseElement.getParentNode()).getAttributes();
            NodeList childNodes = soapBodyResponseElement.getChildNodes();
            int len = childNodes.getLength();
            Node child, node;
            for (int i = 0; i < len; i++) {
                node = childNodes.item(i);
                if (node instanceof Element) {
                    //child = importNodeWithNoPrefix(context.outputDocument, node, true);
                    child = context.outputDocument.importNode(node, true);
                    // add envelope attributes (e.g namespace declarations to avoid unbound prefixes for XSL transformation)
                    for (int j = 0; j < attributes.getLength(); j++) {
                        Node attr = attributes.item(j);
                        ((Element) child)
                                .setAttributeNode((Attr) context.outputDocument.importNode(attr, true));
                    }
                    context.outputDocument.getDocumentElement().appendChild(child);
                }
            }
        } else {
            XMLUtils.copyDocument(xmlHttpDocument, context.outputDocument);
        }
    }
    // Normal case
    else
        XMLUtils.copyDocument(xmlHttpDocument, context.outputDocument);
}

From source file:com.inbravo.scribe.rest.service.crm.ms.MSCRMMessageFormatUtils.java

/**
 * // w  w  w  .j  av a2s  . c o m
 * @param entity
 * @return
 * @throws Exception
 */
public static final List<Element> createV5EntityFromBusinessObject(final Entity entity) throws Exception {

    /* Create list of elements */
    final List<Element> elementList = new ArrayList<Element>();

    /* Set entity id */
    elementList.add(createMessageElement("id", entity.getId()));

    /* Step 2: get all node attributes */
    final AttributeCollection attCol = entity.getAttributes();

    /* Check if entity is not null */
    if (attCol != null) {

        /* Get all attributes for the CRM field */
        final KeyValuePairOfstringanyType[] kvpsatArr = attCol.getKeyValuePairOfstringanyTypeArray();

        /* This is to avoid : 'DOM Level 3 Not implemented' error */
        final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        final Document document = builder.newDocument();

        if (logger.isDebugEnabled()) {
            logger.debug("----Inside createV5EntityFromBusinessObject: no of crm fields: " + kvpsatArr.length);
        }

        /* Iterate over all attributes */
        for (final KeyValuePairOfstringanyType kvpsat : kvpsatArr) {

            /* Get field name */
            final String fieldName = kvpsat.getKey();

            if (logger.isDebugEnabled()) {
                logger.debug("----Inside createV5EntityFromBusinessObject: crm field name: " + fieldName);
            }

            /* Get field value */
            String fieldValue = null;

            /* Get field value node */
            final XmlObject xo = kvpsat.getValue();

            /* If object is valid */
            if (xo != null) {

                /* Get DOM node from Xo */
                final Node node = xo.getDomNode();

                /* Check if node is not null */
                if (node != null && node.hasChildNodes()) {

                    /* Get all child nodes */
                    final NodeList nodeList = node.getChildNodes();

                    /* Create new map for attributes */
                    final Map<String, String> attributeMap = new HashMap<String, String>();

                    /* If more than 1 elements in node list */
                    if (nodeList.getLength() > 1) {

                        /* Iterate on all child node list */
                        for (int i = 0; i < nodeList.getLength(); i++) {

                            if (nodeList.item(i) instanceof Element) {

                                final Element childElement = (Element) document.importNode(nodeList.item(i),
                                        true);

                                if (childElement.getNodeName() != null
                                        && childElement.getNodeName().contains(":")) {

                                    /* Get attribute name */
                                    final String attName = childElement.getNodeName().split(":")[1];

                                    /* Get attribute value */
                                    final String attValue = childElement.getTextContent();

                                    if ("id".equalsIgnoreCase(attName)) {

                                        fieldValue = attValue;
                                    } else {

                                        /* Put values in map */
                                        attributeMap.put(attName, attValue);
                                    }
                                }
                            }
                        }

                        /* Create node with attributes */
                        elementList.add(createMessageElement(fieldName, fieldValue, attributeMap));

                    } else if (nodeList.getLength() == 1) {

                        /* Iterate on all child node list */
                        if (nodeList.item(0) instanceof Element) {

                            final Element childElement = (Element) document.importNode(nodeList.item(0), true);

                            /* Get attribute value */
                            fieldValue = childElement.getTextContent();

                            /* Create node with attributes */
                            elementList.add(createMessageElement(fieldName, fieldValue));
                        } else {

                            /* Create node with attributes */
                            elementList.add(createMessageElement(fieldName, nodeList.item(0).getNodeValue()));
                        }
                    }
                } else {

                    /* Create node with attributes */
                    elementList.add(createMessageElement(fieldName, node.getTextContent()));
                }
            }
        }
    }

    return elementList;
}

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

/**
 * based on our use case, it only check the children of the root node...
 * //  w w  w  .  j  a v a  2s .  c  om
 * @param originalDom
 * @param modifiedDom
 * @return Document
 */
private Document replace(final Document originalDom, final Document modifiedDom) {

    /**
     * the children nodes of a xml Document is the first level nodes in the
     * xml doc, for example, for a protocol xml, the children nodes of the
     * doc is <code><protocol></code>
     */

    // it needs to find the latest identical node then start replacing
    // whatever under it...
    Element rootNode = (Element) modifiedDom.getFirstChild();

    Document finalDom = originalDom;

    Element finalDomRoot = (Element) finalDom.getFirstChild();

    NodeList modifiedNodes = rootNode.getChildNodes();

    int l = modifiedNodes.getLength();

    logger.trace("lenght: " + l);
    for (int i = 0; i < l; i++) {
        Node currentNode = modifiedNodes.item(i);

        logger.trace("currentNode: " + currentNode.getNodeName());

        NodeList matchedNodes = finalDomRoot.getElementsByTagName(currentNode.getNodeName());

        for (int j = 0; j < matchedNodes.getLength(); j++) {
            try {
                finalDomRoot.removeChild(matchedNodes.item(j));
            } catch (Exception e) {
                logger.debug("Failed to remove node: " + matchedNodes.item(j).getNodeName());
            }

        }

        finalDomRoot.appendChild(finalDom.importNode(currentNode, true));
    }

    logger.trace("finalDom: " + DomUtils.elementToString(finalDom));

    return finalDom;
}

From source file:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java

/**
 * This method processes the SOAP response from the IdP, and converts it
 * for presenting it back to the WSP that requested a delegated SAML
 * assertion./*from w ww  .j  a  v  a 2  s  .co  m*/
 * 
 * @param samlSession SAML session
 * @param authnState 
 * @return true, if successful
 */
private boolean processSOAPResponse(SAMLSession samlSession, DelegatedSAMLAuthenticationState authnState) {
    this.logger.debug("Step 5 of 5: Processing SOAP response");

    try {
        String expression = "/soap:Envelope/soap:Header/ecp:Response";
        InputStream is = new ByteArrayInputStream(authnState.getSoapResponse().getBytes());
        InputSource source = new InputSource(is);
        DOMParser parser = new DOMParser();
        parser.setFeature("http://xml.org/sax/features/namespaces", true);
        parser.parse(source);
        Document doc = parser.getDocument();
        Node node = EXPRESSION_POOL.evaluate(expression, doc, XPathConstants.NODE);

        if (node != null) {
            String responseConsumerURL = node.getAttributes().getNamedItem("AssertionConsumerServiceURL")
                    .getTextContent();

            logger.debug("Found {} node found in SOAP response.", expression);

            if (responseConsumerURL != null
                    && responseConsumerURL.equals(authnState.getResponseConsumerURL())) {
                logger.debug("responseConsumerURL {} matches {}", responseConsumerURL,
                        authnState.getResponseConsumerURL());

                // Retrieve and save the SOAP prefix used
                String soapPrefix = node.getParentNode().getPrefix();
                Element ecpResponse = (Element) node;
                Element soapHeader = (Element) ecpResponse.getParentNode();
                removeAllChildren(soapHeader);

                // Now on to the PAOS Response
                Element paosResponse = doc.createElementNS("urn:liberty:paos:2003-08", "paos:Response");
                paosResponse.setAttribute(soapPrefix + ":mustUnderstand", "1");
                paosResponse.setAttribute(soapPrefix + ":actor", "http://schemas.xmlsoap.org/soap/actor/next");

                // messageID is optional
                if (authnState.getPaosMessageID() != null)
                    paosResponse.setAttribute("refToMessageID", authnState.getPaosMessageID());

                soapHeader.appendChild(paosResponse);

                if (authnState.getRelayStateElement() != null) {
                    Node relayState = doc.importNode(authnState.getRelayStateElement(), true);
                    soapHeader.appendChild(relayState);
                }

                // Store the modified SOAP Request in the SAML Session
                String modifiedSOAPResponse = writeDomToString(doc);
                authnState.setModifiedSOAPResponse(modifiedSOAPResponse);
                return true;
            }

            logger.debug("responseConsumerURL {} does not match {}", responseConsumerURL,
                    authnState.getResponseConsumerURL());
            Document soapFaultMessage = createSOAPFaultDocument(
                    "AssertionConsumerServiceURL attribute missing or not matching the expected value.");
            Element soapHeader = (Element) soapFaultMessage.getFirstChild().getFirstChild();
            // Now on to the PAOS Response
            Element paosResponse = soapFaultMessage.createElementNS("urn:liberty:paos:2003-08",
                    "paos:Response");
            paosResponse.setAttribute(SOAP_PREFIX + ":mustUnderstand", "1");
            paosResponse.setAttribute(SOAP_PREFIX + ":actor", "http://schemas.xmlsoap.org/soap/actor/next");

            // messageID is optional
            if (authnState.getPaosMessageID() != null) {
                paosResponse.setAttribute("refToMessageID", authnState.getPaosMessageID());
            }

            soapHeader.appendChild(paosResponse);

            if (authnState.getRelayStateElement() != null) {
                Node relayState = soapFaultMessage.importNode(authnState.getRelayStateElement(), true);
                soapHeader.appendChild(relayState);
            }
            // Store the SOAP Fault in the SAML Session
            String modifiedSOAPResponse = writeDomToString(soapFaultMessage);
            authnState.setModifiedSOAPResponse(modifiedSOAPResponse);
            sendSOAPFault(samlSession, authnState);
            return false;

        }

        // There was no response for the ECP.  Look for and propagate an error.
        String errorMessage = getSOAPFaultAsString(is);

        logger.warn("No {} node found in SOAP response. Error: {}", expression, errorMessage);

        if (errorMessage != null) {
            throw new DelegatedAuthenticationRuntimeException(errorMessage);
        }

        return false;
    } catch (XPathExpressionException ex) {
        logger.error("XPath programming error.", ex);
        throw new DelegatedAuthenticationRuntimeException("XPath programming error.", ex);
    } catch (SAXNotRecognizedException ex) {
        logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex);
        throw new DelegatedAuthenticationRuntimeException("XPath programming error.", ex);
    } catch (SAXNotSupportedException ex) {
        logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex);
        throw new DelegatedAuthenticationRuntimeException(
                "Exception caught when trying to process the SOAP esponse from the IdP.", ex);
    } catch (SAXException ex) {
        logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex);
        throw new DelegatedAuthenticationRuntimeException(
                "Exception caught when trying to process the SOAP esponse from the IdP.", ex);
    } catch (DOMException ex) {
        logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex);
        throw new DelegatedAuthenticationRuntimeException(
                "Exception caught when trying to process the SOAP esponse from the IdP.", ex);
    } catch (IOException ex) {
        logger.error(
                "This exception should not ever really occur, as the only I/O this method performs is on a ByteArrayInputStream.",
                ex);
        throw new DelegatedAuthenticationRuntimeException(
                "This exception should not ever really occur, as the only I/O this method performs is on a ByteArrayInputStream.",
                ex);
    } catch (SOAPException ex) {
        logger.error("Error processing a SOAP message.", ex);
        throw new DelegatedAuthenticationRuntimeException("Error processing a SOAP message.", ex);
    }
}

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

/**
 * inList para force to create a <list></list> wrap the result
 *///  w w  w .ja v  a 2 s.co  m
@Override
public synchronized String listElementsByPaths(Set<String> paths, final String xmlData, boolean inList,
        boolean includeChildren) throws SAXException, IOException, XPathExpressionException {
    Assert.hasText(xmlData);

    Document originalDom = parse(xmlData);

    Document finalDom = documentBuilder.newDocument();

    Element root = null;
    if (inList) {
        root = finalDom.createElement("list");
    } else {
        root = finalDom.createElement(originalDom.getFirstChild().getNodeName());
    }

    // Element lastChild = null;

    for (String path : paths) {

        // create the node structure first. and return the last child of the
        // path... the right most node...
        // lastChild = createElementStructureByPath(root, path);
        XPath xPath = getXPathInstance();
        NodeList nodeList = (NodeList) (xPath.evaluate(path, originalDom, XPathConstants.NODESET));

        int l = nodeList.getLength();
        logger.trace("find: " + l);

        Node currentNode = null;
        for (int i = 0; i < l; i++) {
            currentNode = nodeList.item(i);

            root.appendChild(finalDom.importNode(currentNode, includeChildren));

        }

    }

    return DomUtils.elementToString(root);

}

From source file:com.netspective.sparx.util.xml.XmlSource.java

public Document loadXML(File file) {
    if (docSource == null) {
        errors.clear();//from   w  w  w  .j  a  v a  2 s .c  om
        sourceFiles.clear();
        metaInfoElem = null;
        metaInfoOptionsElem = null;
    }

    SourceInfo sourceInfo = new SourceInfo(docSource, file);
    sourceFiles.put(file.getAbsolutePath(), sourceInfo);

    Document doc = null;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder parser = factory.newDocumentBuilder();
        doc = parser.parse(file);
        doc.normalize();
    } catch (Exception e) {
        throw new RuntimeException("XML Parsing error in '" + file.getAbsolutePath() + "': " + e);
    }

    if (docSource == null) {
        xmlDoc = doc;
        docSource = sourceInfo;
    }

    /*
    find all of the <include file="xyz"> elements and "include" all the
    elements in that document as children of the main document
    */

    Element rootElem = doc.getDocumentElement();
    NodeList includes = rootElem.getElementsByTagName("include");
    if (includes != null && includes.getLength() > 0) {
        for (int n = 0; n < includes.getLength(); n++) {
            Element include = (Element) includes.item(n);
            String incFileAttr = include.getAttribute("file");
            File incFile = new File(file.getParentFile(), incFileAttr);
            if (!sourceFiles.containsKey(incFile.getAbsolutePath())) {
                Document includeDoc = loadXML(incFile);
                if (includeDoc != null) {
                    Element includeRoot = includeDoc.getDocumentElement();
                    NodeList incChildren = includeRoot.getChildNodes();
                    for (int c = 0; c < incChildren.getLength(); c++) {
                        Node incCopy = doc.importNode(incChildren.item(c), true);
                        if (incCopy.getNodeType() == Node.ELEMENT_NODE)
                            ((Element) incCopy).setAttribute("_included-from", incFileAttr);
                        rootElem.insertBefore(incCopy, include);
                    }
                }
            }
        }
    }

    /*
     find all of the <pre-process stylesheet="xyz"> elements and "pre-process" using XSLT stylesheets
    */

    NodeList preProcessors = rootElem.getElementsByTagName("pre-process");
    if (preProcessors != null && preProcessors.getLength() > 0) {
        for (int n = 0; n < preProcessors.getLength(); n++) {
            Element preProcessor = (Element) preProcessors.item(n);
            String ppFileAttr = preProcessor.getAttribute("style-sheet");
            if (ppFileAttr.length() == 0) {
                addError("No style-sheet attribute provided for pre-process element");
                continue;
            }
            File ppFile = new File(file.getParentFile(), ppFileAttr);
            docSource.addPreProcessor(new SourceInfo(docSource, ppFile));
            preProcess(ppFile);
        }
    }
    return doc;
}

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

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

    User user = securityService.getLoggedInAdminConsoleUser();

    try {//from   ww  w .  j  a  va 2  s .c  om

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

        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("returnkey", formItems.getString("returnkey"));
        parameters.put("returnview", formItems.getString("returnview"));
        String returnrow = formItems.getString("returnrow", "");
        if (returnrow != null && returnrow.length() > 0) {
            parameters.put("returnrow", returnrow);
        }
        String tmp = formItems.getString("callback", "");
        if (tmp != null && tmp.length() > 0) {
            parameters.put("callback", tmp);
        } else {
            parameters.put("callback", "false");
        }

        tmp = formItems.getString("filter", null);
        if (tmp != null && tmp.length() > 0) {
            parameters.put("filter", tmp);
        }

        parameters.put("referer", formItems.getString("referer", ""));

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

        Document menuDocTemp = XMLTool.domparse(admin.getAdminMenu(user, menuKey));
        Element menuElemTemp = XMLTool.selectElement(menuDocTemp.getDocumentElement(),
                "menu[@key = '" + menuKey + "']");
        Element[] menuItemElems = XMLTool.getElements(menuElemTemp);
        Document menuDoc = XMLTool.createDocument("menutop");
        Element menuTop = menuDoc.getDocumentElement();
        for (int i = 0; i < menuItemElems.length; i++) {
            menuTop.appendChild(menuDoc.importNode(menuItemElems[i], true));
        }

        DOMSource xmlSource = new DOMSource(menuDoc);
        Source xslSource = AdminStore.getStylesheet(session, "menuitem_selector.xsl");

        transformXML(session, response.getWriter(), xmlSource, xslSource, parameters);
    } catch (IOException ioe) {
        String message = "I/O error: %t";
        VerticalAdminLogger.error(this.getClass(), 0, message, ioe);
    } catch (TransformerException te) {
        String message = "XSL transformer error: %t";
        VerticalAdminLogger.error(this.getClass(), 0, message, te);
    }

    return true;
}

From source file:com.msopentech.odatajclient.engine.data.impl.v3.AtomSerializer.java

private Element entry(final AtomEntry entry) throws ParserConfigurationException {
    final DocumentBuilder builder = XMLUtils.DOC_BUILDER_FACTORY.newDocumentBuilder();
    final Document doc = builder.newDocument();

    final Element entryElem = doc.createElement(ODataConstants.ATOM_ELEM_ENTRY);
    entryElem.setAttribute(XMLConstants.XMLNS_ATTRIBUTE, ODataConstants.NS_ATOM);
    entryElem.setAttribute(ODataConstants.XMLNS_METADATA,
            client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA));
    entryElem.setAttribute(ODataConstants.XMLNS_DATASERVICES,
            client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_DATASERVICES));
    entryElem.setAttribute(ODataConstants.XMLNS_GML, ODataConstants.NS_GML);
    entryElem.setAttribute(ODataConstants.XMLNS_GEORSS, ODataConstants.NS_GEORSS);
    if (entry.getBaseURI() != null) {
        entryElem.setAttribute(ODataConstants.ATTR_XMLBASE, entry.getBaseURI().toASCIIString());
    }/*from w w  w  . j a va2s .  co  m*/
    doc.appendChild(entryElem);

    final Element category = doc.createElement(ODataConstants.ATOM_ELEM_CATEGORY);
    category.setAttribute(ODataConstants.ATOM_ATTR_TERM, entry.getType());
    category.setAttribute(ODataConstants.ATOM_ATTR_SCHEME,
            client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_SCHEME));
    entryElem.appendChild(category);

    if (StringUtils.isNotBlank(entry.getTitle())) {
        final Element title = doc.createElement(ODataConstants.ATOM_ELEM_TITLE);
        title.appendChild(doc.createTextNode(entry.getTitle()));
        entryElem.appendChild(title);
    }

    if (StringUtils.isNotBlank(entry.getSummary())) {
        final Element summary = doc.createElement(ODataConstants.ATOM_ELEM_SUMMARY);
        summary.appendChild(doc.createTextNode(entry.getSummary()));
        entryElem.appendChild(summary);
    }

    setLinks(entryElem, entry.getAssociationLinks());
    setLinks(entryElem, entry.getNavigationLinks());
    setLinks(entryElem, entry.getMediaEditLinks());

    final Element content = doc.createElement(ODataConstants.ATOM_ELEM_CONTENT);
    if (entry.isMediaEntry()) {
        if (StringUtils.isNotBlank(entry.getMediaContentType())) {
            content.setAttribute(ODataConstants.ATTR_TYPE, entry.getMediaContentType());
        }
        if (StringUtils.isNotBlank(entry.getMediaContentSource())) {
            content.setAttribute(ODataConstants.ATOM_ATTR_SRC, entry.getMediaContentSource());
        }
        if (content.getAttributes().getLength() > 0) {
            entryElem.appendChild(content);
        }

        if (entry.getMediaEntryProperties() != null) {
            entryElem.appendChild(doc.importNode(entry.getMediaEntryProperties(), true));
        }
    } else {
        content.setAttribute(ODataConstants.ATTR_TYPE, ContentType.APPLICATION_XML.getMimeType());
        if (entry.getContent() != null) {
            content.appendChild(doc.importNode(entry.getContent(), true));
        }
        entryElem.appendChild(content);
    }

    return entryElem;
}

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

/**
 * Queries the CoNE service and transforms the result into a DOM node.
 * /*from  w w w.ja v  a2 s . com*/
 * @param model The type of object (e.g. "persons")
 * @param name The query string.
 * @param ou Specialty for persons
 * @param coneSession A JSESSIONID to not produce a new session with each call.
 * @return A DOM node containing the results.
 */
public static Node queryConeExactWithIdentifier(String model, String identifier, String ou) {
    DocumentBuilder documentBuilder;

    try {
        logger.info("queryConeExactWithIdentifier: " + model + " identifier: " + identifier + " ou: " + ou);

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

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

        String queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/query?format=jquery&dc:identifier/" + URLEncoder.encode("rdf:value", "UTF-8") + "="
                + URLEncoder.encode("\"" + identifier + "\"", "UTF-8") + "&"
                + URLEncoder.encode("escidoc:position/eprints:affiliatedInstitution", "UTF-8") + "="
                + URLEncoder.encode("\"*" + ou + "*\"", "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);
        logger.info("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString());
        if (method.getStatusCode() == 200) {
            ArrayList<String> results = new ArrayList<String>();
            results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n")));
            Set<String> oldIds = new HashSet<String>();
            for (String result : results) {
                if (!"".equals(result.trim())) {
                    String id = result.split("\\|")[1];
                    if (!oldIds.contains(id)) {
                        // 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);

                        ProxyHelper.setProxy(client, detailsUrl.replace("$1", id));
                        client.executeMethod(detailMethod);
                        // TODO "&redirect=true" must be reinserted again
                        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());
                        }
                        oldIds.add(id);
                    }
                }
            }
        } 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. "
                + "Otherwise it should be clarified if any measures have to be taken.", e);
        return null;
        // throw new RuntimeException(e);
    }
}