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

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

Introduction

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

Prototype

public abstract String asText();

Source Link

Usage

From source file:org.agatom.springatom.cmp.action.DefaultActionsModelReader.java

/** {@inheritDoc} */
@Override/*w  w w  .j a v  a  2  s .  c o  m*/
public ActionModel getActionModel(final String name) throws NotFoundException {
    LOGGER.debug(String.format("getActionModel(name=%s)", name));
    final ActionModelReferenceMap map = flattenActionModel.get(name);
    if (map == null) {
        throw new NotFoundException(String.format("No action model found for key=%s", name));
    }
    try {
        final long startTime = System.nanoTime();
        final ActionModel model = new ActionModel()
                .setContent(this.resolveContent(map, Sets.<Action>newTreeSet()));

        JsonNode tmpNode;
        if ((tmpNode = map.node.findValue("description")) != null) {
            model.setDescription(tmpNode.asText());
        }
        if ((tmpNode = map.node.findValue("name")) != null) {
            model.setName(tmpNode.asText());
        }

        final long endTime = System.nanoTime() - startTime;

        LOGGER.trace(String.format("getActionModel(name=%s) took %d ms", name,
                TimeUnit.NANOSECONDS.toMillis(endTime)));

        return model;
    } catch (Exception ignore) {

    }
    return null;
}

From source file:scott.barleyrs.rest.CrudService.java

private Object getEntityKey(ObjectNode jsObject, EntityType entityType) {
    JsonNode keyNode = jsObject.get(entityType.getKeyNodeName());
    if (keyNode == null || keyNode.isNull()) {
        return null;
    }//from w  w  w  .  j  a va2s .c  om
    String keyAsString = keyNode.asText();
    if (keyAsString == null || keyAsString.isEmpty()) {
        return null;
    }
    return convertForKey(entityType, keyAsString);
}

From source file:io.cloudslang.content.json.actions.GetValueFromObject.java

/**
 * This operation accepts an object in the JavaScript Object Notation format (JSON) and returns a value for the specified key.
 *
 * @param object The string representation of a JSON object.
 *               Objects in JSON are a collection of name value pairs, separated by a colon and surrounded with curly brackets {}.
 *               The name must be a string value, and the value can be a single string or any valid JSON object or array.
 *               Examples: {"one":1, "two":2}, {"one":{"a":"a","B":"B"}, "two":"two", "three":[1,2,3.4]}
 * @param key    The key in the object to get the value of.
 *               Examples: city, location[0].city
 * @return a map containing the output of the operation. Keys present in the map are:
 * <p/>//from ww w  . j  av  a2s  .  c o  m
 * <br><br><b>returnResult</b> - This will contain the value for the specified key in the object.
 * <br><b>exception</b> - In case of success response, this result is empty. In case of failure response,
 * this result contains the java stack trace of the runtime exception.
 * <br><br><b>returnCode</b> - The returnCode of the operation: 0 for success, -1 for failure.
 */
@Action(name = "Get Value from Object", outputs = { @Output(OutputNames.RETURN_RESULT),
        @Output(OutputNames.RETURN_CODE), @Output(OutputNames.EXCEPTION) }, responses = {
                @Response(text = ResponseNames.SUCCESS, field = OutputNames.RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED),
                @Response(text = ResponseNames.FAILURE, field = OutputNames.RETURN_CODE, value = ReturnCodes.FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true) })
public Map<String, String> execute(@Param(value = Constants.InputNames.OBJECT, required = true) String object,
        @Param(value = Constants.InputNames.KEY, required = true) String key) {

    Map<String, String> returnResult = new HashMap<>();

    if (StringUtilities.isBlank(object)) {
        return populateResult(returnResult, new Exception("Empty object provided!"));
    }
    if (key == null) {
        return populateResult(returnResult, new Exception("Null key provided!"));
    }

    final JsonNode jsonRoot;
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        jsonRoot = objectMapper.readTree(object);
    } catch (Exception exception) {
        final String value = "Invalid object provided! " + exception.getMessage();
        return populateResult(returnResult, value, exception);
    }

    int startIndex = 0;
    final JsonNode valueFromObject;
    try {
        valueFromObject = getObject(jsonRoot, key.split(ESCAPED_SLASH + "."), startIndex);
    } catch (Exception exception) {
        return populateResult(returnResult, exception);
    }
    if (valueFromObject.isValueNode()) {
        return populateResult(returnResult, valueFromObject.asText(), null);
    } else {
        return populateResult(returnResult, valueFromObject.toString(), null);
    }

}

From source file:net.logstash.logback.pattern.AbstractJsonPatternParser.java

private ChildrenWriter<Event> parseChildren(JsonNode node) {
    List<FieldWriter<Event>> children = new ArrayList<FieldWriter<Event>>();
    for (Iterator<Map.Entry<String, JsonNode>> nodeFields = node.fields(); nodeFields.hasNext();) {
        Map.Entry<String, JsonNode> field = nodeFields.next();

        String key = field.getKey();
        JsonNode value = field.getValue();

        if (value.isTextual()) {
            ValueGetter<?, Event> getter = makeComputableValueGetter(value.asText());
            children.add(new ComputableObjectFieldWriter<Event>(key, getter));
        } else {/*from w  ww. j  ava 2s . c  om*/
            children.add(new DelegatingObjectFieldWriter<Event>(key, parseValue(value)));
        }
    }
    return new ChildrenWriter<Event>(children);
}

From source file:org.waarp.openr66.protocol.http.rest.handler.DbHostConfigurationR66RestMethodHandler.java

protected DbHostConfiguration getItem(HttpRestHandler handler, RestArgument arguments, RestArgument result,
        Object body)//from  w w w . j av a2 s  . c o  m
        throws HttpIncorrectRequestException, HttpInvalidAuthenticationException, HttpNotFoundRequestException {
    ObjectNode arg = arguments.getUriArgs().deepCopy();
    arg.setAll(arguments.getBody());
    try {
        JsonNode node = RestArgument.getId(arg);
        String id;
        if (node.isMissingNode()) {
            // shall not be but continue however
            id = arg.path(DbHostConfiguration.Columns.HOSTID.name()).asText();
        } else {
            id = node.asText();
        }
        return new DbHostConfiguration(handler.getDbSession(), id);
    } catch (WaarpDatabaseException e) {
        throw new HttpNotFoundRequestException("Issue while reading from database " + arg, e);
    }
}

From source file:de.thingweb.thing.Thing.java

public URI getUri(int index) {
    JsonNode uris = getMetadata().get("uris");
    if (uris != null) {
        try {//from  ww  w  .ja v  a 2  s .c o  m
            if (uris.getNodeType() == JsonNodeType.STRING) {
                return new URI(uris.asText());
            } else if (uris.getNodeType() == JsonNodeType.ARRAY) {
                ArrayNode an = (ArrayNode) uris;
                return new URI(an.get(index).asText());
            }
        } catch (URISyntaxException e) {
            throw new RuntimeException("TD with malformed base uris");
        }
    } else {
        throw new RuntimeException("TD without base uris field");
    }
    // should never be reached
    throw new RuntimeException("Unexpected error while retrieving uri at index " + index);
}

From source file:de.cubeisland.engine.core.webapi.WebSocketRequestHandler.java

private void handleTextWebSocketFrame(final ChannelHandlerContext ctx, TextWebSocketFrame frame) {
    // TODO log exceptions!!!
    JsonNode jsonNode;//from  w  ww  . j  a  va2 s  .co  m
    try {
        jsonNode = objectMapper.readTree(frame.text());
    } catch (IOException e) {
        this.log.info("the frame data was no valid json!");
        return;
    }
    JsonNode action = jsonNode.get("action");
    JsonNode msgid = jsonNode.get("msgid");
    ObjectNode responseNode = objectMapper.createObjectNode();
    if (action == null) {
        responseNode.put("response", "No action");
    } else {
        JsonNode data = jsonNode.get("data");
        switch (action.asText()) {
        case "http":
            QueryStringDecoder qsDecoder = new QueryStringDecoder(normalizePath(data.get("uri").asText()),
                    this.UTF8, true, 100);

            JsonNode reqMethod = data.get("method");
            RequestMethod method = reqMethod != null ? getByName(reqMethod.asText()) : GET;
            JsonNode reqdata = data.get("body");
            ApiHandler handler = this.server.getApiHandler(normalizePath(qsDecoder.path()));
            if (handler == null) {
                responseNode.put("response", "Unknown route");
                break;
            }
            Parameters params = new Parameters(qsDecoder.parameters(),
                    core.getCommandManager().getProviderManager());
            ApiRequest request = new ApiRequest((InetSocketAddress) ctx.channel().remoteAddress(), method,
                    params, EMPTY_HEADERS, reqdata, authUser);
            ApiResponse response = handler.execute(request);
            if (msgid != null) {
                responseNode.set("response", objectMapper.valueToTree(response.getContent()));
            }
            break;
        case "subscribe":
            this.server.subscribe(data.asText().trim(), this);
            break;
        case "unsubscribe":
            this.server.unsubscribe(data.asText().trim(), this);
            break;
        default:
            responseNode.put("response", action.asText() + " -- " + data.asText());
        }

    }
    if (msgid != null && responseNode.elements().hasNext()) {
        responseNode.put("msgid", msgid);
        ctx.writeAndFlush(responseNode);
    }
}

From source file:com.arantius.tivocommander.SeasonPass.java

protected void startRequest() {
    mSubscriptionData.clear();//from  w w w. ja v  a2  s.co  m
    mSubscriptionIds.clear();
    mSubscriptionStatus.clear();
    MindRpcResponseListener idSequenceCallback = new MindRpcResponseListener() {
        public void onResponse(MindRpcResponse response) {
            JsonNode body = response.getBody();

            for (JsonNode node : body.path("objectIdAndType")) {
                mSubscriptionIds.add(node.asText());
            }
            for (int i = 0; i < mSubscriptionIds.size(); i++) {
                mSubscriptionData.add(null);
                mSubscriptionStatus.add(SubscriptionStatus.MISSING);
            }
            mListAdapter.notifyDataSetChanged();
        }
    };
    MindRpc.addRequest(new SubscriptionSearch(), idSequenceCallback);
}

From source file:com.redhat.lightblue.crud.ldap.translator.ResultTranslatorTest.java

@Test
public void testTranslate_SimpleField_BinaryType() throws Exception {
    byte[] bite = new byte[] { 1, 2, 3, 'a', 'b', 'c' };

    SearchResultEntry result = new SearchResultEntry(-1, "uid=john.doe,dc=example,dc=com",
            new Attribute[] { new Attribute("key", bite) });

    EntityMetadata md = fakeEntityMetadata("fakeMetadata", new SimpleField("key", BinaryType.TYPE));

    DocCtx document = new ResultTranslator(factory, md, new TrivialLdapFieldNameTranslator()).translate(result);

    assertNotNull(document);//  w w  w. ja  v  a 2  s .  co  m
    JsonDoc jsonDocument = document.getOutputDocument();

    JsonNode keyNode = jsonDocument.get(new Path("key"));
    assertEquals(bite, keyNode.binaryValue());

    JSONAssert.assertEquals("{\"key\":\"" + keyNode.asText() + "\",\"dn\":\"uid=john.doe,dc=example,dc=com\"}",
            jsonDocument.toString(), true);
}