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

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

Introduction

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

Prototype

public ArrayNode add(JsonNode paramJsonNode) 

Source Link

Usage

From source file:org.modeshape.web.jcr.rest.model.RestNodeType.java

@Override
public ObjectNode toJSON(Json json) {
    ObjectNode content = json.newObject();
    content.put("mixin", isMixin);
    content.put("abstract", isAbstract);
    content.put("queryable", isQueryable);
    content.put("hasOrderableChildNodes", hasOrderableChildNodes);

    if (!propertyTypes.isEmpty()) {
        ArrayNode propertyDefinitions = content.putArray("propertyDefinitions");
        for (RestPropertyType restPropertyType : propertyTypes) {
            propertyDefinitions.add(restPropertyType.toJSON(json));
        }// ww w.  j a va2s .c  om
    }

    if (!superTypesLinks.isEmpty()) {
        ArrayNode superTypesLinksArrayNode = content.putArray("superTypes");
        for (String superTypesLink : superTypesLinks) {
            superTypesLinksArrayNode.add(superTypesLink);
        }
    }

    if (!subTypesLinks.isEmpty()) {
        ArrayNode subTypesLinksArrayNode = content.putArray("subTypes");
        for (String subTypesLink : subTypesLinks) {
            subTypesLinksArrayNode.add(subTypesLink);
        }
    }

    ObjectNode result = json.newObject();
    result.put(name, content);
    return result;
}

From source file:org.onosproject.tvue.TopologyResource.java

/**
 * Returns a JSON array of all paths between the specified hosts.
 *
 * @param src source host id/* w w w  .ja va2  s.  c  o m*/
 * @param dst target host id
 * @return JSON array of paths
 */
@javax.ws.rs.Path("/paths/{src}/{dst}")
@GET
@Produces("application/json")
public Response paths(@PathParam("src") String src, @PathParam("dst") String dst) {
    ObjectMapper mapper = new ObjectMapper();
    PathService pathService = get(PathService.class);
    Set<Path> paths = pathService.getPaths(elementId(src), elementId(dst));

    ArrayNode pathsNode = mapper.createArrayNode();
    for (Path path : paths) {
        pathsNode.add(json(mapper, path));
    }

    // Now put the vertexes and edges into a root node and ship them off
    ObjectNode rootNode = mapper.createObjectNode();
    rootNode.set("paths", pathsNode);
    return Response.ok(rootNode.toString()).build();
}

From source file:ijfx.service.ui.ImageJInfoService.java

@AngularMethod(sync = true, description = "Return the list of all widgets", inputDescription = "No input")
public JSObject getModuleList() {
    try {/*  w w  w  . j av a2  s  . co  m*/
        ObjectMapper mapper = new ObjectMapper();
        logger.fine("Getting module list");
        SimpleModule simpleModule = new SimpleModule("ModuleSerializer");
        // simpleModule.addSerializer(ModuleItem<?>.class,new ModuleItemSerializer());
        simpleModule.addSerializer(ModuleInfo.class, new ModuleSerializer());
        simpleModule.addSerializer(ModuleItem.class, new ModuleItemSerializer());
        mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.registerModule(simpleModule);

        ArrayNode arrayNode = mapper.createArrayNode();

        moduleService.getModules().forEach(module -> {

            //System.out.println("Adding "+module.getName());
            arrayNode.add(mapper.convertValue(module, JsonNode.class));

        });

        //String json = mapper.writeValueAsString(moduleService.getModules());
        logger.fine("JSON done !");

        return JSONUtils.parseToJSON(appService.getCurrentWebEngine(), arrayNode.toString());
        //return JSONUtils.parseToJSON(appService.getCurrentWebEngine(), json);

    } catch (Exception ex) {
        logger.log(Level.SEVERE, null, ex);
    }
    logger.warning("Returning null");
    return null;
}

From source file:org.modeshape.web.jcr.rest.model.RestNode.java

private void addJcrProperties(ObjectNode node) {
    // properties
    for (RestProperty restProperty : jcrProperties) {
        if (isReservedField(restProperty.name))
            continue; // skip
        if (restProperty.isMultiValue()) {
            ArrayNode arrayNode = node.putArray(restProperty.name);
            for (String value : restProperty.getValues()) {
                arrayNode.add(value);
            }//ww  w.j a  v a  2s  .c o  m
        } else if (restProperty.getValue() != null) {
            node.put(restProperty.name, restProperty.getValue());
        }
    }
}

From source file:org.wrml.runtime.format.application.vnd.wrml.design.schema.SchemaDesignFormatter.java

public static ObjectNode createSchemaDesignObjectNode(final ObjectMapper objectMapper, final Schema schema) {

    final Context context = schema.getContext();
    final SyntaxLoader syntaxLoader = context.getSyntaxLoader();
    final SchemaLoader schemaLoader = context.getSchemaLoader();
    final ObjectNode rootNode = objectMapper.createObjectNode();

    final URI schemaUri = schema.getUri();
    final Prototype prototype = schemaLoader.getPrototype(schemaUri);

    rootNode.put(PropertyName.uri.name(), syntaxLoader.formatSyntaxValue(schemaUri));
    rootNode.put(PropertyName.title.name(), schema.getTitle());
    rootNode.put(PropertyName.description.name(), schema.getDescription());
    rootNode.put(PropertyName.version.name(), schema.getVersion());

    final String titleSlotName = getTitleSlotName(schemaUri, schemaLoader);
    if (titleSlotName != null) {
        rootNode.put(PropertyName.titleSlotName.name(), titleSlotName);
    }/*from www.j ava2s .c o  m*/

    final UniqueName uniqueName = schema.getUniqueName();
    final ObjectNode uniqueNameNode = objectMapper.createObjectNode();
    uniqueNameNode.put(PropertyName.fullName.name(), uniqueName.getFullName());
    uniqueNameNode.put(PropertyName.namespace.name(), uniqueName.getNamespace());
    uniqueNameNode.put(PropertyName.localName.name(), uniqueName.getLocalName());
    rootNode.put(PropertyName.uniqueName.name(), uniqueNameNode);

    final Set<URI> declaredBaseSchemaUris = prototype.getDeclaredBaseSchemaUris();
    if (declaredBaseSchemaUris != null && !declaredBaseSchemaUris.isEmpty()) {
        final Set<URI> addedBaseSchemaUris = new LinkedHashSet<>();
        final ArrayNode baseSchemasNode = objectMapper.createArrayNode();
        rootNode.put(PropertyName.baseSchemas.name(), baseSchemasNode);

        for (final URI baseSchemaUri : declaredBaseSchemaUris) {
            if (!addedBaseSchemaUris.contains(baseSchemaUri)) {
                final ObjectNode baseSchemaNode = buildSchemaNode(objectMapper, baseSchemaUri, schemaLoader,
                        addedBaseSchemaUris);
                baseSchemasNode.add(baseSchemaNode);
                addedBaseSchemaUris.add(baseSchemaUri);
            }
        }
    }

    final Set<String> keySlotNames = prototype.getDeclaredKeySlotNames();
    if (keySlotNames != null && !keySlotNames.isEmpty()) {
        final ArrayNode keyPropertyNamesNode = objectMapper.createArrayNode();

        for (final String keySlotName : keySlotNames) {
            keyPropertyNamesNode.add(keySlotName);
        }

        if (keyPropertyNamesNode.size() > 0) {
            rootNode.put(PropertyName.keyPropertyNames.name(), keyPropertyNamesNode);
        }
    }

    final Set<String> allKeySlotNames = prototype.getAllKeySlotNames();
    final ArrayNode allKeySlotNamesNode = objectMapper.createArrayNode();
    rootNode.put(PropertyName.allKeySlotNames.name(), allKeySlotNamesNode);

    final ObjectNode keySlotMap = objectMapper.createObjectNode();
    rootNode.put(PropertyName.keys.name(), keySlotMap);

    final String uriSlotName = PropertyName.uri.name();
    if (allKeySlotNames.contains(uriSlotName)) {
        allKeySlotNamesNode.add(uriSlotName);

        final ObjectNode slot = createSlot(objectMapper, prototype, uriSlotName);
        keySlotMap.put(uriSlotName, slot);
    }

    for (final String keySlotName : allKeySlotNames) {
        if (!Document.SLOT_NAME_URI.equals(keySlotName)) {
            allKeySlotNamesNode.add(keySlotName);

            final ObjectNode slot = createSlot(objectMapper, prototype, keySlotName);
            keySlotMap.put(keySlotName, slot);
        }
    }

    rootNode.put(PropertyName.keyCount.name(), keySlotMap.size());

    final SortedSet<String> allSlotNames = prototype.getAllSlotNames();

    if (allSlotNames != null && !allSlotNames.isEmpty()) {

        final ObjectNode slotMapNode = objectMapper.createObjectNode();
        rootNode.put(PropertyName.slots.name(), slotMapNode);

        final ArrayNode propertyNamesNode = objectMapper.createArrayNode();

        for (final String slotName : allSlotNames) {
            final ProtoSlot protoSlot = prototype.getProtoSlot(slotName);
            if (protoSlot instanceof LinkProtoSlot) {
                continue;
            }

            if (allKeySlotNames.contains(slotName)) {
                // Skip key slots (handled separately)
                continue;
            }

            if (protoSlot.getDeclaringSchemaUri().equals(schemaUri)) {
                propertyNamesNode.add(slotName);
            }

            final ObjectNode slotNode = createSlot(objectMapper, prototype, slotName);

            if (slotNode != null) {
                slotMapNode.put(slotName, slotNode);
            }

        }
        if (propertyNamesNode.size() > 0) {
            rootNode.put(PropertyName.propertyNames.name(), propertyNamesNode);
        }

        rootNode.put(PropertyName.slotCount.name(), slotMapNode.size());
    }

    final Set<String> comparablePropertyNames = prototype.getComparableSlotNames();
    if (comparablePropertyNames != null && !comparablePropertyNames.isEmpty()) {
        final ArrayNode comparablePropertyNamesNode = objectMapper.createArrayNode();

        for (final String comparablePropertyName : comparablePropertyNames) {
            comparablePropertyNamesNode.add(comparablePropertyName);
        }

        if (comparablePropertyNamesNode.size() > 0) {
            rootNode.put(PropertyName.comparablePropertyNames.name(), comparablePropertyNamesNode);
        }
    }

    final Collection<LinkProtoSlot> linkProtoSlots = prototype.getLinkProtoSlots().values();
    if (linkProtoSlots != null && !linkProtoSlots.isEmpty()) {
        final ArrayNode linkNamesNode = objectMapper.createArrayNode();
        final ObjectNode linksMapNode = objectMapper.createObjectNode();
        rootNode.put(PropertyName.links.name(), linksMapNode);

        for (final LinkProtoSlot linkProtoSlot : linkProtoSlots) {

            if (linkProtoSlot.getDeclaringSchemaUri().equals(schemaUri)) {
                linkNamesNode.add(linkProtoSlot.getName());
            }

            final ObjectNode linkNode = objectMapper.createObjectNode();

            String linkTitle = linkProtoSlot.getTitle();
            if (linkTitle == null) {
                linkTitle = linkProtoSlot.getName();
            }

            linkNode.put(PropertyName.name.name(), linkProtoSlot.getName());
            linkNode.put(PropertyName.title.name(), linkTitle);

            final Method method = linkProtoSlot.getMethod();
            final URI linkRelationUri = linkProtoSlot.getLinkRelationUri();
            final URI declaringSchemaUri = linkProtoSlot.getDeclaringSchemaUri();

            linkNode.put(PropertyName.rel.name(), syntaxLoader.formatSyntaxValue(linkRelationUri));

            final Keys linkRelationKeys = context.getApiLoader().buildDocumentKeys(linkRelationUri,
                    schemaLoader.getLinkRelationSchemaUri());
            final LinkRelation linkRelation = context.getModel(linkRelationKeys,
                    schemaLoader.getLinkRelationDimensions());

            linkNode.put(PropertyName.relationTitle.name(), linkRelation.getTitle());
            linkNode.put(PropertyName.description.name(), linkProtoSlot.getDescription());
            linkNode.put(PropertyName.method.name(), method.getProtocolGivenName());
            linkNode.put(PropertyName.declaringSchemaUri.name(),
                    syntaxLoader.formatSyntaxValue(declaringSchemaUri));

            URI requestSchemaUri = linkProtoSlot.getRequestSchemaUri();
            if (schemaLoader.getDocumentSchemaUri().equals(requestSchemaUri)) {
                if (SystemLinkRelation.self.getUri().equals(linkRelationUri)
                        || SystemLinkRelation.save.getUri().equals(linkRelationUri)) {
                    requestSchemaUri = schemaUri;
                }
            }

            if (requestSchemaUri == null && method == Method.Save) {
                requestSchemaUri = schemaUri;
            }

            if (requestSchemaUri != null) {
                linkNode.put(PropertyName.requestSchemaUri.name(),
                        syntaxLoader.formatSyntaxValue(requestSchemaUri));

                final Schema requestSchema = schemaLoader.load(requestSchemaUri);
                if (requestSchema != null) {
                    linkNode.put(PropertyName.requestSchemaTitle.name(), requestSchema.getTitle());
                }
            }

            URI responseSchemaUri = linkProtoSlot.getResponseSchemaUri();
            if (schemaLoader.getDocumentSchemaUri().equals(responseSchemaUri)) {
                if (SystemLinkRelation.self.getUri().equals(linkRelationUri)
                        || SystemLinkRelation.save.getUri().equals(linkRelationUri)) {
                    responseSchemaUri = schemaUri;
                }
            }

            if (responseSchemaUri != null) {
                linkNode.put(PropertyName.responseSchemaUri.name(),
                        syntaxLoader.formatSyntaxValue(responseSchemaUri));

                final Schema responseSchema = schemaLoader.load(responseSchemaUri);
                if (responseSchema != null) {
                    linkNode.put(PropertyName.responseSchemaTitle.name(), responseSchema.getTitle());
                }
            }

            linksMapNode.put(linkTitle, linkNode);

        }

        if (linkNamesNode.size() > 0) {
            rootNode.put(PropertyName.linkNames.name(), linkNamesNode);
        }

        rootNode.put(PropertyName.linkCount.name(), linksMapNode.size());

    }

    return rootNode;
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.TestJsonNodeWritableUtils.java

@SuppressWarnings("deprecation")
@Test//  w ww .  j  a v  a 2 s .  co  m
public void test_mapWritableWrapper() {
    final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty());

    final MapWritable m1 = new MapWritable();

    m1.put(new Text("test1"), new BooleanWritable(true));

    final MapWritable m2 = new MapWritable();
    m2.put(new Text("nested"), m1);
    m2.put(new Text("test2"), new Text("test2"));

    final ArrayWritable a1 = new ArrayWritable(IntWritable.class);
    a1.set(new Writable[] { new IntWritable(4), new IntWritable(5) });

    final ArrayWritable a2 = new ArrayWritable(MapWritable.class);
    a2.set(new Writable[] { m1, m1 });

    m2.put(new Text("array"), a2);
    m1.put(new Text("array"), a1);

    final JsonNode j2 = JsonNodeWritableUtils.from(m2);

    assertEquals(3, j2.size());

    // Check j's contents
    assertEquals(Stream.of("nested", "test2", "array").sorted().collect(Collectors.toList()),
            Optionals.streamOf(j2.fieldNames(), false).sorted().collect(Collectors.toList()));
    assertEquals("test2", j2.get("test2").asText());

    final JsonNode j1 = j2.get("nested");
    assertEquals(2, j1.size());
    final JsonNode j1b = JsonNodeWritableUtils.from(m1);
    assertTrue("{\"test1\":true,\"array\":[4,5]}".equals(j1b.toString())
            || "{\"array\":[4,5],\"test1\":true}".equals(j1b.toString())); //(tests entrySet)
    final ArrayNode an = mapper.createArrayNode();
    an.add(mapper.convertValue(4, JsonNode.class));
    an.add(mapper.convertValue(5, JsonNode.class));
    assertEquals(Arrays.asList(mapper.convertValue(true, JsonNode.class), an),
            Optionals.streamOf(((ObjectNode) j1).elements(), false).collect(Collectors.toList()));

    // OK, now test adding:

    assertEquals(2, j1.size());

    final ObjectNode o1 = (ObjectNode) j1;
    o1.put("added", "added_this");

    final ObjectNodeWrapper o1c = (ObjectNodeWrapper) o1;
    assertFalse(o1c.containsKey("not_present"));
    assertTrue(o1c.containsKey("added"));
    assertTrue(o1c.containsKey("test1"));

    assertEquals(Stream.of("test1", "array", "added").sorted().collect(Collectors.toList()),
            Optionals.streamOf(j1.fieldNames(), false).sorted().collect(Collectors.toList()));
    assertEquals(
            Arrays.asList(mapper.convertValue(true, JsonNode.class), an,
                    mapper.convertValue("added_this", JsonNode.class)),
            Optionals.streamOf(((ObjectNode) j1).elements(), false).collect(Collectors.toList()));
    assertTrue(j1.toString().contains("added_this"));
    assertTrue(j1.toString().contains("4,5"));

    assertEquals(mapper.convertValue("added_this", JsonNode.class), j1.get("added"));

    assertEquals(3, j1.size());

    // OK now test removing:

    assertEquals(null, o1.remove("not_present"));
    assertEquals(mapper.convertValue(true, JsonNode.class), o1.remove("test1"));
    assertEquals(2, o1.size());
    ObjectNode o1b = o1.remove(Arrays.asList("added", "array"));
    assertEquals(0, o1.size());
    assertEquals(0, o1b.size());

    o1.putAll(JsonNodeWritableUtils.from(m1)); // will be minus one object
    assertEquals(2, o1.size());
    assertTrue(o1c.containsValue(mapper.convertValue(true, JsonNode.class)));
    assertFalse(o1c.containsValue("banana"));

    final ObjectNodeWrapper o2 = (ObjectNodeWrapper) JsonNodeWritableUtils.from(m2);
    assertFalse(o2.isEmpty());
    assertTrue(o2.containsKey("array"));
    assertFalse(o2.containsValue("array"));
    assertTrue(o2.containsValue(mapper.convertValue("test2", JsonNode.class)));
    assertEquals(TextNode.class, o2.remove("test2").getClass());
    assertEquals(2, o2.size());
    o2.removeAll();
    assertEquals(0, o2.size());
}

From source file:automenta.knowtention.channel.LineFileChannel.java

private synchronized void update(List<String> lines) {

    channel.tx(new Runnable() {
        @Override// w  w w . j  a v a  2s .  c  om
        public void run() {

            ArrayNode l = Core.newJson.arrayNode();

            for (int i = 0; i < lines.size(); i++)
                l.add(lines.get(i));

            ObjectNode o = Core.newJson.objectNode();
            o.put("id", id);
            //o.put("content", (file.getAbsolutePath() + ":" + getClass().getSimpleName()) );
            o.put("list", l);
            channel.addVertex(o);

        }
    });

}

From source file:org.apache.streams.neo4j.http.Neo4jHttpPersistWriter.java

@Override
protected ObjectNode preparePayload(StreamsDatum entry) throws Exception {

    List<Pair<String, Map<String, Object>>> statements = Neo4jPersistUtil.prepareStatements(entry);

    ObjectNode requestNode = mapper.createObjectNode();
    ArrayNode statementsArray = mapper.createArrayNode();

    for (Pair<String, Map<String, Object>> statement : statements) {
        statementsArray.add(httpGraphHelper.writeData(statement));
    }/*w ww . j a v a  2s  . c o m*/

    requestNode.put("statements", statementsArray);
    return requestNode;

}

From source file:com.almende.eve.agent.AgentConfig.java

/**
 * Gets the transport config./*  w w w .j a va 2  s .c  o  m*/
 * 
 * @return the transport config
 */
public ArrayNode getTransports() {
    final JsonNode res = this.get("transports");
    if (res != null && !res.isArray()) {
        LOG.warning("Transports have to be an array!");
        ArrayNode other = JOM.createArrayNode();
        other.add(res);
        return other;
    }
    return (ArrayNode) res;
}

From source file:com.github.fge.jsonschema.core.keyword.syntax.SyntaxProcessorTest.java

@Test
public void unknownKeywordsAreReportedAsWarnings() throws ProcessingException {
    final ObjectNode node = FACTORY.objectNode();
    node.put("foo", "");
    node.put("bar", "");

    final SchemaTree tree = new CanonicalSchemaTree(SchemaKey.anonymousKey(), node);
    final ValueHolder<SchemaTree> holder = ValueHolder.hold("schema", tree);

    final ArrayNode ignored = FACTORY.arrayNode();
    // They appear in alphabetical order in the report!
    ignored.add("bar");
    ignored.add("foo");
    final Iterable<String> iterable = Iterables.transform(ignored, new Function<JsonNode, String>() {
        @Override/*from www .  j  a  v  a2  s. com*/
        public String apply(final JsonNode input) {
            return input.textValue();
        }
    });

    final ArgumentCaptor<ProcessingMessage> captor = ArgumentCaptor.forClass(ProcessingMessage.class);

    processor.process(report, holder);
    verify(report).log(same(LogLevel.WARNING), captor.capture());

    final ProcessingMessage message = captor.getValue();

    assertMessage(message).hasField("ignored", ignored)
            .hasMessage(BUNDLE.printf("core.unknownKeywords", iterable));
}