List of usage examples for org.apache.commons.jxpath JXPathContext setVariables
public void setVariables(Variables vars)
From source file:org.apache.cocoon.components.expression.jxpath.JXPathExpression.java
private JXPathContext getContext(ExpressionContext context) { // This could be made more efficient by caching the // JXPathContext within the Context object. JXPathContext jxcontext = JXPathContext.newContext(context.getContextBean()); jxcontext.setVariables(new VariableAdapter(context)); jxcontext.setLenient(this.lenient); jxcontext.setNamespaceContextPointer(new NamespacesTablePointer(context.getNamespaces())); return jxcontext; }
From source file:org.apache.cocoon.el.impl.jxpath.JXPathExpression.java
private JXPathContext getContext(ObjectModel objectModel) { // This could be made more efficient by caching the // JXPathContext within the Context object. JXPathContext jxobjectModel = JXPathContext.newContext(objectModel.get(ObjectModel.CONTEXTBEAN)); jxobjectModel.setVariables(new VariableAdapter(objectModel)); jxobjectModel.setLenient(this.lenient); jxobjectModel.setNamespaceContextPointer( new NamespacesTablePointer((NamespacesTable) objectModel.get(ObjectModel.NAMESPACE))); return jxobjectModel; }
From source file:org.apache.cocoon.forms.transformation.FormsPipelineConfig.java
/** * Creates and initializes a FormsPipelineConfig object based on the passed * arguments of the setup() of the specific Pipeline-component. * * @param objectModel the objectmodel as passed in the setup() * @param parameters the parameters as passed in the setup() * @return an instance of FormsPipelineConfig initialized according to the * settings in the sitemap.//www.j a v a 2 s . co m */ public static FormsPipelineConfig createConfig(Map objectModel, Parameters parameters) { // create and set the jxpathContext... Object flowContext = FlowHelper.getContextObject(objectModel); WebContinuation wk = FlowHelper.getWebContinuation(objectModel); JXPathContext jxpc = JXPathContext.newContext(flowContext); // We manually create a cocoon object here to provide the same way // of accessing things as in the jxtg // as soon as we have our unified om, we should use that Request request = ObjectModelHelper.getRequest(objectModel); Session session = request.getSession(false); final Map cocoonOM = new HashMap(); cocoonOM.put("continuation", wk); cocoonOM.put("request", request); if (session != null) { cocoonOM.put("session", session); } cocoonOM.put("parameters", parameters); FormsVariables vars = new FormsVariables(); vars.declareVariable("cocoon", cocoonOM); // These four are deprecated! vars.declareVariable("continuation", wk); vars.declareVariable("request", request); vars.declareVariable("session", session); vars.declareVariable("parameters", parameters); vars.addDeprecatedVariable("continuation"); vars.addDeprecatedVariable("request"); vars.addDeprecatedVariable("session"); vars.addDeprecatedVariable("parameters"); jxpc.setVariables(vars); Locale localeParameter = null; String localeStr = parameters.getParameter("locale", null); if (localeStr != null) { localeParameter = I18nUtils.parseLocale(localeStr); } String attributeName = parameters.getParameter("attribute-name", null); String actionExpression = parameters.getParameter("form-action", null); String formMethod = parameters.getParameter("form-method", null); //TODO (20031223 mpo)think about adding form-encoding for the Generator. // Note generator will also need some text to go on the submit-button? // Alternative to adding more here is to apply xinclude ? return new FormsPipelineConfig(jxpc, request, localeParameter, attributeName, actionExpression, formMethod); }
From source file:org.apache.cocoon.generation.JXTemplateGenerator.java
private void execute(final XMLConsumer consumer, MyJexlContext jexlContext, JXPathContext jxpathContext, StartElement macroCall, Event startEvent, Event endEvent) throws SAXException { Event ev = startEvent;/*from w w w.j a v a2s. co m*/ LocationFacade loc = new LocationFacade(ev.location); consumer.setDocumentLocator(loc); while (ev != endEvent) { loc.setDocumentLocation(ev.location); if (ev instanceof Characters) { TextEvent text = (TextEvent) ev; Iterator iter = text.substitutions.iterator(); while (iter.hasNext()) { Object subst = iter.next(); char[] chars; if (subst instanceof char[]) { chars = (char[]) subst; } else { JXTExpression expr = (JXTExpression) subst; try { Object val = getNode(expr, jexlContext, jxpathContext); if (val instanceof Node) { executeDOM(consumer, jexlContext, jxpathContext, (Node) val); continue; } else if (val instanceof NodeList) { NodeList nodeList = (NodeList) val; int len = nodeList.getLength(); for (int i = 0; i < len; i++) { Node n = nodeList.item(i); executeDOM(consumer, jexlContext, jxpathContext, n); } continue; } else if (val instanceof Node[]) { Node[] nodeList = (Node[]) val; int len = nodeList.length; for (int i = 0; i < len; i++) { Node n = nodeList[i]; executeDOM(consumer, jexlContext, jxpathContext, n); } continue; } else if (val instanceof XMLizable) { ((XMLizable) val).toSAX(new IncludeXMLConsumer(consumer)); continue; } chars = val != null ? val.toString().toCharArray() : ArrayUtils.EMPTY_CHAR_ARRAY; } catch (Exception e) { throw new JXTException(e.getMessage(), ev.location, e); } } consumer.characters(chars, 0, chars.length); } } else if (ev instanceof EndElement) { EndElement endElement = (EndElement) ev; StartElement startElement = endElement.startElement; StartDefine def = (StartDefine) definitions.get(startElement.qname); if (def == null) { consumer.endElement(startElement.namespaceURI, startElement.localName, startElement.raw); namespaces.leaveScope(consumer); } } else if (ev instanceof EndPrefixMapping) { EndPrefixMapping endPrefixMapping = (EndPrefixMapping) ev; namespaces.removeDeclaration(endPrefixMapping.prefix); } else if (ev instanceof IgnorableWhitespace) { TextEvent text = (TextEvent) ev; characters(jexlContext, jxpathContext, text, new CharHandler() { public void characters(char[] ch, int offset, int len) throws SAXException { consumer.ignorableWhitespace(ch, offset, len); } }); } else if (ev instanceof SkippedEntity) { SkippedEntity skippedEntity = (SkippedEntity) ev; consumer.skippedEntity(skippedEntity.name); } else if (ev instanceof StartIf) { StartIf startIf = (StartIf) ev; Object val; try { val = getValue(startIf.test, jexlContext, jxpathContext, Boolean.TRUE); } catch (Exception e) { throw new JXTException(e.getMessage(), ev.location, e); } boolean result = false; if (val instanceof Boolean) { result = ((Boolean) val).booleanValue(); } else { result = (val != null); } if (!result) { ev = startIf.endInstruction.next; continue; } } else if (ev instanceof StartForEach) { StartForEach startForEach = (StartForEach) ev; final Object items = startForEach.items; Iterator iter = null; int begin, end, step; String var, varStatus; try { if (items != null) { JXTExpression expr = (JXTExpression) items; if (expr.compiledExpression instanceof CompiledExpression) { CompiledExpression compiledExpression = (CompiledExpression) expr.compiledExpression; Object val = compiledExpression.getPointer(jxpathContext, expr.raw).getNode(); // FIXME: workaround for JXPath bug iter = val instanceof NativeArray ? new JSIntrospector.NativeArrayIterator((NativeArray) val) : compiledExpression.iteratePointers(jxpathContext); } else if (expr.compiledExpression instanceof Expression) { Expression e = (Expression) expr.compiledExpression; Object result = e.evaluate(jexlContext); if (result != null) { iter = Introspector.getUberspect().getIterator(result, new Info(ev.location.getURI(), ev.location.getLineNumber(), ev.location.getColumnNumber())); } if (iter == null) { iter = EMPTY_ITER; } } else { // literal value iter = new Iterator() { Object val = items; public boolean hasNext() { return val != null; } public Object next() { Object res = val; val = null; return res; } public void remove() { // EMPTY } }; } } else { iter = NULL_ITER; } begin = startForEach.begin == null ? 0 : getIntValue(startForEach.begin, jexlContext, jxpathContext); end = startForEach.end == null ? Integer.MAX_VALUE : getIntValue(startForEach.end, jexlContext, jxpathContext); step = startForEach.step == null ? 1 : getIntValue(startForEach.step, jexlContext, jxpathContext); var = getStringValue(startForEach.var, jexlContext, jxpathContext); varStatus = getStringValue(startForEach.varStatus, jexlContext, jxpathContext); } catch (Exception exc) { throw new JXTException(exc.getMessage(), ev.location, exc); } MyJexlContext localJexlContext = new MyJexlContext(jexlContext); MyVariables localJXPathVariables = new MyVariables((MyVariables) jxpathContext.getVariables()); int i = 0; // Move to the begin row while (i < begin && iter.hasNext()) { iter.next(); i++; } LoopTagStatus status = null; if (varStatus != null) { status = new LoopTagStatus(); status.begin = begin; status.end = end; status.step = step; status.first = true; localJexlContext.put(varStatus, status); localJXPathVariables.declareVariable(varStatus, status); } int skipCounter, count = 1; JXPathContext localJXPathContext = null; while (i <= end && iter.hasNext()) { Object value = iter.next(); if (value instanceof Pointer) { Pointer ptr = (Pointer) value; localJXPathContext = jxpathContext.getRelativeContext(ptr); localJXPathContext.setNamespaceContextPointer(new NamespacesTablePointer(namespaces)); try { value = ptr.getNode(); } catch (Exception exc) { throw new JXTException(exc.getMessage(), ev.location, null); } } else { localJXPathContext = jxpathContextFactory.newContext(jxpathContext, value); localJXPathContext.setNamespaceContextPointer(new NamespacesTablePointer(namespaces)); } localJXPathContext.setVariables(localJXPathVariables); if (var != null) { localJexlContext.put(var, value); } if (status != null) { status.index = i; status.count = count; status.first = i == begin; status.current = value; status.last = (i == end || !iter.hasNext()); } execute(consumer, localJexlContext, localJXPathContext, macroCall, startForEach.next, startForEach.endInstruction); // Skip rows skipCounter = step; while (--skipCounter > 0 && iter.hasNext()) { iter.next(); } // Increase index i += step; count++; } ev = startForEach.endInstruction.next; continue; } else if (ev instanceof StartChoose) { StartChoose startChoose = (StartChoose) ev; StartWhen startWhen = startChoose.firstChoice; while (startWhen != null) { Object val; try { val = getValue(startWhen.test, jexlContext, jxpathContext, Boolean.TRUE); } catch (Exception e) { throw new JXTException(e.getMessage(), ev.location, e); } boolean result; if (val instanceof Boolean) { result = ((Boolean) val).booleanValue(); } else { result = (val != null); } if (result) { execute(consumer, jexlContext, jxpathContext, macroCall, startWhen.next, startWhen.endInstruction); break; } startWhen = startWhen.nextChoice; } if (startWhen == null && startChoose.otherwise != null) { execute(consumer, jexlContext, jxpathContext, macroCall, startChoose.otherwise.next, startChoose.otherwise.endInstruction); } ev = startChoose.endInstruction.next; continue; } else if (ev instanceof StartSet) { StartSet startSet = (StartSet) ev; Object value = null; String var = null; try { if (startSet.var != null) { var = getStringValue(startSet.var, jexlContext, jxpathContext); } if (startSet.value != null) { value = getNode(startSet.value, jexlContext, jxpathContext); } } catch (Exception exc) { throw new JXTException(exc.getMessage(), ev.location, exc); } if (value == null) { NodeList nodeList = toDOMNodeList("set", startSet, jexlContext, macroCall); // JXPath doesn't handle NodeList, so convert it to an array int len = nodeList.getLength(); Node[] nodeArr = new Node[len]; for (int i = 0; i < len; i++) { nodeArr[i] = nodeList.item(i); } value = nodeArr; } if (var != null) { jxpathContext.getVariables().declareVariable(var, value); jexlContext.put(var, value); } ev = startSet.endInstruction.next; continue; } else if (ev instanceof StartElement) { StartElement startElement = (StartElement) ev; StartDefine def = (StartDefine) definitions.get(startElement.qname); if (def != null) { Map attributeMap = new HashMap(); Iterator i = startElement.attributeEvents.iterator(); while (i.hasNext()) { String attributeName; Object attributeValue; AttributeEvent attrEvent = (AttributeEvent) i.next(); attributeName = attrEvent.localName; if (attrEvent instanceof CopyAttribute) { CopyAttribute copy = (CopyAttribute) attrEvent; attributeValue = copy.value; } else if (attrEvent instanceof SubstituteAttribute) { SubstituteAttribute substEvent = (SubstituteAttribute) attrEvent; if (substEvent.substitutions.size() == 1 && substEvent.substitutions.get(0) instanceof JXTExpression) { JXTExpression expr = (JXTExpression) substEvent.substitutions.get(0); Object val; try { val = getNode(expr, jexlContext, jxpathContext); } catch (Exception e) { throw new JXTException(e.getMessage(), ev.location, e); } attributeValue = val != null ? val : ""; } else { StringBuffer buf = new StringBuffer(); Iterator iterSubst = substEvent.substitutions.iterator(); while (iterSubst.hasNext()) { Subst subst = (Subst) iterSubst.next(); if (subst instanceof Literal) { Literal lit = (Literal) subst; buf.append(lit.value); } else if (subst instanceof JXTExpression) { JXTExpression expr = (JXTExpression) subst; Object val; try { val = getValue(expr, jexlContext, jxpathContext); } catch (Exception e) { throw new JXTException(e.getMessage(), ev.location, e); } buf.append(val != null ? val.toString() : ""); } } attributeValue = buf.toString(); } } else { throw new Error("this shouldn't have happened"); } attributeMap.put(attributeName, attributeValue); } MyVariables parent = (MyVariables) jxpathContext.getVariables(); MyVariables vars = new MyVariables(parent); MyJexlContext localJexlContext = new MyJexlContext(jexlContext); HashMap macro = new HashMap(); macro.put("body", startElement); macro.put("arguments", attributeMap); localJexlContext.put("macro", macro); vars.declareVariable("macro", macro); Iterator iter = def.parameters.entrySet().iterator(); while (iter.hasNext()) { Map.Entry e = (Map.Entry) iter.next(); String key = (String) e.getKey(); StartParameter startParam = (StartParameter) e.getValue(); Object default_ = startParam.default_; Object val = attributeMap.get(key); if (val == null) { val = default_; } localJexlContext.put(key, val); vars.declareVariable(key, val); } JXPathContext localJXPathContext = jxpathContextFactory.newContext(null, jxpathContext.getContextBean()); localJXPathContext.setNamespaceContextPointer(new NamespacesTablePointer(namespaces)); localJXPathContext.setVariables(vars); call(ev.location, startElement, consumer, localJexlContext, localJXPathContext, def.body, def.endInstruction); ev = startElement.endElement.next; continue; } Iterator i = startElement.attributeEvents.iterator(); AttributesImpl attrs = new AttributesImpl(); while (i.hasNext()) { AttributeEvent attrEvent = (AttributeEvent) i.next(); if (attrEvent instanceof CopyAttribute) { CopyAttribute copy = (CopyAttribute) attrEvent; attrs.addAttribute(copy.namespaceURI, copy.localName, copy.raw, copy.type, copy.value); } else if (attrEvent instanceof SubstituteAttribute) { StringBuffer buf = new StringBuffer(); SubstituteAttribute substEvent = (SubstituteAttribute) attrEvent; Iterator iterSubst = substEvent.substitutions.iterator(); while (iterSubst.hasNext()) { Subst subst = (Subst) iterSubst.next(); if (subst instanceof Literal) { Literal lit = (Literal) subst; buf.append(lit.value); } else if (subst instanceof JXTExpression) { JXTExpression expr = (JXTExpression) subst; Object val; try { val = getValue(expr, jexlContext, jxpathContext); } catch (Exception e) { throw new JXTException(e.getMessage(), ev.location, e); } buf.append(val != null ? val.toString() : ""); } } attrs.addAttribute(attrEvent.namespaceURI, attrEvent.localName, attrEvent.raw, attrEvent.type, buf.toString()); } } namespaces.enterScope(consumer); consumer.startElement(startElement.namespaceURI, startElement.localName, startElement.raw, attrs); } else if (ev instanceof StartFormatNumber) { StartFormatNumber startFormatNumber = (StartFormatNumber) ev; try { String result = startFormatNumber.format(jexlContext, jxpathContext); if (result != null) { char[] chars = result.toCharArray(); consumer.characters(chars, 0, chars.length); } } catch (Exception e) { throw new JXTException(e.getMessage(), ev.location, e); } } else if (ev instanceof StartFormatDate) { StartFormatDate startFormatDate = (StartFormatDate) ev; try { String result = startFormatDate.format(jexlContext, jxpathContext); if (result != null) { char[] chars = result.toCharArray(); consumer.characters(chars, 0, chars.length); } } catch (Exception e) { throw new JXTException(e.getMessage(), ev.location, e); } } else if (ev instanceof StartPrefixMapping) { StartPrefixMapping startPrefixMapping = (StartPrefixMapping) ev; namespaces.addDeclaration(startPrefixMapping.prefix, startPrefixMapping.uri); } else if (ev instanceof StartComment) { StartComment startJXComment = (StartComment) ev; // Parse the body of the comment NodeList nodeList = toDOMNodeList("comment", startJXComment, jexlContext, macroCall); // JXPath doesn't handle NodeList, so convert it to an array int len = nodeList.getLength(); final StringBuffer buf = new StringBuffer(); Properties omit = XMLUtils.createPropertiesForXML(true); for (int i = 0; i < len; i++) { try { String str = XMLUtils.serializeNode(nodeList.item(i), omit); buf.append(StringUtils.substringAfter(str, ">")); // cut the XML header } catch (Exception e) { throw new JXTException(e.getMessage(), startJXComment.location, e); } } char[] chars = new char[buf.length()]; buf.getChars(0, chars.length, chars, 0); consumer.comment(chars, 0, chars.length); ev = startJXComment.endInstruction.next; continue; } else if (ev instanceof EndCDATA) { consumer.endCDATA(); } else if (ev instanceof EndDTD) { consumer.endDTD(); } else if (ev instanceof EndEntity) { consumer.endEntity(((EndEntity) ev).name); } else if (ev instanceof StartCDATA) { consumer.startCDATA(); } else if (ev instanceof StartDTD) { StartDTD startDTD = (StartDTD) ev; consumer.startDTD(startDTD.name, startDTD.publicId, startDTD.systemId); } else if (ev instanceof StartEntity) { consumer.startEntity(((StartEntity) ev).name); } else if (ev instanceof StartOut) { StartOut startOut = (StartOut) ev; Object val; try { val = getNode(startOut.compiledExpression, jexlContext, jxpathContext, startOut.lenient); if (val instanceof Node) { executeDOM(consumer, jexlContext, jxpathContext, (Node) val); } else if (val instanceof NodeList) { NodeList nodeList = (NodeList) val; int len = nodeList.getLength(); for (int i = 0; i < len; i++) { Node n = nodeList.item(i); executeDOM(consumer, jexlContext, jxpathContext, n); } } else if (val instanceof Node[]) { Node[] nodeList = (Node[]) val; int len = nodeList.length; for (int i = 0; i < len; i++) { Node n = nodeList[i]; executeDOM(consumer, jexlContext, jxpathContext, n); } } else if (val instanceof XMLizable) { ((XMLizable) val).toSAX(new IncludeXMLConsumer(consumer)); } else { char[] ch = val == null ? ArrayUtils.EMPTY_CHAR_ARRAY : val.toString().toCharArray(); consumer.characters(ch, 0, ch.length); } } catch (Exception e) { throw new JXTException(e.getMessage(), ev.location, e); } } else if (ev instanceof StartTemplate) { // EMPTY } else if (ev instanceof StartEval) { StartEval startEval = (StartEval) ev; JXTExpression expr = startEval.value; try { Object val = getNode(expr, jexlContext, jxpathContext); if (!(val instanceof StartElement)) { throw new Exception("macro invocation required instead of: " + val); } StartElement call = (StartElement) val; execute(consumer, jexlContext, jxpathContext, call, call.next, call.endElement); } catch (Exception exc) { throw new JXTException(exc.getMessage(), ev.location, exc); } ev = startEval.endInstruction.next; continue; } else if (ev instanceof StartEvalBody) { StartEvalBody startEval = (StartEvalBody) ev; try { execute(consumer, jexlContext, jxpathContext, null, macroCall.next, macroCall.endElement); } catch (Exception exc) { throw new JXTException(exc.getMessage(), ev.location, exc); } ev = startEval.endInstruction.next; continue; } else if (ev instanceof StartDefine) { StartDefine startDefine = (StartDefine) ev; definitions.put(startDefine.qname, startDefine); ev = startDefine.endInstruction.next; continue; } else if (ev instanceof StartImport) { StartImport startImport = (StartImport) ev; String uri; AttributeEvent e = startImport.uri; if (e instanceof CopyAttribute) { CopyAttribute copy = (CopyAttribute) e; uri = copy.value; } else { StringBuffer buf = new StringBuffer(); SubstituteAttribute substAttr = (SubstituteAttribute) e; Iterator i = substAttr.substitutions.iterator(); while (i.hasNext()) { Subst subst = (Subst) i.next(); if (subst instanceof Literal) { Literal lit = (Literal) subst; buf.append(lit.value); } else if (subst instanceof JXTExpression) { JXTExpression expr = (JXTExpression) subst; Object val; try { val = getValue(expr, jexlContext, jxpathContext); } catch (Exception exc) { throw new JXTException(exc.getMessage(), ev.location, exc); } buf.append(val != null ? val.toString() : ""); } } uri = buf.toString(); } Source input = null; StartDocument doc; try { input = resolver.resolveURI(uri); SourceValidity validity = null; synchronized (cache) { doc = (StartDocument) cache.get(input.getURI()); if (doc != null) { boolean recompile = false; if (doc.compileTime == null) { recompile = true; } else { int valid = doc.compileTime.isValid(); if (valid == SourceValidity.UNKNOWN) { validity = input.getValidity(); valid = doc.compileTime.isValid(validity); } if (valid != SourceValidity.VALID) { recompile = true; } } if (recompile) { doc = null; // recompile } } } if (doc == null) { Parser parser = new Parser(); // call getValidity before using the stream is faster if the source is a SitemapSource if (validity == null) { validity = input.getValidity(); } SourceUtil.parse(this.manager, input, parser); doc = parser.getStartEvent(); doc.compileTime = validity; synchronized (cache) { cache.put(input.getURI(), doc); } } } catch (Exception exc) { throw new JXTException(exc.getMessage(), ev.location, exc); } finally { resolver.release(input); } JXPathContext selectJXPath = jxpathContext; MyJexlContext selectJexl = jexlContext; if (startImport.select != null) { try { Object obj = getValue(startImport.select, jexlContext, jxpathContext); selectJXPath = jxpathContextFactory.newContext(null, obj); selectJXPath.setNamespaceContextPointer(new NamespacesTablePointer(namespaces)); selectJXPath.setVariables(variables); selectJexl = new MyJexlContext(jexlContext); fillContext(obj, selectJexl); } catch (Exception exc) { throw new JXTException(exc.getMessage(), ev.location, exc); } } try { execute(consumer, selectJexl, selectJXPath, macroCall, doc.next, doc.endDocument); } catch (Exception exc) { throw new JXTException( "Exception occurred in imported template " + uri + ": " + exc.getMessage(), ev.location, exc); } ev = startImport.endInstruction.next; continue; } else if (ev instanceof StartDocument) { if (((StartDocument) ev).endDocument != null) { // if this isn't a document fragment consumer.startDocument(); } } else if (ev instanceof EndDocument) { consumer.endDocument(); } else if (ev instanceof ProcessingInstruction) { ProcessingInstruction pi = (ProcessingInstruction) ev; consumer.processingInstruction(pi.target, pi.data); } ev = ev.next; } }
From source file:org.apache.cocoon.jxpath.JXPathCocoonContexts.java
/** * Returns a JXPathContext bound to the "request" scope. * Caches that context within the request itself. *///w w w . j a v a 2 s. c om public final JXPathContext getRequestContext() { final Map objectModel = ContextHelper.getObjectModel(this.context); Request request = ObjectModelHelper.getRequest(objectModel); JXPathContext context = (JXPathContext) request.getAttribute(Constants.JXPATH_CONTEXT); if (context == null) { Context envContext = ObjectModelHelper.getContext(objectModel); JXPathContext parentContext = null; Session session = request.getSession(false); if (session != null) { parentContext = getSessionContext(session, envContext); } else { parentContext = getApplicationContext(envContext); } request = new RequestProxy(request); context = factory.newContext(parentContext, request); context.setVariables(new KeywordVariables(Constants.REQUEST_SCOPE, request)); request.setAttribute(Constants.JXPATH_CONTEXT, context); } return context; }
From source file:org.apache.cocoon.jxpath.JXPathCocoonContexts.java
/** * Returns a JXPathContext bound to the "session" scope. * Caches that context within the session itself. *///from ww w . j a va 2s . co m public final JXPathContext getSessionContext(Session session, Context envContext) { JXPathContext context = (JXPathContext) session.getAttribute(Constants.JXPATH_CONTEXT); if (context == null) { JXPathContext parentContext = getApplicationContext(envContext); session = new SessionProxy(session); context = factory.newContext(parentContext, session); context.setVariables(new KeywordVariables(Constants.SESSION_SCOPE, session)); session.setAttribute(Constants.JXPATH_CONTEXT, context); } return context; }
From source file:org.apache.cocoon.jxpath.JXPathCocoonContexts.java
/** * Returns a JXPathContext bound to the "application" scope. Caches that context * within the servlet context itself./*from w w w. j a v a 2 s. com*/ */ public final JXPathContext getApplicationContext(Context envContext) { JXPathContext context = (JXPathContext) envContext.getAttribute(Constants.JXPATH_CONTEXT); if (context == null) { envContext = new ContextProxy(envContext); context = factory.newContext(null, envContext); context.setVariables(new KeywordVariables(Constants.APPLICATION_SCOPE, envContext)); envContext.setAttribute(Constants.JXPATH_CONTEXT, context); } return context; }
From source file:org.openvpms.web.component.im.doc.FileNameFormatter.java
/** * Formats a file name using the jxpath expression returned by {@link DocumentTemplate#getFileNameExpression()}. * <p/>/*from ww w .j ava 2 s . co m*/ * Any extension is removed from the original file name. * * @param name the original file name. The base name of this is passed to the expression in the {@code $file} * variable * @param object the context object. If this an act, any related customer, patient, or supplier will be passed as * the variables $customer, $patient, and $supplier respectively. May be {@code null} * @param template the document template * @return the formatted name, or the base name of {@code name} if the template doesn't specify a format or * generation fails */ public String format(String name, IMObject object, DocumentTemplate template) { String result; String file = FilenameUtils.getBaseName(name); String expression = template.getFileNameExpression(); if (!StringUtils.isEmpty(expression)) { JXPathContext context = JXPathHelper.newContext(object != null ? object : new Object()); FileNameVariables variables = new FileNameVariables(archetypeService, lookups); context.setVariables(variables); Party patient = null; Party customer = null; Party supplier = null; if (object instanceof Act) { Act act = (Act) object; ActBean bean = new ActBean(act); if (bean.hasNode("patient")) { patient = (Party) bean.getNodeParticipant("patient"); } if (bean.hasNode("customer")) { customer = (Party) bean.getNodeParticipant("customer"); } else if (patient != null) { PatientRules rules = ServiceHelper.getBean(PatientRules.class); customer = rules.getOwner(patient, act.getActivityStartTime(), false); } if (bean.hasNode("supplier")) { supplier = (Party) bean.getNodeParticipant("supplier"); } } variables.declareVariable("customer", customer); variables.declareVariable("patient", patient); variables.declareVariable("supplier", supplier); variables.declareVariable("file", file); try { Object value = context.getValue(expression); result = (value != null) ? clean(value.toString()) : file; } catch (Throwable exception) { log.error("Failed to evaluate expression: " + expression, exception); result = file; } } else { result = file; } return result; }
From source file:org.paxml.core.Context.java
/** * Select objects with xpath./*w ww .j av a 2 s . c o m*/ * * @param from * the object to select properties from, null to select from * entire context. * @param xpath * the xpath * @param alwaysList * true to return a list with one item inside if the xpath * results in one object to be selected. * @return either a list of objects that satisfies the xpath, or the object * itself if the xpath results in one object to be selected and the * "alwaysList" parameter is false. */ public Object xpathSelect(Object from, String xpath, boolean alwaysList) { Variables vars = new BasicVariables(); if (from == null) { ObjectTree nameGlobal = getRootContext().getNameMap(false, true); ObjectTree nameLocal = getNameMap(true, false); vars.declareVariable(XPATH_NAME_GLOBAL_VAR, nameGlobal); vars.declareVariable(XPATH_NAME_LOCAL_VAR, nameLocal); ObjectTree nameAuto = new ObjectTree(null, nameGlobal); nameAuto.addValues(nameLocal); from = nameAuto; } JXPathContext xpathContext = JXPathContext.newContext(from); xpathContext.setVariables(vars); xpathContext.setIdentityManager(this); setXpathFunctions(xpathContext); try { Object selected = xpathContext.iterate(xpath); List<Object> list = new ArrayList<Object>(1); if (selected instanceof Iterator) { final Iterator<?> it = (Iterator<?>) selected; while (it.hasNext()) { Object obj = it.next(); list.add(getXpathResultObject(obj)); } if (list.size() == 1) { selected = list.get(0); } else { selected = list; } } else { selected = getXpathResultObject(selected); if (selected != null && alwaysList) { list.add(selected); } } if (alwaysList) { return list; } else { if (selected instanceof List) { list = (List) selected; final int size = list.size(); if (size == 0) { return null; } else if (size == 1) { return list.get(0); } } return selected; } } catch (NullPointerException e) { // when jxpath throws null pointer exception, it has problem // searching non-existing paths return null; } }