Example usage for com.fasterxml.jackson.databind ObjectMapper createObjectNode

List of usage examples for com.fasterxml.jackson.databind ObjectMapper createObjectNode

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper createObjectNode.

Prototype

@Override
public ObjectNode createObjectNode() 

Source Link

Document

Note: return type is co-variant, as basic ObjectCodec abstraction can not refer to concrete node types (as it's part of core package, whereas impls are part of mapper package)

Usage

From source file:com.gsma.mobileconnect.cache.DiscoveryCacheValueTest.java

@Test
public void create_withoutTtl_shouldThrowException() {
    // GIVEN/* ww  w .j  a  v a 2  s  .  c o  m*/
    ObjectMapper objectMapper = new ObjectMapper();

    // THEN
    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage(containsString("ttl"));

    new DiscoveryCacheValue(null, objectMapper.createObjectNode());
}

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

private ObjectNode json(ObjectMapper mapper, ElementId id, int group, String label, boolean isOnline) {
    return mapper.createObjectNode().put("name", id.toString()).put("label", label).put("group", group)
            .put("online", isOnline);
}

From source file:net.sf.taverna.t2.activities.wsdl.xmlsplitter.XMLInputSplitterActivityFactory.java

@Override
public JsonNode getActivityConfigurationSchema() {
    ObjectMapper objectMapper = new ObjectMapper();
    try {//from   w w w . j a  v  a2 s .co m
        return objectMapper.readTree(getClass().getResource("/xml-splitter.schema.json"));
    } catch (IOException e) {
        return objectMapper.createObjectNode();
    }
}

From source file:gov.lanl.adore.djatoka.openurl.OpenURLJP2KMetadata.java

/**
 * Returns the OpenURLResponse of a JSON object defining the core image properties. Having obtained a result, this
 * method is then responsible for transforming it into an OpenURLResponse that acts as a proxy for
 * HttpServletResponse.//from w w  w  .  j  a va  2s . com
 */
@Override
public OpenURLResponse resolve(final ServiceType serviceType, final ContextObject contextObject,
        final OpenURLRequest openURLRequest, final OpenURLRequestProcessor processor) {

    String responseFormat = RESPONSE_TYPE;
    int status = HttpServletResponse.SC_OK;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {
        final ObjectMapper mapper = new ObjectMapper();
        final ObjectNode rootNode = mapper.createObjectNode();
        final IExtract jp2 = new KduExtractExe();

        ImageRecord r = ReferentManager.getImageRecord(contextObject.getReferent());
        r = jp2.getMetadata(r);

        rootNode.put("identifier", r.getIdentifier());
        rootNode.put("imagefile", r.getImageFile());
        rootNode.put("width", r.getWidth());
        rootNode.put("height", r.getHeight());
        rootNode.put("dwtLevels", r.getDWTLevels());
        rootNode.put("levels", r.getLevels());
        rootNode.put("compositingLayerCount", r.getCompositingLayerCount());

        mapper.writeValue(baos, rootNode);
    } catch (final DjatokaException e) {
        responseFormat = "text/plain";
        status = HttpServletResponse.SC_NOT_FOUND;
    } catch (final Exception e) {
        baos = new ByteArrayOutputStream();

        try {
            if (e.getMessage() != null) {
                baos.write(e.getMessage().getBytes("UTF-8"));
            } else {
                LOGGER.error(e.getMessage(), e);
                baos.write("Internal Server Error: ".getBytes());
            }
        } catch (final UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (final IOException e2) {
            e2.printStackTrace();
        }

        responseFormat = "text/plain";
        status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    final HashMap<String, String> header_map = new HashMap<String, String>();
    header_map.put("Content-Length", baos.size() + "");
    header_map.put("Date", HttpDate.getHttpDate());
    return new OpenURLResponse(status, responseFormat, baos.toByteArray(), header_map);
}

From source file:com.rusticisoftware.tincan.ContextActivities.java

@Override
public ObjectNode toJSONNode(TCAPIVersion version) {
    ObjectMapper mapper = Mapper.getInstance();
    ObjectNode node = mapper.createObjectNode();

    if (this.parent != null && this.parent.size() > 0) {
        if (version.equals(TCAPIVersion.V095) && this.getParent().size() > 1) {
            throw new IncompatibleTCAPIVersion("Version " + TCAPIVersion.V095.toString()
                    + " doesn't support lists of activities (parent)");
        }/*ww w .j a v a2s .  c om*/

        if (version.equals(TCAPIVersion.V095)) {
            node.put("parent", this.getParent().get(0).toJSONNode(version));
        } else {
            ArrayNode parent = mapper.createArrayNode();
            node.put("parent", parent);

            for (Activity element : this.getParent()) {
                parent.add(element.toJSONNode(version));
            }
        }
    }
    if (this.grouping != null && this.grouping.size() > 0) {
        if (version.equals(TCAPIVersion.V095) && this.getGrouping().size() > 1) {
            throw new IncompatibleTCAPIVersion("Version " + TCAPIVersion.V095.toString()
                    + " doesn't support lists of activities (grouping)");
        }

        if (version.equals(TCAPIVersion.V095)) {
            node.put("grouping", this.getGrouping().get(0).toJSONNode(version));
        } else {
            ArrayNode grouping = mapper.createArrayNode();
            node.put("grouping", grouping);

            for (Activity element : this.getGrouping()) {
                grouping.add(element.toJSONNode(version));
            }
        }
    }
    if (this.other != null && this.other.size() > 0) {
        if (version.equals(TCAPIVersion.V095) && this.getOther().size() > 1) {
            throw new IncompatibleTCAPIVersion(
                    "Version " + TCAPIVersion.V095.toString() + " doesn't support lists of activities (other)");
        }

        if (version.equals(TCAPIVersion.V095)) {
            node.put("other", this.getGrouping().get(0).toJSONNode(version));
        } else {
            ArrayNode other = mapper.createArrayNode();
            node.put("other", other);

            for (Activity element : this.getOther()) {
                other.add(element.toJSONNode(version));
            }
        }
    }
    if (this.category != null && this.category.size() > 0) {
        if (version.ordinal() <= TCAPIVersion.V100.ordinal()) {
            ArrayNode category = mapper.createArrayNode();
            node.put("category", category);

            for (Activity element : this.getCategory()) {
                category.add(element.toJSONNode(version));
            }
        } else {
            throw new IncompatibleTCAPIVersion(
                    "Version " + version.toString() + " doesn't support the category context activity");
        }
    }

    return node;
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.services.ElasticsearchIndexService.java

/** Check if a new mapping based on a schema is equivalent to a mapping previously stored (from a schema) 
 * @param stored_mapping//from   ww w . j a  va  2s .c  o  m
 * @param new_mapping
 * @param mapper
 * @return
 * @throws JsonProcessingException
 * @throws IOException
 */
protected static boolean mappingsAreEquivalent(final IndexTemplateMetaData stored_mapping,
        final JsonNode new_mapping, final ObjectMapper mapper) throws JsonProcessingException, IOException {

    final ObjectNode stored_json_mappings = StreamSupport.stream(stored_mapping.mappings().spliterator(), false)
            .reduce(mapper.createObjectNode(), Lambdas.wrap_u(
                    (acc, kv) -> (ObjectNode) acc.setAll((ObjectNode) mapper.readTree(kv.value.string()))),
                    (acc1, acc2) -> acc1); // (can't occur)

    final JsonNode new_json_mappings = Optional.ofNullable(new_mapping.get("mappings"))
            .orElse(mapper.createObjectNode());

    final JsonNode stored_json_settings = mapper.convertValue(Optional.ofNullable(stored_mapping.settings())
            .orElse(ImmutableSettings.settingsBuilder().build()).getAsMap(), JsonNode.class);

    final JsonNode new_json_settings = Optional.ofNullable(new_mapping.get("settings"))
            .orElse(mapper.createObjectNode());

    final ObjectNode stored_json_aliases = StreamSupport
            .stream(Optional.ofNullable(
                    stored_mapping.aliases()).orElse(
                            ImmutableOpenMap.of())
                    .spliterator(), false)
            .reduce(mapper.createObjectNode(), Lambdas.wrap_u((acc, kv) -> (ObjectNode) acc.set(kv.key,
                    kv.value.filteringRequired() ? mapper.createObjectNode().set("filter",
                            mapper.readTree(kv.value.filter().string())) : mapper.createObjectNode())),
                    (acc1, acc2) -> acc1); // (can't occur)

    final JsonNode new_json_aliases = Optional.ofNullable(new_mapping.get("aliases"))
            .orElse(mapper.createObjectNode());

    return stored_json_mappings.equals(new_json_mappings) && stored_json_settings.equals(new_json_settings)
            && stored_json_aliases.equals(new_json_aliases);
}

From source file:org.commonjava.indy.metrics.zabbix.api.IndyZabbixApi.java

/**
 *
 * @param name/*from   w  w w . j  a v  a 2  s  . c  o  m*/
 * @return hostid
 */
public String getHost(String name) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode jsonNode = mapper.createObjectNode();
    ArrayNode arrayNode = mapper.createArrayNode();
    arrayNode.add(name);
    jsonNode.put("host", arrayNode);
    Request request = RequestBuilder.newBuilder().method("host.get").paramEntry("filter", jsonNode).build();
    JsonNode response = call(request);
    if (response.get("result").isNull() || response.get("result").get(0) == null) {
        return null;
    }
    return response.get("result").get(0).get("hostid").asText();
}

From source file:org.commonjava.indy.metrics.zabbix.api.IndyZabbixApi.java

/**
 *
 * @param name/*from w w w .  java 2  s  . c  o m*/
 * @return groupId
 */
public String getHostgroup(String name) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode jsonNode = mapper.createObjectNode();
    ArrayNode arrayNode = mapper.createArrayNode();
    arrayNode.add(name);
    jsonNode.put("name", arrayNode);
    Request request = RequestBuilder.newBuilder().method("hostgroup.get").paramEntry("filter", jsonNode)
            .build();
    JsonNode response = call(request);
    if (response.get("result").isNull() || response.get("result").get(0) == null) {
        return null;
    }
    return response.get("result").get(0).get("groupid").asText();
}

From source file:cn.org.once.cstack.controller.ScriptingController.java

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public @ResponseBody JsonNode scriptingLoad(@PathVariable @RequestBody Integer id)
        throws ServiceException, JsonProcessingException {
    logger.info("Load");
    User user = authentificationUtils.getAuthentificatedUser();
    try {//from   ww  w . j  a  v  a  2s. c  o m
        Script script = scriptingService.load(id);
        User user1 = userService.findById(script.getCreationUserId());
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.createObjectNode();
        ((ObjectNode) rootNode).put("id", script.getId());
        ((ObjectNode) rootNode).put("title", script.getTitle());
        ((ObjectNode) rootNode).put("content", script.getContent());
        ((ObjectNode) rootNode).put("creation_date", script.getCreationDate().toString());
        ((ObjectNode) rootNode).put("creation_user", user1.getFirstName() + " " + user1.getLastName());

        return rootNode;
    } finally {
        authentificationUtils.allowUser(user);
    }
}

From source file:org.jsonschema2pojo.rules.EnumRuleTest.java

@Test
public void applyGeneratesUniqueEnumNamesForMultipleEnumNodesWithSameName() {

    Answer<String> firstArgAnswer = new FirstArgAnswer<String>();
    when(nameHelper.getFieldName(anyString(), any(JsonNode.class))).thenAnswer(firstArgAnswer);
    when(nameHelper.replaceIllegalCharacters(anyString())).thenAnswer(firstArgAnswer);
    when(nameHelper.normalizeName(anyString())).thenAnswer(firstArgAnswer);

    JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName());

    ObjectMapper objectMapper = new ObjectMapper();
    ArrayNode arrayNode = objectMapper.createArrayNode();
    arrayNode.add("open");
    arrayNode.add("closed");
    ObjectNode enumNode = objectMapper.createObjectNode();
    enumNode.put("type", "string");
    enumNode.put("enum", arrayNode);

    // We're always a string for the purposes of this test
    when(typeRule.apply("status", enumNode, jpackage, schema)).thenReturn(jpackage.owner()._ref(String.class));

    JType result1 = rule.apply("status", enumNode, jpackage, schema);
    JType result2 = rule.apply("status", enumNode, jpackage, schema);

    assertThat(result1.fullName(), is("org.jsonschema2pojo.rules.Status"));
    assertThat(result2.fullName(), is("org.jsonschema2pojo.rules.Status_"));
}