List of usage examples for org.apache.commons.jxpath JXPathContext getPointer
public abstract Pointer getPointer(String xpath);
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 *///from w ww .ja v a 2 s. 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 icons list element (<device/iconList>) in the description XML file * This list can be null/*from w w w.j a v a 2s. com*/ * @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 w w w.j a v a 2 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.j av a 2 s .co 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.alfresco.web.forms.xforms.Schema2XForms.java
private void addAttributeSet(final Document xformsDocument, final Element modelSection, final Element defaultInstanceElement, final Element formSection, final XSModel schema, final XSComplexTypeDefinition controlType, final XSElementDeclaration owner, final String pathToRoot, final boolean checkIfExtension, final ResourceBundle resourceBundle) throws FormBuilderException { XSObjectList attrUses = controlType.getAttributeUses(); if (attrUses == null) { return;/*from ww w .j ava 2 s .c o m*/ } for (int i = 0; i < attrUses.getLength(); i++) { final XSAttributeUse currentAttributeUse = (XSAttributeUse) attrUses.item(i); final XSAttributeDeclaration currentAttribute = currentAttributeUse.getAttrDeclaration(); String attributeName = currentAttributeUse.getName(); if (attributeName == null || attributeName.length() == 0) { attributeName = currentAttributeUse.getAttrDeclaration().getName(); } //test if extended ! if (checkIfExtension && SchemaUtil.doesAttributeComeFromExtension(currentAttributeUse, controlType)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "[addAttributeSet] This attribute comes from an extension: recopy form controls. Model section =\n" + XMLUtil.toString(modelSection)); } //find the existing bind Id //(modelSection is the enclosing bind of the element) final NodeList binds = modelSection.getElementsByTagNameNS(NamespaceConstants.XFORMS_NS, "bind"); String bindId = null; for (int j = 0; j < binds.getLength() && bindId == null; j++) { Element bind = (Element) binds.item(j); String nodeset = bind.getAttributeNS(NamespaceConstants.XFORMS_NS, "nodeset"); if (nodeset != null) { //remove "@" in nodeset String name = nodeset.substring(1); if (name.equals(attributeName)) { bindId = bind.getAttributeNS(null, "id"); } } } //find the control Element control = null; if (bindId != null) { if (LOGGER.isDebugEnabled()) LOGGER.debug("[addAttributeSet] bindId found: " + bindId); JXPathContext context = JXPathContext.newContext(formSection.getOwnerDocument()); final Pointer pointer = context .getPointer("//*[@" + NamespaceConstants.XFORMS_PREFIX + ":bind='" + bindId + "']"); if (pointer != null) { control = (Element) pointer.getNode(); } else if (LOGGER.isDebugEnabled()) { LOGGER.debug("[addAttributeSet] unable to resolve pointer for: //*[@" + NamespaceConstants.XFORMS_PREFIX + ":bind='" + bindId + "']"); } } if (LOGGER.isDebugEnabled()) { if (control == null) { LOGGER.debug("[addAttributeSet] control = <not found>"); } else { LOGGER.debug("[addAttributeSet] control = " + control.getTagName()); } } //copy it if (control == null) { if (LOGGER.isDebugEnabled()) LOGGER.debug("Corresponding control not found"); } else { Element newControl = (Element) control.cloneNode(true); //set new Ids to XForm elements this.resetXFormIds(newControl); formSection.appendChild(newControl); } } else { String attrNamespace = currentAttribute.getNamespace(); String namespacePrefix = ""; if (attrNamespace != null && attrNamespace.length() > 0) { String prefix = NamespaceResolver.getPrefix(xformsDocument.getDocumentElement(), attrNamespace); if (prefix != null && prefix.length() > 0) { namespacePrefix = prefix + ":"; } } final String newPathToRoot = (pathToRoot == null || pathToRoot.length() == 0 ? "@" + namespacePrefix + currentAttribute.getName() : (pathToRoot.endsWith("/") ? pathToRoot + "@" + namespacePrefix + currentAttribute.getName() : pathToRoot + "/@" + namespacePrefix + currentAttribute.getName())); if (LOGGER.isDebugEnabled()) LOGGER.debug("[addAttributeSet] adding attribute " + attributeName + " at " + newPathToRoot); try { String defaultValue = (currentAttributeUse.getConstraintType() == XSConstants.VC_NONE ? null : currentAttributeUse.getConstraintValue()); // make sure boolean attributes have a default value if (defaultValue == null && "boolean".equals(currentAttribute.getTypeDefinition().getName())) { defaultValue = "false"; } if (namespacePrefix.length() > 0) { defaultInstanceElement.setAttributeNS(this.targetNamespace, attributeName, defaultValue); } else { defaultInstanceElement.setAttribute(attributeName, defaultValue); } } catch (Exception e) { throw new FormBuilderException("error retrieving default value for attribute " + attributeName + " at " + newPathToRoot, e); } this.addSimpleType(xformsDocument, modelSection, formSection, schema, currentAttribute.getTypeDefinition(), currentAttributeUse, newPathToRoot, resourceBundle); } } }
From source file:org.alfresco.web.forms.xforms.Schema2XForms.java
/** */// ww w . j ava2s .c o m private void addGroup(final Document xformsDocument, final Element modelSection, final Element defaultInstanceElement, final Element formSection, final XSModel schema, final XSModelGroup group, final XSComplexTypeDefinition controlType, final XSElementDeclaration owner, final String pathToRoot, final SchemaUtil.Occurrence occurs, final boolean checkIfExtension, final ResourceBundle resourceBundle) throws FormBuilderException { if (group == null) { return; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("[addGroup] Start of addGroup, from owner = " + owner.getName() + " and controlType = " + controlType.getName()); LOGGER.debug("[addGroup] group before =\n" + XMLUtil.toString(formSection)); } final Element repeatSection = this.addRepeatIfNecessary(xformsDocument, modelSection, formSection, owner.getTypeDefinition(), pathToRoot, occurs); final XSObjectList particles = group.getParticles(); for (int counter = 0; counter < particles.getLength(); counter++) { final XSParticle currentNode = (XSParticle) particles.item(counter); XSTerm term = currentNode.getTerm(); final SchemaUtil.Occurrence childOccurs = new SchemaUtil.Occurrence(currentNode); if (LOGGER.isDebugEnabled()) { LOGGER.debug("[addGroup] next term = " + term.getName() + ", occurs = " + childOccurs); } if (term instanceof XSModelGroup) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("[addGroup] term is a group"); } this.addGroup(xformsDocument, modelSection, defaultInstanceElement, repeatSection, schema, ((XSModelGroup) term), controlType, owner, pathToRoot, childOccurs, checkIfExtension, resourceBundle); } else if (term instanceof XSElementDeclaration) { XSElementDeclaration element = (XSElementDeclaration) term; if (LOGGER.isDebugEnabled()) { LOGGER.debug("[addGroup] term is an element declaration: " + term.getName()); } //special case for types already added because used in an extension //do not add it when it comes from an extension !!! //-> make a copy from the existing form control if (checkIfExtension && SchemaUtil.doesElementComeFromExtension(element, controlType)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "[addGroup] This element comes from an extension: recopy form controls. Model Section =\n" + XMLUtil.toString(modelSection)); } //find the existing bind Id //(modelSection is the enclosing bind of the element) NodeList binds = modelSection.getElementsByTagNameNS(NamespaceConstants.XFORMS_NS, "bind"); String bindId = null; for (int i = 0; i < binds.getLength() && bindId == null; i++) { Element bind = (Element) binds.item(i); String nodeset = bind.getAttributeNS(NamespaceConstants.XFORMS_NS, "nodeset"); Pair<String, String> parsed = parseName(nodeset, xformsDocument); if (nodeset != null && EqualsHelper.nullSafeEquals(parsed.getSecond(), element.getNamespace()) && parsed.getFirst().equals(element.getName())) { bindId = bind.getAttributeNS(null, "id"); } } if (LOGGER.isDebugEnabled()) LOGGER.debug("[addGroup] found bindId " + bindId + " for element " + element.getName()); //find the control Element control = null; if (bindId != null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("[addGroup] bindId found: " + bindId); } final JXPathContext context = JXPathContext.newContext(formSection.getOwnerDocument()); final Pointer pointer = context .getPointer("//*[@" + NamespaceConstants.XFORMS_PREFIX + ":bind='" + bindId + "']"); if (pointer != null) { control = (Element) pointer.getNode(); } else if (LOGGER.isDebugEnabled()) { LOGGER.debug("[addGroup] unable to resolve pointer for: //*[@" + NamespaceConstants.XFORMS_PREFIX + ":bind='" + bindId + "']"); } } if (LOGGER.isDebugEnabled()) { if (control == null) { LOGGER.debug("[addGroup] control = <not found>"); } else { LOGGER.debug("[addGroup] control = " + control.getTagName()); } } //copy it if (control == null) { if (LOGGER.isDebugEnabled()) LOGGER.debug("Corresponding control not found"); this.addElementToGroup(xformsDocument, modelSection, defaultInstanceElement, repeatSection, schema, element, pathToRoot, childOccurs, resourceBundle); } else { Element newControl = (Element) control.cloneNode(true); //set new Ids to XForm elements this.resetXFormIds(newControl); repeatSection.appendChild(newControl); } } else { this.addElementToGroup(xformsDocument, modelSection, defaultInstanceElement, repeatSection, schema, element, pathToRoot, childOccurs, resourceBundle); } } else { LOGGER.warn("Unhandled term " + term + " found in group from " + owner.getName() + " for pathToRoot = " + pathToRoot); } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("[addGroup] group after =\n" + XMLUtil.toString(formSection)); LOGGER.debug("[addGroup] End of addGroup, from owner = " + owner.getName() + " and controlType = " + controlType.getName()); } }
From source file:org.apache.cocoon.components.source.impl.XModuleSource.java
/** * Implement this method to obtain SAX events. * *///from w w w . j a va 2s .c om public void toSAX(ContentHandler handler) throws SAXException { Object obj = getInputAttribute(this.attributeType, this.attributeName); if (obj == null) throw new SAXException(" The attribute: " + this.attributeName + " is empty"); if (!(this.xPath.length() == 0 || this.xPath.equals("/"))) { JXPathContext context = JXPathContext.newContext(obj); obj = context.getPointer(this.xPath).getNode(); if (obj == null) throw new SAXException("the xpath: " + this.xPath + " applied on the attribute: " + this.attributeName + " returns null"); } if (obj instanceof Document) { DOMStreamer domStreamer = new DOMStreamer(handler); domStreamer.stream((Document) obj); } else if (obj instanceof Node) { DOMStreamer domStreamer = new DOMStreamer(handler); handler.startDocument(); domStreamer.stream((Node) obj); handler.endDocument(); } else if (obj instanceof XMLizable) { ((XMLizable) obj).toSAX(handler); } else { throw new SAXException( "The object type: " + obj.getClass() + " could not be serialized to XML: " + obj); } }
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 . java 2 s . c o m 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 . j a v a 2 s.c o m*/ 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()); } }
From source file:org.apache.cocoon.forms.binding.ContextJXPathBinding.java
/** * Actively performs the binding from the ObjectModel wrapped in a jxpath * context to the CocoonForm./*from ww w .ja v a 2 s.co m*/ */ public void doLoad(Widget frmModel, JXPathContext jxpc) throws BindingException { Pointer ptr = jxpc.getPointer(this.xpath); if (ptr.getNode() != null) { JXPathContext subContext = jxpc.getRelativeContext(ptr); super.doLoad(frmModel, subContext); if (getLogger().isDebugEnabled()) getLogger().debug("done loading " + toString()); } else { if (getLogger().isDebugEnabled()) { getLogger().debug("non-existent path: skipping " + toString()); } } }