Example usage for com.fasterxml.jackson.databind.node ArrayNode elements

List of usage examples for com.fasterxml.jackson.databind.node ArrayNode elements

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind.node ArrayNode elements.

Prototype

public Iterator<JsonNode> elements() 

Source Link

Usage

From source file:com.enitalk.opentok.OpenTokListener.java

@Scheduled(fixedDelay = 10000L)
public void updateFinalStatus() {
    try {// w  w  w .ja  v  a2  s . co m
        Criteria cc3 = Criteria.where("status").is(2);
        Criteria cc1 = Criteria.where("video").exists(false);
        Query q = Query.query(Criteria.where("endDate").lt(new DateTime().toDate()).andOperator(cc3, cc1));
        q.fields().exclude("_id").include("opentok").include("ii");

        List<HashMap> eligibleEvents = mongo.find(q, HashMap.class, "events");
        if (!eligibleEvents.isEmpty()) {
            ArrayNode evs = jackson.convertValue(eligibleEvents, ArrayNode.class);
            Iterator<JsonNode> evIt = evs.elements();
            while (evIt.hasNext()) {
                JsonNode ev = evIt.next();
                HashMultimap<String, String> mmap = HashMultimap.create();

                List<JsonNode> alls = ev.path("opentok").findParents("id");
                alls.forEach((JsonNode op) -> {
                    mmap.put(op.path("id").asText(), op.path("status").asText());
                });

                logger.info("Opentok multimap {}", mmap);
                long uploadedArchives = mmap.keySet().stream().filter((String id) -> {
                    return mmap.get(id).contains("uploaded");
                }).count();
                if (uploadedArchives == mmap.keySet().size()) {
                    logger.info("All archives uploaded, process further");
                    mongo.updateFirst(Query.query(Criteria.where("ii").is(ev.path("ii").asText())),
                            new Update().set("video", 0), "events");

                } else {
                    logger.info("Only {} of {} archives uploaded", uploadedArchives, mmap);
                }
            }
        }

    } catch (Exception e) {
        logger.error(ExceptionUtils.getFullStackTrace(e));
    }
}

From source file:org.calrissian.mango.json.deser.NodeDeserializer.java

protected Node parseField(String fieldKey, JsonNode fieldJson) throws IOException {
    switch (fieldKey) {
    case "and": {
        AndNode andNode = new AndNode();
        JsonNode children = fieldJson.get("children");
        if (children instanceof ArrayNode) {
            ArrayNode childrenArray = (ArrayNode) children;
            Iterator<JsonNode> elements = childrenArray.elements();
            while (elements.hasNext()) {
                JsonNode entry = elements.next();
                Iterator<String> fieldNames = entry.fieldNames();
                while (fieldNames.hasNext()) {
                    String key = fieldNames.next();
                    andNode.addChild(parseField(key, entry.get(key)));
                }/*ww w . j  a v a  2 s.co  m*/
            }
        }
        return andNode;
    }
    case "or": {
        OrNode orNode = new OrNode();
        JsonNode children = fieldJson.get("children");
        if (children instanceof ArrayNode) {
            ArrayNode childrenArray = (ArrayNode) children;
            Iterator<JsonNode> elements = childrenArray.elements();
            while (elements.hasNext()) {
                JsonNode entry = elements.next();
                Iterator<String> fieldNames = entry.fieldNames();
                while (fieldNames.hasNext()) {
                    String key = fieldNames.next();
                    orNode.addChild(parseField(key, entry.get(key)));
                }
            }
        }
        return orNode;
    }
    case "eq": {
        String key = fieldJson.get("key").asText();
        String type = fieldJson.get("type").asText();
        String val_str = fieldJson.get("value").asText();

        Object obj = this.typeRegistry.decode(type, val_str);
        return new EqualsLeaf(key, obj, null);
    }
    case "neq": {
        String key = fieldJson.get("key").asText();
        String type = fieldJson.get("type").asText();
        String val_str = fieldJson.get("value").asText();

        Object obj = this.typeRegistry.decode(type, val_str);
        return new NotEqualsLeaf(key, obj, null);
    }
    case "range": {
        String key = fieldJson.get("key").asText();
        String type = fieldJson.get("type").asText();
        String start_str = fieldJson.get("start").asText();
        String end_str = fieldJson.get("end").asText();

        Object start = this.typeRegistry.decode(type, start_str);
        Object end = this.typeRegistry.decode(type, end_str);
        return new RangeLeaf(key, start, end, null);
    }
    default:
        throw new IllegalArgumentException("Unsupported field: " + fieldKey);
    }
}

From source file:com.redhat.lightblue.eval.NaryFieldRelationalExpressionEvaluator.java

@Override
public boolean evaluate(QueryEvaluationContext ctx) {
    LOGGER.debug("evaluate {} {} {}", field, operator, rfield);
    KeyValueCursor<Path, JsonNode> cursor = ctx.getNodes(field);
    boolean ret = false;
    while (cursor.hasNext()) {
        cursor.next();//from w w  w. jav  a  2  s.c  o  m
        JsonNode valueNode = cursor.getCurrentValue();
        Object docValue;
        if (valueNode != null) {
            docValue = fieldMd.getType().fromJson(valueNode);
        } else {
            docValue = null;
        }
        boolean in = false;
        KeyValueCursor<Path, JsonNode> rcursor = ctx.getNodes(rfield);
        while (rcursor.hasNext()) {
            rcursor.next();
            JsonNode lnode = rcursor.getCurrentValue();
            if (lnode != null && lnode instanceof ArrayNode) {
                ArrayNode listNode = (ArrayNode) lnode;
                LOGGER.debug("value={} list={}", valueNode, listNode);

                for (Iterator<JsonNode> itr = listNode.elements(); itr.hasNext();) {
                    JsonNode rvalue = itr.next();
                    if (docValue == null) {
                        if (rvalue == null || rvalue instanceof NullNode)
                            in = true;
                        break;
                    } else if (fieldMd.getType().compare(docValue, rvalue) == 0) {
                        in = true;
                        break;
                    }
                }
                LOGGER.debug("in={}", in);
                if (in) {
                    ret = true;
                    break;
                }
            }
        }
    }
    ctx.setResult(operator.apply(ret));
    return ctx.getResult();
}

From source file:org.springframework.data.rest.webmvc.json.patch.JsonPatchPatchConverter.java

/**
 * Constructs a {@link Patch} object given a JsonNode.
 * /*from  ww w.j  a v a  2  s  .co  m*/
 * @param jsonNode a JsonNode containing the JSON Patch
 * @return a {@link Patch}
 */
public Patch convert(JsonNode jsonNode) {
    if (!(jsonNode instanceof ArrayNode)) {
        throw new IllegalArgumentException("JsonNode must be an instance of ArrayNode");
    }

    ArrayNode opNodes = (ArrayNode) jsonNode;
    List<PatchOperation> ops = new ArrayList<PatchOperation>(opNodes.size());
    for (Iterator<JsonNode> elements = opNodes.elements(); elements.hasNext();) {
        JsonNode opNode = elements.next();

        String opType = opNode.get("op").textValue();
        String path = opNode.get("path").textValue();

        JsonNode valueNode = opNode.get("value");
        Object value = valueFromJsonNode(path, valueNode);
        String from = opNode.has("from") ? opNode.get("from").textValue() : null;

        if (opType.equals("test")) {
            ops.add(new TestOperation(path, value));
        } else if (opType.equals("replace")) {
            ops.add(new ReplaceOperation(path, value));
        } else if (opType.equals("remove")) {
            ops.add(new RemoveOperation(path));
        } else if (opType.equals("add")) {
            ops.add(new AddOperation(path, value));
        } else if (opType.equals("copy")) {
            ops.add(new CopyOperation(path, from));
        } else if (opType.equals("move")) {
            ops.add(new MoveOperation(path, from));
        } else {
            throw new PatchException("Unrecognized operation type: " + opType);
        }
    }

    return new Patch(ops);
}

From source file:org.apache.streams.components.http.provider.SimpleHTTPGetProvider.java

protected List<ObjectNode> executeGet(URI uri) {

    Preconditions.checkNotNull(uri);//from w ww.  ja v a 2  s .c om

    List<ObjectNode> results = new ArrayList<>();

    HttpGet httpget = prepareHttpGet(uri);

    CloseableHttpResponse response = null;

    String entityString = null;
    try {
        response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        // TODO: handle retry
        if (response.getStatusLine().getStatusCode() == 200 && entity != null) {
            entityString = EntityUtils.toString(entity);
            if (!entityString.equals("{}") && !entityString.equals("[]")) {
                JsonNode jsonNode = mapper.readValue(entityString, JsonNode.class);
                if (jsonNode != null && jsonNode instanceof ObjectNode) {

                    results.add((ObjectNode) jsonNode);
                } else if (jsonNode != null && jsonNode instanceof ArrayNode) {
                    ArrayNode arrayNode = (ArrayNode) jsonNode;
                    Iterator<JsonNode> iterator = arrayNode.elements();
                    while (iterator.hasNext()) {
                        ObjectNode element = (ObjectNode) iterator.next();

                        results.add(element);
                    }
                }
            }
        }
    } catch (IOException e) {
        LOGGER.error("IO error:\n{}\n{}\n{}", uri.toString(), response, e.getMessage());
    } finally {
        try {
            response.close();
        } catch (IOException e) {
        }
    }
    return results;
}

From source file:com.redhat.lightblue.eval.ArrayContainsEvaluator.java

@Override
public boolean evaluate(QueryEvaluationContext ctx) {
    boolean ret = false;
    JsonNode node = ctx.getNode(expr.getArray());
    if (node instanceof ArrayNode) {
        ArrayNode array = (ArrayNode) node;
        List<Value> values = expr.getValues();
        ContainsOperator op = expr.getOp();
        Type t = elem.getType();//from w ww . ja v a 2 s  . c o m
        int numElementsContained = 0;
        for (Iterator<JsonNode> itr = array.elements(); itr.hasNext();) {
            JsonNode valueNode = itr.next();
            for (Value value : values) {
                Object v = value.getValue();
                if (isValueInNode(valueNode, v, t)) {
                    numElementsContained++;
                    break;
                }
            }
        }
        ret = evaluateContainsOperator(op, numElementsContained, values);
    }
    ctx.setResult(ret);
    return ret;
}

From source file:com.Anderson.example.games.tanc.GameplayFragment.java

void AssignToQuestionary(JsonNode jNode) {
    ArrayNode slaidsNode = (ArrayNode) jNode.get("questions");
    Iterator<JsonNode> questionsIterator = slaidsNode.elements();

    int temp = 0;
    while (questionsIterator.hasNext()) {
        JsonNode questions = questionsIterator.next();
        mQuestionary.mQuestions[temp] = new Question();
        mQuestionary.mQuestions[temp].setCorrectAnswer(questions.get("answer").asText());
        mQuestionary.mQuestions[temp].mAnswers.add(mQuestionary.mQuestions[temp].CorrectAnswer);
        mQuestionary.mQuestions[temp].mAnswers.add(questions.get("choice1").asText());
        mQuestionary.mQuestions[temp].mAnswers.add(questions.get("choice2").asText());
        mQuestionary.mQuestions[temp].mAnswers.add(questions.get("choice3").asText());
        Collections.shuffle(mQuestionary.mQuestions[temp].mAnswers);
        mQuestionary.mQuestions[temp].setDescription(questions.get("description").asText());
        temp++;/*from  w ww.  j  a v  a2 s  .  c o  m*/
    }
}

From source file:com.enitalk.opentok.CheckAvailabilityRunnable.java

@Override
@Scheduled(fixedDelay = 10000L)//from   w  w  w  .  j  a va 2  s .  com
public void run() {
    try {
        Query q = Query.query(Criteria.where("video").in(2, 3).andOperator(
                Criteria.where("checkDate").lt(DateTime.now().toDate()), Criteria.where("video").exists(true)));
        List<HashMap> evs = mongo.find(q, HashMap.class, "events");
        if (evs.isEmpty()) {
            return;
        }

        ArrayNode events = jackson.convertValue(evs, ArrayNode.class);
        Iterator<JsonNode> it = events.elements();
        mongo.updateMulti(q, new Update().set("video", 3), "events");

        while (it.hasNext()) {
            JsonNode en = it.next();
            rabbit.send("youtube_check", MessageBuilder.withBody(jackson.writeValueAsBytes(en)).build());
        }

    } catch (Exception e) {
        logger.info(ExceptionUtils.getFullStackTrace(e));
    }
}

From source file:nosqltools.JSONUtilities.java

public String printDiff(JsonNode resCompNode) {
    String opType = "";
    String path = "";
    String value = "";
    Iterator<JsonNode> elements = null;

    ArrayNode opNodes = (ArrayNode) resCompNode;
    List<String> res = new ArrayList<String>();
    elements = opNodes.elements();
    while (elements.hasNext()) {
        JsonNode opNode = elements.next();
        //stores the type of operation performed
        opType = opNode.get("op").textValue();
        //stores the path of the nodes visited
        path = opNode.get("path").textValue().substring(1);

        if (!opType.equals("remove")) {
            //the value is not shown the the operation is removed because of null pointer exception 
            //stores the value of the operation
            value = ": " + opNode.get("value").toString();
        } else {//from  ww  w. ja v  a2s.c  om
            value = " ";
        }

        res.add(opType + " operation -> " + path + value);
    }

    return res.toString();
}

From source file:org.apache.streams.components.http.provider.SimpleHttpProvider.java

/**
 Override this to change how entity gets converted to objects
 *//*from ww w  . j a v  a  2 s  . c om*/
protected List<ObjectNode> parse(JsonNode jsonNode) {

    List<ObjectNode> results = new ArrayList<>();

    if (jsonNode != null && jsonNode instanceof ObjectNode) {
        results.add((ObjectNode) jsonNode);
    } else if (jsonNode != null && jsonNode instanceof ArrayNode) {
        ArrayNode arrayNode = (ArrayNode) jsonNode;
        Iterator<JsonNode> iterator = arrayNode.elements();
        while (iterator.hasNext()) {
            ObjectNode element = (ObjectNode) iterator.next();

            results.add(element);
        }
    }

    return results;
}