Search in sources :

Example 31 with XPathExpressionException

use of javax.xml.xpath.XPathExpressionException in project perun by CESNET.

the class ExtSourceXML method xpathParsing.

/**
	 * Get query and maxResults.
	 * Prepare document and xpathExpression by query.
	 * Get all nodes by xpath from document and parse them one by one.
	 *
	 * The way of xml take from "file" or "uri" (configuration file)
	 *
	 * @param query xpath query from config file
	 * @param maxResults never get more than maxResults results (0 mean unlimited)
	 *
	 * @return List of results, where result is Map<String,String> like <name, value>
	 * @throws InternalErrorException
	 */
protected List<Map<String, String>> xpathParsing(String query, int maxResults) throws InternalErrorException {
    //Prepare result list
    List<Map<String, String>> subjects = new ArrayList<Map<String, String>>();
    //Create new document factory builder
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        throw new InternalErrorException("Error when creating newDocumentBuilder.", ex);
    }
    Document doc;
    try {
        if (file != null && !file.isEmpty()) {
            doc = builder.parse(file);
        } else if (uri != null && !uri.isEmpty()) {
            doc = builder.parse(this.createTwoWaySSLConnection(uri));
        } else {
            throw new InternalErrorException("Document can't be parsed, because there is no way (file or uri) to this document in xpathParser.");
        }
    } catch (SAXParseException ex) {
        throw new InternalErrorException("Error when parsing uri by document builder.", ex);
    } catch (SAXException ex) {
        throw new InternalErrorException("Problem with parsing is more complex, not only invalid characters.", ex);
    } catch (IOException ex) {
        throw new InternalErrorException("Error when parsing uri by document builder. Problem with input or output.", ex);
    }
    //Prepare xpath expression
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression queryExpr;
    try {
        queryExpr = xpath.compile(query);
    } catch (XPathExpressionException ex) {
        throw new InternalErrorException("Error when compiling xpath query.", ex);
    }
    //Call query on document node and get back nodesets
    NodeList nodeList;
    try {
        nodeList = (NodeList) queryExpr.evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException ex) {
        throw new InternalErrorException("Error when evaluate xpath query on document.", ex);
    }
    //Test if there is any nodeset in result
    if (nodeList.getLength() == 0) {
        //There is no results, return empty subjects
        return subjects;
    }
    //Iterate through nodes and convert them to Map<String,String>
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node singleNode = nodeList.item(i);
        // remove node from original structure in order to keep access time constant (otherwise is exp.)
        singleNode.getParentNode().removeChild(singleNode);
        Map<String, String> map = convertNodeToMap(singleNode);
        if (map != null)
            subjects.add(map);
        //Reducing results by maxResults
        if (maxResults > 0) {
            if (subjects.size() >= maxResults)
                break;
        }
    }
    this.close();
    return subjects;
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) XPathFactory(javax.xml.xpath.XPathFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) SAXParseException(org.xml.sax.SAXParseException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 32 with XPathExpressionException

use of javax.xml.xpath.XPathExpressionException in project perun by CESNET.

the class MuPasswordManagerModule method parseUCO.

/**
	 * Parse UCO from XML body response and convert it to map of parameters.
	 *
	 * @param document XML document to be parsed
	 * @param requestID unique ID of a request
	 * @return Map of response params
	 * @throws InternalErrorException
	 */
private Map<String, String> parseUCO(Document document, int requestID) throws InternalErrorException {
    Map<String, String> result = new HashMap<>();
    //Prepare xpath expression
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression ucoExpr;
    try {
        ucoExpr = xpath.compile("//resp/uco/text()");
    } catch (XPathExpressionException ex) {
        throw new InternalErrorException("Error when compiling xpath query. Request ID: " + requestID, ex);
    }
    try {
        String uco = (String) ucoExpr.evaluate(document, XPathConstants.STRING);
        result.put("urn:perun:user:attribute-def:def:login-namespace:mu", uco);
    } catch (XPathExpressionException ex) {
        throw new InternalErrorException("Error when evaluate xpath query on resulting document for request ID: " + requestID, ex);
    }
    return result;
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) XPathFactory(javax.xml.xpath.XPathFactory) HashMap(java.util.HashMap) XPathExpressionException(javax.xml.xpath.XPathExpressionException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException)

Example 33 with XPathExpressionException

use of javax.xml.xpath.XPathExpressionException in project perun by CESNET.

the class MuPasswordManagerModule method parseResponse.

/**
	 * Parse XML response from IS MU to XML document.
	 *
	 * @param inputStream Stream to be parsed to Document
	 * @param requestID ID of request made to IS MU.
	 * @return XML document for further processing
	 * @throws InternalErrorException
	 */
private Document parseResponse(InputStream inputStream, int requestID) throws InternalErrorException {
    //Create new document factory builder
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        throw new InternalErrorException("Error when creating newDocumentBuilder. Request ID: " + requestID, ex);
    }
    String response = null;
    try {
        response = convertStreamToString(inputStream, "UTF-8");
    } catch (IOException ex) {
        log.error("Unable to convert InputStream to String: {}", ex);
    }
    log.trace("Request ID: " + requestID + " Response: " + response);
    Document doc;
    try {
        doc = builder.parse(new InputSource(new StringReader(response)));
    } catch (SAXParseException ex) {
        throw new InternalErrorException("Error when parsing uri by document builder. Request ID: " + requestID, ex);
    } catch (SAXException ex) {
        throw new InternalErrorException("Problem with parsing is more complex, not only invalid characters. Request ID: " + requestID, ex);
    } catch (IOException ex) {
        throw new InternalErrorException("Error when parsing uri by document builder. Problem with input or output. Request ID: " + requestID, ex);
    }
    //Prepare xpath expression
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression isErrorExpr;
    XPathExpression getErrorTextExpr;
    XPathExpression getDbErrorTextExpr;
    try {
        isErrorExpr = xpath.compile("//resp/stav/text()");
        getErrorTextExpr = xpath.compile("//resp/error/text()");
        getDbErrorTextExpr = xpath.compile("//resp/dberror/text()");
    } catch (XPathExpressionException ex) {
        throw new InternalErrorException("Error when compiling xpath query. Request ID: " + requestID, ex);
    }
    // OK or ERROR
    String responseStatus;
    try {
        responseStatus = (String) isErrorExpr.evaluate(doc, XPathConstants.STRING);
    } catch (XPathExpressionException ex) {
        throw new InternalErrorException("Error when evaluate xpath query on document to resolve response status. Request ID: " + requestID, ex);
    }
    log.trace("Request ID: " + requestID + " Response status: " + responseStatus);
    if ("OK".equals(responseStatus)) {
        return doc;
    } else {
        try {
            String error = (String) getErrorTextExpr.evaluate(doc, XPathConstants.STRING);
            if (error == null || error.isEmpty()) {
                error = (String) getDbErrorTextExpr.evaluate(doc, XPathConstants.STRING);
            }
            throw new InternalErrorException("IS MU (password manager backend) responded with error to a Request ID: " + requestID + " Error: " + error);
        } catch (XPathExpressionException ex) {
            throw new InternalErrorException("Error when evaluate xpath query on document to resolve error status. Request ID: " + requestID, ex);
        }
    }
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) XPathExpressionException(javax.xml.xpath.XPathExpressionException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) XPathFactory(javax.xml.xpath.XPathFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) SAXParseException(org.xml.sax.SAXParseException) StringReader(java.io.StringReader) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 34 with XPathExpressionException

use of javax.xml.xpath.XPathExpressionException in project ORCID-Source by ORCID.

the class LoadFundRefData method getOrganization.

/**
     * FUNDREF FUNCTIONS
     * */
/**
     * Get an RDF organization from the given RDF file
     * */
private RDFOrganization getOrganization(Document xmlDocument, NamedNodeMap attrs) {
    RDFOrganization organization = new RDFOrganization();
    try {
        Node node = attrs.getNamedItem("rdf:resource");
        String itemDoi = node.getNodeValue();
        LOGGER.info("Processing item {}", itemDoi);
        //Get item node
        Node organizationNode = (Node) xPath.compile(itemExpression.replace("%s", itemDoi)).evaluate(xmlDocument, XPathConstants.NODE);
        // Get organization name
        String orgName = (String) xPath.compile(orgNameExpression).evaluate(organizationNode, XPathConstants.STRING);
        // Get status indicator
        Node statusNode = (Node) xPath.compile(statusExpression).evaluate(organizationNode, XPathConstants.NODE);
        String status = null;
        if (statusNode != null) {
            NamedNodeMap statusAttrs = statusNode.getAttributes();
            if (statusAttrs != null) {
                String statusAttribute = statusAttrs.getNamedItem("rdf:resource").getNodeValue();
                if (isDeprecatedStatus(statusAttribute)) {
                    status = OrganizationStatus.DEPRECATED.name();
                }
            }
        }
        // Get country code
        Node countryNode = (Node) xPath.compile(orgCountryExpression).evaluate(organizationNode, XPathConstants.NODE);
        NamedNodeMap countryAttrs = countryNode.getAttributes();
        String countryGeonameUrl = countryAttrs.getNamedItem("rdf:resource").getNodeValue();
        String countryCode = fetchFromGeoNames(countryGeonameUrl, "countryCode");
        // Get state name
        Node stateNode = (Node) xPath.compile(orgStateExpression).evaluate(organizationNode, XPathConstants.NODE);
        String stateName = null;
        String stateCode = null;
        if (stateNode != null) {
            NamedNodeMap stateAttrs = stateNode.getAttributes();
            String stateGeoNameCode = stateAttrs.getNamedItem("rdf:resource").getNodeValue();
            stateName = fetchFromGeoNames(stateGeoNameCode, "name");
            stateCode = fetchFromGeoNames(stateGeoNameCode, STATE_NAME);
        }
        // Get type
        String orgType = (String) xPath.compile(orgTypeExpression).evaluate(organizationNode, XPathConstants.STRING);
        // Get subType
        String orgSubType = (String) xPath.compile(orgSubTypeExpression).evaluate(organizationNode, XPathConstants.STRING);
        // Fill the organization object
        organization.doi = itemDoi;
        organization.name = orgName;
        organization.country = countryCode;
        organization.state = stateName;
        organization.stateCode = stateCode;
        // TODO: since we don't have city, we fill this with the state, this
        // should be modified soon
        organization.city = stateCode;
        organization.type = orgType;
        organization.subtype = orgSubType;
        organization.status = status;
    } catch (XPathExpressionException xpe) {
        LOGGER.error("XPathExpressionException {}", xpe.getMessage());
    }
    return organization;
}
Also used : NamedNodeMap(org.w3c.dom.NamedNodeMap) XPathExpressionException(javax.xml.xpath.XPathExpressionException) Node(org.w3c.dom.Node) JsonNode(com.fasterxml.jackson.databind.JsonNode)

Example 35 with XPathExpressionException

use of javax.xml.xpath.XPathExpressionException in project jdk8u_jdk by JetBrains.

the class XPathExFuncTest method testEnableExtFunc.

/**
     * Security is enabled, use new feature: enableExtensionFunctions
     */
public void testEnableExtFunc() {
    Policy p = new SimplePolicy(new AllPermission());
    Policy.setPolicy(p);
    System.setSecurityManager(new SecurityManager());
    try {
        evaluate(true);
        System.out.println("testEnableExt: OK");
    } catch (XPathFactoryConfigurationException e) {
        fail(e.getMessage());
    } catch (XPathExpressionException e) {
        fail(e.getMessage());
    } finally {
        System.setSecurityManager(null);
    }
}
Also used : Policy(java.security.Policy) XPathExpressionException(javax.xml.xpath.XPathExpressionException) AllPermission(java.security.AllPermission) XPathFactoryConfigurationException(javax.xml.xpath.XPathFactoryConfigurationException)

Aggregations

XPathExpressionException (javax.xml.xpath.XPathExpressionException)157 XPath (javax.xml.xpath.XPath)79 NodeList (org.w3c.dom.NodeList)74 Document (org.w3c.dom.Document)51 Node (org.w3c.dom.Node)50 IOException (java.io.IOException)47 XPathExpression (javax.xml.xpath.XPathExpression)42 SAXException (org.xml.sax.SAXException)32 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)29 XPathFactory (javax.xml.xpath.XPathFactory)29 ArrayList (java.util.ArrayList)23 Element (org.w3c.dom.Element)22 InputSource (org.xml.sax.InputSource)20 HashMap (java.util.HashMap)19 Test (org.junit.Test)17 DocumentBuilder (javax.xml.parsers.DocumentBuilder)14 Response (com.jayway.restassured.response.Response)12 ValidatableResponse (com.jayway.restassured.response.ValidatableResponse)12 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)12 AbstractIntegrationTest (org.codice.ddf.itests.common.AbstractIntegrationTest)12