Example usage for javax.xml.xpath XPathFactory newXPath

List of usage examples for javax.xml.xpath XPathFactory newXPath

Introduction

In this page you can find the example usage for javax.xml.xpath XPathFactory newXPath.

Prototype

public abstract XPath newXPath();

Source Link

Document

Return a new XPath using the underlying object model determined when the XPathFactory was instantiated.

Usage

From source file:io.fabric8.forge.ipaas.repository.NexusConnectionRepository.java

protected void indexNexus() throws Exception {
    // must have q parameter so use connector to find all connectors
    String query = nexusUrl + "?q=connector";
    URL url = new URL(query);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from w w w  .ja v a 2 s.c om*/
    factory.setIgnoringElementContentWhitespace(true);
    factory.setIgnoringComments(true);

    DocumentBuilder documentBuilder = factory.newDocumentBuilder();

    InputStream is = url.openStream();
    Document dom = documentBuilder.parse(is);

    XPathFactory xpFactory = XPathFactory.newInstance();
    XPath exp = xpFactory.newXPath();
    NodeList list = (NodeList) exp.evaluate("//classifier[text() = '" + CLASSIFIER + "']", dom,
            XPathConstants.NODESET);

    Set<NexusArtifactDto> newArtifacts = new LinkedHashSet<>();
    for (int i = 0; i < list.getLength(); i++) {
        Node node = list.item(i);
        Node parent = node.getParentNode();

        String g = getNodeText(parent.getChildNodes(), "groupId");
        String a = getNodeText(parent.getChildNodes(), "artifactId");
        String v = getNodeText(parent.getChildNodes(), "version");
        String l = getNodeText(parent.getChildNodes(), "artifactLink");

        if (g != null & a != null & v != null & l != null) {
            NexusArtifactDto dto = new NexusArtifactDto();
            dto.setGroupId(g);
            dto.setArtifactId(a);
            dto.setVersion(v);
            dto.setArtifactLink(l);

            System.out.println("Found connector: " + dto.getGroupId() + ":" + dto.getArtifactId() + ":"
                    + dto.getVersion());

            // is it a new artifact
            boolean newArtifact = true;
            for (NexusArtifactDto existing : indexedArtifacts) {
                if (existing.getGroupId().equals(dto.getGroupId())
                        && existing.getArtifactId().equals(dto.getArtifactId())
                        && existing.getVersion().equals(dto.getVersion())) {
                    newArtifact = false;
                    break;
                }
            }
            if (newArtifact) {
                newArtifacts.add(dto);
            }
        }
    }

    // now download the new artifact JARs and look inside to find more details
    for (NexusArtifactDto dto : newArtifacts) {
        try {
            // download using url classloader reader
            URL jarUrl = new URL(dto.getArtifactLink());
            String json = loadCamelConnectorJSonSchema(jarUrl);

            ObjectMapper mapper = new ObjectMapper();
            ConnectionCatalogDto cat = mapper.readerFor(ConnectionCatalogDto.class).readValue(json);

            indexedArtifacts.add(dto);
            connectors.putIfAbsent(dto, cat);
            System.out.println("Added connector: " + dto.getGroupId() + ":" + dto.getArtifactId() + ":"
                    + dto.getVersion());
        } catch (Exception e) {
            System.err.println("Error downloading connector JAR " + dto.getArtifactLink()
                    + ". This exception is ignored. " + e.getMessage());
        }
    }

    IOHelpers.close(is);
}

From source file:eu.esdihumboldt.hale.io.wfs.AbstractWFSWriter.java

@Override
public IOReport execute(ProgressIndicator progress) throws IOProviderConfigurationException, IOException {
    progress.begin("WFS Transaction", ProgressIndicator.UNKNOWN);

    // configure internal provider
    internalProvider.setDocumentWrapper(createTransaction());

    final PipedInputStream pIn = new PipedInputStream();
    PipedOutputStream pOut = new PipedOutputStream(pIn);
    currentExecuteStream = pOut;/*from   w ww. ja  v a 2s  . co m*/

    Future<Response> futureResponse = null;
    IOReporter reporter = createReporter();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    try {
        // read the stream (in another thread)
        futureResponse = executor.submit(new Callable<Response>() {

            @Override
            public Response call() throws Exception {

                Proxy proxy = ProxyUtil.findProxy(targetWfs.getLocation());
                Request request = Request.Post(targetWfs.getLocation()).bodyStream(pIn,
                        ContentType.APPLICATION_XML);
                Executor executor = FluentProxyUtil.setProxy(request, proxy);

                // authentication
                String user = getParameter(PARAM_USER).as(String.class);
                String password = getParameter(PARAM_PASSWORD).as(String.class);

                if (user != null) {
                    // target host
                    int port = targetWfs.getLocation().getPort();
                    String hostName = targetWfs.getLocation().getHost();
                    String scheme = targetWfs.getLocation().getScheme();
                    HttpHost host = new HttpHost(hostName, port, scheme);

                    // add credentials
                    Credentials cred = ClientProxyUtil.createCredentials(user, password);
                    executor.auth(new AuthScope(host), cred);
                    executor.authPreemptive(host);
                }

                try {
                    return executor.execute(request);
                } finally {
                    pIn.close();
                }
            }
        });

        // write the stream
        SubtaskProgressIndicator subprogress = new SubtaskProgressIndicator(progress);
        reporter = (IOReporter) super.execute(subprogress);
    } finally {
        executor.shutdown();
    }

    try {
        Response response = futureResponse.get();
        HttpResponse res = response.returnResponse();
        int statusCode = res.getStatusLine().getStatusCode();
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        if (statusCode >= 200 && statusCode < 300) {
            // success
            reporter.setSuccess(reporter.isSuccess());

            // construct summary from response
            try {
                Document responseDoc = parseResponse(res.getEntity());

                // totalInserted
                String inserted = xpath.compile("//TransactionSummary/totalInserted").evaluate(responseDoc);
                // XXX totalUpdated
                // XXX totalReplaced
                // XXX totalDeleted
                reporter.setSummary("Inserted " + inserted + " features.");
            } catch (XPathExpressionException e) {
                log.error("Error in XPath used to evaluate service response");
            } catch (ParserConfigurationException | SAXException e) {
                reporter.error(new IOMessageImpl(MessageFormat.format(
                        "Server returned status code {0}, but could not parse server response", statusCode),
                        e));
                reporter.setSuccess(false);
            }
        } else {
            // failure
            reporter.error(
                    new IOMessageImpl("Server reported failure with code " + res.getStatusLine().getStatusCode()
                            + ": " + res.getStatusLine().getReasonPhrase(), null));
            reporter.setSuccess(false);

            try {
                Document responseDoc = parseResponse(res.getEntity());
                String errorText = xpath.compile("//ExceptionText/text()").evaluate(responseDoc);
                reporter.setSummary("Request failed: " + errorText);
            } catch (XPathExpressionException e) {
                log.error("Error in XPath used to evaluate service response");
            } catch (ParserConfigurationException | SAXException e) {
                reporter.error(new IOMessageImpl("Could not parse server response", e));
                reporter.setSuccess(false);
            }
        }
    } catch (ExecutionException | InterruptedException e) {
        reporter.error(new IOMessageImpl("Failed to execute WFS-T request", e));
        reporter.setSuccess(false);
    }

    progress.end();

    return reporter;
}

From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.spec.DuplicateGerritListenersPreloadedProjectHudsonTestCase.java

/**
 * Evaluates the xpath expression on the document and returns the node it resolves to.
 *
 * @param doc        the doc to search//from  w  w  w. j ava 2  s.c  o m
 * @param expression the xpath expression
 * @return the node
 * @throws XPathExpressionException if so.
 */
Node xPath(Document doc, String expression) throws XPathExpressionException {
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile(expression);
    return (Node) expr.evaluate(doc, XPathConstants.NODE);
}

From source file:org.ala.harvester.PpmlHarvester.java

private int getCount(Document currentResDom, String xpathToCount) throws Exception {
    int resultNum = 0;

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    resultNum = Integer.valueOf((String) xpath.evaluate(xpathToCount, currentResDom, XPathConstants.STRING));

    return resultNum;
}

From source file:ch.dbs.actions.bestellung.EZBVascoda.java

/**
 * This class uses the EZB API from//  w  w  w. j  av  a 2  s .c  o m
 * http://ezb.uni-regensburg.de/ezeit/vascoda/openURL?pid=format%3Dxml. This
 * API differs from the EZB/ZDB API (http://services.dnb.de). It brings back
 * no print information and other information for electronic holdings. It
 * seems to be more stable.
 */
public EZBForm read(final String content) {

    final EZBForm ezbform = new EZBForm();

    try {

        if (content != null) {

            final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(true);
            final DocumentBuilder builder = domFactory.newDocumentBuilder();
            final Document doc = builder.parse(new InputSource(new StringReader(content)));

            final XPathFactory factory = XPathFactory.newInstance();
            final XPath xpath = factory.newXPath();

            // issns
            final XPathExpression exprRefE = xpath.compile("//OpenURLResponse");
            final NodeList resultListRefE = (NodeList) exprRefE.evaluate(doc, XPathConstants.NODESET);

            String title = null;
            String levelAvailable = null;

            for (int i = 0; i < resultListRefE.getLength(); i++) {
                final Node firstResultNode = resultListRefE.item(i);
                final Element result = (Element) firstResultNode;

                // First ISSN
                //                    final String issn = getValue(result.getElementsByTagName("issn"));
                //                    System.out.println(issn);

                // title
                // unfortunately this will bring back the title sent by OpenURL, unless if not
                // specified in the OpenURL request. It then brings back the title form the EZB...!
                title = getValue(result.getElementsByTagName("title"));
                if (title != null) {
                    title = Jsoup.clean(title, Whitelist.none());
                    title = Jsoup.parse(title).text();
                }

                // this is the overall level of the best match and not the level of each individual result
                final NodeList levelNode = result.getElementsByTagName("available");
                final Element levelElement = (Element) levelNode.item(0);
                if (levelElement != null) {
                    levelAvailable = levelElement.getAttribute("level");
                }

            }

            // electronic data
            final XPathExpression exprE = xpath.compile("//OpenURLResponse/OpenURLResult/Resultlist/Result");
            final NodeList resultListE = (NodeList) exprE.evaluate(doc, XPathConstants.NODESET);

            for (int i = 0; i < resultListE.getLength(); i++) {
                final Node firstResultNode = resultListE.item(i);
                final Element result = (Element) firstResultNode;

                final NodeList state = result.getElementsByTagName("access");
                final Element stateElement = (Element) state.item(0);
                int color = 0;
                if (stateElement != null) {
                    color = Integer.valueOf(stateElement.getAttribute("color"));
                }

                final EZBDataOnline online = new EZBDataOnline();

                // state
                // 1 free accessible
                if (color == EZBState.FREE.getValue()) {
                    online.setAmpel("green");
                    online.setComment("availresult.free");
                    online.setState(JOPState.FREE.getValue()); // translate state to EZB/ZDB-API
                    // 2 licensed ; 3 partially licensed
                } else if (color == EZBState.LICENSED.getValue()
                        || color == EZBState.LICENSED_PARTIALLY.getValue()) {
                    online.setAmpel("yellow");
                    online.setComment("availresult.abonniert");
                    online.setState(JOPState.LICENSED.getValue()); // translate state to EZB/ZDB-API
                    // not licensed
                } else if (color == EZBState.NOT_LICENSED.getValue()) {
                    online.setAmpel("red");
                    online.setComment("availresult.not_licensed");
                    online.setState(JOPState.NOT_LICENSED.getValue()); // translate state to EZB/ZDB-API
                } else {
                    online.setAmpel("red");
                    online.setComment("availresult.not_licensed");
                    online.setState(JOPState.NOT_LICENSED.getValue()); // translate state to EZB/ZDB-API
                }

                // LinkToArticle not always present
                String url = getValue(result.getElementsByTagName("LinkToArticle"));
                // LinkToJournal always present
                if (url == null) {
                    url = getValue(result.getElementsByTagName("LinkToJournal"));
                }
                online.setUrl(url);

                // try to get level from link
                String levelLinkToArticle = null;
                final NodeList levelNode = result.getElementsByTagName("LinkToArticle");
                final Element levelElement = (Element) levelNode.item(0);
                if (levelElement != null) {
                    levelLinkToArticle = levelElement.getAttribute("level");
                }

                if (levelLinkToArticle != null) {
                    online.setLevel(levelLinkToArticle); // specific level of each result
                } else {
                    online.setLevel(levelAvailable); // overall level of best match
                }

                if (title != null) {
                    online.setTitle(title);
                } else {
                    online.setTitle(url);
                }
                online.setReadme(getValue(result.getElementsByTagName("LinkToReadme")));

                ezbform.getOnline().add(online);
            }

            // Title not found
            if (resultListE.getLength() == 0) {
                final EZBDataOnline online = new EZBDataOnline();
                online.setAmpel("red");
                online.setComment("availresult.nohits");
                online.setState(JOPState.NO_HITS.getValue()); // translate state to EZB/ZDB-API

                ezbform.getOnline().add(online);
            }

        }

    } catch (final XPathExpressionException e) {
        LOG.error(e.toString());
    } catch (final SAXParseException e) {
        LOG.error(e.toString());
    } catch (final SAXException e) {
        LOG.error(e.toString());
    } catch (final IOException e) {
        LOG.error(e.toString());
    } catch (final ParserConfigurationException e) {
        LOG.error(e.toString());
    } catch (final Exception e) {
        LOG.error(e.toString());
    }

    return ezbform;
}

From source file:ch.dbs.actions.bestellung.EZBXML.java

public List<JournalDetails> searchByJourids(final List<String> jourids, final String bibid) {

    final List<JournalDetails> list = new ArrayList<JournalDetails>();
    final Http http = new Http();

    final StringBuffer link = new StringBuffer(
            "http://rzblx1.uni-regensburg.de/ezeit/detail.phtml?xmloutput=1&colors=7&lang=de&bibid=");
    link.append(bibid);/* ww w  .  j  a va 2s .  c  om*/
    link.append("&jour_id=");

    final StringBuffer infoLink = new StringBuffer(
            "http://ezb.uni-regensburg.de/ezeit/detail.phtml?colors=7&lang=de&bibid=");
    infoLink.append(bibid);
    infoLink.append("&jour_id=");

    try {

        for (final String jourid : jourids) {

            final JournalDetails jd = new JournalDetails();

            final String content = http.getContent(link.toString() + jourid, Connect.TIMEOUT_1.getValue(),
                    Connect.TRIES_1.getValue(), null);

            if (content != null) {

                final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
                domFactory.setNamespaceAware(true);
                final DocumentBuilder builder = domFactory.newDocumentBuilder();
                final Document doc = builder.parse(new InputSource(new StringReader(content)));

                final XPathFactory factory = XPathFactory.newInstance();
                final XPath xpath = factory.newXPath();

                final XPathExpression exprJournal = xpath.compile("//journal");
                final XPathExpression exprPissns = xpath.compile("//journal/detail/P_ISSNs");
                final XPathExpression exprEissns = xpath.compile("//journal/detail/E_ISSNs");
                final NodeList resultJournal = (NodeList) exprJournal.evaluate(doc, XPathConstants.NODESET);

                for (int i = 0; i < resultJournal.getLength(); i++) {
                    final Node firstResultNode = resultJournal.item(i);
                    final Element journal = (Element) firstResultNode;

                    // Title
                    String title = getValue(journal.getElementsByTagName("title"));
                    if (title != null) {
                        title = Jsoup.clean(title, Whitelist.none());
                        title = Jsoup.parse(title).text();
                    }

                    jd.setZeitschriftentitel(title);

                    // P-ISSNs
                    final NodeList resultPissns = (NodeList) exprPissns.evaluate(doc, XPathConstants.NODESET);

                    // get first pissn
                    for (int z = 0; z < resultPissns.getLength(); z++) {
                        final Node firstPissnsNode = resultPissns.item(i);
                        final Element pissnElement = (Element) firstPissnsNode;
                        final String pissn = getValue(pissnElement.getElementsByTagName("P_ISSN"));
                        jd.setIssn(pissn);
                    }

                    // try to get Eissn if we have no Pissn
                    if (jd.getIssn() == null) {

                        // E-ISSNs
                        final NodeList resultEissns = (NodeList) exprEissns.evaluate(doc,
                                XPathConstants.NODESET);

                        // get first eissn
                        for (int z = 0; z < resultEissns.getLength(); z++) {
                            final Node firstEissnsNode = resultEissns.item(i);
                            final Element eissnElement = (Element) firstEissnsNode;
                            final String eissn = getValue(eissnElement.getElementsByTagName("E_ISSN"));
                            jd.setIssn(eissn);
                        }
                    }

                    // add info link
                    jd.setLink(infoLink.toString() + jourid);

                    list.add(jd);
                }
            }
        }

    } catch (final XPathExpressionException e) {
        LOG.error(e.toString());
    } catch (final SAXParseException e) {
        LOG.error(e.toString());
    } catch (final SAXException e) {
        LOG.error(e.toString());
    } catch (final IOException e) {
        LOG.error(e.toString());
    } catch (final ParserConfigurationException e) {
        LOG.error(e.toString());
    } catch (final Exception e) {
        LOG.error(e.toString());
    }

    return list;
}

From source file:be.fgov.kszbcss.rhq.websphere.component.server.WebSphereServerDiscoveryComponent.java

public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<ResourceComponent<?>> context)
        throws InvalidPluginConfigurationException, Exception {
    Set<DiscoveredResourceDetails> result = new HashSet<DiscoveredResourceDetails>();
    for (ProcessScanResult process : context.getAutoDiscoveredProcesses()) {
        ProcessInfo processInfo = process.getProcessInfo();
        String[] commandLine = processInfo.getCommandLine();
        if (log.isDebugEnabled()) {
            log.debug("Examining process " + processInfo.getPid());
            log.debug("Command line: " + Arrays.asList(commandLine));
        }//from w  ww.ja v  a2s  .c om
        int appOptionIndex = -1; // The index of the -application option
        for (int i = 0; i < commandLine.length; i++) {
            if (commandLine[i].equals("-application")) {
                appOptionIndex = i;
                break;
            }
        }
        if (appOptionIndex == -1) {
            log.debug("No -application option found");
            continue;
        }
        if (commandLine.length - appOptionIndex != 7) {
            if (log.isDebugEnabled()) {
                log.debug("Unexpected number of arguments (" + (commandLine.length - appOptionIndex)
                        + ") after -application");
            }
            continue;
        }
        if (!commandLine[appOptionIndex + 1].equals("com.ibm.ws.bootstrap.WSLauncher")) {
            log.debug("Expected com.ibm.ws.bootstrap.WSLauncher after -application");
            continue;
        }
        if (!commandLine[appOptionIndex + 2].equals("com.ibm.ws.runtime.WsServer")) {
            if (log.isDebugEnabled()) {
                log.debug("Process doesn't appear to be a WebSphere server process; main class is "
                        + commandLine[appOptionIndex + 2]);
            }
            continue;
        }
        File repository = new File(commandLine[appOptionIndex + 3]);
        String cell = commandLine[appOptionIndex + 4];
        String node = commandLine[appOptionIndex + 5];
        String processName = commandLine[appOptionIndex + 6];
        if (processName.equals("nodeagent")) {
            log.debug("Process appears to be a node agent");
            continue;
        }
        if (processName.equals("dmgr")) {
            log.debug("Process appears to be a deployment manager");
            continue;
        }
        log.info("Discovered WebSphere application server process " + cell + "/" + node + "/" + processName);
        if (!repository.exists()) {
            log.error("Configuration repository " + repository + " doesn't exist");
            continue;
        }
        if (!repository.canRead()) {
            log.error("Configuration repository " + repository + " not readable");
            continue;
        }

        // Parse the serverindex.xml file for the node
        File serverIndexFile = new File(repository, "cells" + File.separator + cell + File.separator + "nodes"
                + File.separator + node + File.separator + "serverindex.xml");
        if (log.isDebugEnabled()) {
            log.debug("Attempting to read " + serverIndexFile);
        }
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder builder = dbf.newDocumentBuilder();
        Document serverIndex;
        try {
            serverIndex = builder.parse(serverIndexFile);
        } catch (Exception ex) {
            log.error("Unable to parse " + serverIndexFile, ex);
            continue;
        }

        // Extract the port number
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        SimpleNamespaceContext nsContext = new SimpleNamespaceContext();
        nsContext.setPrefix("serverindex",
                "http://www.ibm.com/websphere/appserver/schemas/5.0/serverindex.xmi");
        xpath.setNamespaceContext(nsContext);
        int port = -1;
        String protocol = null;
        for (PortSpec portSpec : portSpecs) {
            if (log.isDebugEnabled()) {
                log.debug("Attempting to extract " + portSpec.getEndPointName());
            }
            String portString = (String) xpath.evaluate("/serverindex:ServerIndex/serverEntries[@serverName='"
                    + processName + "']/specialEndpoints[@endPointName='" + portSpec.getEndPointName()
                    + "']/endPoint/@port", serverIndex, XPathConstants.STRING);
            if (portString == null || portString.length() == 0) {
                log.debug(portSpec.getEndPointName() + " not found");
                continue;
            }
            int candidatePort;
            try {
                candidatePort = Integer.parseInt(portString);
            } catch (NumberFormatException ex) {
                log.warn("Found non numerical port number in " + serverIndexFile);
                continue;
            }
            if (log.isDebugEnabled()) {
                log.debug("Port is " + candidatePort);
            }
            if (candidatePort != 0) {
                if (log.isDebugEnabled()) {
                    log.debug("Using " + portSpec.getEndPointName() + "=" + candidatePort + ", protocol "
                            + portSpec.getProtocol());
                }
                port = candidatePort;
                protocol = portSpec.getProtocol();
                break;
            }
        }
        if (port == -1) {
            log.error("Unable to locate usable port in " + serverIndexFile);
            continue;
        }

        // Check if this is a managed server by looking for WebSphere instances of type NODE_AGENT
        boolean unmanaged = ((NodeList) xpath.evaluate(
                "/serverindex:ServerIndex/serverEntries[@serverType='NODE_AGENT']", serverIndex,
                XPathConstants.NODESET)).getLength() == 0;

        Configuration conf = new Configuration();
        conf.put(new PropertySimple("host", "localhost"));
        conf.put(new PropertySimple("port", port));
        conf.put(new PropertySimple("protocol", protocol));
        conf.put(new PropertySimple("loggingProvider", "none")); // TODO: autodetect XM4WAS
        conf.put(new PropertySimple("childJmxServerName", "JVM"));
        conf.put(new PropertySimple("unmanaged", unmanaged));
        result.add(new DiscoveredResourceDetails(context.getResourceType(),
                cell + "/" + node + "/" + processName, processName, null,
                processName + " (cell " + cell + ", node " + node + ")", conf, processInfo));
    }
    return result;
}

From source file:com.laex.j2objc.AntDelegate.java

/**
 * Append exclude pattern to xml.//from   w  w  w  .  ja v a 2  s  .  c  o  m
 * 
 * @param path
 *            the path
 * @param pats
 *            the pats
 * @throws ParserConfigurationException
 *             the parser configuration exception
 * @throws SAXException
 *             the SAX exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws XPathExpressionException
 *             the x path expression exception
 * @throws CoreException
 *             the core exception
 * @throws TransformerException
 *             the transformer exception
 */
private void appendExcludePatternToXML(IFile path, String[] pats) throws ParserConfigurationException,
        SAXException, IOException, XPathExpressionException, CoreException, TransformerException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document dom = builder.parse(path.getContents());

    XPathFactory xpathfactory = XPathFactory.newInstance();
    XPath xpath = xpathfactory.newXPath();
    XPathExpression expr = xpath.compile("project/target/move/fileset");

    Node node = (Node) expr.evaluate(dom, XPathConstants.NODE);
    NodeList children = node.getChildNodes();

    // don't why the last node in the xml should be indexed by length - 2
    Node excludeCopy = children.item(children.getLength() - 2).cloneNode(true);
    for (String pattern : pats) {
        if (StringUtils.isNotEmpty(pattern.trim())) {
            Node newnode = excludeCopy.cloneNode(true);
            newnode.getAttributes().getNamedItem("name").setNodeValue(pattern);
            node.appendChild(newnode);
        }
    }

    // Setup transformers
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    StringWriter sw = new StringWriter();
    transformer.transform(new DOMSource(dom), new StreamResult(sw));
    String output = sw.getBuffer().toString();

    // save the ouput
    ByteArrayInputStream bis = new ByteArrayInputStream(output.getBytes("utf-8"));
    path.setContents(bis, 0, null);
}