Example usage for com.fasterxml.jackson.databind.node ObjectNode ObjectNode

List of usage examples for com.fasterxml.jackson.databind.node ObjectNode ObjectNode

Introduction

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

Prototype

public ObjectNode(JsonNodeFactory paramJsonNodeFactory) 

Source Link

Usage

From source file:com.turn.shapeshifter.NamedSchemaParserTest.java

@Test
public void testParseWithEmptyObject() throws Exception {
    NamedSchema schema = NamedSchema.of(Union.getDescriptor(), "Union");
    SchemaRegistry registry = new SchemaRegistry();
    registry.register(schema);//from  ww  w  .j av a 2  s .  co  m
    Union union = Union.newBuilder()
            .mergeFrom(new NamedSchemaParser(schema).parse(new ObjectNode(JsonNodeFactory.instance), registry))
            .build();
    Assert.assertEquals(Union.getDefaultInstance(), union);
}

From source file:net.pterodactylus.sone.web.ajax.GetStatusAjaxPage.java

/**
 * {@inheritDoc}/*from   ww  w.j a  v  a2s . c o m*/
 */
@Override
protected JsonReturnObject createJsonObject(FreenetRequest request) {
    final Sone currentSone = getCurrentSone(request.getToadletContext(), false);
    /* load Sones. always return the status of the current Sone. */
    Set<Sone> sones = new HashSet<Sone>(
            Collections.singleton(getCurrentSone(request.getToadletContext(), false)));
    String loadSoneIds = request.getHttpRequest().getParam("soneIds");
    if (loadSoneIds.length() > 0) {
        String[] soneIds = loadSoneIds.split(",");
        for (String soneId : soneIds) {
            /* just add it, we skip null further down. */
            sones.add(webInterface.getCore().getSone(soneId).orNull());
        }
    }
    ArrayNode jsonSones = new ArrayNode(instance);
    for (Sone sone : sones) {
        if (sone == null) {
            continue;
        }
        jsonSones.add(createJsonSone(sone));
    }
    /* load notifications. */
    List<Notification> notifications = ListNotificationFilters
            .filterNotifications(webInterface.getNotifications().getNotifications(), currentSone);
    Collections.sort(notifications, Notification.CREATED_TIME_SORTER);
    /* load new posts. */
    Collection<Post> newPosts = webInterface.getNewPosts();
    if (currentSone != null) {
        newPosts = Collections2.filter(newPosts, new Predicate<Post>() {

            @Override
            public boolean apply(Post post) {
                return ListNotificationFilters.isPostVisible(currentSone, post);
            }

        });
    }
    ArrayNode jsonPosts = new ArrayNode(instance);
    for (Post post : newPosts) {
        ObjectNode jsonPost = new ObjectNode(instance);
        jsonPost.put("id", post.getId());
        jsonPost.put("sone", post.getSone().getId());
        jsonPost.put("recipient", post.getRecipientId().orNull());
        jsonPost.put("time", post.getTime());
        jsonPosts.add(jsonPost);
    }
    /* load new replies. */
    Collection<PostReply> newReplies = webInterface.getNewReplies();
    if (currentSone != null) {
        newReplies = Collections2.filter(newReplies, new Predicate<PostReply>() {

            @Override
            public boolean apply(PostReply reply) {
                return ListNotificationFilters.isReplyVisible(currentSone, reply);
            }

        });
    }
    /* remove replies to unknown posts. */
    newReplies = Collections2.filter(newReplies, PostReply.HAS_POST_FILTER);
    ArrayNode jsonReplies = new ArrayNode(instance);
    for (PostReply reply : newReplies) {
        ObjectNode jsonReply = new ObjectNode(instance);
        jsonReply.put("id", reply.getId());
        jsonReply.put("sone", reply.getSone().getId());
        jsonReply.put("post", reply.getPostId());
        jsonReply.put("postSone", reply.getPost().get().getSone().getId());
        jsonReplies.add(jsonReply);
    }
    return createSuccessJsonObject().put("loggedIn", currentSone != null)
            .put("options", createJsonOptions(currentSone)).put("sones", jsonSones)
            .put("notificationHash", notifications.hashCode()).put("newPosts", jsonPosts)
            .put("newReplies", jsonReplies);
}

From source file:com.amazonaws.service.apigateway.importer.impl.SchemaTransformer.java

private void replaceRefs(JsonNode root, HashMap<String, String> schemaMap) {

    ObjectNode definitionsNode = new ObjectNode(JsonNodeFactory.instance);

    for (Map.Entry<String, String> entry : schemaMap.entrySet()) {
        JsonNode schemaNode = deserialize(entry.getValue());
        definitionsNode.set(entry.getKey(), schemaNode);
    }/*  w  ww  . ja  va  2 s  . c  om*/

    ((ObjectNode) root).set("definitions", definitionsNode);
}

From source file:com.mapr.synth.samplers.VinSampler.java

@Override
public JsonNode sample() {
    ObjectNode r = new ObjectNode(nodeFactory);

    String manufacturer = randomCode(legalCodes);
    String restraint = randomCode(restraintCodes);

    int year = randomCode(legalYears);
    String yearCode = computeYearCode(year);
    int sequence = sequenceCounter.incrementAndGet();

    String front;//from   ww w . j  a  v a2 s .co m
    String plant;

    String make = makes.get(manufacturer);

    switch (make) {
    case "Ford": {
        String model = randomCode(fordModelCodes);
        String engine = randomCode(fordEngineCodes);
        plant = randomCode(fordPlantCodes);
        front = pad(manufacturer, 3, "AAAAAAAAAAAAAAAAAA") + restraint + pad(model, 3, "0000000000000000")
                + engine;
        if (verbose) {
            r.set("model", new TextNode(fordModels.get(model)));
            r.set("engine", new TextNode(fordEngines.get(engine)));
        }
        break;
    }
    case "BMW":
    case "BMW M": {
        String model = randomCode(bmwModelCodes);
        plant = randomCode(bmwPlantCodes);
        front = pad(manufacturer, 3, "AAAAAAAAAAAAAAAAAA") + restraint + model;
        if (verbose) {
            r.set("model", new TextNode(bmwModels.get(model)));
            r.set("plant", new TextNode(bmwPlants.get(plant)));
        }
        break;
    }
    default: {
        String model = gibberish(4);
        plant = gibberish(1);
        front = pad(manufacturer, 3, "AAAAAAAAAAAAAAAAAA") + restraint + model;
        break;
    }
    }
    String check = "0";

    String rawVin = front + check + yearCode + plant + String.format("%06d", sequence);
    String vin = addCheckDigit(rawVin);

    if (verbose) {
        r.set("VIN", new TextNode(vin));
        r.set("manufacturer", new TextNode(makes.get(manufacturer)));
        r.set("year", new IntNode(year));
    } else {
        return new TextNode(vin);
    }
    return r;
}

From source file:com.turn.shapeshifter.NamedSchemaSerializer.java

/**
 * Serializes a repeated mapped field./*from  w ww. j  a v  a  2s .  co  m*/
 *
 * @param message the message being serialized
 * @param registry a registry of schemas, for enclosed object types
 * @param field the descriptor of the repeated field to serialize
 * @param count the count of repeated items in the field
 * @return the JSON representation of the serialized mapped field
 * @throws SerializationException
 * @see {@link NamedSchema#mapRepeatedField(String, String)}
 */
private ObjectNode serializeMappedField(Message message, ReadableSchemaRegistry registry, FieldDescriptor field,
        int count) throws SerializationException {
    ObjectNode objectNode = new ObjectNode(JsonNodeFactory.instance);
    for (int i = 0; i < count; i++) {
        Message value = (Message) message.getRepeatedField(field, i);
        String key = String.valueOf(value.getField(schema.getMappings().get(field.getName())));
        JsonNode valueNode = serializeValue(value, field, registry);
        if (!valueNode.isNull() && key != null) {
            objectNode.put(key, valueNode);
        }
    }
    return objectNode;
}

From source file:com.msopentech.odatajclient.testservice.utils.Commons.java

public static InputStream getLinksAsJSON(final String entitySetName,
        final Map.Entry<String, Collection<String>> link) throws IOException {
    final ObjectNode links = new ObjectNode(JsonNodeFactory.instance);
    links.put(JSON_ODATAMETADATA_NAME, ODATA_METADATA_PREFIX + entitySetName + "/$links/" + link.getKey());

    final ArrayNode uris = new ArrayNode(JsonNodeFactory.instance);

    for (String uri : link.getValue()) {
        final String absoluteURI;
        if (URI.create(uri).isAbsolute()) {
            absoluteURI = uri;//w  ww  .ja va2  s. c o m
        } else {
            absoluteURI = DEFAULT_SERVICE_URL + uri;
        }
        uris.add(new ObjectNode(JsonNodeFactory.instance).put("url", absoluteURI));
    }

    if (uris.size() == 1) {
        links.setAll((ObjectNode) uris.get(0));
    } else {
        links.set("value", uris);
    }

    return IOUtils.toInputStream(links.toString());
}

From source file:com.mapr.synth.samplers.SsnSampler.java

@Override
public JsonNode sample() {
    while (true) {
        int i = rand.nextInt(codes.size());
        List<String> fields = values.get(codes.get(i));

        if (keepTypes.contains(fields.get(names.indexOf("type")))) {
            if (verbose) {
                ObjectNode rx = new ObjectNode(nodeFactory);
                Iterator<String> nx = names.iterator();
                for (String field : fields) {
                    Preconditions.checkState(nx.hasNext());
                    String fieldName = nx.next();
                    if (keepFields.contains(fieldName)) {
                        rx.set(fieldName, new TextNode(field));
                    }//w w w. j av  a 2 s .com
                }
                Preconditions.checkState(!nx.hasNext());
                if (keepFields.contains("ssn")) {
                    rx.set("ssn", new TextNode(String.format("%s-%02d-%04d", codes.get(i), rand.nextInt(99) + 1,
                            rand.nextInt(9999) + 1)));
                }
                return rx;
            } else {
                return new TextNode(String.format("%s-%02d-%04d", codes.get(i), rand.nextInt(99) + 1,
                        rand.nextInt(9999) + 1));
            }
        }
    }
}

From source file:com.microsoft.rest.serializer.FlatteningSerializer.java

@Override
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
    if (value == null) {
        jgen.writeNull();//  w  ww. j  a v a 2s .  co  m
        return;
    }

    // BFS for all collapsed properties
    ObjectNode root = mapper.valueToTree(value);
    ObjectNode res = root.deepCopy();
    Queue<ObjectNode> source = new LinkedBlockingQueue<ObjectNode>();
    Queue<ObjectNode> target = new LinkedBlockingQueue<ObjectNode>();
    source.add(root);
    target.add(res);
    while (!source.isEmpty()) {
        ObjectNode current = source.poll();
        ObjectNode resCurrent = target.poll();
        Iterator<Map.Entry<String, JsonNode>> fields = current.fields();
        while (fields.hasNext()) {
            Map.Entry<String, JsonNode> field = fields.next();
            ObjectNode node = resCurrent;
            String key = field.getKey();
            JsonNode outNode = resCurrent.get(key);
            if (field.getKey().matches(".+[^\\\\]\\..+")) {
                String[] values = field.getKey().split("((?<!\\\\))\\.");
                for (int i = 0; i < values.length; ++i) {
                    values[i] = values[i].replace("\\.", ".");
                    if (i == values.length - 1) {
                        break;
                    }
                    String val = values[i];
                    if (node.has(val)) {
                        node = (ObjectNode) node.get(val);
                    } else {
                        ObjectNode child = new ObjectNode(JsonNodeFactory.instance);
                        node.put(val, child);
                        node = child;
                    }
                }
                node.set(values[values.length - 1], resCurrent.get(field.getKey()));
                resCurrent.remove(field.getKey());
                outNode = node.get(values[values.length - 1]);
            }
            if (field.getValue() instanceof ObjectNode) {
                source.add((ObjectNode) field.getValue());
                target.add((ObjectNode) outNode);
            } else if (field.getValue() instanceof ArrayNode && (field.getValue()).size() > 0
                    && (field.getValue()).get(0) instanceof ObjectNode) {
                Iterator<JsonNode> sourceIt = field.getValue().elements();
                Iterator<JsonNode> targetIt = outNode.elements();
                while (sourceIt.hasNext()) {
                    source.add((ObjectNode) sourceIt.next());
                    target.add((ObjectNode) targetIt.next());
                }
            }
        }
    }
    jgen.writeTree(res);
}

From source file:es.bsc.amon.controller.AppsDBMapper.java

/**
 *
 * @param start/*from w w w  .  j  a v a2  s  . co  m*/
 * @param end
 * @param showInstances if true, shows instances information instead of nodes information
 * @return
 */
public ObjectNode getAllApps(long start, long end, boolean showInstances) {
    DBObject query = (DBObject) JSON.parse("{ '$or' : [" + "{ '$and' : [ { timestamp : { '$gte' : " + start
            + " }}, { timestamp : {'$lte' : " + end + "}} ] }," + "{ '$and' : [ { endtime : { '$gte' : " + start
            + " }}, { endtime : {'$lte' : " + end + "}} ] }" + "]}");
    //DBObject orderby = new BasicDBObject("timestamp":-1);
    BasicDBList ret = DBManager.instance.find(EventsDBMapper.COLL_NAME, query);

    Map<String, Set<String>> appsInfo = new HashMap<>();

    Iterator<Object> iter = ret.iterator();
    while (iter.hasNext()) {
        DBObject event = (DBObject) iter.next();
        try {
            String appName = event.get(EventsDBMapper.APPID).toString();
            Object node = event.get(showInstances ? EventsDBMapper.INSTANCEID : EventsDBMapper.NODEID);
            String nodeName = node == null ? "" : node.toString();
            Set<String> appSet = appsInfo.get(appName);
            if (appSet == null) {
                appSet = new TreeSet<String>();
                appsInfo.put(appName, appSet);
            }
            appSet.add(nodeName);
        } catch (NullPointerException ex) {
            Logger.warn("This element did not parsed as an application: " + event.toString()
                    + ". Removing it from DB...");
            try {
                EventsDBMapper.getInstance().remove(event);
            } catch (Exception e) {
                Logger.error("Cannot remove it from database");
            }
        }
    }

    ObjectNode all = new ObjectNode(JsonNodeFactory.instance);
    for (Map.Entry<String, Set<String>> entry : appsInfo.entrySet()) {
        ArrayNode nodes = new ArrayNode(JsonNodeFactory.instance);
        for (String n : entry.getValue()) {
            nodes.add(n);
        }
        all.put(entry.getKey(), nodes);
    }
    return all;
}

From source file:net.pterodactylus.sone.web.ajax.GetNotificationsAjaxPage.java

/**
 * Creates a JSON object that contains all options that are currently in
 * effect for the given Sone (or overall, if the given Sone is {@code null}
 * ).//from  w  w w . j a va  2s .c o  m
 *
 * @param currentSone
 *            The current Sone (may be {@code null})
 * @return The current options
 */
private static JsonNode createJsonOptions(Sone currentSone) {
    ObjectNode options = new ObjectNode(instance);
    if (currentSone != null) {
        options.put("ShowNotification/NewSones",
                currentSone.getOptions().getBooleanOption("ShowNotification/NewSones").get());
        options.put("ShowNotification/NewPosts",
                currentSone.getOptions().getBooleanOption("ShowNotification/NewPosts").get());
        options.put("ShowNotification/NewReplies",
                currentSone.getOptions().getBooleanOption("ShowNotification/NewReplies").get());
    }
    return options;
}