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

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

Introduction

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

Prototype

public JsonNode get(String paramString) 

Source Link

Usage

From source file:com.meltmedia.jackson.crypto.EncryptWithObjectMapperTest.java

@Test
public void shouldEncryptString() throws IOException {
    WithEncrypted toEncrypt = new WithEncrypted().withStringValue("some value");

    ObjectNode encrypted = mapper.readValue(mapper.writeValueAsString(toEncrypt), ObjectNode.class);

    assertThat("has nested value", encrypted.at("/stringValue/value").isNull(), equalTo(false));
    assertThat("nested value is encrypted", encrypted.at("/stringValue/value").asText(),
            not(containsString("some value")));

    EncryptedJson result = mapper.convertValue(encrypted.get("stringValue"), EncryptedJson.class);
    JsonNode roundTrip = service.decryptAs(result, "UTF-8", JsonNode.class);

    assertThat(roundTrip.asText(), equalTo("some value"));
}

From source file:kz.nurlan.kaspandr.KaspandrWindow.java

private String checkLessonCountByGroup(String lessons)
        throws JsonParseException, JsonMappingException, IOException {
    String resultString = "";

    ObjectNode rootNode1 = mapper.readValue("{\"lessons\":[" + lessons + "]}", ObjectNode.class);
    JsonNode lessonsNode1 = rootNode1.get("lessons");

    HashMap<String, Integer> groupMap = new HashMap<String, Integer>();
    HashMap<String, String> groupNameMap = new HashMap<String, String>();
    ValueComparator bvc = new ValueComparator(groupNameMap);
    TreeMap<String, String> sortedGroupNameMap = new TreeMap<String, String>(bvc);

    groupMap.put("all", 0);

    if (lessonsNode1 != null && lessonsNode1.isArray()) {
        Iterator<JsonNode> it = lessonsNode1.elements();

        while (it.hasNext()) {
            JsonNode lesson = it.next();

            if (lesson.get("id") != null && !lesson.get("status").textValue().equalsIgnoreCase("deleted")
                    && lesson.get("group") != null && !lesson.get("group").textValue().isEmpty()) {
                if (groupMap.containsKey(lesson.get("group").textValue()))
                    groupMap.put(lesson.get("group").textValue(),
                            groupMap.get(lesson.get("group").textValue()) + 1);
                else
                    groupMap.put(lesson.get("group").textValue(), 1);

                groupNameMap.put(lesson.get("group").textValue(), lesson.get("groupName").textValue());
            }//from w w w .  j ava 2 s . c om

            groupMap.put("all", groupMap.get("all") + 1);
        }
    }
    sortedGroupNameMap.putAll(groupNameMap);

    int count = 0;
    for (String group : groupMap.keySet()) {
        if (!group.equals("all")) {
            count += groupMap.get(group);
        }
    }

    for (String group : sortedGroupNameMap.keySet()) {
        if (!resultString.isEmpty())
            resultString += ", ";

        resultString += groupNameMap.get(group) + "(" + groupMap.get(group) + ")";
    }
    resultString = "Lessons(" + count + "/" + groupMap.get("all") + "); " + resultString;

    return resultString;
}

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();/*from w  ww .j  a va  2  s. c  o  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:com.joyent.manta.client.multipart.ServerSideMultipartManagerTest.java

public void canCreateMpuRequestBodyJsonWithHeaders() throws IOException {
    final String path = "/user/stor/object";
    final MantaHttpHeaders headers = new MantaHttpHeaders();

    headers.setDurabilityLevel(5);//from  w  w  w  . j  ava2s.co m
    headers.setContentLength(423534L);
    headers.setContentMD5("e59ff97941044f85df5297e1c302d260");
    headers.setContentType(ContentType.APPLICATION_OCTET_STREAM.toString());
    final Set<String> roles = new HashSet<>();
    roles.add("manta");
    roles.add("role2");
    headers.setRoles(roles);

    final byte[] json = ServerSideMultipartManager.createMpuRequestBody(path, null, headers);

    ObjectNode jsonObject = mapper.readValue(json, ObjectNode.class);

    try {
        Assert.assertEquals(jsonObject.get("objectPath").textValue(), path);
        ObjectNode jsonHeaders = (ObjectNode) jsonObject.get("headers");

        Assert.assertEquals(jsonHeaders.get(MantaHttpHeaders.HTTP_DURABILITY_LEVEL.toLowerCase()).asInt(),
                headers.getDurabilityLevel().intValue());
        Assert.assertEquals(jsonHeaders.get(HttpHeaders.CONTENT_LENGTH.toLowerCase()).asLong(),
                headers.getContentLength().longValue());
        Assert.assertEquals(jsonHeaders.get(HttpHeaders.CONTENT_MD5.toLowerCase()).textValue(),
                headers.getContentMD5());
        Assert.assertEquals(jsonHeaders.get(MantaHttpHeaders.HTTP_ROLE_TAG.toLowerCase()).textValue(),
                headers.getFirstHeaderStringValue(MantaHttpHeaders.HTTP_ROLE_TAG.toLowerCase()));
        Assert.assertEquals(jsonHeaders.get(HttpHeaders.CONTENT_TYPE.toLowerCase()).textValue(),
                "application/octet-stream");
    } catch (AssertionError e) {
        System.err.println(new String(json, StandardCharsets.UTF_8));
        throw e;
    }
}

From source file:com.heliosapm.tsdblite.handlers.json.SplitTraceInputHandler.java

protected ObjectName metaObjectName(final JsonNode node) {
    try {//from  ww  w.ja  va  2  s . co m
        final String metric = node.get("Metric").textValue();
        final ObjectNode tags = (ObjectNode) node.get("Tags");
        if (tags != null && tags.size() > 0) {
            Map<String, String> t = new HashMap<String, String>(tags.size());
            for (Iterator<String> n = tags.fieldNames(); n.hasNext();) {
                final String key = n.next();
                final String value = tags.get(key).asText();
                t.put(key, value);
            }
            return toHostObjectName(JMXHelper.objectName(metric, t));
            //            return JMXHelper.objectName(metric, t);
        } else {
            return JMXHelper.objectName(toHostObjectName(JMXHelper.objectName(metric + ":*")).toString());
            //            return JMXHelper.objectName(metric + ":type=static");
        }
    } catch (Exception ex) {
        return null;
    }
}

From source file:com.addthis.codec.jackson.CodecTypeDeserializer.java

private Object _deserializeObjectFromProperty(ObjectNode objectNode, ObjectCodec objectCodec,
        DeserializationContext ctxt) throws IOException {
    String type = objectNode.get(_typePropertyName).asText();
    if (!_typeIdVisible) {
        objectNode.remove(_typePropertyName);
    }//from   w ww  . j  a  v  a  2  s. c  o  m
    JsonDeserializer<Object> deser;
    try {
        deser = _findDeserializer(ctxt, type);
    } catch (Throwable cause) {
        throw wrapWithPath(cause, Class.class, _typePropertyName);
    }
    ConfigObject aliasDefaults = pluginMap.aliasDefaults(type);
    String primaryField;
    if (aliasDefaults.containsKey("_primary")) {
        primaryField = (String) aliasDefaults.get("_primary").unwrapped();
    } else {
        primaryField = null;
    }
    boolean unwrapPrimary = handleDefaultsAndImplicitPrimary(objectNode, aliasDefaults, deser, ctxt);
    try {
        JsonParser treeParser = objectCodec.treeAsTokens(objectNode);
        treeParser.nextToken();
        return deser.deserialize(treeParser, ctxt);
    } catch (IOException cause) {
        if (unwrapPrimary) {
            throw Jackson.maybeUnwrapPath(primaryField, cause);
        } else {
            throw cause;
        }
    }
}

From source file:com.heliosapm.tsdblite.handlers.json.SplitTraceInputHandler.java

protected String metaObject(final JsonNode node) {
    try {//from w w w  .j  a va 2s  .c  om
        final String metric = node.get("Metric").textValue();
        final ObjectNode tags = (ObjectNode) node.get("Tags");
        if (tags != null && tags.size() > 0) {
            Map<String, String> t = new HashMap<String, String>(tags.size());
            for (Iterator<String> n = tags.fieldNames(); n.hasNext();) {
                final String key = n.next();
                final String value = tags.get(key).asText();
                t.put(key, value);
            }
            return metric + ":" + t;
            //            return JMXHelper.objectName(metric, t);
        } else {
            return metric + ":*";
            //            return JMXHelper.objectName(toHostObjectName(JMXHelper.objectName(metric + ":*")).toString());            
            //            return JMXHelper.objectName(metric + ":type=static");
        }
    } catch (Exception ex) {
        return null;
    }
}

From source file:org.apache.streams.components.http.processor.SimpleHTTPGetProcessor.java

/**
 Override this to place result in non-standard location on document.
 *///from   w ww.  j a v a  2s . c  om
protected ActivityObject getEntityToExtend(ObjectNode rootDocument) {

    if (this.configuration.getEntity().equals(HttpProcessorConfiguration.Entity.ACTIVITY)) {
        return mapper.convertValue(rootDocument, ActivityObject.class);
    } else {
        return mapper.convertValue(rootDocument.get(this.configuration.getEntity().toString()),
                ActivityObject.class);
    }
}

From source file:com.palominolabs.crm.sf.rest.RestConnectionImpl.java

@Nonnull
private SaveResult getSaveResult(@Nullable String saveResultJson) throws IOException {
    ObjectNode objectNode = this.objectReader.withType(ObjectNode.class).readValue(parse(saveResultJson));
    String id = objectNode.get("id").textValue();
    boolean success = objectNode.get("success").booleanValue();

    List<ApiError> errors = this.objectReader.withType(HttpApiClient.API_ERRORS_TYPE)
            .readValue(objectNode.get("errors"));

    return new SaveResultImpl(new Id(id), success, errors);
}

From source file:com.joyent.manta.client.multipart.ServerSideMultipartManagerTest.java

public void canCreateMpuRequestBodyJsonWithHeadersAndMetadata() throws IOException {
    final String path = "/user/stor/object";
    final MantaHttpHeaders headers = new MantaHttpHeaders();

    headers.setDurabilityLevel(5);/* w ww. ja v a  2s .  co  m*/
    headers.setContentLength(423534L);
    headers.setContentMD5("e59ff97941044f85df5297e1c302d260");
    headers.setContentType(ContentType.APPLICATION_OCTET_STREAM.toString());
    final Set<String> roles = new HashSet<>();
    roles.add("manta");
    roles.add("role2");
    headers.setRoles(roles);

    final MantaMetadata metadata = new MantaMetadata();
    metadata.put("m-mykey1", "key value 1");
    metadata.put("m-mykey2", "key value 2");
    metadata.put("e-mykey", "i should be ignored");

    final byte[] json = ServerSideMultipartManager.createMpuRequestBody(path, metadata, headers);

    ObjectNode jsonObject = mapper.readValue(json, ObjectNode.class);

    try {
        Assert.assertEquals(jsonObject.get("objectPath").textValue(), path);
        ObjectNode jsonHeaders = (ObjectNode) jsonObject.get("headers");

        Assert.assertEquals(jsonHeaders.get(MantaHttpHeaders.HTTP_DURABILITY_LEVEL.toLowerCase()).asInt(),
                headers.getDurabilityLevel().intValue());
        Assert.assertEquals(jsonHeaders.get(HttpHeaders.CONTENT_LENGTH.toLowerCase()).asLong(),
                headers.getContentLength().longValue());
        Assert.assertEquals(jsonHeaders.get(HttpHeaders.CONTENT_MD5.toLowerCase()).textValue(),
                headers.getContentMD5());
        Assert.assertEquals(jsonHeaders.get(MantaHttpHeaders.HTTP_ROLE_TAG.toLowerCase()).textValue(),
                headers.getFirstHeaderStringValue(MantaHttpHeaders.HTTP_ROLE_TAG.toLowerCase()));
        Assert.assertEquals(jsonHeaders.get(HttpHeaders.CONTENT_TYPE.toLowerCase()).textValue(),
                "application/octet-stream");

        Assert.assertEquals(jsonHeaders.get("m-mykey1").textValue(), metadata.get("m-mykey1"));
        Assert.assertEquals(jsonHeaders.get("m-mykey2").textValue(), metadata.get("m-mykey2"));

        Assert.assertNull(jsonHeaders.get("e-mykey"), "Encrypted headers should not be included");
    } catch (AssertionError e) {
        System.err.println(new String(json, StandardCharsets.UTF_8));
        throw e;
    }
}