Example usage for com.fasterxml.jackson.databind JsonNode toString

List of usage examples for com.fasterxml.jackson.databind JsonNode toString

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind JsonNode toString.

Prototype

public abstract String toString();

Source Link

Usage

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

@Test
public void two_$parent_array_query_projection_with_match() throws Exception {
    Projection p = EvalTestContext.projectionFromJson(
            "{'field':'field6.nf7.$parent.$parent.field7','match':{'field':'elemf3','op':'>','rvalue':4},'project':{'field':'*'}}");
    Projector projector = Projector.getInstance(p, md);
    JsonNode expectedNode = JsonUtils.json(
            "{'field7':[{'elemf1':'elvalue2_1','elemf2':'elvalue2_2','elemf3':5},{'elemf1':'elvalue3_1','elemf2':'elvalue3_2','elemf3':6}]}"
                    .replace('\'', '\"'));

    JsonDoc pdoc = projector.project(jsonDoc, JSON_NODE_FACTORY);

    Assert.assertEquals(expectedNode.toString(), pdoc.toString());
}

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

@Test
public void one_$this_array_query_projection_with_match() throws Exception {
    Projection p = EvalTestContext.projectionFromJson(
            "{'field':'field7.$this','match':{'field':'elemf3','op':'>','rvalue':4},'project':{'field':'*'}}");
    Projector projector = Projector.getInstance(p, md);
    JsonNode expectedNode = JsonUtils.json(
            "{'field7':[{'elemf1':'elvalue2_1','elemf2':'elvalue2_2','elemf3':5},{'elemf1':'elvalue3_1','elemf2':'elvalue3_2','elemf3':6}]}"
                    .replace('\'', '\"'));

    JsonDoc pdoc = projector.project(jsonDoc, JSON_NODE_FACTORY);

    Assert.assertEquals(expectedNode.toString(), pdoc.toString());
}

From source file:org.graylog2.inputs.codecs.GelfCodec.java

@Nullable
@Override//from   w w  w.jav a2  s  .  c o  m
public Message decode(@Nonnull final RawMessage rawMessage) {
    final GELFMessage gelfMessage = new GELFMessage(rawMessage.getPayload(), rawMessage.getRemoteAddress());
    final String json = gelfMessage.getJSON(decompressSizeLimit);

    final JsonNode node;

    try {
        node = objectMapper.readTree(json);
    } catch (final Exception e) {
        log.error("Could not parse JSON, first 400 characters: " + StringUtils.abbreviate(json, 403), e);
        throw new IllegalStateException("JSON is null/could not be parsed (invalid JSON)", e);
    }

    // Timestamp.
    final double messageTimestamp = doubleValue(node, "timestamp");
    final DateTime timestamp;
    if (messageTimestamp <= 0) {
        timestamp = rawMessage.getTimestamp();
    } else {
        // we treat this as a unix timestamp
        timestamp = Tools.dateTimeFromDouble(messageTimestamp);
    }

    final Message message = new Message(stringValue(node, "short_message"), stringValue(node, "host"),
            timestamp);

    message.addField("full_message", stringValue(node, "full_message"));

    final String file = stringValue(node, "file");

    if (file != null && !file.isEmpty()) {
        message.addField("file", file);
    }

    final long line = longValue(node, "line");
    if (line > -1) {
        message.addField("line", line);
    }

    // Level is set by server if not specified by client.
    final int level = intValue(node, "level");
    if (level > -1) {
        message.addField("level", level);
    }

    // Facility is set by server if not specified by client.
    final String facility = stringValue(node, ("facility"));
    if (facility != null && !facility.isEmpty()) {
        message.addField("facility", facility);
    }

    // Add additional data if there is some.
    final Iterator<Map.Entry<String, JsonNode>> fields = node.fields();

    while (fields.hasNext()) {
        final Map.Entry<String, JsonNode> entry = fields.next();

        String key = entry.getKey();
        // Do not index useless GELF "version" field.
        if ("version".equals(key)) {
            continue;
        }

        // Don't include GELF syntax underscore in message field key.
        if (key.startsWith("_") && key.length() > 1) {
            key = key.substring(1);
        }

        // We already set short_message and host as message and source. Do not add as fields again.
        if (key.equals("short_message") || key.equals("host")) {
            continue;
        }

        // Skip standard or already set fields.
        if (message.getField(key) != null
                || (Message.RESERVED_FIELDS.contains(key) && !Message.RESERVED_SETTABLE_FIELDS.contains(key))) {
            continue;
        }

        // Convert JSON containers to Strings, and pick a suitable number representation.
        final JsonNode value = entry.getValue();

        final Object fieldValue;
        if (value.isContainerNode()) {
            fieldValue = value.toString();
        } else if (value.isFloatingPointNumber()) {
            fieldValue = value.asDouble();
        } else if (value.isIntegralNumber()) {
            fieldValue = value.asLong();
        } else if (value.isNull()) {
            log.debug("Field [{}] is NULL. Skipping.", key);
            continue;
        } else if (value.isTextual()) {
            fieldValue = value.asText();
        } else {
            log.debug("Field [{}] has unknown value type. Skipping.", key);
            continue;
        }

        message.addField(key, fieldValue);
    }

    return message;
}

From source file:org.createnet.raptor.cli.command.IndexCommand.java

protected List<Indexer.IndexRecord> getObjects(int offset, int limit) {
    try {/*ww  w.ja  v  a2 s. c  o  m*/

        BaseQuery query = new BaseQuery();

        query.offset = offset;
        query.limit = limit;

        logger.debug("Loading {} objects from offset {}", limit, offset);

        List<JsonNode> objList = storage.getObjectConnection().list(query);
        List<Indexer.IndexRecord> list = new ArrayList();

        for (JsonNode rawobj : objList) {

            Indexer.IndexRecord indexRecord = indexer.getIndexRecord(IndexerService.IndexNames.object);

            indexRecord.id = rawobj.get("id").asText();
            indexRecord.body = rawobj.toString();

            list.add(indexRecord);
        }

        return list;
    } catch (ConfigurationException | Storage.StorageException ex) {
        logger.debug("Exception while loading objects", ex);
        throw new ObjectIndexerException(ex);
    }
}

From source file:com.evrythng.java.wrapper.mapping.ShortIdTemplateDeserializer.java

@Override
public ShortIdTemplate deserialize(final JsonParser jp, final DeserializationContext ctx) throws IOException {

    ObjectMapper mapper = JSONUtils.OBJECT_MAPPER;
    JsonNode node = mapper.readTree(jp);
    JsonNode typeNode = node.get(ShortIdTemplate.FIELD_TYPE);
    if (typeNode == null) {
        throw new JsonMappingException("Cannot deserialize task on batch without type field");
    }//from  w  w w .j  a v a2 s. c o m
    String typeRaw = getFieldValue(typeNode);
    Class<? extends ShortIdTemplate> subtypeClass = classForType(
            ShortIdTemplate.Type.valueOf(typeRaw.toUpperCase()));
    return mapper.readValue(node.toString(), subtypeClass);
}

From source file:com.discover.cls.processors.cls.JSONToAttributes.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();/*from   w  w w  . ja  va  2  s . c  om*/
    if (flowFile == null) {
        return;
    }

    final String flattenJsonSeparator = context.getProperty(FLATTEN_JSON_SEPARATOR).getValue();
    final boolean flattenJson = context.getProperty(FLATTEN_JSON).asBoolean();
    final boolean flattenJsonArrays = context.getProperty(FLATTEN_JSON_ARRAYS).asBoolean();
    final String attributeNameFromProperty = context.getProperty(JSON_ATTRIBUTE_NAME)
            .evaluateAttributeExpressions().getValue();
    final String attributeContent = flowFile.getAttribute(attributeNameFromProperty);
    final byte[] content = getContent(session, flowFile, attributeNameFromProperty, attributeContent);
    final boolean toOverride = context.getProperty(OVERRIDE_ATTRIBUTES).asBoolean();
    final boolean preserveType = context.getProperty(PRESERVE_TYPE).asBoolean();

    if (attributeNameFromProperty != null && !"".equals(attributeNameFromProperty)
            && attributeContent == null) {
        getLogger().error(JSON_ATTRIBUTE_NAME.getDisplayName() + " is defined, but the attribute '"
                + attributeNameFromProperty + "' does not exist.");
        session.transfer(flowFile, REL_FAILURE);
        return;
    }

    if (content == null || Arrays.equals(content, new byte[0])) {
        // No content. push through.
        getLogger().debug("No content is defined. Passing flow file to 'no content' relationship.");
        session.transfer(flowFile, REL_NO_CONTENT);
        return;
    }

    try {
        final JsonNode jsonNode = OBJECT_MAPPER.readTree(content);
        final Map<String, String> attributes = new LinkedHashMap<>();

        if (flattenJson) {
            addKeys("", jsonNode, flattenJsonSeparator, preserveType, flattenJsonArrays, attributes);
        } else {
            final Iterator<Map.Entry<String, JsonNode>> fields = jsonNode.fields();
            while (fields.hasNext()) {
                Map.Entry<String, JsonNode> entry = fields.next();
                if (toOverride || flowFile.getAttribute(entry.getKey()) == null) {
                    JsonNode value = entry.getValue();
                    switch (value.getNodeType()) {
                    case ARRAY:
                        attributes.put(entry.getKey(), value.toString());
                        break;
                    case BINARY:
                        attributes.put(entry.getKey(), value.toString());
                        break;
                    case BOOLEAN:
                        attributes.put(entry.getKey(), Boolean.toString(value.asBoolean()));
                        break;
                    case MISSING:
                        attributes.put(entry.getKey(), value.toString());
                        break;
                    case NULL:
                        attributes.put(entry.getKey(), value.toString());
                        break;
                    case NUMBER:
                        attributes.put(entry.getKey(), Long.toString(value.asLong()));
                        break;
                    case OBJECT:
                        attributes.put(entry.getKey(), value.toString());
                        break;
                    case POJO:
                        attributes.put(entry.getKey(), value.toString());
                        break;
                    case STRING:
                        attributes.put(entry.getKey(), preserveType ? value.toString() : value.textValue());
                        break;
                    }
                }
            }
        }

        flowFile = session.putAllAttributes(flowFile, attributes);
        session.getProvenanceReporter().modifyAttributes(flowFile);
        session.transfer(flowFile, REL_SUCCESS);
    } catch (IOException e) {
        getLogger().error("Failed parsing JSON.", new Object[] { e });
        session.transfer(flowFile, REL_FAILURE);
    }
}

From source file:com.redhat.lightblue.config.rdbms.RDBMSDataSourceConfiguration.java

@Override
public void initializeFromJson(JsonNode node) {
    if (node != null) {
        JsonNode x = node.get("metadataDataStoreParser");
        try {//from  w w  w  .j av a 2  s  . c o m
            if (x != null) {
                metadataDataStoreParser = Class.forName(x.asText());
            }
        } catch (Exception e) {
            throw new IllegalArgumentException(node.toString() + ":" + e);
        }
        x = node.get("database");
        if (x != null) {
            databaseName = x.asText();
        }
        JsonNode jsonNodeServers = node.get("connections");
        if (jsonNodeServers != null && jsonNodeServers.isArray()) {
            Iterator<JsonNode> elements = jsonNodeServers.elements();
            while (elements.hasNext()) {
                JsonNode next = elements.next();
                String datasourceName;
                String JNDI;
                x = next.get("datasourceName");
                if (x != null) {
                    datasourceName = x.asText();
                } else {
                    throw new IllegalStateException("No datasourceName was found: " + node.toString());
                }

                x = next.get("JNDI");
                if (x != null) {
                    JNDI = x.asText();
                } else {
                    throw new IllegalStateException("No JNDI was found: " + node.toString());
                }
                dataSourceJDNIMap.put(datasourceName, JNDI);
            }
        } else {
            throw new IllegalStateException("No connection was found: " + node.toString());
        }
    }
}

From source file:com.epam.dlab.backendapi.core.commands.CommandExecutorMockAsync.java

/**
 * Return the section of resource statuses for docker action status.
 *//*from w  w w .  ja  v a2 s .c o m*/
private String getResponseLibInstall(boolean isSuccess) {
    List<LibInstallDTO> list;
    try {
        JsonNode json = MAPPER.readTree(parser.getJson());
        json = json.get("libs");
        list = MAPPER.readValue(json.toString(), new TypeReference<List<LibInstallDTO>>() {
        });
    } catch (IOException e) {
        throw new DlabException("Can't parse json content: " + e.getLocalizedMessage(), e);
    }

    for (LibInstallDTO lib : list) {
        if (isSuccess) {
            lib.setStatus(LibStatus.INSTALLED.toString());
        } else {
            lib.setStatus(LibStatus.FAILED.toString());
            lib.setErrorMessage("Mock error message");
        }
    }

    try {
        return MAPPER.writeValueAsString(list);
    } catch (JsonProcessingException e) {
        throw new DlabException("Can't generate json content: " + e.getLocalizedMessage(), e);
    }
}

From source file:com.almende.eve.state.redis.RedisState.java

@Override
public boolean locPutIfUnchanged(final String key, final JsonNode newVal, JsonNode oldVal) {
    boolean result = false;
    final Jedis redis = provider.getInstance();
    try {//from   w  w  w . j a  v  a 2s  . c  om
        JsonNode cur = get(key);
        if (oldVal == null) {
            oldVal = NullNode.getInstance();
        }
        final String nkey = makeKey(key);
        if (oldVal.equals(cur) || oldVal.toString().equals(cur.toString())) {
            redis.set(nkey, newVal.toString());
            redis.sadd(getId() + "_" + KEYS, nkey);
            result = true;
        }
    } catch (Exception e) {
        LOG.log(Level.WARNING, "", e);
        // Don't let users loop if exception is thrown. They
        // would get into a deadlock....
        result = true;
    }
    provider.returnInstance(redis);
    return result;
}

From source file:com.redhat.lightblue.crud.ldap.ITCaseLdapCRUDControllerTest.java

@Test
public void series1_phase2_Person_FindSingle() throws Exception {
    Response response = getLightblueFactory().getMediator()
            .find(createRequest_FromResource(FindRequest.class, "./crud/find/person-find-single.json"));

    assertNotNull(response);//from w  ww  . j  av  a 2  s. com
    assertNoErrors(response);
    assertNoDataErrors(response);
    assertEquals(1, response.getMatchCount());

    JsonNode entityData = response.getEntityData();
    assertNotNull(entityData);
    JSONAssert.assertEquals(
            "[{\"dn\":\"uid=john.doe," + BASEDB_USERS
                    + "\",\"uid\":\"john.doe\",\"objectType\":\"person\",\"objectClass#\":4}]",
            entityData.toString(), true);
}