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:com.discursive.jccook.collections.predicate.XPathPredicate.java

public boolean evaluate(Object object) {
    boolean matches = false;
    JXPathContext context = JXPathContext.newContext(object);
    if (variables != null) {
        populateVariables(context);//from  www  .jav  a2s  . c  o  m
    }
    try {
        Object value = context.getValue(path);
        if (value != null) {
            matches = true;
        }
    } catch (JXPathException e) {
        // If this happens there is no match
    }
    return matches;
}

From source file:com.pavelvlasov.uml.eval.JXPathEvaluator.java

public String evaluate(String expr, Object contextObject) {
    Object res = null;/* ww  w  .  j  a v a 2s . c om*/
    if (contextObject instanceof Element) {
        res = ((Element) contextObject).navigate(expr);
    } else {
        JXPathContext parentContext = parentContextResolver == null ? null
                : parentContextResolver.resolveParentContext(contextObject);

        /*
         * Don't cache results if parent context resolver is not null
         */
        if (parentContextResolver != null) {
            CachingInvocationHandler.doNotCacheCurrentResult();
        }

        JXPathContext context = parentContext == null ? JXPathContext.newContext(contextObject)
                : JXPathContext.newContext(parentContext, contextObject);
        res = context.getValue(expr);
    }
    return res == null ? "" : res.toString();
}

From source file:com.intuit.tank.http.json.JsonResponse.java

@Override
public String getValue(String key) {

    try {//from   w w w . j  a v a2  s  . c om
        if (NumberUtils.isDigits(key)) {
            Integer.parseInt(key);
            JSONObject jsonResponse = new JSONObject(this.response);
            return (String) jsonResponse.get(key);
        }
    } catch (Exception e) {
    }
    try {
        if (this.jsonMap == null) {
            initialize();
        }
        String keyTrans = key.replace("@", "");
        // note that indexing is 1 based not zero based
        JXPathContext context = JXPathContext.newContext(this.jsonMap);
        String output = URLDecoder.decode(String.valueOf(context.getValue(keyTrans)), "UTF-8");
        if (output.equalsIgnoreCase("null"))
            return "";
        return output;
    } catch (Exception ex) {
        return "";
    }
}

From source file:com.opera.core.systems.scope.AbstractService.java

/**
 * Query a collection with JXPath and return value of node
 *
 * @param collection/* w ww  . j  a  v  a 2s  . c o m*/
 * @param query a valid XPath query
 * @return result
 */
public Object xpathQuery(Collection<?> collection, String query) {
    JXPathContext pathContext = JXPathContext.newContext(collection);
    Object result = null;
    try {
        result = pathContext.getValue(query);
    } catch (JXPathNotFoundException e) {
        logger.log(Level.WARNING, "JXPath exception: {0}", e.getMessage());
    }
    return result;
}

From source file:de.innovationgate.wga.server.api.Xml.java

/**
 * Executes an XPath expression on some XML text or JavaBean
 * This function always returns single values. If the xpath expression matches multiple values it will only return the first one. To retrieve lists of values use {@link #xpathList(Object, String)}.
 * The given object to parse as XML is either a dom4j branch object (mostly document or element), a String containing XML text or a JavaBean. In the last case this function uses JXPath functionality to find a bean property value.
 * This uses the Apache library JXPath under the hood. See their documentation for details how XPath is used to browser JavaBeans.
 * @param object Object to inspect//www  .j a v a2s  . c o m
 * @param xpath XPath expression
 * @param ns Map of namespace prefix declarations used in the XPath. Keys are prefixes, values are namespace URIs.
 * @return Returned value
 * @throws DocumentException
 */
public Object xpath(Object object, String xpath, Map<String, String> ns) throws WGException, DocumentException {
    Object result;
    if (object instanceof String || object instanceof Branch) {
        Branch branch = retrieveBranch(object);
        XPath xpathObj = createXPath(xpath, branch, ns);
        result = xpathObj.evaluate(branch);
    }

    // Do JXPath on Bean
    else {
        JXPathContext jxContext = JXPathContext.newContext(object);
        jxContext.setLenient(true);
        result = jxContext.getValue(xpath);
    }
    return convertXMLObjects(result, false);
}

From source file:jp.co.opentone.bsol.framework.test.AbstractTestCase.java

/**
 * ???Excel????./*ww  w.  jav a  2s . c o m*/
 * <p>
 * ????
 * <ul>
 * <li>Excel?</li>
 * <li>Excel????</li>
 * <li>Excel?</li>
 * <li>?????</li>
 * </ul>
 * </p>
 * @param sheetCount Excel?
 * @param sheetName Excel????
 * @param sheetRow Excel?????
 * @param expected 
 * @param actual Excel
 * @throws Exception ??
 */
@SuppressWarnings("unchecked")
protected void assertExcel(int sheetCount, String sheetName, int sheetRow, List<Object> expected, byte[] actual)
        throws Exception {
    // JXPathContext?
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(new ByteArrayInputStream(actual));
    JXPathContext context = JXPathContext.newContext(document);
    // ????
    context.registerNamespace("NS", "urn:schemas-microsoft-com:office:spreadsheet");

    // ?TEST
    assertEquals(sheetCount, ((Double) context.getValue("count(/NS:Workbook/NS:Worksheet)")).intValue());
    // ?TEST??
    assertEquals(sheetName, context.getValue("/NS:Workbook/NS:Worksheet/@ss:Name"));
    // ?TEST
    assertEquals(sheetRow + 1, Integer
            .parseInt((String) context.getValue("/NS:Workbook/NS:Worksheet/NS:Table/@ss:ExpandedRowCount")));

    // Row??
    int rows = ((Double) context.getValue("count(/NS:Workbook/NS:Worksheet/NS:Table/NS:Row)")).intValue();
    assertEquals(sheetRow + 1, rows);

    // ????
    for (int i = 1; i <= rows; i++) {
        // XPath??
        context.getVariables().declareVariable("index", i);
        // Pointer?????JXPathContext?
        Pointer pointer = context.getPointer("/NS:Workbook/NS:Worksheet/NS:Table/NS:Row[$index]");
        JXPathContext contextRow = context.getRelativeContext(pointer);
        contextRow.registerNamespace("NS", "urn:schemas-microsoft-com:office:spreadsheet");

        List<Object> expectedRow = (List<Object>) expected.get(i - 1);

        // Column??
        int columns = ((Double) contextRow.getValue("count(NS:Cell)")).intValue();
        // ????
        for (int j = 1; j <= columns; j++) {
            // Pointer?????JXPathContext?
            contextRow.getVariables().declareVariable("index", j);
            Pointer pointerColumn = contextRow.getPointer("NS:Cell[$index]");
            JXPathContext contextColumn = contextRow.getRelativeContext(pointerColumn);

            // 
            String actualColumn = (String) contextColumn.getValue("NS:Data");
            // actualColumn?String?????String??
            String expectedColumn;
            Object o = expectedRow.get(j - 1);
            if (o == null) {
                expectedColumn = "";
            } else if (o instanceof Date) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
                expectedColumn = dateFormat.format(o);
            } else {
                expectedColumn = o.toString();
            }
            // ?TEST?
            assertEquals(expectedColumn, actualColumn);
        }
    }
}

From source file:net.sbbi.upnp.services.UPNPService.java

private void parseSCPD() {
    try {/*  w  ww  .  j  a v  a  2s  .c o m*/
        DocumentContainer.registerXMLParser(DocumentContainer.MODEL_DOM, new JXPathParser());
        UPNPService = new DocumentContainer(SCPDURL, DocumentContainer.MODEL_DOM);
        JXPathContext context = JXPathContext.newContext(this);
        Pointer rootPtr = context.getPointer("UPNPService/scpd");
        JXPathContext rootCtx = context.getRelativeContext(rootPtr);

        specVersionMajor = Integer.parseInt((String) rootCtx.getValue("specVersion/major"));
        specVersionMinor = Integer.parseInt((String) rootCtx.getValue("specVersion/minor"));

        parseServiceStateVariables(rootCtx);

        Pointer actionsListPtr = rootCtx.getPointer("actionList");
        JXPathContext actionsListCtx = context.getRelativeContext(actionsListPtr);
        Double arraySize = (Double) actionsListCtx.getValue("count( action )");
        UPNPServiceActions = new HashMap();
        for (int i = 1; i <= arraySize.intValue(); i++) {
            ServiceAction action = new ServiceAction();
            action.name = (String) actionsListCtx.getValue("action[" + i + "]/name");
            action.parent = this;
            Pointer argumentListPtr = null;
            try {
                argumentListPtr = actionsListCtx.getPointer("action[" + i + "]/argumentList");
            } catch (JXPathException ex) {
                // there is no arguments list.
            }
            if (argumentListPtr != null) {
                JXPathContext argumentListCtx = actionsListCtx.getRelativeContext(argumentListPtr);
                Double arraySizeArgs = (Double) argumentListCtx.getValue("count( argument )");

                List orderedActionArguments = new ArrayList();
                for (int z = 1; z <= arraySizeArgs.intValue(); z++) {
                    ServiceActionArgument arg = new ServiceActionArgument();
                    arg.name = (String) argumentListCtx.getValue("argument[" + z + "]/name");
                    String direction = (String) argumentListCtx.getValue("argument[" + z + "]/direction");
                    arg.direction = direction.equals(ServiceActionArgument.DIRECTION_IN)
                            ? ServiceActionArgument.DIRECTION_IN
                            : ServiceActionArgument.DIRECTION_OUT;
                    String stateVarName = (String) argumentListCtx
                            .getValue("argument[" + z + "]/relatedStateVariable");
                    ServiceStateVariable stateVar = (ServiceStateVariable) UPNPServiceStateVariables
                            .get(stateVarName);
                    if (stateVar == null) {
                        throw new IllegalArgumentException(
                                "Unable to find any state variable named " + stateVarName + " for service "
                                        + getServiceId() + " action " + action.name + " argument " + arg.name);
                    }
                    arg.relatedStateVariable = stateVar;
                    orderedActionArguments.add(arg);
                }

                if (arraySizeArgs.intValue() > 0) {
                    action.setActionArguments(orderedActionArguments);
                }
            }

            UPNPServiceActions.put(action.getName(), action);
        }
        parsedSCPD = true;
    } catch (Throwable t) {
        throw new RuntimeException("Error during lazy SCDP file parsing at " + SCPDURL, t);
    }
}

From source file:net.sbbi.upnp.services.UPNPService.java

private void parseServiceStateVariables(JXPathContext rootContext) {
    Pointer serviceStateTablePtr = rootContext.getPointer("serviceStateTable");
    JXPathContext serviceStateTableCtx = rootContext.getRelativeContext(serviceStateTablePtr);
    Double arraySize = (Double) serviceStateTableCtx.getValue("count( stateVariable )");
    UPNPServiceStateVariables = new HashMap();
    for (int i = 1; i <= arraySize.intValue(); i++) {
        ServiceStateVariable srvStateVar = new ServiceStateVariable();
        String sendEventsLcl = null;
        try {//from   w w  w .ja  v a  2s . co  m
            sendEventsLcl = (String) serviceStateTableCtx.getValue("stateVariable[" + i + "]/@sendEvents");
        } catch (JXPathException defEx) {
            // sendEvents not provided defaulting according to specs to "yes"
            sendEventsLcl = "yes";
        }
        srvStateVar.parent = this;
        srvStateVar.sendEvents = sendEventsLcl.equalsIgnoreCase("no") ? false : true;
        srvStateVar.name = (String) serviceStateTableCtx.getValue("stateVariable[" + i + "]/name");
        srvStateVar.dataType = (String) serviceStateTableCtx.getValue("stateVariable[" + i + "]/dataType");
        try {
            srvStateVar.defaultValue = (String) serviceStateTableCtx
                    .getValue("stateVariable[" + i + "]/defaultValue");
        } catch (JXPathException defEx) {
            // can happend since default value is not
        }
        Pointer allowedValuesPtr = null;
        try {
            allowedValuesPtr = serviceStateTableCtx.getPointer("stateVariable[" + i + "]/allowedValueList");
        } catch (JXPathException ex) {
            // there is no allowed values list.
        }
        if (allowedValuesPtr != null) {
            JXPathContext allowedValuesCtx = serviceStateTableCtx.getRelativeContext(allowedValuesPtr);
            Double arraySizeAllowed = (Double) allowedValuesCtx.getValue("count( allowedValue )");
            srvStateVar.allowedvalues = new HashSet();
            for (int z = 1; z <= arraySizeAllowed.intValue(); z++) {
                String allowedValue = (String) allowedValuesCtx.getValue("allowedValue[" + z + "]");
                srvStateVar.allowedvalues.add(allowedValue);
            }
        }

        Pointer allowedValueRangePtr = null;
        try {
            allowedValueRangePtr = serviceStateTableCtx
                    .getPointer("stateVariable[" + i + "]/allowedValueRange");
        } catch (JXPathException ex) {
            // there is no allowed values list, can happen
        }
        if (allowedValueRangePtr != null) {

            srvStateVar.minimumRangeValue = (String) serviceStateTableCtx
                    .getValue("stateVariable[" + i + "]/allowedValueRange/minimum");
            srvStateVar.maximumRangeValue = (String) serviceStateTableCtx
                    .getValue("stateVariable[" + i + "]/allowedValueRange/maximum");
            try {
                srvStateVar.stepRangeValue = (String) serviceStateTableCtx
                        .getValue("stateVariable[" + i + "]/allowedValueRange/step");
            } catch (JXPathException stepEx) {
                // can happend since step is not mandatory
            }
        }
        UPNPServiceStateVariables.put(srvStateVar.getName(), srvStateVar);
    }

}

From source file:net.sbbi.upnp.devices.UPNPRootDevice.java

private String getMandatoryData(JXPathContext ctx, String ctxFieldName) {
    String value = (String) ctx.getValue(ctxFieldName);
    if (value != null && value.length() == 0) {
        throw new JXPathException(
                "Mandatory field " + ctxFieldName + " not provided, uncompliant UPNP device !!");
    }//from w  w w.  j ava 2s  . c o m
    return value;
}

From source file:net.sbbi.upnp.services.UPNPService.java

public UPNPService(JXPathContext serviceCtx, URL baseDeviceURL, UPNPDevice serviceOwnerDevice)
        throws MalformedURLException {
    this.serviceOwnerDevice = serviceOwnerDevice;
    serviceType = (String) serviceCtx.getValue("serviceType");
    serviceId = (String) serviceCtx.getValue("serviceId");
    SCPDURL = UPNPRootDevice.getURL((String) serviceCtx.getValue("SCPDURL"), baseDeviceURL);
    controlURL = UPNPRootDevice.getURL((String) serviceCtx.getValue("controlURL"), baseDeviceURL);
    eventSubURL = UPNPRootDevice.getURL((String) serviceCtx.getValue("eventSubURL"), baseDeviceURL);
    USN = serviceOwnerDevice.getUDN().concat("::").concat(serviceType);
}