List of usage examples for org.apache.commons.jxpath JXPathContext iterate
public abstract Iterator iterate(String xpath);
From source file:jsondb.JsonDBTemplate.java
@SuppressWarnings("unchecked") @Override//from w w w. j a va 2 s . c o m public <T> List<T> findAllAndModify(String jxQuery, Update update, String collectionName) { CollectionMetaData cmd = cmdMap.get(collectionName); Map<Object, T> collection = (Map<Object, T>) collectionsRef.get().get(collectionName); if ((null == cmd) || (null == collection)) { throw new InvalidJsonDbApiUsageException("Die Collection mit dem Namen '" + collectionName + "' wurde nicht gefunden. Bitte zuvor anlegen."); } cmd.getCollectionLock().writeLock().lock(); try { JXPathContext context = contextsRef.get().get(collectionName); Iterator<T> resultItr = context.iterate(jxQuery); Map<Object, T> clonedModifiedObjects = new HashMap<Object, T>(); while (resultItr.hasNext()) { T objectToModify = resultItr.next(); T clonedModifiedObject = (T) Util.deepCopy(objectToModify); for (Entry<String, Object> entry : update.getUpdateData().entrySet()) { Object newValue = Util.deepCopy(entry.getValue()); if (encrypted && cmd.hasSecret() && cmd.isSecretField(entry.getKey())) { newValue = dbConfig.getCipher().encrypt(newValue.toString()); } try { BeanUtils.copyProperty(clonedModifiedObject, entry.getKey(), newValue); } catch (IllegalAccessException | InvocationTargetException e) { Logger.error( "Failed to copy updated data into existing collection document using BeanUtils", e); return null; } } Object id = Util.getIdForEntity(clonedModifiedObject, cmd.getIdAnnotatedFieldGetterMethod()); clonedModifiedObjects.put(id, clonedModifiedObject); } JsonWriter jw = null; try { jw = new JsonWriter(dbConfig, cmd, collectionName, fileObjectsRef.get().get(collectionName)); } catch (IOException ioe) { Logger.error("Failed to obtain writer for " + collectionName, ioe); throw new JsonDBException("Failed to save " + collectionName, ioe); } boolean updateResult = jw.updateInJsonFile(collection, clonedModifiedObjects); if (updateResult) { collection.putAll(clonedModifiedObjects); //Clone it once more because we want to disconnect it from the in-memory objects before returning. List<T> returnObjects = new ArrayList<T>(); for (T obj : clonedModifiedObjects.values()) { //Clone it once more because we want to disconnect it from the in-memory objects before returning. T returnObj = (T) Util.deepCopy(obj); if (encrypted && cmd.hasSecret() && null != returnObj) { CryptoUtil.decryptFields(returnObj, cmd, dbConfig.getCipher()); } returnObjects.add(returnObj); } return returnObjects; } return null; } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { Logger.error("Error when decrypting value for a @Secret annotated field for entity: " + collectionName, e); throw new JsonDBException( "Error when decrypting value for a @Secret annotated field for entity: " + collectionName, e); } finally { cmd.getCollectionLock().writeLock().unlock(); } }
From source file:jsondb.JsonDBTemplate.java
@Override public <T> List<T> findAllAndRemove(String jxQuery, String collectionName) { CollectionMetaData cmd = cmdMap.get(collectionName); @SuppressWarnings("unchecked") Map<Object, T> collection = (Map<Object, T>) collectionsRef.get().get(collectionName); if ((null == cmd) || (null == collection)) { throw new InvalidJsonDbApiUsageException( "Collection by name '" + collectionName + "' not found. Create collection first."); }//from www .j a v a 2s . com cmd.getCollectionLock().writeLock().lock(); try { JXPathContext context = contextsRef.get().get(collectionName); @SuppressWarnings("unchecked") Iterator<T> resultItr = context.iterate(jxQuery); Set<Object> removeIds = new HashSet<Object>(); while (resultItr.hasNext()) { T objectToRemove = resultItr.next(); Object idToRemove = Util.getIdForEntity(objectToRemove, cmd.getIdAnnotatedFieldGetterMethod()); removeIds.add(idToRemove); } if (removeIds.size() < 1) { return null; } JsonWriter jw; try { jw = new JsonWriter(dbConfig, cmd, collectionName, fileObjectsRef.get().get(collectionName)); } catch (IOException ioe) { Logger.error("Failed to obtain writer for " + collectionName, ioe); throw new JsonDBException("Failed to save " + collectionName, ioe); } boolean substractResult = jw.removeFromJsonFile(collection, removeIds); List<T> removedObjects = null; if (substractResult) { removedObjects = new ArrayList<T>(); for (Object id : removeIds) { // Don't need to clone it, this object no more exists in the collection removedObjects.add(collection.remove(id)); } } return removedObjects; } finally { cmd.getCollectionLock().writeLock().unlock(); } }
From source file:jsondb.JsonDBTemplate.java
@Override public <T> T findAndRemove(String jxQuery, String collectionName) { if (null == jxQuery) { throw new InvalidJsonDbApiUsageException("Query string cannot be null."); }/*from w ww .ja v a 2s . c o m*/ CollectionMetaData cmd = cmdMap.get(collectionName); @SuppressWarnings("unchecked") Map<Object, T> collection = (Map<Object, T>) collectionsRef.get().get(collectionName); if ((null == cmd) || (null == collection)) { throw new InvalidJsonDbApiUsageException( "Collection by name '" + collectionName + "' not found. Create collection first."); } cmd.getCollectionLock().writeLock().lock(); try { JXPathContext context = contextsRef.get().get(collectionName); @SuppressWarnings("unchecked") Iterator<T> resultItr = context.iterate(jxQuery); T objectToRemove = null; while (resultItr.hasNext()) { objectToRemove = resultItr.next(); break; // Use only the first element we find. } if (null != objectToRemove) { Object idToRemove = Util.getIdForEntity(objectToRemove, cmd.getIdAnnotatedFieldGetterMethod()); if (!collection.containsKey(idToRemove)) { //This will never happen since the object was located based of jxQuery throw new InvalidJsonDbApiUsageException(String .format("Objects with Id %s not found in collection %s", idToRemove, collectionName)); } JsonWriter jw; try { jw = new JsonWriter(dbConfig, cmd, collectionName, fileObjectsRef.get().get(collectionName)); } catch (IOException ioe) { Logger.error("Failed to obtain writer for " + collectionName, ioe); throw new JsonDBException("Failed to save " + collectionName, ioe); } boolean substractResult = jw.removeFromJsonFile(collection, idToRemove); if (substractResult) { T objectRemoved = collection.remove(idToRemove); // Don't need to clone it, this object no more exists in the collection return objectRemoved; } else { Logger.error("Unexpected, Failed to substract the object"); } } return null; //Either the jxQuery found nothing or actual FileIO failed to substract it. } finally { cmd.getCollectionLock().writeLock().unlock(); } }
From source file:fr.cls.atoll.motu.library.misc.data.CatalogData.java
static public List<Object> findJaxbElementUsingJXPath(Object object, String xPath) { List<Object> listObjectFound = new ArrayList<Object>(); JXPathContext context = JXPathContext.newContext(object); context.setLenient(true);/* w w w.ja v a 2s. c o m*/ // Object oo = // context.getValue("//threddsMetadataGroup[name='{http://www.unidata.ucar.edu/namespaces/thredds/InvCatalog/v1.0}serviceName']/value"); // Object oo = // context.getValue("//threddsMetadataGroup[name='{http://www.unidata.ucar.edu/namespaces/thredds/InvCatalog/v1.0}serviceName']/value"); // Iterator it = // context.iterate("//threddsMetadataGroup[name='{http://www.unidata.ucar.edu/namespaces/thredds/InvCatalog/v1.0}serviceName']/value"); Iterator<?> it = context.iterate(xPath); while (it.hasNext()) { listObjectFound.add(it.next()); } return listObjectFound; }
From source file:nz.org.take.r2ml.util.TypeVariablesFilter.java
public void repair(RuleBase ruleBase) throws R2MLException { JXPathContext context = JXPathContext.newContext(ruleBase); ObjectFactory of = new ObjectFactory(); // search objectclassificationatoms that contain untyped variables context = JXPathContext.newContext(ruleBase); Iterator implicitTypedVars = context.iterate( "//qfAndOrNafNegFormula" + "[declaredType='class de.tu_cottbus.r2ml.ObjectClassificationAtom']" + "[value/objectTerm/declaredType='class de.tu_cottbus.r2ml.ObjectVariable']" + "[not(value/objectTerm/value/classID)]" + "/value"); while (implicitTypedVars.hasNext()) { try {//from ww w . j a va 2 s .c om ObjectClassificationAtom classification = (ObjectClassificationAtom) implicitTypedVars.next(); ObjectVariable var = (ObjectVariable) classification.getObjectTerm().getValue(); ObjectVariable newVar = of.createObjectVariable(); newVar.setName(var.getName()); newVar.setTypeCategory(var.getTypeCategory()); newVar.setClassID(classification.getClassID()); classification.setObjectTerm(of.createObjectVariable(newVar)); } catch (RuntimeException e) { if (R2MLDriver.get().logger.isDebugEnabled()) R2MLDriver.get().logger.debug("Exception occured while typing all variables.", e); throw new R2MLException("Unable to type variables in rule base, abort rule import."); } } // search already typed variables and save them in a hash-map Iterator typedVar = context .iterate("//objectTerm[declaredType='class de.tu_cottbus.r2ml.ObjectVariable']/value[classID]");// ce.iterate(context); Map<String, QName> classID4name = new HashMap<String, QName>(); while (typedVar.hasNext()) { try { ObjectVariable element = (ObjectVariable) typedVar.next(); classID4name.put(element.getName(), element.getClassID()); } catch (RuntimeException e) { } } // search all untyped variables and look up the types in the classId // hashmap Iterator untypedVar = context.iterate( "//objectTerm[declaredType='class de.tu_cottbus.r2ml.ObjectVariable']/value[not(classID)]"); while (untypedVar.hasNext()) { ObjectVariable element = (ObjectVariable) untypedVar.next(); QName classID = classID4name.get(element.getName()); if (classID != null) { element.setClassID(classID); } } }
From source file:org.apache.cocoon.components.modules.input.JXPathHelper.java
public static Object[] getAttributeValues(String name, Configuration modeConf, JXPathHelperConfiguration setup, Object contextObj) throws ConfigurationException { if (contextObj == null) { return null; }//from w ww. jav a 2s. com try { JXPathContext jxContext = JXPathContext.newContext(contextObj); setup(setup, jxContext, modeConf); List values = null; Iterator i = jxContext.iterate(name); if (i.hasNext()) { values = new LinkedList(); } while (i.hasNext()) { values.add(i.next()); } Object[] obj = null; if (values != null) { obj = values.toArray(); if (obj.length == 0) { obj = null; } } return obj; } catch (Exception e) { throw new ConfigurationException("Module does not support <" + name + ">" + "attribute.", e); } }
From source file:org.apache.cocoon.forms.binding.MultiValueJXPathBinding.java
public void doLoad(Widget frmModel, JXPathContext jctx) throws BindingException { Widget widget = selectWidget(frmModel, this.multiValueId); if (widget == null) { throw new BindingException("The widget with the ID [" + this.multiValueId + "] referenced in the binding does not exist in the form definition."); }/*w w w. j a v a2 s . c o m*/ // Move to multi value context Pointer ptr = jctx.getPointer(this.multiValuePath); if (ptr.getNode() != null) { // There are some nodes to load from JXPathContext multiValueContext = jctx.getRelativeContext(ptr); // build a jxpath iterator for pointers Iterator rowPointers = multiValueContext.iterate(this.rowPath); LinkedList list = new LinkedList(); while (rowPointers.hasNext()) { Object value = rowPointers.next(); if (value != null && convertor != null) { if (value instanceof String) { ConversionResult conversionResult = convertor.convertFromString((String) value, convertorLocale, null); if (conversionResult.isSuccessful()) value = conversionResult.getResult(); else value = null; } else { getLogger().warn("Convertor ignored on backend-value which isn't of type String."); } } list.add(value); } widget.setValue(list.toArray()); } if (getLogger().isDebugEnabled()) getLogger().debug("done loading values " + toString()); }
From source file:org.apache.cocoon.woody.binding.MultiValueJXPathBinding.java
public void doLoad(Widget frmModel, JXPathContext jctx) throws BindingException { Widget widget = frmModel.getWidget(this.multiValueId); if (widget == null) { throw new BindingException("The widget with the ID [" + this.multiValueId + "] referenced in the binding does not exist in the form definition."); }/*from w w w . j av a2 s. com*/ // Move to multi value context Pointer ptr = jctx.getPointer(this.multiValuePath); if (ptr.getNode() != null) { // There are some nodes to load from JXPathContext multiValueContext = jctx.getRelativeContext(ptr); // build a jxpath iterator for pointers Iterator rowPointers = multiValueContext.iterate(this.rowPath); LinkedList list = new LinkedList(); while (rowPointers.hasNext()) { Object value = rowPointers.next(); if (value != null && convertor != null) { if (value instanceof String) { value = convertor.convertFromString((String) value, convertorLocale, null); } else { getLogger().warn("Convertor ignored on backend-value which isn't of type String."); } } list.add(value); } widget.setValue(list.toArray()); } if (getLogger().isDebugEnabled()) getLogger().debug("done loading values " + toString()); }
From source file:org.chiba.xml.xforms.ui.RepeatIndexTest.java
/** * Sets up the test.// ww w .j ava 2 s . c o m * * @throws Exception in any error occurred during setup. */ protected void setUp() throws Exception { this.chibaBean = new ChibaBean(); this.chibaBean.setXMLContainer(getClass().getResourceAsStream("RepeatIndexTest.xhtml")); this.chibaBean.init(); JXPathContext context = JXPathContext.newContext(this.chibaBean.getXMLContainer()); // iterate unrolled repeats Iterator repeatIterator = context.iterate("//xf:repeat[chiba:data]/@id"); this.enclosingRepeat = (Repeat) this.chibaBean.getContainer().lookup(repeatIterator.next().toString()); this.nestedRepeat1 = (Repeat) this.chibaBean.getContainer().lookup(repeatIterator.next().toString()); this.nestedRepeat2 = (Repeat) this.chibaBean.getContainer().lookup(repeatIterator.next().toString()); this.nestedRepeat3 = (Repeat) this.chibaBean.getContainer().lookup(repeatIterator.next().toString()); // iterate repeated inputs Iterator inputIterator = context.iterate("//xf:input/@id"); this.input11 = (Text) this.chibaBean.getContainer().lookup(inputIterator.next().toString()); this.input12 = (Text) this.chibaBean.getContainer().lookup(inputIterator.next().toString()); inputIterator.next(); // skip repeat prototype this.input21 = (Text) this.chibaBean.getContainer().lookup(inputIterator.next().toString()); this.input22 = (Text) this.chibaBean.getContainer().lookup(inputIterator.next().toString()); inputIterator.next(); // skip repeat prototype this.input31 = (Text) this.chibaBean.getContainer().lookup(inputIterator.next().toString()); this.input32 = (Text) this.chibaBean.getContainer().lookup(inputIterator.next().toString()); // iterate repeated actions Iterator actionIterator = context.iterate("//xf:action/@id"); this.action11 = (XFormsAction) this.chibaBean.getContainer().lookup(actionIterator.next().toString()); this.action12 = (XFormsAction) this.chibaBean.getContainer().lookup(actionIterator.next().toString()); actionIterator.next(); // skip repeat prototype this.action21 = (XFormsAction) this.chibaBean.getContainer().lookup(actionIterator.next().toString()); this.action22 = (XFormsAction) this.chibaBean.getContainer().lookup(actionIterator.next().toString()); actionIterator.next(); // skip repeat prototype this.action31 = (XFormsAction) this.chibaBean.getContainer().lookup(actionIterator.next().toString()); this.action32 = (XFormsAction) this.chibaBean.getContainer().lookup(actionIterator.next().toString()); }
From source file:org.chiba.xml.xforms.ui.RepeatItemTest.java
/** * Sets up the test./*from w w w.j av a 2s .c o m*/ * * @throws Exception in any error occurred during setup. */ protected void setUp() throws Exception { this.chibaBean = new ChibaBean(); this.chibaBean.setXMLContainer(getClass().getResourceAsStream("RepeatItemTest.xhtml")); this.chibaBean.init(); JXPathContext context = JXPathContext.newContext(this.chibaBean.getXMLContainer()); // iterate unrolled repeats Iterator repeatIterator = context.iterate("//xf:repeat[chiba:data]/@id"); this.enclosingRepeat = (Repeat) this.chibaBean.getContainer().lookup(repeatIterator.next().toString()); this.nestedRepeat1 = (Repeat) this.chibaBean.getContainer().lookup(repeatIterator.next().toString()); this.nestedRepeat2 = (Repeat) this.chibaBean.getContainer().lookup(repeatIterator.next().toString()); this.nestedRepeat3 = (Repeat) this.chibaBean.getContainer().lookup(repeatIterator.next().toString()); }