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

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

Introduction

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

Prototype

public abstract JXPathContext getRelativeContext(Pointer pointer);

Source Link

Document

Returns a JXPathContext that is relative to the current JXPathContext.

Usage

From source file:com.yahoo.xpathproto.JXPathCopier.java

public static JXPathContext getRelativeContext(JXPathContext context, String path) {
    Pointer pointer = context.getPointer(path);
    if ((pointer == null) || (pointer.getNode() == null)) {
        return null;
    }/*  w w w  . j ava  2s . co  m*/

    return context.getRelativeContext(pointer);
}

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  ww  .ja v  a 2 s. c  o  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.services.UPNPService.java

private void parseSCPD() {
    try {/*w  ww .j a va2s . 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.devices.UPNPRootDevice.java

/**
 * Parsing an UPNPdevice services list element (<device/serviceList>) in the description XML file
 * @param device the device object that will store the services list (UPNPService) objects
 * @param deviceCtx an XPath context for object population
 * @throws MalformedURLException if some URL provided in the description
 *                               file for a service entry is invalid
 *//*from www .j a  v  a 2 s  . c  o m*/
private void fillUPNPServicesList(UPNPDevice device, JXPathContext deviceCtx) throws MalformedURLException {
    Pointer serviceListPtr = deviceCtx.getPointer("serviceList");
    JXPathContext serviceListCtx = deviceCtx.getRelativeContext(serviceListPtr);
    Double arraySize = (Double) serviceListCtx.getValue("count( service )");
    if (log.isDebugEnabled())
        log.debug("device services count is " + arraySize);
    device.services = new ArrayList();
    for (int i = 1; i <= arraySize.intValue(); i++) {

        Pointer servicePtr = serviceListCtx.getPointer("service[" + i + "]");
        JXPathContext serviceCtx = serviceListCtx.getRelativeContext(servicePtr);
        // TODO possibility of bugs if deviceDefLoc contains a file name
        URL base = URLBase != null ? URLBase : deviceDefLoc;
        UPNPService service = new UPNPService(serviceCtx, base, this);
        device.services.add(service);
    }
}

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

/**
 * Constructor for the root device, constructs itself from
 * An xml device definition file provided by the UPNP device via http normally.
 * @param deviceDefLoc the location of the XML device definition file
 *                     using "the urn:schemas-upnp-org:device-1-0" namespace
 * @param maxAge the maximum age in secs of this UPNP device before considered to be outdated
 * @throws MalformedURLException if the location URL is invalid and cannot be used to populate this root object and its child devices
 *         IllegalStateException if the device has an unsupported version, currently only version 1.0 is supported
 *//*w w  w. jav a2  s  . co  m*/
public UPNPRootDevice(URL deviceDefLoc, String maxAge) throws MalformedURLException, IllegalStateException {
    this.deviceDefLoc = deviceDefLoc;
    DocumentContainer.registerXMLParser(DocumentContainer.MODEL_DOM, new JXPathParser());
    UPNPDevice = new DocumentContainer(deviceDefLoc, DocumentContainer.MODEL_DOM);
    validityTime = Integer.parseInt(maxAge) * 1000;
    creationTime = System.currentTimeMillis();

    JXPathContext context = JXPathContext.newContext(this);
    Pointer rootPtr = context.getPointer("UPNPDevice/root");
    JXPathContext rootCtx = context.getRelativeContext(rootPtr);

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

    if (!(specVersionMajor == 1 && specVersionMinor == 0)) {
        throw new IllegalStateException(
                "Unsupported device version (" + specVersionMajor + "." + specVersionMinor + ")");
    }
    boolean buildURLBase = true;
    String base = null;
    try {
        base = (String) rootCtx.getValue("URLBase");
        if (base != null && base.trim().length() > 0) {
            URLBase = new URL(base);
            if (log.isDebugEnabled())
                log.debug("device URLBase " + URLBase);
            buildURLBase = false;
        }
    } catch (JXPathException ex) {
        // URLBase is not mandatory we assume we use the URL of the device
    } catch (MalformedURLException malformedEx) {
        // crappy urlbase provided
        log.warn("Error occured during device baseURL " + base
                + " parsing, building it from device default location", malformedEx);
    }
    if (buildURLBase) {
        String URL = deviceDefLoc.getProtocol() + "://" + deviceDefLoc.getHost() + ":" + deviceDefLoc.getPort();
        String path = deviceDefLoc.getPath();
        if (path != null) {
            int lastSlash = path.lastIndexOf('/');
            if (lastSlash != -1) {
                URL += path.substring(0, lastSlash);
            }
        }
        URLBase = new URL(URL);
    }
    Pointer devicePtr = rootCtx.getPointer("device");
    JXPathContext deviceCtx = rootCtx.getRelativeContext(devicePtr);

    fillUPNPDevice(this, null, deviceCtx, URLBase);
}

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

/**
 * Parsing an UPNPdevice icons list element (<device/iconList>) in the description XML file
 * This list can be null//  w  ww .j  av  a  2 s.  co m
 * @param device the device object that will store the icons list (DeviceIcon) objects
 * @param deviceCtx an XPath context for object population
 * @throws MalformedURLException if some URL provided in the description
 *                               file for an icon URL
 */
private void fillUPNPDeviceIconsList(UPNPDevice device, JXPathContext deviceCtx, URL baseURL)
        throws MalformedURLException {
    Pointer iconListPtr;
    try {
        iconListPtr = deviceCtx.getPointer("iconList");
    } catch (JXPathException ex) {
        // no pointers for icons list, this can happen
        // simply returning
        return;
    }
    JXPathContext iconListCtx = deviceCtx.getRelativeContext(iconListPtr);
    Double arraySize = (Double) iconListCtx.getValue("count( icon )");
    if (log.isDebugEnabled())
        log.debug("device icons count is " + arraySize);
    device.deviceIcons = new ArrayList();
    for (int i = 1; i <= arraySize.intValue(); i++) {

        DeviceIcon ico = new DeviceIcon();
        ico.mimeType = (String) iconListCtx.getValue("icon[" + i + "]/mimetype");
        ico.width = Integer.parseInt((String) iconListCtx.getValue("icon[" + i + "]/width"));
        ico.height = Integer.parseInt((String) iconListCtx.getValue("icon[" + i + "]/height"));
        ico.depth = Integer.parseInt((String) iconListCtx.getValue("icon[" + i + "]/depth"));
        ico.url = getURL((String) iconListCtx.getValue("icon[" + i + "]/url"), baseURL);
        if (log.isDebugEnabled())
            log.debug("icon URL is " + ico.url);
        device.deviceIcons.add(ico);
    }
}

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

/**
 * ???Excel????./*from ww  w .  ja va2  s .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.devices.UPNPRootDevice.java

/**
 * Parsing an UPNPdevice description element (<device>) in the description XML file
 * @param device the device object that will be populated
 * @param parent the device parent object
 * @param deviceCtx an XPath context for object population
 * @param baseURL the base URL of the UPNP device
 * @throws MalformedURLException if some URL provided in the description file is invalid
 *//*from  w  ww . jav a2  s  .c o  m*/
private void fillUPNPDevice(UPNPDevice device, UPNPDevice parent, JXPathContext deviceCtx, URL baseURL)
        throws MalformedURLException {

    device.deviceType = getMandatoryData(deviceCtx, "deviceType");
    if (log.isDebugEnabled())
        log.debug("parsing device " + device.deviceType);
    device.friendlyName = getMandatoryData(deviceCtx, "friendlyName");
    device.manufacturer = getNonMandatoryData(deviceCtx, "manufacturer");
    String base = getNonMandatoryData(deviceCtx, "manufacturerURL");
    try {
        if (base != null)
            device.manufacturerURL = new URL(base);
    } catch (java.net.MalformedURLException ex) {
        // crappy data provided, keep the field null
    }
    try {
        device.presentationURL = getURL(getNonMandatoryData(deviceCtx, "presentationURL"), URLBase);
    } catch (java.net.MalformedURLException ex) {
        // crappy data provided, keep the field null
    }
    device.modelDescription = getNonMandatoryData(deviceCtx, "modelDescription");
    device.modelName = getMandatoryData(deviceCtx, "modelName");
    device.modelNumber = getNonMandatoryData(deviceCtx, "modelNumber");
    device.modelURL = getNonMandatoryData(deviceCtx, "modelURL");
    device.serialNumber = getNonMandatoryData(deviceCtx, "serialNumber");
    device.UDN = getMandatoryData(deviceCtx, "UDN");
    device.USN = UDN.concat("::").concat(deviceType);
    String tmp = getNonMandatoryData(deviceCtx, "UPC");
    if (tmp != null) {
        try {
            device.UPC = Long.parseLong(tmp);
        } catch (Exception ex) {
            // non all numeric field provided, non upnp compliant device
        }
    }
    device.parent = parent;

    fillUPNPServicesList(device, deviceCtx);
    fillUPNPDeviceIconsList(device, deviceCtx, URLBase);

    Pointer deviceListPtr;
    try {
        deviceListPtr = deviceCtx.getPointer("deviceList");
    } catch (JXPathException ex) {
        // no pointers for this device list, this can happen
        // if the device has no child devices, simply returning
        return;
    }
    JXPathContext deviceListCtx = deviceCtx.getRelativeContext(deviceListPtr);
    Double arraySize = (Double) deviceListCtx.getValue("count( device )");
    device.childDevices = new ArrayList();
    if (log.isDebugEnabled())
        log.debug("child devices count is " + arraySize);
    for (int i = 1; i <= arraySize.intValue(); i++) {
        Pointer devicePtr = deviceListCtx.getPointer("device[" + i + "]");
        JXPathContext childDeviceCtx = deviceListCtx.getRelativeContext(devicePtr);
        UPNPDevice childDevice = new UPNPDevice();
        fillUPNPDevice(childDevice, device, childDeviceCtx, baseURL);
        if (log.isDebugEnabled())
            log.debug("adding child device " + childDevice.getDeviceType());
        device.childDevices.add(childDevice);
    }
}

From source file:org.apache.cocoon.forms.binding.AggregateJXPathBinding.java

/**
 * Narrows the scope on the form-model to the member widget-field, and
 * narrows the scope on the object-model to the member xpath-context
 * before continuing the binding over the child-bindings.
 *///from  ww w.  j  ava 2 s. com
public void doLoad(Widget frmModel, JXPathContext jxpc) throws BindingException {
    AggregateField aggregate = (AggregateField) selectWidget(frmModel, this.widgetId);
    JXPathContext subContext = jxpc.getRelativeContext(jxpc.getPointer(this.xpath));
    super.doLoad(aggregate, subContext);
    aggregate.combineFields();
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("Done loading " + toString());
    }
}

From source file:org.apache.cocoon.forms.binding.AggregateJXPathBinding.java

/**
 * Narrows the scope on the form-model to the member widget-field, and
 * narrows the scope on the object-model to the member xpath-context
 * before continuing the binding over the child-bindings.
 *//*from w w w  .  ja v a  2s .com*/
public void doSave(Widget frmModel, JXPathContext jxpc) throws BindingException {
    AggregateField aggregate = (AggregateField) selectWidget(frmModel, this.widgetId);
    JXPathContext subContext = jxpc.getRelativeContext(jxpc.getPointer(this.xpath));
    super.doSave(aggregate, subContext);
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("Done saving " + toString());
    }
}