Package javax.xml.xpath

Examples of javax.xml.xpath.XPath


  public void execute(WorkItem workItem, ProcessContext context) throws Exception {
        String from = assignment.getFrom();
        String to = assignment.getTo();
       
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpathFrom = factory.newXPath();

        XPathExpression exprFrom = xpathFrom.compile(from);

        XPath xpathTo = factory.newXPath();

        XPathExpression exprTo = xpathTo.compile(to);

        Object target = null;
        Object source = null;
       
        if (isInput) {
View Full Code Here


        return this.id;
    }

    public Object evaluate(final ProcessContext context) throws Exception {       
      XPathFactory factory = XPathFactory.newInstance();
      XPath xpathEvaluator = factory.newXPath();
      xpathEvaluator.setXPathFunctionResolver(
          new  XPathFunctionResolver() {
            public XPathFunction resolveFunction(QName functionName, int arity)
            {
              String localName = functionName.getLocalPart();
              if ("getVariable".equals(localName)) {
                return new GetVariableData();
              }
              else {
                throw new RuntimeException("Unknown BPMN function: " + functionName);
              }
            }

            class GetVariableData implements XPathFunction {
              public Object evaluate(List args) throws XPathFunctionException {
                String varname = (String) args.get(0);
                return context.getVariable(varname);
              }
            }
          }
      );
      xpathEvaluator.setXPathVariableResolver(new XPathVariableResolver() {
           
            public Object resolveVariable(QName variableName) {
                return context.getVariable(variableName.getLocalPart());
            }
        });

    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        return xpathEvaluator.evaluate(this.expression, builder.newDocument(), XPathConstants.BOOLEAN);
    }
View Full Code Here

                s = sb.toString();
            }
           
            Document document = getDocument(s);
               
            XPath xpath = XPathFactory.newInstance().newXPath();
            Node node = (Node) xpath.evaluate("/html/body", document, XPathConstants.NODE);

            String text = node.getTextContent();
           
            while (text.length() > 1 && (text.startsWith("\r") || text.startsWith("\n")))
                text = text.substring(1);
View Full Code Here

        assert (xqtsVersion.equals(targetXQTSVersion)) : "version mismatch! expected version: "
                + xqtsVersion + ", target version: " + targetXQTSVersion;
    }

    protected static int countTests(final String testPath) throws XPathExpressionException {
        final XPath xpath = XPathFactory.newInstance().newXPath();
        NamespaceBinder resolver = new NamespaceBinder();
        resolver.declarePrefix(CATALONG_URI_PREFIX, CATALONG_URI);
        xpath.setNamespaceContext(resolver);
        final String count = "count(" + testPath + ")";
        XPathExpression expr = xpath.compile(count);
        final Document catalog = catalogPool.borrowObject();
        final Double d = (Double) expr.evaluate(catalog, XPathConstants.NUMBER);
        catalogPool.returnObject(catalog);
        return d.intValue();
    }
View Full Code Here

        catalogPool.returnObject(catalog);
        return d.intValue();
    }

    public void invokeTest(final String testPath) throws Exception {
        XPath xpath = XPathFactory.newInstance().newXPath();
        NamespaceBinder resolver = new NamespaceBinder();
        resolver.declarePrefix(CATALONG_URI_PREFIX, CATALONG_URI);
        xpath.setNamespaceContext(resolver);

        final Document catalog = catalogPool.borrowObject();
        try {
            NodeList rs = (NodeList) xpath.evaluate(testPath, catalog, XPathConstants.NODESET);
            final int rslen = rs.getLength();
            for(int i = 0; i < rslen; i++) {
                if(doPrint) {
                    println("\n------------------------------------------------");
                }
                final StaticContext statEnv = new StaticContext();
                statEnv.setConstructionModeStrip(true);

                Node testCase = rs.item(i);
                final String testName = xpath.evaluate("./@name", testCase);
                final String testFilePath = xpath.evaluate("./@FilePath", testCase);
                final String queryFileName = xpath.evaluate("./*[local-name()='query']/@name", testCase);
                File queryFile = new File(xqtsQueryPath, testFilePath + queryFileName + ".xq");
                final URI baseUri = new File(xqtsQueryPath, testFilePath).toURI();

                XQueryModule xqmod = new XQueryModule();

                {// ((//*:test-group)//*:test-case)/*:module
                    NodeList moduleNodes = (NodeList) xpath.evaluate("./*[local-name()='module']", testCase, XPathConstants.NODESET);
                    final int modcount = moduleNodes.getLength();
                    if(modcount > 0) {
                        ModuleManager moduleManager = statEnv.getModuleManager();
                        SimpleModuleResolver modResolver = new SimpleModuleResolver();
                        moduleManager.setModuleResolver(modResolver);
                        for(int j = 0; j < modcount; j++) {
                            Node moduleNode = moduleNodes.item(j);
                            String moduleId = moduleNode.getTextContent();
                            String moduleFileStr = xpath.evaluate("/*[local-name()='test-suite']/*[local-name()='sources']/*[local-name()='module']/@FileName[../@ID='"
                                    + moduleId + "']", catalog);
                            File moduleFile = new File(xqtsDir, moduleFileStr + ".xq");
                            String physical = moduleFile.toURI().toString();
                            String logical = xpath.evaluate("./@namespace", moduleNode);
                            modResolver.addMappingRule(logical, physical);
                        }
                    }
                }
                {// ((//*:test-group)//*:test-case)/*:input-file
                    NodeList vars1 = (NodeList) xpath.evaluate("./*[local-name()='input-file']/@variable", testCase, XPathConstants.NODESET);
                    loadVariables(vars1, testCase, xqmod, statEnv, xpath, catalog, false);
                }
                { // ((//*:test-group)//*:test-case)/*:input-URI
                    NodeList vars2 = (NodeList) xpath.evaluate("./*[local-name()='input-URI']/@variable", testCase, XPathConstants.NODESET);
                    loadVariables(vars2, testCase, xqmod, statEnv, xpath, catalog, true);
                }
                {// ((//*:test-group)//*:test-case)/*:defaultCollection
                    String colId = xpath.evaluate("./*[local-name()='defaultCollection']/text()", testCase);
                    if(colId != null) {
                        NodeList list = (NodeList) xpath.evaluate("/*[local-name()='test-suite']/*[local-name()='sources']/*[local-name()='collection'][@ID='"
                                + colId + "']/*[local-name()='input-document']/text()", catalog, XPathConstants.NODESET);
                        final int listlen = list.getLength();
                        if(listlen > 0) {
                            final Map<String, DTMDocument> defaultCollectionMap = new HashMap<String, DTMDocument>(listlen);
                            for(int j = 0; j < listlen; j++) {
                                String name = list.item(j).getTextContent();
                                String docName = name + ".xml";
                                DTMDocument testDataDoc = _docCache.get(name);
                                if(testDataDoc == null) {
                                    File testDataFile = new File(xqtsDir, docName);
                                    DocumentTableModel dtm = new DocumentTableModel(false);
                                    dtm.loadDocument(new FileInputStream(testDataFile));
                                    testDataDoc = dtm.documentNode();
                                    _docCache.put(name, testDataDoc);
                                }
                                defaultCollectionMap.put(docName, testDataDoc);
                                // import namespace decl
                                Map<String, String> nsmap = testDataDoc.documentTable().getDeclaredNamespaces();
                                NamespaceBinder nsResolver = statEnv.getStaticalyKnownNamespaces();
                                nsResolver.declarePrefixs(nsmap);
                            }
                            statEnv.setDefaultCollection(defaultCollectionMap);
                        }
                    }
                }
                Sequence<? extends Item> contextItem = null;
                {// ((//*:test-group)//*:test-case)/*:contextItem
                    String contextItemRef = xpath.evaluate("./*[local-name()='contextItem']/text()", testCase);
                    if(contextItemRef != null && contextItemRef.length() > 0) {
                        String contextItemFileRef = xpath.evaluate("/*[local-name()='test-suite']/*[local-name()='sources']/*[local-name()='source']/@FileName[../@ID='"
                                + contextItemRef + "']", catalog);
                        DTMDocument contextItemDoc = _docCache.get(contextItemRef);
                        if(contextItemDoc == null) {
                            File contextItemFile = new File(xqtsDir, contextItemFileRef);
                            DocumentTableModel dtm = new DocumentTableModel(false);
                            dtm.loadDocument(new FileInputStream(contextItemFile));
                            contextItemDoc = dtm.documentNode();
                            _docCache.put(contextItemRef, contextItemDoc);
                        }
                        contextItem = contextItemDoc;
                    }
                }
                {// ((//*:test-group)//*:test-case)/*:input-query
                    String inputVarName = xpath.evaluate("./*[local-name()='input-query']/@variable", testCase);
                    if(inputVarName != null && inputVarName.length() > 0) {
                        String dateData = xpath.evaluate("./*[local-name()='input-query']/@date", testCase);
                        assert (dateData != null) : dateData;
                        QualifiedName varName = QNameTable.instantiate(XMLConstants.DEFAULT_NS_PREFIX, inputVarName);
                        Variable var = new Variable.GlobalVariable(varName, null);
                        var.setResult(new DateTimeValue(dateData, DateType.DATE));
                        xqmod.putVariable(varName, var);
                    }
                }

                // -----------------------------------------------------------
                // #1 execute
                final String resString;
                {
                    final String query = IOUtils.toString(new FileInputStream(queryFile), "UTF-8");
                    if(doPrint) {
                        println("Query: ");
                        println(query);
                    }
                    final NodeList expectedErrors = (NodeList) xpath.evaluate("./*[local-name()='expected-error']", testCase, XPathConstants.NODESET);
                    {
                        XQueryProcessor proc = new XQueryProcessor(xqmod);
                        proc.setStaticContext(statEnv);
                        if(contextItem != null) {
                            proc.setContextItem(contextItem);
                        }
                        final StringWriter res_sw = new StringWriter();
                        try {
                            XQueryModule mod = proc.parse(query, baseUri);
                            Sequence result = proc.execute(mod);
                            SAXWriter saxwriter = new SAXWriter(res_sw, SAXWriter.DEFAULT_ENCODING);
                            saxwriter.setXMLDeclaration(false);
                            Serializer ser = new SAXSerializer(saxwriter, res_sw);
                            ser.emit(result);
                        } catch (Throwable ex) {
                            final int errors = expectedErrors.getLength();
                            if(errors == 0) {
                                final Node expectedOutputs = (Node) xpath.evaluate("./*[local-name()='output-file'][last()]", testCase, XPathConstants.NODE);
                                assert (expectedOutputs != null);
                                final Element output = (Element) expectedOutputs;
                                final String expFileName = output.getTextContent();
                                final File testFileDir = new File(xqtsResultPath, testFilePath);
                                String expectedResult = _expectedResultStrCache.get(expFileName);
                                if(expectedResult == null) {
                                    File expected = new File(testFileDir, expFileName);
                                    expectedResult = IOUtils.toString(new FileInputStream(expected));
                                    _expectedResultStrCache.put(expFileName, expectedResult);
                                }
                                if(doPrint) {
                                    println("Expected Result: ");
                                    println(expectedResult);
                                }
                                final String compareForm = output.getAttribute("compare");
                                final String errmsg;
                                if("Ignore".equals(compareForm)) {
                                    errmsg = "Unexpected exception: \n" + PrintUtils.getMessage(ex);
                                    String smallerrmsg = "Unexpected exception: "
                                            + PrintUtils.prettyPrintStackTrace(ex);
                                    reportTestResult(testName, "fail", smallerrmsg);
                                } else if("Inspect".equals(compareForm)) {
                                    errmsg = "Inspectection is required, got exception: \n"
                                            + PrintUtils.prettyPrintStackTrace(ex);
                                    String smallerrmsg = "Inspectection is required, got exception: "
                                            + PrintUtils.getOneLineMessage(ex);
                                    reportTestResult(testName, "not tested", smallerrmsg);
                                } else {
                                    errmsg = (expectedResult == null) ? "No result"
                                            : ('\'' + expectedResult + '\'')
                                                    + " is expected, but caused following exception: \n"
                                                    + PrintUtils.prettyPrintStackTrace(ex);
                                    String smallerrmsg = (expectedResult == null) ? "No result"
                                            : ('\'' + expectedResult + '\'')
                                                    + " is expected, but caused following exception: "
                                                    + PrintUtils.getOneLineMessage(ex);
                                    reportTestResult(testName, "fail", smallerrmsg);
                                }
                                Assert.fail(errmsg);
                            } else {
                                String errMsg = ex.getMessage();
                                if(errMsg == null) {
                                    errMsg = PrintUtils.getOneLineMessage(ex);
                                }
                                final int lastei = errors - 1;
                                for(int ei = 0; ei < errors; ei++) {
                                    final String expectedError = expectedErrors.item(ei).getTextContent();
                                    final boolean contain = (errMsg == null) ? false
                                            : errMsg.contains(expectedError);
                                    if(contain) {
                                        reportTestResult(testName, "pass", null);
                                        break;
                                    } else {
                                        final String msg = "Expected-error: " + expectedError
                                                + ", Actual Error: " + errMsg;
                                        if(!(ex instanceof XQueryException || ex instanceof XQRTException)) {
                                            reportTestResult(testName, "fail", msg);
                                            ex.printStackTrace();
                                            Assert.fail(msg);
                                        } else {
                                            if(ei == lastei) {
                                                final String passmsg = "Expected-error: "
                                                        + expectedError + ", Actual Error: "
                                                        + getErrCode(ex);
                                                reportTestResult(testName, "fail", passmsg);
                                                ex.printStackTrace();
                                                Assert.fail(msg);
                                            }
                                        }
                                    }
                                }
                                return;
                            }
                        }
                        resString = res_sw.toString();
                        if(doPrint) {
                            println("\nActual Result: ");
                            println(resString);
                        }
                    }
                    final int errors = expectedErrors.getLength();
                    if(errors > 0) {
                        final StringBuilder buf = new StringBuilder(256);
                        for(int ei = 0; ei < errors; ei++) {
                            if(ei != 0) {
                                buf.append(" or ");
                            }
                            final String expectedError = expectedErrors.item(ei).getTextContent();
                            buf.append(expectedError);
                        }
                        buf.append(" is expected, but was ..\n");
                        buf.append(resString);
                        Assert.fail(buf.toString());
                    }
                }

                // -----------------------------------------------------------
                // #2 probe
                {
                    NodeList expectedOutputs = (NodeList) xpath.evaluate("./*[local-name()='output-file']", testCase, XPathConstants.NODESET);
                    final int expectedOuts = expectedOutputs.getLength();
                    if(expectedOuts == 0) {
                        Assert.fail("Expected condition is not found in '" + testName + '\'');
                    }
                    final File testFileDir = new File(xqtsResultPath, testFilePath);
View Full Code Here

        assert (created) : "File creation failed: " + testCaseList.getAbsolutePath();
    }

    private static void generate() throws Exception {
        final Document catalog = XQTSTestBase.catalogPool.borrowObject();
        final XPath xpath = XPathFactory.newInstance().newXPath();
        NamespaceBinder resolver = new NamespaceBinder();
        resolver.declarePrefix(XQTSTestBase.CATALONG_URI_PREFIX, XQTSTestBase.CATALONG_URI);
        xpath.setNamespaceContext(resolver);
        int tcCount = 0, tcGenCount = 0;
        File testDestDir = new File(TEST_RESOURCE_DIR);
        assert (testDestDir.exists()) : testDestDir.getAbsolutePath();
        File destFile = new File(testDestDir, "TestCase.list");
        PrintWriter pw = new PrintWriter(destFile);
        NodeList rs = (NodeList) xpath.evaluate(ADDR_TEST_GROUPS, catalog, XPathConstants.NODESET);
        final int rslen = rs.getLength();
        for(int i = 0; i < rslen; i++) {
            final String ADDR_TEST_GROUP = '(' + ADDR_TEST_GROUPS + ")[" + (i + 1) + ']';
            Node testGroup = rs.item(i);
            assert (testGroup != null);
            assert (testGroup.hasAttributes());
            String filepath = (String) xpath.evaluate("ns:test-case[1]/@FilePath", testGroup, XPathConstants.STRING);
            if(filepath == null || filepath.length() == 0) {
                // test-group might have no test-case
                continue;
            }
            assert (filepath.endsWith("/")) : filepath;
            String testDir = filepath.replace('-', '_').toLowerCase().substring(0, filepath.lastIndexOf('/'));
            String packageName = testDir.replace('/', '.');
            String[] dirs = testDir.split("/");
            assert (dirs.length > 0);
            File parentDir = new File(TEST_DEST_DIR);
            assert (parentDir.isDirectory());
            for(String dir : dirs) {
                assert (parentDir.exists());
                File curDir = new File(parentDir, dir);
                if(!curDir.exists()) {
                    boolean mkdirSucc = curDir.mkdir();
                    assert (mkdirSucc);
                    System.err.println("Created directory.. " + curDir.getAbsolutePath());
                }
                parentDir = curDir;
            }
            assert (parentDir.exists());
            final String CLASS_NAME = toClassName(testGroup.getAttributes().getNamedItem("name").getNodeValue())
                    + "Test";
            final String CLASS_SRC_FILE = CLASS_NAME + ".java";
            File classSrcFile = new File(parentDir, CLASS_SRC_FILE);
            if(!classSrcFile.exists()) {
                final String tmpl = IOUtils.toString(TestCodeGenerator.class.getResourceAsStream("XQTSTest.template"));
                final String PACKAGE_NAME = ("xqts." + testDir.replace('/', '.'));
                assert (CLASS_NAME != null);
                final String TEST_PATH = '(' + ADDR_TEST_GROUP + "//ns:test-case)";
                final String code = tmpl.replace("$XQTS_VERSION", XQTSTestBase.xqtsVersion).replace("$PACKAGE", PACKAGE_NAME).replace("$TEST_PATH", TEST_PATH).replace("$CLASSNAME", CLASS_NAME);
                final StringBuilder codeBuf = new StringBuilder(512);
                assert (code.length() > 0);
                codeBuf.append(code, 0, code.lastIndexOf('}') - 1);
                final int count = countTests(TEST_PATH, catalog);
                assert (count >= 1) : count;
                String methodTmpl = IOUtils.toString(TestCodeGenerator.class.getResourceAsStream("TestMethod.template"));
                methodTmpl = methodTmpl.replace("$TIMEOUT", XQTSTestBase.XQTS_PROP.getProperty("test.timeout")).replace("$TESTPATH", TEST_PATH);
                NodeList methods = (NodeList) xpath.evaluate(TEST_PATH + "/@name", catalog, XPathConstants.NODESET);
                assert (count == methods.getLength());
                for(int j = 0; j < count; j++) {
                    String methodName = methods.item(j).getTextContent();
                    assert (methodName != null);
                    methodName = toClassName(methodName);
View Full Code Here

        pw.write(line);
    }

    protected static int countTests(String testPath, Document catalog)
            throws XPathExpressionException {
        final XPath xpath = XPathFactory.newInstance().newXPath();
        NamespaceBinder resolver = new NamespaceBinder();
        resolver.declarePrefix(XQTSTestBase.CATALONG_URI_PREFIX, XQTSTestBase.CATALONG_URI);
        xpath.setNamespaceContext(resolver);
        final String count = "count(" + testPath + ")";
        XPathExpression expr = xpath.compile(count);
        final Double d = (Double) expr.evaluate(catalog, XPathConstants.NUMBER);
        return d.intValue();
    }
View Full Code Here

          "XPathExpression");
      try
      {
        if (xPathExpr != null)
        {
          XPath xPath = XPathFactory.newInstance().newXPath();
          String function = xPath.evaluate(xPathExpr, doc
              .getDocumentElement());
          function = XStringSupport.replaceAll(function, " ", "");
          setFunction(function);
        }
      }
View Full Code Here

        }
        return answer;
    }
   
    protected XPathExpression createXPathExpression() throws XPathExpressionException, XPathFactoryConfigurationException {
        XPath xPath = getXPathFactory().newXPath();

        xPath.setNamespaceContext(getNamespaceContext());
        return xPath.compile(text);
    }
View Full Code Here


  public Map<String, String> extractXmlNamespaces(Node contextNode)
      throws JRException {
    Map<String, String> namespaces = new HashMap<String, String>();
    XPath namespaceXPath = xpathFact.newXPath();
    String namespaceXPathString = "//namespace::*";
   

    try {
      NodeList nlist = (NodeList) namespaceXPath.evaluate(
          namespaceXPathString, contextNode, XPathConstants.NODESET);
      for (int i = 0; i < nlist.getLength(); i++) {
        Node node = nlist.item(i);
        namespaces.put(node.getNodeName().substring("xmlns:".length()),
            node.getNodeValue());
View Full Code Here

TOP

Related Classes of javax.xml.xpath.XPath

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.