List of usage examples for org.apache.commons.jxpath JXPathContext iterate
public abstract Iterator iterate(String xpath);
From source file:blueprint.sdk.util.JXPathHelper.java
/** * @param xpath XPath to evaluate// w ww . j av a 2s. c o m * @param context target context, JXPathContext.newContext(Node) * @return Iterator or null(not found) */ @SuppressWarnings({ "unchecked", "WeakerAccess" }) public static Iterator<String> evaluateIterator(String xpath, JXPathContext context) { Iterator<String> result = null; try { result = context.iterate(xpath); } catch (JXPathNotFoundException ignored) { } return result; }
From source file:com.betfair.testing.utils.cougar.assertions.AssertionUtils.java
private static void doJsonSorting(JSONObject doc, String x) throws XPathExpressionException, IOException, JSONException { JXPathContext ctx = JXPathContext.newContext(doc); String parentX = x.substring(0, x.lastIndexOf("/")); if ("".equals(parentX)) { parentX = "/"; }/*from w w w . jav a 2 s. com*/ String childName = x.substring(x.lastIndexOf("/") + 1); Iterator it = ctx.iterate(parentX); while (it.hasNext()) { JSONObject p = (JSONObject) it.next(); JSONArray n = p.getJSONArray(childName); List allKids = new ArrayList<>(n.length()); for (int j = 0; j < n.length(); j++) { allKids.add(n.get(j)); } Collections.sort(allKids, new Comparator<Object>() { @Override public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); } }); JSONArray newArray = new JSONArray(allKids); p.put(childName, newArray); } }
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 www . j ava 2s . com*/ 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: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 ww w . j a va2s . c o 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.yahoo.xpathproto.ImageHandler.java
@Override public List<Message.Builder> getRepeatedProtoBuilder(JXPathContext context, Context vars, Config.Entry entry) { List<Message.Builder> builders = new ArrayList(); Iterator iterator = context.iterate(entry.getPath()); while (iterator.hasNext()) { Object value = iterator.next(); builders.add(copyObjectToImageAsset(JXPathContext.newContext(value))); }//from w ww.j av a2s .com return builders; }
From source file:de.tudarmstadt.ukp.dkpro.core.dictionaryannotator.semantictagging.SemanticFieldAnnotator.java
@Override public void process(JCas aJCas) throws AnalysisEngineProcessException { CAS cas = aJCas.getCas();// w ww. j av a 2s . c om for (AnnotationFS cover : CasUtil.select(cas, CasUtil.getAnnotationType(cas, annotationType))) { // If there is a constraint, check if it matches if (constraint != null) { JXPathContext ctx = JXPathContext.newContext(cover); boolean match = ctx.iterate(constraint).hasNext(); if (!match) { continue; } } // If the target type is a token, use it directly, otherwise select the covered tokens Collection<Token> tokens; if (cover instanceof Token) { tokens = Collections.singleton((Token) cover); } else { tokens = JCasUtil.selectCovered(aJCas, Token.class, cover); } for (Token token : tokens) { try { String semanticField = semanticFieldResource.getSemanticTag(token); SemanticField semanticFieldAnnotation = new SemanticField(aJCas, token.getBegin(), token.getEnd()); semanticFieldAnnotation.setValue(semanticField); semanticFieldAnnotation.addToIndexes(); } catch (ResourceAccessException e) { throw new AnalysisEngineProcessException(e); } } } }
From source file:fr.isima.ponge.wsprotocol.impl.BusinessProtocolImplTest.java
@SuppressWarnings("unchecked") public void testAddRemoveOperationLogic() { Iterator it;//from ww w . j a v a2 s . co m String str; JXPathContext ctx = JXPathContext.newContext(bp2); TestCase.assertEquals("s0", bp2.getInitialState().getName()); //$NON-NLS-1$ it = ctx.iterate("finalStates/name"); //$NON-NLS-1$ TestCase.assertTrue(it.hasNext()); TestCase.assertEquals("s1", (String) it.next()); //$NON-NLS-1$ TestCase.assertFalse(it.hasNext()); it = ctx.iterate("states[name='s0']/successors/name"); //$NON-NLS-1$ TestCase.assertTrue(it.hasNext()); TestCase.assertEquals("s1", (String) it.next()); //$NON-NLS-1$ TestCase.assertEquals("s0", (String) it.next()); //$NON-NLS-1$ TestCase.assertFalse(it.hasNext()); it = ctx.iterate("states[name='s0']/predecessors/name"); //$NON-NLS-1$ TestCase.assertTrue(it.hasNext()); TestCase.assertEquals("s0", (String) it.next()); //$NON-NLS-1$ TestCase.assertFalse(it.hasNext()); it = ctx.iterate("states[name='s1']/predecessors/name"); //$NON-NLS-1$ TestCase.assertTrue(it.hasNext()); TestCase.assertEquals("s0", (String) it.next()); //$NON-NLS-1$ TestCase.assertFalse(it.hasNext()); it = ctx.iterate("states[name='s1']/successors/name"); //$NON-NLS-1$ TestCase.assertFalse(it.hasNext()); it = ctx.iterate("messages/name"); //$NON-NLS-1$ // Strange, sometimes b is before a and vice-versa ... TestCase.assertTrue(it.hasNext()); str = (String) it.next(); if ("a".equals(str)) //$NON-NLS-1$ { TestCase.assertEquals("b", (String) it.next()); //$NON-NLS-1$ } else if ("b".equals(str)) //$NON-NLS-1$ { TestCase.assertEquals("a", (String) it.next()); //$NON-NLS-1$ } else { TestCase.fail(); } TestCase.assertFalse(it.hasNext()); it = ctx.iterate("states[name='s0']/outgoingOperations/message/name"); //$NON-NLS-1$ TestCase.assertTrue(it.hasNext()); TestCase.assertEquals("a", (String) it.next()); //$NON-NLS-1$ TestCase.assertEquals("b", (String) it.next()); //$NON-NLS-1$ TestCase.assertFalse(it.hasNext()); it = ctx.iterate("states[name='s0']/incomingOperations/message/name"); //$NON-NLS-1$ TestCase.assertTrue(it.hasNext()); TestCase.assertEquals("b", (String) it.next()); //$NON-NLS-1$ TestCase.assertFalse(it.hasNext()); it = ctx.iterate("states[name='s1']/incomingOperations/message/name"); //$NON-NLS-1$ TestCase.assertTrue(it.hasNext()); TestCase.assertEquals("a", (String) it.next()); //$NON-NLS-1$ TestCase.assertFalse(it.hasNext()); it = ctx.iterate("states[name='s1']/outgoingOperations/message/name"); //$NON-NLS-1$ TestCase.assertFalse(it.hasNext()); Operation toRemove = (Operation) ctx.getValue("operations[message/name='a']"); //$NON-NLS-1$ bp2.removeOperation(toRemove); List remainingOps = (List) ctx.getValue("states[name='s0']/incomingOperations"); //$NON-NLS-1$ TestCase.assertTrue(remainingOps.size() == 1); List remainingSucc = (List) ctx.getValue("states[name='s0']/successors"); //$NON-NLS-1$ TestCase.assertTrue(remainingSucc.size() == 1); State s0 = bp2.getInitialState(); bp2.removeState(s0); TestCase.assertNull(bp2.getInitialState()); }
From source file:de.tudarmstadt.ukp.dkpro.core.tokit.TokenMerger.java
@Override public void process(JCas aJCas) throws AnalysisEngineProcessException { CAS cas = aJCas.getCas();/* w ww. ja v a 2 s . c o m*/ if (posValue != null) { mappingProvider.configure(cas); } Collection<Annotation> toRemove = new ArrayList<Annotation>(); for (AnnotationFS cover : CasUtil.select(cas, CasUtil.getAnnotationType(cas, annotationType))) { List<Token> covered = selectCovered(Token.class, cover); if (covered.size() < 2) { continue; } if (constraint != null) { JXPathContext ctx = JXPathContext.newContext(cover); boolean match = ctx.iterate(constraint).hasNext(); if (!match) { continue; } } Iterator<Token> i = covered.iterator(); // Extend first token Token token = i.next(); token.setEnd(covered.get(covered.size() - 1).getEnd()); // Optionally update the POS value if (posValue != null) { updatePos(token, toRemove); } // Record lemma - may be needed for join later List<String> lemmata = new ArrayList<String>(); if (token.getLemma() != null) { lemmata.add(token.getLemma().getValue()); } // Mark the rest for deletion - record lemmata if desired for later join while (i.hasNext()) { Token t = i.next(); Lemma lemma = t.getLemma(); if (lemma != null) { lemmata.add(lemma.getValue()); toRemove.add(lemma); } POS pos = t.getPos(); if (pos != null) { toRemove.add(pos); } toRemove.add(t); } // Join lemmata if desired if (lemmaMode == LemmaMode.JOIN) { Lemma lemma = token.getLemma(); if (!lemmata.isEmpty()) { if (lemma == null) { lemma = new Lemma(aJCas); } lemma.setValue(StringUtils.join(lemmata, " ")); } // Remove if there was nothing to join... I don't really ever expect to get here else if (lemma != null) { token.setLemma(null); toRemove.add(lemma); } } // Remove the lemma - if desired else if (lemmaMode == LemmaMode.REMOVE) { Lemma lemma = token.getLemma(); if (lemma != null) { token.setLemma(null); toRemove.add(lemma); } } // Update offsets for lemma if (token.getLemma() != null) { token.getLemma().setBegin(token.getBegin()); token.getLemma().setEnd(token.getEnd()); } } // Remove tokens no longer needed for (Annotation t : toRemove) { t.removeFromIndexes(); } }
From source file:de.innovationgate.wgpublisher.webtml.Item.java
public void tmlEndTag() throws WGException, TMLException { String itemName = this.getName(); TMLContext tmlContext = this.getTMLContext(); List result = null;/*from ww w . j av a 2 s . c o m*/ String type = this.getType(); // add warning on illegal use of highlight attribute if (stringToBoolean(getHighlight())) { if (!type.equals("content")) { addWarning("Highlighting can only be used with type 'content' - skipped."); } } // Retrieve value if (type.equals("content")) { result = tmlContext.itemlist(itemName, buildNamedActionParameters(false)); if (stringToBoolean(getHighlight())) { if (this.stringToBoolean(this.getScriptlets())) { addWarning("Highlighting cannot be used with scriptlets - skipped."); } else if (this.getAliases() != null) { addWarning("Highlighting cannot be used with aliases - skipped."); } else if (getXpath() != null) { addWarning("Highlighting cannot be used together with xpath - skipped."); } else { // highlight itemvalue with information from lucene query result = Collections.singletonList(tmlContext.highlightitem(itemName, getHighlightprefix(), getHighlightsuffix(), getStatus().encode)); getStatus().encode = "none"; } } } else if (type.equals("profile")) { TMLUserProfile profile = tmlContext.getprofile(); if (profile == null) { this.addWarning("Current user has no profile", true); return; } result = profile.itemlist(itemName); } else if (type.equals("portlet")) { TMLPortlet portlet = tmlContext.getportlet(); if (portlet == null) { this.addWarning("Current user has no portlet registration", true); return; } result = portlet.itemlist(itemName); } else if (type.equals("tmlform")) { TMLForm form = tmlContext.gettmlform(); if (form == null) { addWarning("There is no current WebTML form at this position in the current request"); return; } result = form.fieldlist(itemName); } // The item does not exist or is empty. Treat as empty list. if (result == null) { result = new ArrayList(); } // Eventually execute xpath String xpath = getXpath(); if (xpath != null && result.size() > 0) { Object firstResult = result.get(0); if (firstResult instanceof Node) { Node resultNode = (Node) firstResult; result = resultNode.selectNodes(xpath); } else if (firstResult instanceof String) { try { Document doc = DocumentHelper.parseText((String) firstResult); result = doc.selectNodes(xpath); } catch (DocumentException e) { addWarning("Unable to parse item content '" + itemName + "' as XML: " + firstResult); } } else if (ExpressionEngineFactory.getTMLScriptEngine() .determineTMLScriptType(firstResult) == RhinoExpressionEngine.TYPE_XMLOBJECT) { result = ExpressionEngineFactory.getTMLScriptEngine().xpathTMLScriptBean(firstResult, xpath); } else { JXPathContext jxcontext = JXPathContext.newContext(firstResult); Iterator jxresults = jxcontext.iterate(xpath); result = new ArrayList(); while (jxresults.hasNext()) { result.add(jxresults.next()); } } } // Eventually resolve scriptlets if (result.size() > 0 && this.stringToBoolean(this.getScriptlets()) == true) { RhinoExpressionEngine engine = ExpressionEngineFactory.getTMLScriptEngine(); String resolvedResultStr = null; try { Map params = new HashMap(); params.put(RhinoExpressionEngine.SCRIPTLETOPTION_LEVEL, RhinoExpressionEngine.LEVEL_SCRIPTLETS); resolvedResultStr = engine.resolveScriptlets(result.get(0), getTMLContext(), params); result = new ArrayList(); result.add(resolvedResultStr); } catch (Exception e) { throw new TMLException("Exception parsing scriptlets", e, false); } } // BI-Editor (See Root-Class for attrib WGACore.ATTRIB_EDITDOCUMENT) Object attribEdit = this.getPageContext().getRequest().getAttribute(WGACore.ATTRIB_EDITDOCUMENT); if (attribEdit != null && getEditor() != null && attribEdit.equals(this.getTMLContext().getcontent().getContentKey().toString())) { buildEditor(itemName, result); setResult(result); } else { // if aliases are defined, replace values with aliases List aliases = this.retrieveAliases(); if (aliases.isEmpty()) this.setResult(result); else { WGA wga = WGA.get(); this.setResult(wga.aliases(WGUtils.toString(result), aliases)); } } }
From source file:com.lrodriguez.SVNBrowser.java
private void doXpathQuery(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws ServletException, IOException { //example/* w w w. j a v a2 s .com*/ //?xpathQuery=.[revision < 9315 and revision>9000 and author='echow' or author ='lrodrigu' and type='A'] logDebug("dispatching xpath query: " + request.getParameter(XPATH_QUERY)); SVNRepository repository = ((SVNHttpSession) request.getSession().getAttribute(SVNSESSION)).getRepository(); Collection svnLogEntries = null; try { svnLogEntries = getSVNLogEntries(request, 0, repository.getDatedRevision(new Date())); } catch (SVNException e) { e.printStackTrace(); request.setAttribute(ERROR, e.getErrorMessage()); request.getRequestDispatcher(INDEX_JSP).forward(request, response); return; } List entriesList = new ArrayList(); if (svnLogEntries != null && svnLogEntries.size() > 0) { List entryFacadeList = getAllEntries(svnLogEntries); JXPathContext context = JXPathContext.newContext(entryFacadeList); context.setLenient(true); for (Iterator iter = context.iterate(request.getParameter(XPATH_QUERY)); iter.hasNext();) { Object currEntryFacade = iter.next(); entriesList.add(currEntryFacade); } } session.setAttribute(UNIQUE_ENTRIES, entriesList); request.getRequestDispatcher(INDEX_JSP).forward(request, response); return; }