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:pl.psnc.synat.wrdz.zmkd.format.UdfrSparqlEndpointAccessBean.java

/**
 * Retrieves the nodes from the given document using the given XPath path.
 * /*from w  w  w.  j  av a 2  s .  com*/
 * @param document
 *            the document to retrieve the nodes from
 * @param path
 *            XPath
 * @return list of matching nodes
 */
private NodeList xpath(Document document, String path) {
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(new NamespaceContextImpl(NS_PREFIX, NS_URI));

    try {
        return (NodeList) xpath.evaluate(path, document, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new WrdzRuntimeException("Incorrect XPath expression", e);
    }
}

From source file:com.amalto.core.util.Util.java

private static String[] getTextNodes(Node contextNode, String xPath, final Node namespaceNode)
        throws TransformerException {
    String[] results;// w  w  w  .  j  a v a 2 s  .c  o  m
    // test for hard-coded values
    if (xPath.startsWith("\"") && xPath.endsWith("\"")) { //$NON-NLS-1$ //$NON-NLS-2$
        return new String[] { xPath.substring(1, xPath.length() - 1) };
    }
    // test for incomplete path (elements missing /text())
    if (!xPath.matches(".*@[^/\\]]+")) { // attribute
        if (!xPath.endsWith(")")) { // function
            xPath += "/text()";
        }
    }
    try {
        XPath path = XPathFactory.newInstance().newXPath();
        path.setNamespaceContext(new NamespaceContext() {

            @Override
            public String getNamespaceURI(String s) {
                return namespaceNode.getNamespaceURI();
            }

            @Override
            public String getPrefix(String s) {
                return namespaceNode.getPrefix();
            }

            @Override
            public Iterator getPrefixes(String s) {
                return Collections.singleton(namespaceNode.getPrefix()).iterator();
            }
        });
        NodeList xo = (NodeList) path.evaluate(xPath, contextNode, XPathConstants.NODESET);
        results = new String[xo.getLength()];
        for (int i = 0; i < xo.getLength(); i++) {
            results[i] = xo.item(i).getTextContent();
        }
    } catch (Exception e) {
        String err = "Unable to get the text node(s) of " + xPath + ": " + e.getClass().getName() + ": "
                + e.getLocalizedMessage();
        throw new TransformerException(err);
    }
    return results;

}

From source file:com.tibco.businessworks6.sonar.plugin.source.XmlSource.java

/**
 * Return hard coded violations of all elements related to the xPathQuery evaluated on the input context
 * /*from  w w  w  .  j  a  v a  2 s.com*/
 * @param rule         violated {@link Rule}
 * @param context      input context {@link Node}
 * @param xPathQuery    XPath query {@link String}
 * @param message      violations message {@link String}
 * 
 * @return List<Violation>
 */
public List<Violation> getViolationsHardCodedXPath(Rule rule, Node context, String xPathQuery, String message) {
    // Init violation 
    List<Violation> violations = new ArrayList<Violation>();
    try {
        XPath xpath = XPathFactory.newInstance().newXPath();
        NodeList nodesFound = (NodeList) xpath.evaluate(xPathQuery, context, XPathConstants.NODESET);
        int length = nodesFound.getLength();
        for (int i = 0; i < length; i++) {
            Node nodeFound = nodesFound.item(i);
            violations.addAll(
                    getViolationsHardCodedNode(rule, nodeFound, message + " (" + i + "/" + length + ")"));
        }
    } catch (Exception e) {
        LOGGER.error("context", e);
        violations.add(new DefaultViolation(rule, getLineForNode(context), message + " (not found)"));
    }
    return violations;
}

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

@Test
public void CoreResourceHasAtMostOneDiscussion() throws XPathExpressionException {
    String eval = "//" + getNode() + "/" + "oslc:discussion";

    NodeList discussions = (NodeList) OSLCUtils.getXPath().evaluate(eval, doc, XPathConstants.NODESET);
    assertTrue(getFailureMessage(), discussions.getLength() <= 1);
}

From source file:com.epam.catgenome.manager.externaldb.ncbi.parser.NCBIGeneInfoParser.java

/**
 * Method parsing NCBI xml gene information
 *
 * @param xml -- input string with xml content from NCBI db
 * @return NCBIGeneVO//  www  . j  a  va2s .c  o m
 */
public NCBIGeneVO parseGeneInfo(String xml) throws ExternalDbUnavailableException {

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    NCBIGeneVO ncbiGeneVO = new NCBIGeneVO();

    try {

        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(xml));
        Document document = builder.parse(is);
        ncbiGeneVO.setGeneId(xPath.compile(ID_XPATH).evaluate(document));
        ncbiGeneVO.setOrganismScientific(xPath.compile(ORGANISM_XPATH + "/Org-ref_taxname").evaluate(document));
        ncbiGeneVO.setOrganismCommon(xPath.compile(ORGANISM_XPATH + "/Org-ref_common").evaluate(document));
        ncbiGeneVO.setPrimarySource(xPath.compile(PRIMARY_SOURCE_XPATH).evaluate(document));
        ncbiGeneVO.setPrimarySourcePrefix(xPath.compile(PRIMARY_SOURCE_PREFIX_XPATH).evaluate(document));
        ncbiGeneVO.setGeneType(xPath.compile(ENTREZ_GENE_TYPE_XPATH).evaluate(document));
        ncbiGeneVO.setRefSeqStatus(xPath.compile(REFSEQ_STATUS_XPATH).evaluate(document));
        ncbiGeneVO.setGeneSummary(xPath.compile(ENTREZ_GENE_SUMMARY_XPATH).evaluate(document));

        ncbiGeneVO.setOfficialSymbol(xPath.compile(OFFICIAL_SYMBOL_XPATH).evaluate(document));
        ncbiGeneVO.setOfficialFullName(xPath.compile(OFFICIAL_FULL_NAME_XPATH).evaluate(document));
        ncbiGeneVO.setLocusTag(xPath.compile(LOCUS_TAG_XPATH).evaluate(document));
        ncbiGeneVO.setLineage(xPath.compile(LINEAGE_XPATH).evaluate(document));
        ncbiGeneVO.setRnaName(xPath.compile(RNA_NAME_XPATH).evaluate(document));

        NodeList alsoKnown = (NodeList) xPath.compile(ALSO_KNOWN_AS_XPATH).evaluate(document,
                XPathConstants.NODESET);
        List<String> alsoKnownList = new ArrayList<>(alsoKnown.getLength());
        fillGeneAlsoKnownList(alsoKnown, alsoKnownList);
        ncbiGeneVO.setAlsoKnownAs(alsoKnownList);

        NodeList interactionsNodesList = (NodeList) xPath.compile(INTERACTIONS_XPATH).evaluate(document,
                XPathConstants.NODESET);

        List<NCBIGeneVO.NCBIGeneInteractionVO> geneInteractionsList = new ArrayList<>(
                interactionsNodesList.getLength());

        fillGeneInteractionsList(interactionsNodesList, geneInteractionsList);

        ncbiGeneVO.setInteractions(geneInteractionsList);

    } catch (ParserConfigurationException | SAXException | XPathExpressionException e) {
        LOG.error(PARSING_EXCEPTION_HAPPENED, e);
    } catch (IOException e) {
        throw new ExternalDbUnavailableException(getMessage(MessagesConstants.ERROR_NO_RESULT_BY_EXTERNAL_DB),
                e);
    }

    return ncbiGeneVO;
}

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

@Test
public void changeRequestHasAtMostOneDiscussion() throws XPathExpressionException {
    NodeList discussions = (NodeList) OSLCUtils.getXPath()
            .evaluate("//oslc_cm_v2:ChangeRequest/oslc:discussion", doc, XPathConstants.NODESET);
    assertTrue(getFailureMessage(), discussions.getLength() <= 1);
}

From source file:eu.domibus.ebms3.sender.ReliabilityChecker.java

private NodeList getNonRepudiationNodeList(Node securityInfo) throws EbMS3Exception {
    NodeList nodes = null;//from www. j  a  v  a 2 s.com
    try {
        nodes = (NodeList) ReliabilityChecker.xPath.evaluate(ReliabilityChecker.XPATH_EXPRESSION_STRING,
                securityInfo, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        assert false;
        // due to the fact that we use a static expression this can never occur.
        throw new RuntimeException(e);
    }

    if (nodes == null) {
        throw new EbMS3Exception(EbMS3Exception.EbMS3ErrorCode.EBMS_0302,
                "No Reference Data found in either security header or nonrepudiationinformation", null,
                MSHRole.SENDING);
    }

    return nodes;
}

From source file:com.redhat.plugin.eap6.EAP6DeploymentStructureMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    initializeDictionaries();//w w w . j a  va  2  s.c  o m
    // Are we to generate the file?
    if (generate) {

        // First gather any subdeployments
        if (subDeployments != null) {
            getLog().info("Sub deployments:" + subDeployments);
            for (SubDeployment sd : subDeployments) {
                Artifact artifact = findArtifact(sd.getGroupId(), sd.getArtifactId());
                if (artifact == null)
                    throw new MojoExecutionException("Cannot find file for artifact " + sd);
                getLog().debug("Sub deployment artifact:" + artifact + " file:" + artifact.getFile());
                try {
                    final File artifactFile = artifact.getFile();
                    if (artifactFile != null) {
                        sd.setName(artifactFile.getName());
                        if (artifactFile.canRead()) {
                            Document doc = getDeploymentStructure(artifactFile);
                            if (doc == null)
                                throw new MojoExecutionException("No deployment structure in " + artifact
                                        + ", add eap6 plugin to that project to generate deployment structure");
                            sd.setDocument(doc);
                        } else {
                            getLog().warn(
                                    "Can not read artifact-file <" + artifactFile.getAbsolutePath() + ">");
                        }
                    } else {
                        getLog().warn(
                                "Can not resolve artifact-file for artifact <" + artifact.toString() + ">");
                    }
                } catch (Exception e) {
                    throw new MojoExecutionException(e.toString());
                }
            }
        }

        // Is there a skeleton file?
        Document doc = initializeSkeletonFile(JBOSS_DEPLOYMENT_STRUCTURE);

        try {
            buildDeploymentStructure(doc, artifactsAsModules, subDeployments);

            // Check if there are any modules that are possibly unnecessary
            NodeList nl = (NodeList) xp_module.evaluate(doc, XPathConstants.NODESET);
            int n = nl.getLength();
            printNodeList(nl);
            for (int i = 0; i < n; i++) {
                String mname = ((Element) nl.item(i)).getAttribute("name");
                // If this module is not in dependencies, warn
                Artifact a = reverseMap.get(mname);
                if (a == null)
                    getLog().warn("No dependencies to module " + mname);
                else {
                    if (!a.getScope().equals(Artifact.SCOPE_PROVIDED))
                        getLog().warn("Module does not appear with provided scope in POM:" + mname);
                }
            }
            NodeList nlSub = (NodeList) xp_subdeployment.evaluate(doc, XPathConstants.NODESET);
            printNodeList(nlSub);
            int nSub = nlSub.getLength();
            for (int i = 0; i < nSub; i++) {
                String subDepl = ((Element) nlSub.item(i)).getTagName();// Attribute("name");
                getLog().debug(subDepl);
                NodeList nlSubModules = (NodeList) xp_subdeployment_module.evaluate(doc,
                        XPathConstants.NODESET);
                printNodeList(nlSubModules);
            }

        } catch (Exception e) {
            throw new MojoFailureException("Cannot process XML", e);
        }

        if (destinationDir == null) {
            if (project.getPackaging().equalsIgnoreCase("war")) {
                File f = new File(project.getBuild().getDirectory(), project.getBuild().getFinalName());
                f.mkdir();
                destinationDir = new File(f, "WEB-INF");
            } else if (project.getPackaging().equalsIgnoreCase("ear"))
                destinationDir = new File(
                        new File(project.getBuild().getDirectory(), project.getBuild().getFinalName()),
                        "META-INF");
            else
                destinationDir = new File(project.getBuild().getOutputDirectory(), "META-INF");
        }
        if (!destinationDir.exists())
            destinationDir.mkdirs();
        // String xml = getStringFromDocument(doc);
        writeXmlFile(doc, destinationDir, isSubDeployment ? JBOSS_SUBDEPLOYMENT : JBOSS_DEPLOYMENT_STRUCTURE);
        addResourceDir(destinationDir);
    }
}

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

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // =====================================================================================
    initialize(request);//from  w  ww. j av  a  2 s.c o  m

    int userId = 0;
    int groupId = 0;
    String user = "";

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

    Credential credential = null;
    Connection c = null;
    try {
        //On initialise le dataProvider
        if (ds == null) // Case where we can't deploy context.xml
        {
            c = getConnection();
        } else {
            c = ds.getConnection();
        }
        dataProvider.setConnection(c);
        credential = new Credential(c);
    } catch (Exception e) {
        e.printStackTrace();
    }

    /// uuid: celui de la ressource

    /// /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]]

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

    /// Rcupration des paramtres
    String url = request.getPathInfo();
    String[] token = url.split("/");
    String uuid = token[1];

    String size = request.getParameter("size");
    if (size == null)
        size = "S";

    String lang = request.getParameter("lang");
    if (lang == null) {
        lang = "fr";
    }

    /// Vrification des droits d'accs
    if (!credential.hasNodeRight(userId, groupId, uuid, Credential.WRITE)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        //throw new Exception("L'utilisateur userId="+userId+" n'a pas le droit WRITE sur le noeud "+nodeUuid);
    }

    String data;
    String fileid = "";
    try {
        data = dataProvider.getResNode(uuid, userId, groupId);

        /// Parse les donnes
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader("<node>" + data + "</node>"));
        Document doc = documentBuilder.parse(is);
        DOMImplementationLS impl = (DOMImplementationLS) doc.getImplementation().getFeature("LS", "3.0");
        LSSerializer serial = impl.createLSSerializer();
        serial.getDomConfig().setParameter("xml-declaration", false);

        /// Cherche si on a dj envoy quelque chose
        XPath xPath = XPathFactory.newInstance().newXPath();
        String filterRes = "//filename[@lang=\"" + lang + "\"]";
        NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);

        String filename = "";
        if (nodelist.getLength() > 0)
            filename = nodelist.item(0).getTextContent();

        if (!"".equals(filename)) {
            /// Already have one, per language
            String filterId = "//fileid[@lang='" + lang + "']";
            NodeList idlist = (NodeList) xPath.compile(filterId).evaluate(doc, XPathConstants.NODESET);
            if (idlist.getLength() != 0) {
                Element fileNode = (Element) idlist.item(0);
                fileid = fileNode.getTextContent();
            }
        }
    } catch (Exception e2) {
        e2.printStackTrace();
    }

    int last = fileid.lastIndexOf("/") + 1; // FIXME temp patch
    if (last < 0)
        last = 0;
    fileid = fileid.substring(last);
    /// request.getHeader("REFERRER");

    /// criture des donnes
    String urlTarget = "http://" + server + "/" + fileid;
    //      String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs";

    // Unpack form, fetch binary data and send
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Configure a repository (to ensure a secure temp location is used)
    /*
    ServletContext servletContext = this.getServletConfig().getServletContext();
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    factory.setRepository(repository);
    //*/

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    String json = "";
    HttpURLConnection connection = null;
    // Parse the request
    try {
        List<FileItem> items = upload.parseRequest(request);
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if ("uploadfile".equals(item.getFieldName())) {
                // Send raw data
                InputStream inputData = item.getInputStream();

                /*
                URL urlConn = new URL(urlTarget);
                connection = (HttpURLConnection) urlConn.openConnection();
                connection.setDoOutput(true);
                connection.setUseCaches(false);                 /// We don't want to cache data
                connection.setInstanceFollowRedirects(false);   /// Let client follow any redirection
                String method = request.getMethod();
                connection.setRequestMethod(method);
                        
                String context = request.getContextPath();
                connection.setRequestProperty("app", context);
                //*/

                String fileName = item.getName();
                long filesize = item.getSize();
                String contentType = item.getContentType();

                //               /*
                connection = CreateConnection(urlTarget, request);
                connection.setRequestProperty("filename", uuid);
                connection.setRequestProperty("content-type", "application/octet-stream");
                connection.setRequestProperty("content-length", Long.toString(filesize));
                //*/
                connection.connect();

                OutputStream outputData = connection.getOutputStream();
                IOUtils.copy(inputData, outputData);

                /// Those 2 lines are needed, otherwise, no request sent
                int code = connection.getResponseCode();
                String msg = connection.getResponseMessage();

                InputStream objReturn = connection.getInputStream();
                StringWriter idResponse = new StringWriter();
                IOUtils.copy(objReturn, idResponse);
                fileid = idResponse.toString();

                connection.disconnect();

                /// Construct Json
                StringWriter StringOutput = new StringWriter();
                JsonWriter writer = new JsonWriter(StringOutput);
                writer.beginObject();
                writer.name("files");
                writer.beginArray();
                writer.beginObject();

                writer.name("name").value(fileName);
                writer.name("size").value(filesize);
                writer.name("type").value(contentType);
                writer.name("url").value(origin);
                writer.name("fileid").value(fileid);
                //                               writer.name("deleteUrl").value(ref);
                //                                       writer.name("deleteType").value("DELETE");
                writer.endObject();

                writer.endArray();
                writer.endObject();

                writer.close();

                json = StringOutput.toString();

                /*
                DataOutputStream datawriter = new DataOutputStream(connection.getOutputStream());
                byte[] buffer = new byte[1024];
                int dataSize;
                while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 )
                {
                   datawriter.write(buffer, 0, dataSize);
                }
                datawriter.flush();
                datawriter.close();
                //*/
                //               outputData.close();
                //               inputData.close();

                break;
            }
        }
    } catch (FileUploadException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    /*
    HttpURLConnection connection = CreateConnection( urlTarget, request );
            
    connection.setRequestProperty("referer", origin);
            
    /// Send post data
    ServletInputStream inputData = request.getInputStream();
    DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
            
    byte[] buffer = new byte[1024];
    int dataSize;
    while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 )
    {
       writer.write(buffer, 0, dataSize);
    }
    inputData.close();
    writer.close();
            
    /// So we can forward some Set-Cookie
    String ref = request.getHeader("referer");
            
    /// Prend le JSON du fileserver
    InputStream in = connection.getInputStream();
            
    InitAnswer(connection, response, ref);
            
    BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
    StringBuilder builder = new StringBuilder();
    for( String line = null; (line = reader.readLine()) != null; )
       builder.append(line).append("\n");
    //*/

    /// Envoie la mise  jour au backend
    /*
    try
    {
       PostForm.updateResource(session.getId(), backend, uuid, lang, json);
    }
    catch( Exception e )
    {
       e.printStackTrace();
    }
    //*/

    connection.disconnect();
    /// Renvoie le JSON au client
    response.setContentType("application/json");
    PrintWriter respWriter = response.getWriter();
    respWriter.write(json);

    //      RetrieveAnswer(connection, response, ref);
    dataProvider.disconnect();
}

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

@Test
public void CoreResourceHasAtMostOneInstanceShape() throws XPathExpressionException {
    String eval = "//" + getNode() + "/" + "oslc:instanceShape";

    NodeList instances = (NodeList) OSLCUtils.getXPath().evaluate(eval, doc, XPathConstants.NODESET);
    assertTrue(getFailureMessage(), instances.getLength() <= 1);
}