List of usage examples for org.apache.commons.jxpath JXPathContext getValue
public abstract Object getValue(String xpath);
From source file:com.discursive.jccook.xml.jxpath.PersonExample.java
public void start() throws IOException, SAXException { List people = new ArrayList(); Person person1 = new Person(); person1.setFirstName("Ahmad"); person1.setLastName("Russell"); person1.setAge(28);//from ww w . j a v a 2s . co m people.add(person1); Person person2 = new Person(); person2.setFirstName("Tom"); person2.setLastName("Russell"); person2.setAge(35); people.add(person2); Person person3 = new Person(); person3.setFirstName("Ahmad"); person3.setLastName("Abuzayedeh"); person3.setAge(33); people.add(person3); System.out.println("** People older than 30"); JXPathContext context = JXPathContext.newContext(people); Iterator iterator = context.iterate(".[@age > 30]"); printPeople(iterator); context = JXPathContext.newContext(people); System.out.println("** People with first name 'Ahmad'"); iterator = context.iterate(".[@firstName = 'Ahmad']"); printPeople(iterator); context = JXPathContext.newContext(people); System.out.println("** Second Person in List"); Person p = (Person) context.getValue(".[2]"); System.out.println("Person: " + p.getFirstName() + " " + p.getLastName() + ", age: " + p.getAge()); }
From source file:net.sbbi.upnp.devices.UPNPRootDevice.java
private String getNonMandatoryData(JXPathContext ctx, String ctxFieldName) { String value = null;//from w ww . j a v a 2 s .co m try { value = (String) ctx.getValue(ctxFieldName); if (value != null && value.length() == 0) { value = null; } } catch (JXPathException ex) { value = null; } return value; }
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 w w w. j a v a 2 s .com 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:com.idega.chiba.web.xml.xforms.ui.IdegaText.java
protected boolean evalCondition(Element action, String ifCondition) { //get the global XPath context JXPathContext context = this.model.getDefaultInstance().getInstanceContext(); Boolean b;//from w w w.j a v a 2 s .c o m //get the right current context - if we're not bound we've to walk up to get it String currentPath = getParentContextPath(action); if (currentPath == null) { //try to evaluate ifCondition without context -> it may contain an absolute locationpath try { b = (Boolean) context.getValue(ifCondition); } catch (JXPathException jxe) { jxe.printStackTrace(); return true; //default to true behaving as if the if attribute weren't there and therefore executing the action } } else { String expr = XPathUtil.joinStep(new String[] { currentPath, ifCondition }); b = (Boolean) context.getValue("boolean(" + expr + ")"); } return b.booleanValue(); }
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//from w w w .j a v a2s . c o 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: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 . j a v a 2s . c o 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 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 w w.j a va 2 s. com 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:com.idega.chiba.web.xml.xforms.elements.action.IdegaDeleteAction.java
/** * Performs the <code>delete</code> action for all nodes. * /* www . j a va 2 s . co m*/ * @throws XFormsException * if an error occurred during <code>delete</code> processing. */ public void perform() throws XFormsException { super.perform(); // get instance and nodeset information Instance instance = this.model.getInstance(getInstanceId()); String pathExpression = getLocationPath(); int contextSize = instance.countNodeset(pathExpression); if (contextSize == 0) { getLogger().warn(this + " perform: nodeset '" + pathExpression + "' is empty"); return; } String path = null; // since jxpath doesn't provide a means for evaluating an expression // in a certain context, we use a trick here: the expression will be // evaluated during getPointer and the result stored as a variable JXPathContext context = instance.getInstanceContext(); boolean lenient = context.isLenient(); context.setLenient(true); context.getPointer(pathExpression + "[chiba:declare('delete-position', 1)]"); context.setLenient(lenient); // since jxpath's round impl is buggy (returns 0 for NaN) we perform // 'round' manually double value = ((Double) context.getValue("number(chiba:undeclare('delete-position'))")).doubleValue(); long position = Math.round(value); if (Double.isNaN(value) || position < 1 || position > contextSize) { getLogger().warn(this + " perform: expression '1' does not point to an existing node"); return; } path = new StringBuffer(pathExpression).append('[').append(position).append(']').toString(); // delete specified node and dispatch notification event while (instance.existsNode(path)) { try { instance.deleteNode(path); getLogger().info("Node deleted in delete action:" + path); } catch (JXPathException e) { getLogger().warn("Unable to delete:" + path); } } if (StringUtil.isEmpty(path)) { return; } this.container.dispatch(instance.getTarget(), XFormsEventNames.DELETE, path); // update behaviour doRebuild(true); doRecalculate(true); doRevalidate(true); doRefresh(true); }
From source file:com.discursive.jccook.xml.jxpath.PlanetSearch.java
public void planetSearch() throws IOException, SAXException { List planets = new ArrayList(); InputStream input = getClass().getResourceAsStream("./planets.xml"); URL rules = getClass().getResource("./planet-digester-rules.xml"); Digester digester = DigesterLoader.createDigester(rules); digester.push(planets);/*from w ww. jav a 2s . co m*/ digester.parse(input); System.out.println("Number of planets: " + planets.size()); System.out.println("Planet Name where radius > 5000"); JXPathContext context = JXPathContext.newContext(planets); Iterator iterator = context.iterate(".[@radius > 5000]/name"); while (iterator.hasNext()) { Object o = (Object) iterator.next(); System.out.println("Object: " + o); } System.out.println("Planet Name where a moon is named Deimos"); iterator = context.iterate("./moons[. = 'Deimos']/../name"); while (iterator.hasNext()) { String name = (String) iterator.next(); System.out.println("Planet Namet: " + name); } System.out.println("Planet where Helium percentage greater than 2"); iterator = context.iterate("./atmosphere/components/He[.>2]/../../.."); while (iterator.hasNext()) { Planet p = (Planet) iterator.next(); System.out.println("Planet: " + p.getName()); } System.out.println("All of the Moon Names"); iterator = context.iterate("./moons"); while (iterator.hasNext()) { String moon = (String) iterator.next(); context.getVariables().declareVariable("moonName", moon); String planet = (String) context.getValue("./moons[. = $moonName]/../name"); System.out.println("Moon: " + moon + ", \t\t\tPlanet: " + planet); } }
From source file:com.netspective.sparx.console.form.InspectObject.java
public void execute(Writer writer, DialogContext dc) throws IOException, DialogExecuteException { JXPathContext jxPathContext = null; DialogFieldStates fieldStates = dc.getFieldStates(); String contextValue = fieldStates.getState("context").getValue().getTextValue(); String jxPathExprValue = fieldStates.getState("jxpath-expr").getValue().getTextValue(); String action = fieldStates.getState("action").getValue().getTextValue(); if (contextValue.equalsIgnoreCase("Project")) jxPathContext = JXPathContext.newContext(dc.getProject()); else if (contextValue.equalsIgnoreCase("Servlet")) jxPathContext = JXPathContext.newContext(dc.getServlet()); else if (contextValue.equalsIgnoreCase("Application")) jxPathContext = JXPathServletContexts .getApplicationContext(dc.getServlet().getServletConfig().getServletContext()); else if (contextValue.equalsIgnoreCase("Request")) jxPathContext = JXPathServletContexts.getRequestContext(dc.getRequest(), dc.getServlet().getServletConfig().getServletContext()); else if (contextValue.equalsIgnoreCase("Session")) jxPathContext = JXPathServletContexts.getSessionContext(dc.getHttpRequest().getSession(), dc.getServlet().getServletConfig().getServletContext()); Object jxPathValue = null;/*from w ww . ja v a2 s . c om*/ if (action.equalsIgnoreCase("getValue")) jxPathValue = jxPathContext.getValue(jxPathExprValue); else jxPathValue = jxPathContext.iterate(jxPathExprValue); if (jxPathValue != null) { Map vars = new HashMap(); vars.put("jxPathValue", jxPathValue); vars.put("jxPathExpr", jxPathExprValue); inspectJxPathValueTemplate.process(writer, dc, vars); } else writer.write("JXPath expression '" + jxPathExprValue + "' evaluated to NULL."); }