Example usage for javax.xml.xpath XPathConstants NODESET

List of usage examples for javax.xml.xpath XPathConstants NODESET

Introduction

In this page you can find the example usage for javax.xml.xpath XPathConstants NODESET.

Prototype

QName NODESET

To view the source code for javax.xml.xpath XPathConstants NODESET.

Click Source Link

Document

The XPath 1.0 NodeSet data type.

Maps to Java org.w3c.dom.NodeList .

Usage

From source file:com.ephesoft.gxt.systemconfig.server.SystemConfigServiceImpl.java

@Override
public Boolean addNewPlugin(String newPluginName, String xmlSourcePath, String jarSourcePath)
        throws UIException {

    LOGGER.info("Saving the new plugin with following details:\n Plugin Name:\t" + newPluginName
            + "\n Plugin Xml Path:\t" + xmlSourcePath + "\n Plugin Jar path:\t" + jarSourcePath);
    PluginXmlDTO pluginXmlDTO = null;/*from  w w w .j ava2s.c  om*/
    boolean pluginAdded = false;
    // Parse the data from xmlSourcePath file
    XPathFactory xFactory = new org.apache.xpath.jaxp.XPathFactoryImpl();
    XPath xpath = xFactory.newXPath();
    org.w3c.dom.Document pluginXmlDoc = null;

    try {
        pluginXmlDoc = XMLUtil
                .createDocumentFrom(FileUtils.getInputStreamFromZip(newPluginName, xmlSourcePath));
    } catch (Exception e) {
        String errorMsg = "Invalid xml content. Please try again.";
        LOGGER.error(errorMsg + e.getMessage(), e);
        throw new UIException(errorMsg);
    }

    if (pluginXmlDoc != null) {

        // correct syntax
        NodeList pluginNodeList = null;
        try {
            pluginNodeList = (NodeList) xpath.evaluate(SystemConfigSharedConstants.PLUGIN_EXPR, pluginXmlDoc,
                    XPathConstants.NODESET);
        } catch (XPathExpressionException e) {
            String errorMsg = SystemConfigSharedConstants.INVALID_XML_CONTENT_MESSAGE;
            LOGGER.error(errorMsg + e.getMessage(), e);
            throw new UIException(errorMsg);
        }
        if (pluginNodeList != null && pluginNodeList.getLength() == 1) {
            LOGGER.info("Reading the Xml contents");
            String backUpFileName = SystemConfigSharedConstants.EMPTY_STRING;
            String jarName = SystemConfigSharedConstants.EMPTY_STRING;
            String methodName = SystemConfigSharedConstants.EMPTY_STRING;
            String description = SystemConfigSharedConstants.EMPTY_STRING;
            String pluginName = SystemConfigSharedConstants.EMPTY_STRING;
            String workflowName = SystemConfigSharedConstants.EMPTY_STRING;
            String scriptFileName = SystemConfigSharedConstants.EMPTY_STRING;
            String serviceName = SystemConfigSharedConstants.EMPTY_STRING;
            String pluginApplicationContextPath = SystemConfigSharedConstants.EMPTY_STRING;
            boolean isScriptingPlugin = false;
            boolean overrideExisting = false;
            try {
                backUpFileName = (String) xpath.evaluate(SystemConfigSharedConstants.BACK_UP_FILE_NAME_EXPR,
                        pluginNodeList.item(0), XPathConstants.STRING);
                jarName = (String) xpath.evaluate(SystemConfigSharedConstants.JAR_NAME_EXPR,
                        pluginNodeList.item(0), XPathConstants.STRING);
                methodName = (String) xpath.evaluate(SystemConfigSharedConstants.METHOD_NAME_EXPR,
                        pluginNodeList.item(0), XPathConstants.STRING);
                description = (String) xpath.evaluate(SystemConfigSharedConstants.PLUGIN_DESC_EXPR,
                        pluginNodeList.item(0), XPathConstants.STRING);
                pluginName = (String) xpath.evaluate(SystemConfigSharedConstants.PLUGIN_NAME_EXPR,
                        pluginNodeList.item(0), XPathConstants.STRING);
                workflowName = (String) xpath.evaluate(SystemConfigSharedConstants.PLUGIN_WORKFLOW_NAME_EXPR,
                        pluginNodeList.item(0), XPathConstants.STRING);
                scriptFileName = (String) xpath.evaluate(SystemConfigSharedConstants.SCRIPT_FILE_NAME_EXPR,
                        pluginNodeList.item(0), XPathConstants.STRING);
                serviceName = (String) xpath.evaluate(SystemConfigSharedConstants.SERVICE_NAME_EXPR,
                        pluginNodeList.item(0), XPathConstants.STRING);
                isScriptingPlugin = Boolean
                        .parseBoolean((String) xpath.evaluate(SystemConfigSharedConstants.IS_SCRIPT_PLUGIN_EXPR,
                                pluginNodeList.item(0), XPathConstants.STRING));
                pluginApplicationContextPath = (String) xpath.evaluate(
                        SystemConfigSharedConstants.APPLICATION_CONTEXT_PATH, pluginNodeList.item(0),
                        XPathConstants.STRING);
                overrideExisting = Boolean
                        .parseBoolean((String) xpath.evaluate(SystemConfigSharedConstants.OVERRIDE_EXISTING,
                                pluginNodeList.item(0), XPathConstants.STRING));
            } catch (Exception e) {
                String errorMsg = "Error in xml content. A mandatory tag is missing or invalid.";
                LOGGER.error(errorMsg + e.getMessage(), e);
                throw new UIException(errorMsg);
            }

            LOGGER.info("Back Up File Name: " + backUpFileName);
            LOGGER.info("Jar Name" + jarName);
            LOGGER.info("Method Name" + methodName);
            LOGGER.info("Description: " + description);
            LOGGER.info("Name: " + pluginName);
            LOGGER.info("Workflow Name" + workflowName);
            LOGGER.info("Script file Name" + scriptFileName);
            LOGGER.info("Service Name" + serviceName);
            LOGGER.info("Is scripting Plugin:" + isScriptingPlugin);
            LOGGER.info("Plugin application context path: " + pluginApplicationContextPath);
            if (!backUpFileName.isEmpty() && !jarName.isEmpty() && !methodName.isEmpty()
                    && !description.isEmpty() && !pluginName.isEmpty() && !workflowName.isEmpty()
                    && !serviceName.isEmpty() && !pluginApplicationContextPath.isEmpty()) {

                if (isScriptingPlugin && scriptFileName.isEmpty()) {
                    String errorMsg = "Error in xml content. A mandatory field is missing.";
                    LOGGER.error(errorMsg);
                    throw new UIException(errorMsg);
                }
                pluginXmlDTO = setPluginInfo(backUpFileName, jarName, methodName, description, pluginName,
                        workflowName, scriptFileName, serviceName, pluginApplicationContextPath,
                        isScriptingPlugin, overrideExisting);

                extractPluginConfigs(pluginXmlDTO, xpath, pluginNodeList);

                extractPluginDependenciesFromXml(pluginXmlDTO, xpath, pluginNodeList);

                boolean pluginAlreadyExists = !checkIfPluginExists(pluginName);

                saveOrUpdatePluginToDB(pluginXmlDTO);
                createAndDeployPluginProcessDefinition(pluginXmlDTO);
                copyJarToLib(newPluginName, jarSourcePath);

                if (pluginAlreadyExists) {
                    addPathToApplicationContext(pluginXmlDTO.getApplicationContextPath());
                }
                pluginAdded = true;
                LOGGER.info("Plugin added successfully.");
            } else {
                String errorMsg = SystemConfigSharedConstants.INVALID_XML_CONTENT_MESSAGE;
                LOGGER.error(errorMsg);
                throw new UIException(errorMsg);
            }
        } else {
            String errorMsg = "Invalid xml content. Number of plugins expected is one.";
            LOGGER.error(errorMsg);
            throw new UIException(errorMsg);
        }
    }

    return pluginAdded;
}

From source file:net.sourceforge.dita4publishers.impl.ditabos.DitaTreeWalkerBase.java

/**
 * @param bos// ww w  .  j a va2 s .  co  m
 * @param member
 * @param newMembers
 */
private void findObjectDependencies(BoundedObjectSet bos, XmlBosMember member, Set<BosMember> newMembers)
        throws BosException {
    NodeList objects;
    try {
        objects = (NodeList) DitaUtil.allObjects.evaluate(member.getElement(), XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new BosException("Unexcepted exception evaluating xpath " + DitaUtil.allObjects);
    }

    log.debug("findObjectDependencies(): Found " + objects.getLength() + " topic/object elements");

    for (int i = 0; i < objects.getLength(); i++) {
        Element objectElem = (Element) objects.item(i);
        URI targetUri = null;

        // If there is a key reference, attempt to resolve it,
        // then fall back to href, if any.
        String href = null;
        try {
            if (objectElem.hasAttribute("data")) {
                log.debug("findObjectDependencies(): resolving reference to data \""
                        + objectElem.getAttribute("data") + "\"...");
                href = objectElem.getAttribute("data");
                // FIXME: This assumes that the @data value will be a relative URL. In fact, it could be relative
                //        to the value of the @codebase attribute if specified.
                targetUri = AddressingUtil.resolveObjectDataToUri(objectElem,
                        this.failOnAddressResolutionFailure);
            }
        } catch (AddressingException e) {
            if (this.failOnAddressResolutionFailure) {
                throw new BosException(
                        "Failed to resolve @data \"" + objectElem.getAttribute("data") + "\" to a resource", e);
            }
        }

        if (targetUri == null)
            continue;

        BosMember childMember = null;
        if (targetUri != null) {
            log.debug("findObjectDependencies(): Got URI \"" + targetUri.toString() + "\"");
            childMember = bos.constructBosMember((BosMember) member, targetUri);
        }
        bos.addMember(member, childMember);
        newMembers.add(childMember);
        if (href != null)
            member.registerDependency(href, childMember, Constants.OBJECT_DEPENDENCY);
    }

}

From source file:com.eucalyptus.imaging.manifest.DownloadManifestFactory.java

/**
 * Generates download manifest based on bundle manifest and puts in into
 * system owned bucket// w w w  .ja  v  a2 s . co m
 * 
 * @param baseManifest
 *          the base manifest
 * @param keyToUse
 *          public key that used for encryption
 * @param manifestName
 *          name for generated manifest file
 * @param expirationHours
 *          expiration policy in hours for pre-signed URLs
 * @param urlForNc
 *          indicates if urs are constructed for NC use
 * @return pre-signed URL that can be used to download generated manifest
 * @throws DownloadManifestException
 */
public static String generateDownloadManifest(final ImageManifestFile baseManifest, final PublicKey keyToUse,
        final String manifestName, int expirationHours, boolean urlForNc) throws DownloadManifestException {
    EucaS3Client s3Client = null;
    try {
        try {
            s3Client = s3ClientsPool.borrowObject();
        } catch (Exception ex) {
            throw new DownloadManifestException("Can't borrow s3Client from the pool");
        }
        // prepare to do pre-signed urls
        if (!urlForNc)
            s3Client.refreshEndpoint(true);
        else
            s3Client.refreshEndpoint();

        Date expiration = new Date();
        long msec = expiration.getTime() + 1000 * 60 * 60 * expirationHours;
        expiration.setTime(msec);

        // check if download-manifest already exists
        if (objectExist(s3Client, DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName)) {
            LOG.debug("Manifest '" + (DOWNLOAD_MANIFEST_PREFIX + manifestName)
                    + "' is already created and has not expired. Skipping creation");
            URL s = s3Client.generatePresignedUrl(DOWNLOAD_MANIFEST_BUCKET_NAME,
                    DOWNLOAD_MANIFEST_PREFIX + manifestName, expiration, HttpMethod.GET);
            return String.format("%s://imaging@%s%s?%s", s.getProtocol(), s.getAuthority(), s.getPath(),
                    s.getQuery());
        } else {
            LOG.debug("Manifest '" + (DOWNLOAD_MANIFEST_PREFIX + manifestName) + "' does not exist");
        }

        UrlValidator urlValidator = new UrlValidator();

        final String manifest = baseManifest.getManifest();
        if (manifest == null) {
            throw new DownloadManifestException("Can't generate download manifest from null base manifest");
        }
        final Document inputSource;
        final XPath xpath;
        Function<String, String> xpathHelper;
        DocumentBuilder builder = XMLParser.getDocBuilder();
        inputSource = builder.parse(new ByteArrayInputStream(manifest.getBytes()));
        if (!"manifest".equals(inputSource.getDocumentElement().getNodeName())) {
            LOG.error("Expected image manifest. Got " + nodeToString(inputSource, false));
            throw new InvalidBaseManifestException("Base manifest does not have manifest element");
        }

        StringBuilder signatureSrc = new StringBuilder();
        Document manifestDoc = builder.newDocument();
        Element root = (Element) manifestDoc.createElement("manifest");
        manifestDoc.appendChild(root);
        Element el = manifestDoc.createElement("version");
        el.appendChild(manifestDoc.createTextNode("2014-01-14"));
        signatureSrc.append(nodeToString(el, false));
        root.appendChild(el);
        el = manifestDoc.createElement("file-format");
        el.appendChild(manifestDoc.createTextNode(baseManifest.getManifestType().getFileType().toString()));
        root.appendChild(el);
        signatureSrc.append(nodeToString(el, false));

        xpath = XPathFactory.newInstance().newXPath();
        xpathHelper = new Function<String, String>() {
            @Override
            public String apply(String input) {
                try {
                    return (String) xpath.evaluate(input, inputSource, XPathConstants.STRING);
                } catch (XPathExpressionException ex) {
                    return null;
                }
            }
        };

        // extract keys
        // TODO: move this?
        if (baseManifest.getManifestType().getFileType() == FileType.BUNDLE) {
            String encryptedKey = xpathHelper.apply("/manifest/image/ec2_encrypted_key");
            String encryptedIV = xpathHelper.apply("/manifest/image/ec2_encrypted_iv");
            String size = xpathHelper.apply("/manifest/image/size");
            EncryptedKey encryptKey = reEncryptKey(new EncryptedKey(encryptedKey, encryptedIV), keyToUse);
            el = manifestDoc.createElement("bundle");
            Element key = manifestDoc.createElement("encrypted-key");
            key.appendChild(manifestDoc.createTextNode(encryptKey.getKey()));
            Element iv = manifestDoc.createElement("encrypted-iv");
            iv.appendChild(manifestDoc.createTextNode(encryptKey.getIV()));
            el.appendChild(key);
            el.appendChild(iv);
            Element sizeEl = manifestDoc.createElement("unbundled-size");
            sizeEl.appendChild(manifestDoc.createTextNode(size));
            el.appendChild(sizeEl);
            root.appendChild(el);
            signatureSrc.append(nodeToString(el, false));
        }

        el = manifestDoc.createElement("image");
        String bundleSize = xpathHelper.apply(baseManifest.getManifestType().getSizePath());
        if (bundleSize == null) {
            throw new InvalidBaseManifestException("Base manifest does not have size element");
        }
        Element size = manifestDoc.createElement("size");
        size.appendChild(manifestDoc.createTextNode(bundleSize));
        el.appendChild(size);

        Element partsEl = manifestDoc.createElement("parts");
        el.appendChild(partsEl);
        // parts
        NodeList parts = (NodeList) xpath.evaluate(baseManifest.getManifestType().getPartsPath(), inputSource,
                XPathConstants.NODESET);
        if (parts == null) {
            throw new InvalidBaseManifestException("Base manifest does not have parts");
        }

        for (int i = 0; i < parts.getLength(); i++) {
            Node part = parts.item(i);
            String partIndex = part.getAttributes().getNamedItem("index").getNodeValue();
            String partKey = ((Node) xpath.evaluate(baseManifest.getManifestType().getPartUrlElement(), part,
                    XPathConstants.NODE)).getTextContent();
            String partDownloadUrl = partKey;
            if (baseManifest.getManifestType().signPartUrl()) {
                GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(
                        baseManifest.getBaseBucket(), partKey, HttpMethod.GET);
                generatePresignedUrlRequest.setExpiration(expiration);
                URL s = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
                partDownloadUrl = s.toString();
            } else {
                // validate url per EUCA-9144
                if (!urlValidator.isEucalyptusUrl(partDownloadUrl))
                    throw new DownloadManifestException(
                            "Some parts in the manifest are not stored in the OS. Its location is outside Eucalyptus:"
                                    + partDownloadUrl);
            }
            Node digestNode = null;
            if (baseManifest.getManifestType().getDigestElement() != null)
                digestNode = ((Node) xpath.evaluate(baseManifest.getManifestType().getDigestElement(), part,
                        XPathConstants.NODE));
            Element aPart = manifestDoc.createElement("part");
            Element getUrl = manifestDoc.createElement("get-url");
            getUrl.appendChild(manifestDoc.createTextNode(partDownloadUrl));
            aPart.setAttribute("index", partIndex);
            aPart.appendChild(getUrl);
            if (digestNode != null) {
                NamedNodeMap nm = digestNode.getAttributes();
                if (nm == null)
                    throw new DownloadManifestException(
                            "Some parts in manifest don't have digest's verification algorithm");
                Element digest = manifestDoc.createElement("digest");
                digest.setAttribute("algorithm", nm.getNamedItem("algorithm").getTextContent());
                digest.appendChild(manifestDoc.createTextNode(digestNode.getTextContent()));
                aPart.appendChild(digest);
            }
            partsEl.appendChild(aPart);
        }
        root.appendChild(el);
        signatureSrc.append(nodeToString(el, false));
        String signatureData = signatureSrc.toString();
        Element signature = manifestDoc.createElement("signature");
        signature.setAttribute("algorithm", "RSA-SHA256");
        signature.appendChild(manifestDoc
                .createTextNode(Signatures.SHA256withRSA.trySign(Eucalyptus.class, signatureData.getBytes())));
        root.appendChild(signature);
        String downloadManifest = nodeToString(manifestDoc, true);
        // TODO: move this ?
        createManifestsBucketIfNeeded(s3Client);
        putManifestData(s3Client, DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName,
                downloadManifest, expiration);
        // generate pre-sign url for download manifest
        URL s = s3Client.generatePresignedUrl(DOWNLOAD_MANIFEST_BUCKET_NAME,
                DOWNLOAD_MANIFEST_PREFIX + manifestName, expiration, HttpMethod.GET);
        return String.format("%s://imaging@%s%s?%s", s.getProtocol(), s.getAuthority(), s.getPath(),
                s.getQuery());
    } catch (Exception ex) {
        LOG.error("Got an error", ex);
        throw new DownloadManifestException("Can't generate download manifest");
    } finally {
        if (s3Client != null)
            try {
                s3ClientsPool.returnObject(s3Client);
            } catch (Exception e) {
                // sad, but let's not break instances run
                LOG.warn("Could not return s3Client to the pool");
            }
    }
}

From source file:org.eclipse.lyo.testsuite.oslcv2.cm.ChangeRequestXmlTests.java

@Test
public void changeRequestHasAtMostOneClosedElement() throws XPathExpressionException {
    NodeList closedEles = (NodeList) OSLCUtils.getXPath()
            .evaluate("//oslc_cm_v2:ChangeRequest/" + "oslc_cm_v2:closed", doc, XPathConstants.NODESET);
    assertTrue(getFailureMessage(), closedEles.getLength() <= 1);
}

From source file:org.eclipse.lyo.testsuite.oslcv2.TestsBase.java

public static ArrayList<Node> getCapabilityDOMNodesUsingXML(String xpathStmt, ArrayList<String> serviceUrls)
        throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
    // Collection to contain the creationFactory urls from all SPs
    ArrayList<Node> data = new ArrayList<Node>();

    for (String base : serviceUrls) {
        HttpResponse resp = OSLCUtils.getResponseFromUrl(base, base, basicCreds, OSLCConstants.CT_XML, headers);

        Document baseDoc = OSLCUtils.createXMLDocFromResponseBody(EntityUtils.toString(resp.getEntity()));

        NodeList sDescs = (NodeList) OSLCUtils.getXPath().evaluate(xpathStmt, baseDoc, XPathConstants.NODESET);
        for (int i = 0; i < sDescs.getLength(); i++) {
            data.add(sDescs.item(i));//from   www  .  j ava2 s .  co  m
            if (onlyOnce)
                return data;
        }
    }
    return data;
}

From source file:eu.planets_project.tb.impl.services.EvaluationTestbedServiceTemplateImpl.java

/**
 * @param node a Node obtained by getAllEvalResultsRootNodes()
 * @return/*  w ww  .j a va  2 s.  com*/
 * @throws XPathExpressionException
 */
public NodeList getEvalResultMetricNodes(Node node) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList result = (NodeList) xpath.evaluate(sMetric, node, XPathConstants.NODESET);
    return result;
}

From source file:hudson.plugins.plot.XMLSeries.java

/**
 * Convert a given object into a String.
 * /* www  .  j a  va2  s .co  m*/
 * @param obj
 *            Xpath Object
 * @return String representation of the node
 */
private String nodeToString(Object obj) {
    String ret = null;

    if (nodeType == XPathConstants.BOOLEAN) {
        return (((Boolean) obj)) ? "1" : "0";
    }

    if (nodeType == XPathConstants.NUMBER)
        return ((Double) obj).toString().trim();

    if (nodeType == XPathConstants.NODE || nodeType == XPathConstants.NODESET) {
        if (obj instanceof String) {
            ret = ((String) obj).trim();
        } else {
            if (null == obj) {
                return null;
            }

            Node node = (Node) obj;
            NamedNodeMap nodeMap = node.getAttributes();

            if ((null != nodeMap) && (null != nodeMap.getNamedItem("time"))) {
                ret = nodeMap.getNamedItem("time").getTextContent();
            }

            if (null == ret) {
                ret = node.getTextContent().trim();
            }
        }
    }

    if (nodeType == XPathConstants.STRING)
        ret = ((String) obj).trim();

    // for Node/String/NodeSet, try and parse it as a double.
    // we don't store a double, so just throw away the result.
    Scanner scanner = new Scanner(ret);
    if (scanner.hasNextDouble()) {
        return String.valueOf(scanner.nextDouble());
    }
    return null;
}

From source file:org.eclipse.lyo.testsuite.server.oslcv1tests.ServiceProviderCatalogTests.java

@Test
public void serviceProvidersHaveValidTitles() throws XPathException {
    //Get all entries, parse out which have embedded ServiceProviders and check the titles
    NodeList entries = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_disc:entry/*", doc,
            XPathConstants.NODESET);
    for (int i = 0; i < entries.getLength(); i++) {
        Node provider = (Node) OSLCUtils.getXPath().evaluate(
                "//oslc_disc:entry[" + (i + 1) + "]/oslc_disc:ServiceProvider", doc, XPathConstants.NODE);
        //This entry has a catalog, check that it has a title
        if (provider != null) {
            Node pTitle = (Node) OSLCUtils.getXPath().evaluate(
                    "//oslc_disc:entry[" + (i + 1) + "]/oslc_disc:ServiceProvider/dc:title", doc,
                    XPathConstants.NODE);
            assertNotNull(pTitle);/*from w w w.  j  av  a 2 s .  com*/
            //Make sure the title isn't empty
            assertFalse(pTitle.getTextContent().isEmpty());
            Node child = (Node) OSLCUtils.getXPath().evaluate(
                    "//oslc_disc:entry[" + (i + 1) + "]/oslc_disc:ServiceProvider/dc:title/*", doc,
                    XPathConstants.NODE);
            //Make sure the title has no child elements
            assertTrue(child == null);
        }
    }
}

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

private Document replaceIfExistingByXPaths(final Document originalDom, final Document modifiedDom,
        Map<String, String> xPathPairs) throws XPathExpressionException {

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

    //Element modifiedDomRoot = (Element) modifiedDom.getFirstChild();

    Element lastChild = null;//from  www  . j  a v  a2 s  .c o m

    for (Entry<String, String> xPathPair : xPathPairs.entrySet()) {

        /**
         * basically, this is to copy the element specified in srcXPath, and
         * replace/add it to the position pointed by destXPath...
         */
        String srcXPath = xPathPair.getKey();

        logger.debug("srcXPath: " + srcXPath);

        String destXPath = xPathPair.getValue();

        logger.debug("destXPath: " + destXPath);

        XPath xPath = getXPathInstance();
        // find all the nodes specified by destXPath in the originalDom, and
        // delete them all
        NodeList existingNodeList = (NodeList) (xPath.evaluate(destXPath, finalDom, XPathConstants.NODESET));

        xPath.reset();
        // find all the nodes specified by srcXPath in the modifiedDom
        NodeList nodeList = (NodeList) (xPath.evaluate(srcXPath, modifiedDom, XPathConstants.NODESET));

        int el = existingNodeList.getLength();

        logger.debug("find '" + el + "' in originalDom using xPath: " + destXPath);

        int l = nodeList.getLength();

        logger.debug("find '" + l + "' in modifiedXml using xPath: " + srcXPath);

        for (int i = 0; i < el; i++) {
            Node c = existingNodeList.item(i);

            //xPathExpression = xPath.compile(srcXPath);
            //NodeList srcNodeLst = (NodeList) (xPathExpression.evaluate(
            //modifiedDom, XPathConstants.NODESET));
            //NodeList srcNodeLst = modifiedDomRoot.getElementsByTagName(c.getNodeName());

            if (l > 0) {
                // remove this node from its parent...

                c.getParentNode().removeChild(c);
                logger.debug("Node:" + c.getNodeName() + " is removed!");
            }

        }

        // create the node structure first. and return the last child of the
        // path... the right most node...
        lastChild = createElementStructureByPath(finalDomRoot, destXPath);

        List<String> nodeNameList = getNodeList(destXPath);

        String lastNodeName = nodeNameList.get(nodeNameList.size() - 1);

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

            // the name of the last node in srcXPath might not be the same
            // as the name of the last node in destXPath
            Element lastElement = finalDom.createElement(lastNodeName);

            // NodeList currentNodeChildNodes = currentNode.getChildNodes();
            // int s = currentNodeChildNodes.getLength();
            // for(int j = 0; j < s; j++){
            // lastElement.appendChild(finalDom.importNode(currentNodeChildNodes.item(j),
            // true));
            // }
            if (currentNode.hasAttributes()) {
                NamedNodeMap attributes = currentNode.getAttributes();

                for (int j = 0; j < attributes.getLength(); j++) {
                    String attribute_name = attributes.item(j).getNodeName();
                    String attribute_value = attributes.item(j).getNodeValue();

                    lastElement.setAttribute(attribute_name, attribute_value);
                }
            }

            while (currentNode.hasChildNodes()) {
                Node kid = currentNode.getFirstChild();
                currentNode.removeChild(kid);
                lastElement.appendChild(finalDom.importNode(kid, true));
            }

            lastChild.appendChild(lastElement);

        }

    }

    return finalDom;

}

From source file:edu.washington.shibboleth.attribute.resolver.dc.rws.impl.RwsDataConnector.java

/**
 * This queries the web service and return the resolved attributes.
 *
 * @param queryString <code>String</code> the queryString for the rest get
 * @return <code>List</code> of results
 * @throws ResolutionException if an error occurs performing the search
 *///  www  .  j  a va2s . c  o  m
protected Map<String, IdPAttribute> getRwsAttributes(String queryString) throws ResolutionException {
    try {
        String xml = httpDataSource.getResource(baseUrl + queryString);

        /** The parser needs to be synchronized **/
        Document doc = null;
        synchronized (this) {
            doc = documentBuilder.parse(new InputSource(new StringReader(xml)));
        }

        Map<String, IdPAttribute> attributes = new HashMap<String, IdPAttribute>();

        /* look for the requested attributes */
        for (int i = 0; i < rwsAttributes.size(); i++) {
            RwsAttribute attr = rwsAttributes.get(i);

            Object result = attr.xpathExpression.evaluate(doc, XPathConstants.NODESET);
            NodeList nodes = (NodeList) result;
            log.debug("got {} matches to the xpath for {}", nodes.getLength(), attr.name);

            List<String> results = new Vector<String>();
            if (nodes.getLength() == 0 && attr.noResultIsError) {
                log.error("got no attributes for {}, which required attriubtes", attr.name);
                throw new ResolutionException("no attributes for " + attr.name);
            }
            for (int j = 0; j < nodes.getLength(); j++) {
                if (maxResults > 0 && maxResults < j) {
                    log.error("too many results for {}", attr.name);
                    break;
                }
                results.add((String) nodes.item(j).getTextContent());
            }
            addIdPAttributes(attributes, attr.name, results);
        }
        return attributes;

    } catch (IOException e) {
        log.error("rws io exception: " + e);
        throw new ResolutionException("rws resolver io error: " + e.getMessage());
    } catch (SAXException e) {
        log.error("rws sax exception: " + e);
        throw new ResolutionException("rws resolver parse error: " + e.getMessage());
    } catch (IllegalArgumentException e) {
        log.error("rws arg exception: " + e);
        throw new ResolutionException(e.getMessage());
    } catch (XPathExpressionException e) {
        log.error("rws xpath exception: " + e);
        throw new ResolutionException(e.getMessage());
    }

}