Search in sources :

Example 26 with XPathExpressionException

use of javax.xml.xpath.XPathExpressionException in project Tundra by Permafrost.

the class xpath method get.

public static final void get(IData pipeline) throws ServiceException {
    // --- <<IS-START(get)>> ---
    // @subtype unknown
    // @sigtype java 3.5
    // [i] object:0:optional $content
    // [i] field:0:optional $encoding
    // [i] field:0:required $expression
    // [i] record:0:optional $namespace
    // [i] - field:0:optional default
    // [i] field:0:optional $recurse? {"false","true"}
    // [o] record:1:optional $nodes
    // [o] - object:0:required node
    // [o] - field:0:required name.qualified
    // [o] - field:0:optional name.local
    // [o] - field:0:optional name.prefix
    // [o] - field:0:optional name.uri
    // [o] - field:0:required type
    // [o] - field:0:optional value
    // [o] - record:1:optional attributes
    // [o] -- object:0:required node
    // [o] -- field:0:required name.qualified
    // [o] -- field:0:optional name.local
    // [o] -- field:0:optional name.prefix
    // [o] -- field:0:optional name.uri
    // [o] -- field:0:required type
    // [o] -- field:0:optional value
    // [o] - record:1:optional elements
    // [o] -- object:0:required node
    // [o] -- field:0:required name.qualified
    // [o] -- field:0:optional name.local
    // [o] -- field:0:optional name.prefix
    // [o] -- field:0:optional name.uri
    // [o] -- field:0:required type
    // [o] -- field:0:optional value
    // [o] field:0:required $nodes.length
    IDataCursor cursor = pipeline.getCursor();
    try {
        Object content = IDataHelper.get(cursor, "$content");
        Charset charset = IDataHelper.get(cursor, "$encoding", Charset.class);
        String expression = IDataHelper.get(cursor, "$expression", String.class);
        NamespaceContext namespace = IDataHelper.get(cursor, "$namespace", IDataNamespaceContext.class);
        boolean recurse = IDataHelper.getOrDefault(cursor, "$recurse?", Boolean.class, false);
        XPathExpression compiledExpression = XPathHelper.compile(expression, namespace);
        Node node = null;
        if (content instanceof Node) {
            node = (Node) content;
        } else if (content instanceof InputSource) {
            node = DocumentHelper.parse((InputSource) content, namespace);
        } else if (content != null) {
            node = DocumentHelper.parse(InputStreamHelper.normalize(content, charset), charset, true, namespace);
        }
        Nodes nodes = XPathHelper.get(node, compiledExpression);
        if (nodes != null) {
            IDataHelper.put(cursor, "$nodes", nodes.reflect(namespace, recurse));
            IDataHelper.put(cursor, "$nodes.length", nodes.size(), String.class);
        } else {
            IDataHelper.put(cursor, "$nodes.length", "0");
        }
    } catch (XPathExpressionException ex) {
        ExceptionHelper.raise(ex);
    } finally {
        cursor.destroy();
    }
// --- <<IS-END>> ---
}
Also used : XPathExpression(javax.xml.xpath.XPathExpression) InputSource(org.xml.sax.InputSource) IDataNamespaceContext(permafrost.tundra.xml.namespace.IDataNamespaceContext) NamespaceContext(javax.xml.namespace.NamespaceContext) XPathExpressionException(javax.xml.xpath.XPathExpressionException) Node(org.w3c.dom.Node) Charset(java.nio.charset.Charset) Nodes(permafrost.tundra.xml.dom.Nodes)

Example 27 with XPathExpressionException

use of javax.xml.xpath.XPathExpressionException in project tdi-studio-se by Talend.

the class JSONXPathProposalProvider method getProposals4XPath.

/**
     * DOC cmeng Comment method "getProposals4XPath".
     * 
     * @param contents
     * @param position
     * @return
     */
private IContentProposal[] getProposals4XPath(String contents, int position) {
    int nodeFieldMax = 500;
    int nodeLoopMax = 3000;
    int nodeLoopNumberLimit = 10;
    int nodeFieldNumberLimit = 10;
    int currentNodeNumber = 0;
    List<IContentProposal> proposals = new ArrayList<IContentProposal>();
    String beforeCursorExp = null;
    boolean isRelativeExpression = !contents.trim().startsWith(SLASH);
    if (isRelativeTable && isRelativeExpression) {
        // beforeCursorExp = linker.getCurrentLoopXPath() + SLASH + contents;
        beforeCursorExp = contents;
    } else {
        beforeCursorExp = contents.substring(0, position);
    }
    int lastIndexSlash = beforeCursorExp.lastIndexOf(SLASH);
    int lastIndexPipe = beforeCursorExp.lastIndexOf(PIPE);
    String currentExpr = null;
    if (isRelativeTable && isRelativeExpression) {
        currentExpr = beforeCursorExp;
    }
    if (lastIndexSlash == -1 || lastIndexSlash < lastIndexPipe && lastIndexPipe != -1) {
        currentExpr = EMPTY_STRING;
    } else if (lastIndexPipe < lastIndexSlash && lastIndexPipe != -1) {
        currentExpr = beforeCursorExp.substring(lastIndexPipe + 1, lastIndexSlash + 1);
    } else if (lastIndexSlash != -1) {
        currentExpr = beforeCursorExp.substring(0, lastIndexSlash + 1);
    // currentExpr = beforeCursorExp;
    } else {
        currentExpr = beforeCursorExp;
    }
    currentExpr = currentExpr.trim();
    String currentWord = extractLastWord(beforeCursorExp);
    boolean expressionIsEmpty = currentExpr.trim().length() == 0;
    // String xPathExpression =
    //
    // // + " | " +
    // createXPathExpression(beforeCursorExp)
    // ;
    // System.out.println("#############################");
    // System.out.println("currentExpr='" + currentExpr + "'");
    // System.out.println("beforeCursorExp='"+beforeCursorExp+"'");
    // System.out.println("currentWord='"+currentWord+"'");
    // System.out.println("1");
    ArrayList<Node> allLoopNodes = linker.getAllLoopNodes();
    boolean resultsMayBeIncomplete = false;
    boolean breakAll = false;
    Set<String> alreadyAdded = new HashSet<String>();
    //
    if (isRelativeTable && (isRelativeExpression || expressionIsEmpty)) {
        int allNodesLoopSize = allLoopNodes.size();
        // System.out.println("nodeLoop size list : " + allNodesLoopSize);
        currentNodeNumber += allNodesLoopSize;
        if (allNodesLoopSize > nodeLoopMax) {
            resultsMayBeIncomplete = true;
        } else {
            int nodeLoopNumberOfLoop = allNodesLoopSize;
            if (allNodesLoopSize > nodeLoopNumberLimit) {
                nodeLoopNumberOfLoop = nodeLoopNumberLimit;
                resultsMayBeIncomplete = true;
            }
            for (int i = 0; i < nodeLoopNumberOfLoop; i++) {
                Node nodeLoop = allLoopNodes.get(i);
                // System.out.println("nodeLoop : " + i);
                List<Node> nodeList = null;
                try {
                    nodeList = this.linker.getNodeRetriever().retrieveNodeListFromNode(modifyXpathToSearchAllChildren(currentExpr, true), nodeLoop);
                } catch (XPathExpressionException e) {
                    ExceptionHandler.process(e);
                }
                if (nodeList != null && nodeList.size() == 0) {
                    try {
                        nodeList = linker.getNodeRetriever().retrieveNodeListFromNode(modifyXpathToSearchAllChildren(beforeCursorExp, true), nodeLoop);
                    } catch (XPathExpressionException e) {
                        ExceptionHandler.process(e);
                    }
                }
                if (nodeList != null) {
                    int allNodesFieldsLoopSize = nodeList.size();
                    currentNodeNumber += allNodesFieldsLoopSize;
                    if (allNodesFieldsLoopSize > nodeFieldMax) {
                        resultsMayBeIncomplete = true;
                        breakAll = true;
                    } else {
                        int nodeFieldNumberOfLoop = allNodesFieldsLoopSize;
                        if (allNodesFieldsLoopSize > nodeFieldMax) {
                            nodeFieldNumberOfLoop = nodeFieldNumberLimit;
                            resultsMayBeIncomplete = true;
                        }
                        for (int j = 0; j < nodeFieldNumberOfLoop; ++j) {
                            // System.out.println("nodeField : " + j);
                            Node node = nodeList.get(j);
                            String nodeName = node.getNodeName();
                            String absoluteXPathFromNode = linker.getNodeRetriever().getAbsoluteXPathFromNode(node);
                            if ((currentWord.length() > 0 && nodeName.startsWith(currentWord) || currentWord.length() == 0 || currentWord.equals(//$NON-NLS-1$
                            "/")) && !alreadyAdded.contains(absoluteXPathFromNode)) {
                                XPathContentProposal contentProposal = new XPathContentProposal(node);
                                if (isRelativeTable && isRelativeExpression) {
                                    contentProposal.setRelative(isRelativeTable);
                                    contentProposal.setFirstRelativeNode(contents.indexOf(SLASH) == -1);
                                }
                                proposals.add(contentProposal);
                                alreadyAdded.add(absoluteXPathFromNode);
                            }
                        }
                    // for (int j = 0; j < nodeListLength; ++j) {
                    }
                    if (breakAll) {
                        break;
                    }
                }
            // if (nodeList != null) {
            }
        // for (int i = 0; i < lstSize; i++) {
        }
    // } else {
    }
    // if (!estimationError) {
    // ///////////////////////////////////////////////////////////////////////////////////////////////
    // ///////////////////////////////////////////////////////////////////////////////////////////////
    // ///////////////////////////////////////////////////////////////////////////////////////////////
    // ///////////////////////////////////////////////////////////////////////////////////////////////
    // XPath requests for absolute XPath
    //
    List<Node> nodeList = null;
    if (!expressionIsEmpty) {
        try {
            nodeList = this.linker.getNodeRetriever().retrieveNodeList(modifyXpathToSetFirstAscendant(currentExpr));
        } catch (XPathExpressionException e) {
            ExceptionHandler.process(e);
        }
    }
    if (nodeList != null || expressionIsEmpty) {
        if (!expressionIsEmpty && nodeList.size() > nodeLoopMax) {
            resultsMayBeIncomplete = true;
        } else {
            try {
                nodeList = this.linker.getNodeRetriever().retrieveNodeList(modifyXpathToSearchAllChildren(currentExpr, false));
            } catch (XPathExpressionException e) {
                ExceptionHandler.process(e);
            }
        }
        if (nodeList != null) {
            for (int j = 0; j < nodeList.size(); ++j) {
                // System.out.println("nodeField : " + j);
                Node node = nodeList.get(j);
                String nodeName = node.getNodeName();
                String absoluteXPathFromNode = linker.getNodeRetriever().getAbsoluteXPathFromNode(node);
                if ((currentWord.length() > 0 && nodeName.startsWith(currentWord) || currentWord.length() == 0 || currentWord.equals(//$NON-NLS-1$
                "/")) && !alreadyAdded.contains(absoluteXPathFromNode)) {
                    // System.out.println(absoluteXPathFromNode);
                    XPathContentProposal contentProposal = new XPathContentProposal(node);
                    proposals.add(contentProposal);
                    alreadyAdded.add(absoluteXPathFromNode);
                }
            }
        // for (int j = 0; j < nodeListLength; ++j) {
        }
    // if (nodeList != null) {
    }
    if (resultsMayBeIncomplete) {
        addTooManyNodesContentProposal(proposals);
    }
    IContentProposal[] res = new IContentProposal[proposals.size()];
    res = proposals.toArray(res);
    return res;
}
Also used : XPathExpressionException(javax.xml.xpath.XPathExpressionException) JsonTreeNode(org.talend.repository.ui.wizards.metadata.connection.files.json.JsonTreeNode) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) IContentProposal(org.eclipse.jface.fieldassist.IContentProposal) XPathContentProposal(org.talend.commons.ui.swt.proposal.xpath.XPathContentProposal) HashSet(java.util.HashSet)

Example 28 with XPathExpressionException

use of javax.xml.xpath.XPathExpressionException in project tdi-studio-se by Talend.

the class WsdlTokenManager method getValueFromXML.

private String getValueFromXML(String inputXML, String xPathQuery) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException {
    DocumentBuilder builder;
    try {
        builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = builder.parse(new ByteArrayInputStream(inputXML.getBytes()));
        XPath xpath = XPathFactory.newInstance().newXPath();
        String expression = xPathQuery;
        Node cipherValue = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
        return cipherValue == null ? null : cipherValue.getTextContent();
    } catch (XPathExpressionException e) {
        logger.error(e.getMessage());
        throw e;
    } catch (ParserConfigurationException e) {
        logger.error(e.getMessage());
        throw e;
    } catch (SAXException e) {
        logger.error(e.getMessage());
        throw e;
    } catch (IOException e) {
        logger.error(e.getMessage());
        throw e;
    }
}
Also used : XPath(javax.xml.xpath.XPath) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) XPathExpressionException(javax.xml.xpath.XPathExpressionException) Node(org.w3c.dom.Node) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException)

Example 29 with XPathExpressionException

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

the class ExtSourceXML method getValueFromXpath.

/**
	 * Get xml Node and xpath expression to get value from node by this xpath.
	 *
	 * @param node node for getting value from
	 * @param xpathExpression expression for xpath to looking for value in node
	 * @return string extracted from node by xpath
	 * @throws InternalErrorException
	 */
protected String getValueFromXpath(Node node, String xpathExpression) throws InternalErrorException {
    //Prepare xpath expression
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr;
    try {
        expr = xpath.compile(xpathExpression);
    } catch (XPathExpressionException ex) {
        throw new InternalErrorException("Error when compiling xpath query.", ex);
    }
    String text;
    try {
        text = (String) expr.evaluate(node, XPathConstants.STRING);
    } catch (XPathExpressionException ex) {
        throw new InternalErrorException("Error when evaluate xpath query on node.", ex);
    }
    return text;
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) XPathFactory(javax.xml.xpath.XPathFactory) XPathExpressionException(javax.xml.xpath.XPathExpressionException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException)

Example 30 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)

Aggregations

XPathExpressionException (javax.xml.xpath.XPathExpressionException)139 NodeList (org.w3c.dom.NodeList)65 XPath (javax.xml.xpath.XPath)64 Document (org.w3c.dom.Document)46 Node (org.w3c.dom.Node)46 IOException (java.io.IOException)42 XPathExpression (javax.xml.xpath.XPathExpression)38 SAXException (org.xml.sax.SAXException)27 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)25 XPathFactory (javax.xml.xpath.XPathFactory)23 ArrayList (java.util.ArrayList)22 HashMap (java.util.HashMap)18 Test (org.junit.Test)17 InputSource (org.xml.sax.InputSource)17 Element (org.w3c.dom.Element)16 Response (com.jayway.restassured.response.Response)12 ValidatableResponse (com.jayway.restassured.response.ValidatableResponse)12 DocumentBuilder (javax.xml.parsers.DocumentBuilder)12 AbstractIntegrationTest (org.codice.ddf.itests.common.AbstractIntegrationTest)12 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)11