List of usage examples for org.apache.commons.jxpath JXPathContext newContext
public static JXPathContext newContext(Object contextBean)
From source file:com.googlecode.fascinator.common.JsonConfigHelper.java
/** * Gets a JXPath context for selecting and creating JSON nodes and values * /* ww w . ja va 2s .c om*/ * @return a JXPath context */ private JXPathContext getJXPath() { if (jxPath == null) { jxPath = JXPathContext.newContext(rootNode); jxPath.setFactory(new JsonMapFactory()); jxPath.setLenient(true); } return jxPath; }
From source file:de.iai.ilcd.xml.read.DataSetReader.java
private DataSet parseStream(InputStream inputStream) { JDOMParser parser = new JDOMParser(); parser.setValidating(false);/*from ww w. j a va 2s . c o m*/ Object doc = parser.parseXML(inputStream); JXPathContext context = JXPathContext.newContext(doc); context.setLenient(true); context.registerNamespace("common", "http://lca.jrc.it/ILCD/Common"); parserHelper = new DataSetParsingHelper(context); commonReader = new CommonConstructsReader(parserHelper); return parse(context, out); }
From source file:com.technofovea.hl2parse.vdf.GameConfigReader.java
public GameConfigReader(VdfRoot rootNode) { root = rootNode;//ww w.ja v a 2 s. c om context = JXPathContext.newContext(root); JxPathUtil.addFunctions(context); context.getVariables().declareVariable("rootname", ROOT_NODE); context.getVariables().declareVariable("gamegroup", GAME_NODE); context.getVariables().declareVariable("sdkver", KEY_SDKVERSION); logger.trace("Checking file for defined games..."); for (Pointer p : getGamePointers()) { JXPathContext relativeContext = context.getRelativeContext(p); Game g = new Game(relativeContext); logger.trace("Found game: {}", g.getName()); games.put(g.getName(), g); } try { sdkVersion = new Integer((String) context.getValue( "children[custom:equals(name,$rootname)]/attributes[custom:equals(name,$sdkver)]/value")); } catch (JXPathException jex) { logger.warn("Unable to determine SDK version in game-config", jex); sdkVersion = -1; } }
From source file:net.sf.oval.ogn.ObjectGraphNavigatorJXPathImpl.java
public ObjectGraphNavigationResult navigateTo(final Object root, final String xpath) throws InvalidConfigurationException { Assert.argumentNotNull("root", root); Assert.argumentNotNull("xpath", xpath); try {//ww w .ja va 2 s .c o m final JXPathContext ctx = JXPathContext.newContext(root); ctx.setLenient(true); // do not throw an exception if object graph is incomplete, e.g. contains null-values Pointer pointer = ctx.getPointer(xpath); // no match found or invalid xpath if (pointer instanceof NullPropertyPointer || pointer instanceof NullPointer) return null; if (pointer instanceof BeanPointer) { final Pointer parent = ((BeanPointer) pointer).getImmediateParentPointer(); if (parent instanceof PropertyPointer) { pointer = parent; } } if (pointer instanceof PropertyPointer) { final PropertyPointer pp = (PropertyPointer) pointer; final Class<?> beanClass = pp.getBean().getClass(); AccessibleObject accessor = ReflectionUtils.getField(beanClass, pp.getPropertyName()); if (accessor == null) { accessor = ReflectionUtils.getGetter(beanClass, pp.getPropertyName()); } return new ObjectGraphNavigationResult(root, xpath, pp.getBean(), accessor, pointer.getValue()); } throw new InvalidConfigurationException("Don't know how to handle pointer [" + pointer + "] of type [" + pointer.getClass().getName() + "] for xpath [" + xpath + "]"); } catch (final JXPathNotFoundException ex) { // thrown if the xpath is invalid throw new InvalidConfigurationException(ex); } }
From source file:com.htm.query.jxpath.JXpathQueryEvaluator.java
public void setContext(Object context) { /*/*www . j a v a2 s. co m*/ * If the context is the same like the current context do nothing this * reduces multiple instantiation (e.g. of task instance views). If the * context is of type task instance a view object of this task instance * is created where the queries can be performed on */ if (jXpathContext != null && jXpathContext.getContextBean().equals(context)) { return; } else if (context instanceof ITaskInstance) { TaskInstanceView instanceView = new TaskInstanceView((ITaskInstance) context); this.jXpathContext = JXPathContext.newContext(instanceView); } else { this.jXpathContext = JXPathContext.newContext(context); } }
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//from w w w . java2 s . co 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:eu.tripledframework.eventstore.infrastructure.ReflectionObjectConstructor.java
private Object getValue(String expr, DomainEvent event) { JXPathContext context = JXPathContext.newContext(event); return context.getValue(expr); }
From source file:com.yahoo.xpathproto.ProtoBuilder.java
private static void transformUsingDefinition(final Context vars, final Config config, final JXPathCopier copier, final Config.Entry transform) { boolean isRepeated = false; if (transform.getField() != null) { Descriptors.FieldDescriptor fieldDescriptor = copier.getTarget().getDescriptorForType() .findFieldByName(transform.getField()); if (null == fieldDescriptor) { throw new RuntimeException("Unknown target field in protobuf: " + transform.getField()); }// w w w .ja va 2 s .c om isRepeated = fieldDescriptor.isRepeated(); } JXPathContext context = copier.getSource(); if (isRepeated) { List list = context.selectNodes(transform.getPath()); Iterator iterator = list.iterator(); int limit = 0; int count = 0; if (transform.getLimit() != null) { limit = transform.getLimit(); } logger.debug("Applying limit of {} for field {}", limit, transform.getField()); while (iterator.hasNext() && (count != limit || limit == 0)) { Object value = iterator.next(); JXPathCopier innerCopier = new JXPathCopier(JXPathContext.newContext(value), copier.getTarget()); Message.Builder innerBuilder = transformUsing(vars, config, innerCopier, transform.getDefinition()); if ((transform.getField() != null) && (null != innerBuilder) && (innerBuilder.isInitialized())) { copier.copyObject(innerBuilder.build(), transform.getField()); } count++; } } else { JXPathContext innerContext = JXPathCopier.getRelativeContext(context, transform.getPath()); if (innerContext != null) { JXPathCopier innerCopier = new JXPathCopier(innerContext, copier.getTarget()); Message.Builder innerBuilder = transformUsing(vars, config, innerCopier, transform.getDefinition()); if ((transform.getField() != null) && (null != innerBuilder) && (innerBuilder.isInitialized())) { copier.copyObject(innerBuilder.build(), transform.getField()); } } } }
From source file:net.sbbi.upnp.services.UPNPService.java
private void parseSCPD() { try {//from w w w . 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:jp.go.nict.langrid.bpel.ProcessAnalyzer.java
/** * /*from ww w .j a v a 2s.c o m*/ * */ public static WSDL analyzeWsdl(byte[] body) throws MalformedURLException, SAXException, URISyntaxException { JXPathContext context = JXPathContext.newContext(new DOMParser().parseXML(new ByteArrayInputStream(body))); context.registerNamespace("_", Constants.WSDL_URI); context.registerNamespace("wsdlsoap", Constants.WSDLSOAP_URI); context.registerNamespace("plnk1", Constants.PLNK_URI); context.registerNamespace("plnk2", Constants.PLNK_URI_2); WSDL wsdl = new WSDL(); wsdl.setBody(body); wsdl.setTargetNamespace(new URI(context.getValue("/_:definitions/@targetNamespace").toString())); // // HashMap<String, PartnerLinkType> links = new HashMap<String, PartnerLinkType>(); { Iterator<?> pli = context.iteratePointers("/_:definitions/plnk1:partnerLinkType"); while (pli.hasNext()) { JXPathContext pltc = JXPathContext.newContext(context, ((Pointer) pli.next()).getNode()); pltc.registerNamespace("plnk1", Constants.PLNK_URI); PartnerLinkType plt = new PartnerLinkType(); plt.setName(pltc.getValue("/@name").toString()); HashMap<String, Role> roles = new HashMap<String, Role>(); Iterator<?> ri = pltc.iteratePointers("/plnk1:role"); while (ri.hasNext()) { JXPathContext rc = JXPathContext.newContext(pltc, ((Pointer) ri.next()).getNode()); rc.registerNamespace("plnk1", Constants.PLNK_URI); Role role = new Role(); role.setName(rc.getValue("/@name").toString()); role.setPortType(toQName(rc, rc.getValue("/plnk1:portType/@name").toString())); roles.put(role.getName(), role); } plt.setRoles(roles); links.put(plt.getName(), plt); } } { Iterator<?> pli = context.iteratePointers("/_:definitions/plnk2:partnerLinkType"); while (pli.hasNext()) { JXPathContext pltc = JXPathContext.newContext(context, ((Pointer) pli.next()).getNode()); pltc.registerNamespace("plnk2", Constants.PLNK_URI_2); PartnerLinkType plt = new PartnerLinkType(); plt.setName(pltc.getValue("/@name").toString()); HashMap<String, Role> roles = new HashMap<String, Role>(); Iterator<?> ri = pltc.iteratePointers("/plnk2:role"); while (ri.hasNext()) { JXPathContext rc = JXPathContext.newContext(pltc, ((Pointer) ri.next()).getNode()); Role role = new Role(); role.setName(rc.getValue("/@name").toString()); role.setPortType(toQName(rc, rc.getValue("/@portType").toString())); roles.put(role.getName(), role); } plt.setRoles(roles); links.put(plt.getName(), plt); } } wsdl.setPlinks(links); { // definitions/portType?? HashMap<String, EndpointReference> portTypeToEndpointReference = new HashMap<String, EndpointReference>(); Iterator<?> pti = context.iteratePointers("/_:definitions/_:portType"); while (pti.hasNext()) { JXPathContext ptc = JXPathContext.newContext(context, ((Pointer) pti.next()).getNode()); portTypeToEndpointReference.put(ptc.getValue("/@name").toString(), null); } wsdl.setPortTypeToEndpointReference(portTypeToEndpointReference); } { // definitions/binding?? HashMap<String, QName> bindingTypes = new HashMap<String, QName>(); Iterator<?> bi = context.iteratePointers("/_:definitions/_:binding"); while (bi.hasNext()) { JXPathContext bc = JXPathContext.newContext(context, ((Pointer) bi.next()).getNode()); bindingTypes.put(bc.getValue("/@name").toString(), toQName(bc, bc.getValue("/@type").toString())); } wsdl.setBindingTypes(bindingTypes); } String firstServiceName = null; { // definitions/service?? HashMap<String, Service> services = new HashMap<String, Service>(); Iterator<?> si = context.iteratePointers("/_:definitions/_:service"); while (si.hasNext()) { JXPathContext sc = JXPathContext.newContext(context, ((Pointer) si.next()).getNode()); sc.registerNamespace("_", Constants.WSDL_URI); String serviceName = sc.getValue("/@name").toString(); Service s = new Service(); s.setName(serviceName); if (firstServiceName == null) { firstServiceName = serviceName; } // port?? HashMap<String, Port> ports = new HashMap<String, Port>(); Iterator<?> pi = sc.iteratePointers("/_:port"); while (pi.hasNext()) { JXPathContext pc = JXPathContext.newContext(sc, ((Pointer) pi.next()).getNode()); pc.registerNamespace("wsdlsoap", Constants.WSDLSOAP_URI); Port p = new Port(); p.setName(pc.getValue("/@name").toString()); p.setBinding(toQName(pc, pc.getValue("/@binding").toString())); p.setAddress(new URL(pc.getValue("/wsdlsoap:address/@location").toString())); ports.put(p.getName(), p); } s.setPorts(ports); services.put(s.getName(), s); } wsdl.setServices(services); } if (firstServiceName == null) { wsdl.setFilename("unknown" + WSDL_EXTENSION); } else { wsdl.setFilename(firstServiceName + WSDL_EXTENSION); } return wsdl; }