Example usage for org.apache.commons.jxpath JXPathContext getValue

List of usage examples for org.apache.commons.jxpath JXPathContext getValue

Introduction

In this page you can find the example usage for org.apache.commons.jxpath JXPathContext getValue.

Prototype

public abstract Object getValue(String xpath);

Source Link

Document

Evaluates the xpath and returns the resulting object.

Usage

From source file:org.chiba.xml.xforms.xpath.test.ChibaExtensionFunctionsTest.java

public void testFileDate() throws Exception {
    //determine lastmodified date of test input file
    URL url = getClass().getResource("FileFunctionsTest.xml");
    File inFile = new File(url.getFile());
    long modified = inFile.lastModified();

    //test default date formatting when argument 'format' is omitted
    Calendar calendar = new GregorianCalendar(Locale.getDefault());
    calendar.setTimeInMillis(modified);//from  ww w  . j ava  2  s.c  o  m

    SimpleDateFormat simple1 = new SimpleDateFormat("dd.MM.yyyy H:m:s");
    String s = simple1.format(calendar.getTime());

    ChibaBean chibaBean = initProcessor(inFile);

    Instance instance = chibaBean.getContainer().getDefaultModel().getDefaultInstance();
    JXPathContext context = JXPathContext.newContext(instance);
    String resultofCalc = (String) context.getValue("//filedate1");

    //        DOMUtil.prettyPrintDOM(chibaBean.getContainer().getDefaultModel().getDefaultInstance().getInstanceDocument());
    assertEquals(s, resultofCalc);

    //test date formatting with given pattern
    SimpleDateFormat simple2 = new SimpleDateFormat("yyyy.MM.dd");
    s = simple2.format(calendar.getTime());

    resultofCalc = (String) context.getValue("//filedate2");
    assertEquals(s, resultofCalc);

}

From source file:org.chiba.xml.xforms.xpath.test.ExtensionFunctionsTest.java

public void testInstance() throws Exception {
    Document inDocument = getXmlResource("instance-test.xml");

    ChibaBean chibaBean = new ChibaBean();
    chibaBean.setXMLContainer(inDocument);
    chibaBean.init();// w w  w. j a  v  a 2  s . c  om

    //        XPathExtensionFunctions functions = new XPathExtensionFunctions(chibaBean.getContainer().getDefaultModel());
    XPathExtensionFunctions functions = new XPathExtensionFunctions();
    functions.setNamespaceContext(chibaBean.getContainer().getDefaultModel().getDefaultInstance().getElement());

    JXPathContext context = chibaBean.getContainer().getDefaultModel().getDefaultInstance()
            .getInstanceContext();
    context.setFunctions(functions);

    Object o = context.getValue("instance('first')/some-dummy");
    assertTrue(o.equals("some dummy value"));

    o = context.getValue("xforms:instance('first')/some-dummy");
    assertTrue(o.equals("some dummy value"));

    o = context.getValue("instance('second')/.");
    assertTrue(o.equals("another dummy value"));

    Pointer pointer = context.getPointer("instance('second')/.");
    assertEquals("another dummy value", pointer.getValue());
    assertEquals("/another-dummy[1]", pointer.asPath());

    o = context.getValue("xforms:instance('second')/.");
    assertTrue(o.equals("another dummy value"));
}

From source file:org.chiba.xml.xforms.xpath.XFormsExtensionFunctionsTest.java

public void testCurrent() throws Exception {

    assertEquals("8023.451", this.defaultContext.getValue("instance('instance-3')/convertedAmount"));

    // DOMUtil.prettyPrintDOM(this.chibaBean.getXMLContainer());

    JXPathContext context = JXPathContext.newContext(this.chibaBean.getXMLContainer());
    context.setLenient(true);// w w w  .  j  ava2s.  co m
    assertEquals("Jan", context.getValue("//xf:repeat[2]/xf:group[1]//xf:output/chiba:data[1]"));
    assertEquals("Feb", context.getValue("//xf:repeat[2]/xf:group[2]//xf:output/chiba:data[1]"));
    assertEquals("Mar", context.getValue("//xf:repeat[2]/xf:group[3]//xf:output/chiba:data[1]"));

    this.chibaBean.dispatch("current-trigger", DOMEventNames.ACTIVATE);
    // DOMUtil.prettyPrintDOM(chibaBean.getContainer().getDefaultModel().getInstance("i1").getInstanceDocument());
    assertEquals("Jan", this.defaultContext.getValue("instance('i1')/mon/@result"));

}

From source file:org.cloudml.connectors.util.CloudMLQueryUtil.java

public static Object cloudmlQuery(String jxpath, Object context) {
    JXPathContext jxpathcontext = JXPathContext.newContext(context);
    return jxpathcontext.getValue(jxpath);
}

From source file:org.cloudml.connectors.util.JXPath.java

public Object query(Object context) {
    JXPathContext jpathcontext = JXPathContext.newContext(context);
    return jpathcontext.getValue(literal);
}

From source file:org.cloudml.deployer.CloudMLElementComparator.java

public static Object query(Object obj, String path) {
    try {//  ww w.j a  va2 s.  c om
        JXPathContext jxpc = JXPathContext.newContext(obj);
        return jxpc.getValue(path);
    } catch (NullPointerException e) {
        return null;
    } catch (JXPathNotFoundException e) {
        return null;
    }
}

From source file:org.codehaus.mojo.javascript.assembler.JsBuilderAssemblerReader.java

/**
 * {@inheritDoc}// w  ww. j ava 2 s  . c  om
 * 
 * @see org.codehaus.mojo.javascript.assembler.AssemblerReader#getAssembler(java.io.File)
 */
public Assembler getAssembler(File file) throws Exception {
    logger.info("Reading assembler descriptor " + file.getAbsolutePath());
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document dom = builder.parse(file);

    Assembler assembler = new Assembler();
    JXPathContext xpath = JXPathContext.newContext(dom);
    xpath.setLenient(true);
    String src = (String) xpath.getValue("//directory/@name");
    List nodes = xpath.selectNodes("//target");
    for (Iterator iterator = nodes.iterator(); iterator.hasNext();) {
        Node node = (Node) iterator.next();
        Script script = new Script();
        assembler.addScript(script);
        JXPathContext nodeContext = JXPathContext.newContext(node);
        String fileName = (String) nodeContext.getValue("@file");
        fileName = fileName.replace('\\', '/');
        if (fileName.startsWith(OUTPUT)) {
            fileName = fileName.substring(OUTPUT.length());
        }
        script.setFileName(fileName);

        for (Iterator iter = nodeContext.iterate("//include/@name"); iter.hasNext();) {
            String include = ((String) iter.next()).replace('\\', '/');
            if (src != null && src.length() > 0) {
                include = include.substring(src.length() + 1);
            }
            script.addInclude(include);
        }
    }
    return assembler;
}

From source file:org.commonjava.maven.galley.maven.model.view.JXPathContextAncestryTest.java

@Test
@Ignore/*from w  ww . j a v a2 s.c  o m*/
public void basicJXPathTest() throws Exception {
    final InputStream is = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("jxpath/simple.pom.xml");

    final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);

    final JXPathContext ctx = JXPathContext.newContext(document);

    document.getDocumentElement().removeAttribute("xmlns");

    final String projectGroupIdPath = "ancestor::project/groupId";

    // NOT what's failing...just populating the node set to traverse in order to feed the ancestor:: axis test.
    final List<?> nodes = ctx.selectNodes("/project/dependencies/dependency");
    for (final Object object : nodes) {
        final Node node = (Node) object;
        dump(node);

        final Stack<Node> revPath = new Stack<Node>();

        Node parent = node;
        while (parent != null) {
            revPath.push(parent);
            parent = parent.getParentNode();
        }

        JXPathContext nodeCtx = null;
        while (!revPath.isEmpty()) {
            final Node part = revPath.pop();
            if (nodeCtx == null) {
                nodeCtx = JXPathContext.newContext(part);
            } else {
                nodeCtx = JXPathContext.newContext(nodeCtx, part);
            }
        }

        System.out
                .println("Path derived from context: '" + nodeCtx.getNamespaceContextPointer().asPath() + "'");

        // brute-force approach...try to force population of the parent pointers by painstakingly constructing contexts for all intermediate nodes.
        System.out.println("Selecting groupId for declaring project using path-derived context...");
        System.out.println(nodeCtx.getValue(projectGroupIdPath));

        // Naive approach...this has all the context info it needs to get parent contexts up to and including the document!
        System.out.println("Selecting groupId for declaring project using non-derived context...");
        System.out.println(JXPathContext.newContext(node).getValue(projectGroupIdPath));
    }
}

From source file:org.fireflow.engine.modules.script.functions.XPath.java

public Object getValue(String xpath) {
    Map<String, Object> contextObjects = this.context.getAllContextObject();
    Map<String, String> namespacePrefixUriMap = null;
    if (contextObjects.containsKey(NAMESPACE_PREFIX_URI_MAP)) {
        namespacePrefixUriMap = (Map<String, String>) contextObjects.remove(NAMESPACE_PREFIX_URI_MAP);
    }//ww w . jav  a 2 s .co  m
    JXPathContext jxpathContext = JXPathContext.newContext(contextObjects);

    if (namespacePrefixUriMap != null) {
        Iterator<String> prefixIterator = namespacePrefixUriMap.keySet().iterator();
        while (prefixIterator.hasNext()) {
            String prefix = prefixIterator.next();
            String nsUri = namespacePrefixUriMap.get(prefix);
            jxpathContext.registerNamespace(prefix, nsUri);
        }
    }
    Object result = jxpathContext.getValue(xpath);
    return result;
}

From source file:org.fireflow.pdl.fpdl.test.service.callback.TheCallbackServiceProcessTest1.java

@Test
public void testCallbackService() {
    final WorkflowSession session = WorkflowSessionFactory.createWorkflowSession(fireflowRuntimeContext,
            FireWorkflowSystem.getInstance());
    final WorkflowStatement stmt = session.createWorkflowStatement(FpdlConstants.PROCESS_TYPE_FPDL20);

    //0??//from ww  w. j a v  a2  s .co  m
    final WorkflowProcess process = getWorkflowProcess();

    //1???
    transactionTemplate.execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus arg0) {

            //?
            try {
                ProcessDescriptor descriptor = stmt.uploadProcessObject(process, 0);
                ((ProcessDescriptorImpl) descriptor).setPublishState(true);
                stmt.updateProcessDescriptor(descriptor);
            } catch (InvalidModelException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }
    });

    //2?CallbackManagerinit?Webservice
    //TODO WorkflowServer?webservice

    /*
    WebServiceManager callbackManager = this.runtimeContext.getEngineModule(WebServiceManager.class, FpdlConstants.PROCESS_TYPE_FPDL20);
    try {
       callbackManager.publishAllCallbackServices();
    } catch (WebservicePublishException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
    */

    //3???      
    transactionTemplate.execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus arg0) {

            //??
            try {

                ProcessInstance processInstance = stmt.startProcess(process.getId(), bizId, null);

                if (processInstance != null) {
                    processInstanceId = processInstance.getId();
                }

            } catch (InvalidModelException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (WorkflowProcessNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvalidOperationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }
    });

    //JaxwsWebservice      
    Environment env = fireflowRuntimeContext.getEngineModule(Environment.class,
            FpdlConstants.PROCESS_TYPE_FPDL20);
    URL url = null;
    try {
        String contextPath = env.getWebserviceContextPath();
        if (!contextPath.startsWith("/")) {
            contextPath = "/" + contextPath;
        }
        if (!contextPath.endsWith("/")) {
            contextPath = contextPath + "/";
        }
        String address = "http://" + env.getWebserviceIP() + ":" + Integer.toString(env.getWebservicePort())
                + contextPath;
        url = new URL(address + serviceQName.getLocalPart() + "?wsdl");
    } catch (Exception e) {
        e.printStackTrace();
    }

    javax.xml.ws.Service jawsService = javax.xml.ws.Service.create(url, serviceQName);
    Dispatch<Source> dispatch = jawsService.createDispatch(portQName, Source.class,
            javax.xml.ws.Service.Mode.PAYLOAD);

    String messageStr = "<cal:acceptRequest  xmlns:cal=\"http://www.fireflow.org/junit/callbackservice\">"
            + "<cal:id>" + bizId + "</cal:id>" + "<cal:approveResult>" + approveResult + "</cal:approveResult>"
            + "</cal:acceptRequest>";
    java.io.ByteArrayInputStream byteInStream = new java.io.ByteArrayInputStream(messageStr.getBytes());
    StreamSource source = new StreamSource(byteInStream);

    Source response = dispatch.invoke(source);

    DOMResult result = new DOMResult();
    //      StreamResult result = new StreamResult(System.out);
    Transformer transformer = null;
    try {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformer = transformerFactory.newTransformer();
        transformer.transform(response, result);
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException("Couldn't parse response stream.", e);
    } catch (TransformerException e) {
        throw new RuntimeException("Couldn't parse response stream.", e);
    }

    Document theResponsePayload = (Document) result.getNode();
    Assert.assertNotNull(theResponsePayload);
    JXPathContext jxpathContext = JXPathContext.newContext(theResponsePayload);
    jxpathContext.registerNamespace("ns0", targetNsUri);
    String response2 = (String) jxpathContext.getValue("ns0:acceptResponse/ns0:response2");

    Assert.assertEquals(responseResult, response2);

    this.assertResult(session);
}