Java Code Examples for org.apache.commons.jxpath.JXPathContext#iterate()

The following examples show how to use org.apache.commons.jxpath.JXPathContext#iterate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AssertionUtils.java    From cougar with Apache License 2.0 6 votes vote down vote up
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 = "/";
    }
    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);
    }
}
 
Example 2
Source File: JsonDBTemplate.java    From jsondb-core with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> T findOne(String jxQuery, String collectionName) {
  CollectionMetaData collectionMeta = cmdMap.get(collectionName);
  if((null == collectionMeta) || (!collectionsRef.get().containsKey(collectionName))) {
    throw new InvalidJsonDbApiUsageException("Collection by name '" + collectionName + "' not found. Create collection first");
  }
  collectionMeta.getCollectionLock().readLock().lock();
  try {
    JXPathContext context = contextsRef.get().get(collectionName);
    Iterator<T> resultItr = context.iterate(jxQuery);
    while (resultItr.hasNext()) {
      T document = resultItr.next();
      Object obj = Util.deepCopy(document);
      if(encrypted && collectionMeta.hasSecret() && null!= obj){
        CryptoUtil.decryptFields(obj, collectionMeta, dbConfig.getCipher());
      }
      return (T) obj; // Return the first element we find.
    }
    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 {
    collectionMeta.getCollectionLock().readLock().unlock();
  }
}
 
Example 3
Source File: TestBaseConfigurationXMLReader.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method for checking values in the created document.
 *
 * @param ctx the JXPath context
 * @param path the path to be checked
 * @param values the expected element values
 */
private void check(final JXPathContext ctx, final String path, final String[] values)
{
    final Iterator<?> it = ctx.iterate(path);
    for (final String value : values) {
        assertTrue("Too few values", it.hasNext());
        assertEquals("Wrong property value", value, it.next());
    }
    assertFalse("Too many values", it.hasNext());
}
 
Example 4
Source File: JsonDBTemplate.java    From jsondb-core with MIT License 4 votes vote down vote up
@Override
public <T> T findAndRemove(String jxQuery, String collectionName) {
  if (null == jxQuery) {
    throw new InvalidJsonDbApiUsageException("Query string cannot be null.");
  }
  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();
  }
}
 
Example 5
Source File: JsonDBTemplate.java    From jsondb-core with MIT License 4 votes vote down vote up
@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.");
  }
  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();
  }
}
 
Example 6
Source File: XPath.java    From cloudml with GNU Lesser General Public License v3.0 4 votes vote down vote up
public Iterator iterate(Object context){
	JXPathContext jpathcontext = JXPathContext.newContext(context);
	return jpathcontext.iterate(literal);
}
 
Example 7
Source File: JXPath.java    From cloudml with GNU Lesser General Public License v3.0 4 votes vote down vote up
public Iterator iterate(Object context){
	JXPathContext jpathcontext = JXPathContext.newContext(context);
	return jpathcontext.iterate(literal);
}