Example usage for javax.xml.xpath XPathConstants NODE

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

Introduction

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

Prototype

QName NODE

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

Click Source Link

Document

The XPath 1.0 NodeSet data type.

Usage

From source file:net.firejack.platform.api.content.ContentServiceTest.java

@Test
public void exportImportCollectionTest() {
    Folder folder = createFolder(domain.getId());

    Collection collection = new Collection();
    collection.setName(time + "-collection");
    collection.setParentId(folder.getId());
    collection.setType("COLLECTION");
    collection.setDescription("Some Description");

    ServiceResponse<RegistryNodeTree> response2 = OPFEngine.ContentService.createCollection(collection);
    Assert.assertTrue("Collection should be created.", response2.isSuccess());

    RegistryNodeTree registryNodeTree2 = response2.getItem();
    Assert.assertNotNull("Should not be null.", registryNodeTree2);
    collection.setId(registryNodeTree2.getId());

    ServiceResponse<FileInfo> response3 = OPFEngine.ContentService
            .exportCollectionArchiveFile(collection.getId());
    FileInfo fileInfo = response3.getItem();
    Assert.assertNotNull("Should not be null.", fileInfo);

    File contentArchive;//from   w  w w .j  ava 2  s  .  c  o  m
    try {
        File tempDir = FileUtils.getTempDirectory();
        contentArchive = FileUtils.create(tempDir, "content.zip");
        InputStream stream = fileInfo.getStream();
        FileUtils.writeToFile(contentArchive, stream);
        IOUtils.closeQuietly(stream);

        ArchiveUtils.unZIP(contentArchive, tempDir);

        File contentXml = FileUtils.create(tempDir, "content.xml");

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document document = factory.newDocumentBuilder().parse(contentXml);
        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xpath = xPathFactory.newXPath();
        Object evaluate = xpath.evaluate("/content/collection", document, XPathConstants.NODE);
        String collectionName = (String) xpath.evaluate("@name", evaluate, XPathConstants.STRING);
        Assert.assertEquals("Exported collection should be equal name.", collection.getName(), collectionName);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    ServiceResponse response4 = OPFEngine.ContentService.deleteCollection(collection.getId());
    Assert.assertTrue("Collection should be deleted.", response4.isSuccess());

    try {
        InputStream contentStream = FileUtils.openInputStream(contentArchive);
        ServiceResponse<FileInfo> response5 = OPFEngine.ContentService
                .importCollectionArchiveFile(contentStream);
        Assert.assertTrue("Import should be completed.", response5.isSuccess());
        IOUtils.closeQuietly(contentStream);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    ServiceResponse<Collection> response6 = OPFEngine.ContentService
            .readCollectionsByLikeLookup(folder.getLookup());
    Assert.assertTrue("Collections should be retrieved.", response6.isSuccess());

    Collection collection2 = response6.getItem();
    Assert.assertNotNull("Should not be null.", collection2);
    Assert.assertEquals("Should be the same name.", collection.getName(), collection2.getName());

    deleteFolder(folder);
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.geosearch.GeosearchDataImportWriter.java

private Node getDataSource(String dataSourceName) throws XPathExpressionException {
    Node dataSource = null;//from  w ww .  j  av  a 2s.  co  m

    dataSource = (Node) xpath.compile("/dataConfig/dataSource[@name='".concat(dataSourceName).concat("']"))
            .evaluate(dataImportXML, XPathConstants.NODE);

    return dataSource;
}

From source file:org.apache.flex.utilities.converter.retrievers.download.DownloadRetriever.java

protected String getBinaryUrl(SdkType sdkType, String version, PlatformType platformType)
        throws RetrieverException {
    try {//  w w  w.  j  a va  2 s. co  m
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        final DocumentBuilder builder = factory.newDocumentBuilder();
        final Document doc = builder.parse(getFlexInstallerConfigUrl());

        //Evaluate XPath against Document itself
        final String expression = getUrlXpath(sdkType, version, platformType);
        final XPath xPath = XPathFactory.newInstance().newXPath();
        final Element artifactElement = (Element) xPath.evaluate(expression, doc.getDocumentElement(),
                XPathConstants.NODE);
        if (artifactElement == null) {
            throw new RetrieverException(
                    "Could not find " + sdkType.toString() + " SDK with version " + version);
        }

        final StringBuilder stringBuilder = new StringBuilder();
        if ((sdkType == SdkType.FLEX) || (sdkType == SdkType.SWFOBJECT)) {
            final String path = artifactElement.getAttribute("path");
            final String file = artifactElement.getAttribute("file");
            if (!path.startsWith("http://")) {
                stringBuilder.append("http://archive.apache.org/dist/");
            }
            stringBuilder.append(path);
            if (!path.endsWith("/")) {
                stringBuilder.append("/");
            }
            stringBuilder.append(file);
            if (sdkType == SdkType.FLEX) {
                stringBuilder.append(".zip");
            }
        } else {
            final NodeList pathElements = artifactElement.getElementsByTagName("path");
            final NodeList fileElements = artifactElement.getElementsByTagName("file");
            if ((pathElements.getLength() != 1) && (fileElements.getLength() != 1)) {
                throw new RetrieverException("Invalid document structure.");
            }
            final String path = pathElements.item(0).getTextContent();
            stringBuilder.append(path);
            if (!path.endsWith("/")) {
                stringBuilder.append("/");
            }
            stringBuilder.append(fileElements.item(0).getTextContent());
        }

        return stringBuilder.toString();
    } catch (ParserConfigurationException e) {
        throw new RetrieverException("Error parsing 'sdk-installer-config-4.0.xml'", e);
    } catch (SAXException e) {
        throw new RetrieverException("Error parsing 'sdk-installer-config-4.0.xml'", e);
    } catch (XPathExpressionException e) {
        throw new RetrieverException("Error parsing 'sdk-installer-config-4.0.xml'", e);
    } catch (IOException e) {
        throw new RetrieverException("Error parsing 'sdk-installer-config-4.0.xml'", e);
    }
}

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

@Test
public void changeManagementServiceDescriptionHasValidCreationDialog() throws XPathException {
    //If ServiceDescription is oslc_cm, make sure it has a valid creation dialog child element
    Node cmRequest = (Node) OSLCUtils.getXPath().evaluate("//oslc_cm:changeRequests", doc, XPathConstants.NODE);
    if (cmRequest != null) {
        NodeList sD = (NodeList) OSLCUtils.getXPath()
                .evaluate("//oslc_cm:changeRequests/oslc_cm:creationDialog", doc, XPathConstants.NODESET);
        for (int i = 0; i < sD.getLength(); i++) {
            Node sQUrl = (Node) OSLCUtils.getXPath().evaluate(
                    "//oslc_cm:changeRequests/oslc_cm:creationDialog[" + (i + 1) + "]/oslc_cm:url", doc,
                    XPathConstants.NODE);
            assertNotNull(sQUrl);/* ww w .j  a va2  s.  c  o m*/
            Node sDtitle = (Node) OSLCUtils.getXPath().evaluate(
                    "//oslc_cm:changeRequests/oslc_cm:creationDialog[" + (i + 1) + "]/dc:title", doc,
                    XPathConstants.NODE);
            assertNotNull(sDtitle);
            assertFalse(sDtitle.getTextContent().isEmpty());
        }
    }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        XPathExpression codeFilter = xPath.compile(filterCode);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        if (redirectDoc) {

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

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

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

            builder.addPart("uploadfile", body);

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

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

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

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

From source file:de.codesourcery.jasm16.ide.ProjectConfiguration.java

private Element getElement(XPathExpression expr, Document doc) throws XPathExpressionException {
    return (Element) expr.evaluate(doc, XPathConstants.NODE);
}

From source file:com.offbynull.portmapper.upnpigd.UpnpIgdDiscovery.java

private static Set<UpnpIgdService> parseServiceDescriptions(Map<UpnpIgdServiceReference, byte[]> scpds) {
    Set<UpnpIgdService> descriptions = new HashSet<>();

    for (Entry<UpnpIgdServiceReference, byte[]> scpdEntry : scpds.entrySet()) {
        try {/*  ww  w .ja v a2s .co  m*/
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(new ByteArrayInputStream(scpdEntry.getValue()));

            XPath xPath = XPathFactory.newInstance().newXPath();
            Node geipaActionNode = (Node) xPath.evaluate(
                    "//actionList/action[" + "name='GetExternalIPAddress' " + "and count(argumentList) = 1 "
                            + "and argumentList/argument/name='NewExternalIPAddress']",
                    doc, XPathConstants.NODE);
            Node gspmeActionNode = (Node) xPath
                    .evaluate("//actionList/action[" + "name='GetSpecificPortMappingEntry' "
                            + "and count(argumentList) = 1 " + "and argumentList/argument/name='NewRemoteHost' "
                            + "and argumentList/argument/name='NewExternalPort' "
                            + "and argumentList/argument/name='NewProtocol' "
                            + "and argumentList/argument/name='NewInternalPort' "
                            + "and argumentList/argument/name='NewInternalClient' "
                            + "and argumentList/argument/name='NewEnabled' "
                            + "and argumentList/argument/name='NewPortMappingDescription' "
                            + "and argumentList/argument/name='NewLeaseDuration']", doc, XPathConstants.NODE);
            Node dpmActionNode = (Node) xPath.evaluate("//actionList/action[" + "name='DeletePortMapping' "
                    + "and count(argumentList) = 1 " + "and argumentList/argument/name='NewRemoteHost' "
                    + "and argumentList/argument/name='NewExternalPort' "
                    + "and argumentList/argument/name='NewProtocol']", doc, XPathConstants.NODE);
            Node apmActionNode = (Node) xPath.evaluate("//actionList/action[" + "name='AddPortMapping' "
                    + "and count(argumentList) = 1 " + "and argumentList/argument/name='NewRemoteHost' "
                    + "and argumentList/argument/name='NewExternalPort' "
                    + "and argumentList/argument/name='NewProtocol' "
                    + "and argumentList/argument/name='NewInternalPort' "
                    + "and argumentList/argument/name='NewInternalClient' "
                    + "and argumentList/argument/name='NewEnabled' "
                    + "and argumentList/argument/name='NewPortMappingDescription' "
                    + "and argumentList/argument/name='NewLeaseDuration']", doc, XPathConstants.NODE);

            if (geipaActionNode == null || gspmeActionNode == null || dpmActionNode == null
                    || apmActionNode == null) {
                // One or more of the required methods aren't supported, skip this entry
                continue;
            }

            // set lease range
            String pmldStateMinValue = xPath.evaluate("//serviceStateTable/stateVariable["
                    + "name='PortMappingLeaseDuration']" + "/allowedValueRange/minimum/text()", doc);
            String pmldStateMaxValue = xPath.evaluate("//serviceStateTable/stateVariable["
                    + "name='PortMappingLeaseDuration']" + "/allowedValueRange/maximum/text()", doc);
            Range<Long> leaseDurationRange = extractRangeIfAvailable(pmldStateMinValue, pmldStateMaxValue, 0L,
                    null);

            // set external port range
            String epStateMinValue = xPath.evaluate("//serviceStateTable/stateVariable["
                    + "name='ExternalPort']" + "/allowedValueRange/minimum/text()", doc);
            String epStateMaxValue = xPath.evaluate("//serviceStateTable/stateVariable["
                    + "name='ExternalPort']" + "/allowedValueRange/maximum/text()", doc);
            Range<Long> externalPortRange = extractRangeIfAvailable(epStateMinValue, epStateMaxValue, 1L,
                    65535L);

            UpnpIgdService desc = new UpnpIgdService(scpdEntry.getKey(), leaseDurationRange, externalPortRange);
            descriptions.add(desc);
        } catch (SAXException | ParserConfigurationException | IOException | XPathExpressionException e) { // NOPMD
            throw new IllegalArgumentException(e);
        }
    }

    return descriptions;
}

From source file:com.amalto.core.storage.hibernate.DefaultStorageClassLoader.java

private static void setPropertyValue(Document document, String propertyName, String value)
        throws XPathExpressionException {
    XPathExpression compile = pathFactory
            .compile("hibernate-configuration/session-factory/property[@name='" + propertyName + "']"); //$NON-NLS-1$ //$NON-NLS-2$
    Node node = (Node) compile.evaluate(document, XPathConstants.NODE);
    if (node != null) {
        node.setTextContent(value);/*from   ww  w  . j  a  va2s. c  o  m*/
    } else {
        XPathExpression parentNodeExpression = pathFactory.compile("hibernate-configuration/session-factory"); //$NON-NLS-1$
        Node parentNode = (Node) parentNodeExpression.evaluate(document, XPathConstants.NODE);
        // Create a new property element for this datasource-specified property (TMDM-4927).
        Element property = document.createElement("property"); //$NON-NLS-1$
        Attr propertyNameAttribute = document.createAttribute("name"); //$NON-NLS-1$
        property.setAttributeNode(propertyNameAttribute);
        propertyNameAttribute.setValue(propertyName);
        property.setTextContent(value);
        parentNode.appendChild(property);
    }
}

From source file:gov.niem.ws.util.SecurityUtil.java

/**
 * Check that the certificate in the holder of key assertion matches
 * the passed certificate, sent via another channel (e.g. SSL client auth).
 * The certificate must be validated separately, before making this call.
 * @param assertion SAML holder of key assertion.
 * @param presentedCert certificate claimed to be presented in the HoK.
 * @return/*www  .  j  ava  2 s. co  m*/
 * @throws IOException 
 * @throws SAXException 
 * @throws ParserConfigurationException 
 */
public static boolean confirmHolderOfKey(Document assertion, X509Certificate presentedCert)
        throws ParserConfigurationException, SAXException, IOException {
    Node keyInfoNode = null;
    try {
        keyInfoNode = (Node) subjectConfirmationKeyInfoPath.evaluate(assertion, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }
    if (keyInfoNode == null) {
        System.out.println("key info not found in subject confirmation");
        return false;
    }
    X509Certificate assertionCert = getCertificateFromKeyInfo(keyInfoNode);
    if (assertionCert != null) {
        return assertionCert.equals(presentedCert);
    }

    PublicKey publicKey = getPublicKeyFromKeyInfo(keyInfoNode);
    if (publicKey != null) {
        return publicKey.equals(presentedCert.getPublicKey());
    }

    return false;
}

From source file:com.bekwam.mavenpomupdater.MainViewController.java

private POMObject parseFile(String path) {

    if (log.isDebugEnabled()) {
        log.debug("[PARSE] path=" + path);
    }//from   w w  w  . jav  a  2 s  . c om

    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(path);

        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression expression = xpath.compile("//project/version/text()");
        Node node = (Node) expression.evaluate(doc, XPathConstants.NODE);

        String version = "";
        if (node != null) {
            version = node.getNodeValue();
            if (log.isDebugEnabled()) {
                log.debug("[PARSE]    version=" + node.getNodeValue());
            }
        }

        //           XPath pvXPath = XPathFactory.newInstance().newXPath();
        XPathExpression pvExpression = xpath.compile("//project/parent/version/text()");
        Node pvNode = (Node) pvExpression.evaluate(doc, XPathConstants.NODE);

        String pVersion = "";
        if (pvNode != null) {
            pVersion = pvNode.getNodeValue();
            if (log.isDebugEnabled()) {
                log.debug("[PARSE]    parentVersion=" + pvNode.getNodeValue());
            }
        }

        return new POMObject(true, path, version, pVersion, false);

    } catch (Exception exc) {
        log.error("error parsing path=" + path, exc);

        errorLogDelegate.log(path, exc.getMessage());

        return new POMObject(false, path, "Parse Error (will be skipped)", "Parse Error (will be skipped)",
                true);
    }
}