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.springframework.data.repository.init.Jackson2ResourceReader.java

/**
 * Reads the given {@link JsonNode} into an instance of the type encoded in it using the configured type key.
 * //from w w  w  .ja  va2s . c o m
 * @param node must not be {@literal null}.
 * @param classLoader
 * @return
 */
private Object readSingle(JsonNode node, ClassLoader classLoader) throws IOException {

    JsonNode typeNode = node.findValue(typeKey);
    String typeName = typeNode == null ? null : typeNode.asText();

    Class<?> type = ClassUtils.resolveClassName(typeName, classLoader);

    return mapper.readerFor(type).readValue(node);
}

From source file:org.walkmod.conf.providers.yml.RemovePluginYMLAction.java

@Override
public void doAction(JsonNode node) throws Exception {
    if (node.has("plugins")) {
        ArrayNode pluginList = null;//from w  w  w. ja  v a2  s  .  c o m
        JsonNode aux = node.get("plugins");
        if (aux.isArray()) {
            pluginList = (ArrayNode) node.get("plugins");
            Iterator<JsonNode> it = pluginList.iterator();

            int index = -1;
            int i = 0;
            while (it.hasNext() && index == -1) {
                JsonNode next = it.next();
                if (next.isTextual()) {
                    String text = next.asText();
                    String[] parts = text.split(":");
                    if (parts.length >= 2) {
                        if (parts[0].equals(pluginConfig.getGroupId())
                                && parts[1].equals(pluginConfig.getArtifactId())) {
                            index = i;
                        }
                    }
                }
                i++;
            }
            if (index > -1) {
                pluginList.remove(index);
            }

        } else {
            throw new TransformerException("The plugins element is not a valid array");
        }
    }

    provider.write(node);

}

From source file:io.progix.dropwizard.patch.explicit.PatchInstructionDeserializer.java

/**
 * This method is responsible for deserialization of a {@link PatchInstruction}
 * <p/>/*w  ww .j  a  va  2 s .com*/
 * The value in a patch instruction is mapped to a TreeMap and can be later converted to a class of choice using
 * {@link JsonPatchValue}
 *
 * @see JsonDeserializer
 */
@Override
public PatchInstruction deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    untypedObjectDeserializer.resolve(ctxt);

    JsonNode node = jp.getCodec().readTree(jp);

    PatchOperation operation = PatchOperation.valueOf(node.get("op").asText().toUpperCase());

    String path = node.get("path").asText();

    String from = null;
    JsonNode fromNode = node.get("from");
    if (fromNode != null) {
        from = fromNode.asText();
    }

    List<Object> values = null;
    JsonNode valueNode = node.get("value");
    if (valueNode != null) {
        values = new ArrayList<>();
        if (valueNode.isArray()) {
            Iterator<JsonNode> iterator = valueNode.elements();
            while (iterator.hasNext()) {
                JsonNode elementNode = iterator.next();
                JsonParser p = elementNode.traverse();
                if (!p.hasCurrentToken()) {
                    p.nextToken();
                }
                Object element = untypedObjectDeserializer.deserialize(p, ctxt);
                values.add(element);
            }
        } else {
            JsonParser p = valueNode.traverse();
            if (!p.hasCurrentToken()) {
                p.nextToken();
            }
            Object value = untypedObjectDeserializer.deserialize(p, ctxt);
            values.add(value);
        }
    }

    return new PatchInstruction(operation, path, values, from);
}

From source file:fr.gouv.vitam.cases.ResultRedis.java

/**
 * To be called after a load from Database
 */// w  w  w.  j  a  va 2 s . c o  m
public void getAfterLoad() {
    if (node.has(CURRENTDAIP)) {
        final ArrayNode obj = (ArrayNode) node.withArray(CURRENTDAIP);
        final Set<String> vtset = new HashSet<String>();
        for (JsonNode string : obj) {
            vtset.add(string.asText());
        }
        currentDaip.clear();
        currentDaip.addAll(vtset);
    }
    minLevel = node.path(MINLEVEL).asInt(0);
    maxLevel = node.path(MAXLEVEL).asInt(0);
    nbSubNodes = node.path(NBSUBNODES).asLong(-1);
}

From source file:io.gravitee.definition.jackson.datatype.api.deser.HttpProxyDeserializer.java

@Override
public HttpProxy deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonNode node = jp.getCodec().readTree(jp);

    HttpProxy httpProxy = new HttpProxy();

    JsonNode enabledNode = node.get("enabled");
    if (enabledNode != null) {
        boolean enabled = enabledNode.asBoolean(false);
        httpProxy.setEnabled(enabled);/*from  www  .jav  a 2 s  . c o m*/
    }

    httpProxy.setHost(readStringValue(node, "host"));

    String sPort = readStringValue(node, "port");
    if (sPort != null) {
        httpProxy.setPort(Integer.parseInt(sPort));
    }

    httpProxy.setPassword(readStringValue(node, "password"));
    httpProxy.setUsername(readStringValue(node, "username"));

    final JsonNode typeNode = node.get("type");
    if (typeNode != null) {
        httpProxy.setType(HttpProxyType.valueOf(typeNode.asText().toUpperCase()));
    }

    return httpProxy;
}

From source file:com.baasbox.controllers.Admin.java

/***
 * Change password of a specific user//from  www  . jav  a2  s. c  o m
 * @param username of user
 * @return 
 * @throws UserNotFoundException 
 * @throws SqlInjectionException 
 */
public static Result changePassword(String username) throws SqlInjectionException, UserNotFoundException {
    if (BaasBoxLogger.isTraceEnabled())
        BaasBoxLogger.trace("Method Start");
    Http.RequestBody body = request().body();
    JsonNode bodyJson = body.asJson(); //{"password":"Password"}
    if (BaasBoxLogger.isTraceEnabled())
        BaasBoxLogger.trace("changePassword bodyJson: " + bodyJson);

    if (bodyJson == null)
        return badRequest("The body payload cannot be empty.");
    JsonNode passwordNode = bodyJson.findValue("password");

    if (passwordNode == null)
        return badRequest("The body payload doesn't contain password field");
    String password = passwordNode.asText();

    try {
        UserService.changePassword(username, password);
    } catch (UserNotFoundException e) {
        BaasBoxLogger.debug("Username not found " + username, e);
        return notFound("Username not found");
    } catch (OpenTransactionException e) {
        BaasBoxLogger.error(ExceptionUtils.getFullStackTrace(e));
        throw new RuntimeException(e);
    }
    if (BaasBoxLogger.isTraceEnabled())
        BaasBoxLogger.trace("Method End");
    return ok();
}

From source file:com.ikanow.aleph2.graph.titan.utils.TitanGraphBuildingUtils.java

/** Quick/fast validation of user generated elements (vertices and edges)
 * @param o//from   w  w w .  jav a 2  s.  co m
 * @return
 */
public static Validation<BasicMessageBean, ObjectNode> validateUserElement(final ObjectNode o,
        GraphSchemaBean config) {
    // Same as validation for merged elements, and in addition:
    // - For vertices:
    //   - id is set and is consistent with dedup fields
    // - For edges
    //   - "properties" are valid, and don't have illegal permissions

    return validateMergedElement(o, config).bind(success -> {

        final JsonNode type = o.get(GraphAnnotationBean.type); // (exists and is valid by construction of validateMergedElement)

        final Stream<String> keys_to_check = Patterns.match(type.asText()).<Stream<String>>andReturn()
                .when(t -> GraphAnnotationBean.ElementType.edge.toString().equals(t),
                        __ -> Stream.of(GraphAnnotationBean.inV, GraphAnnotationBean.outV))
                .otherwise(__ -> Stream.of(GraphAnnotationBean.id));

        final Optional<BasicMessageBean> first_error = keys_to_check.<BasicMessageBean>map(k -> {
            final JsonNode key = o.get(k);

            if (null == key) {
                return ErrorUtils.buildErrorMessage("GraphBuilderEnrichmentService", "system.onObjectBatch",
                        ErrorUtils.MISSING_OR_BADLY_FORMED_FIELD, k, "missing");
            } else if (!key.isIntegralNumber() && !key.isObject()) {
                return ErrorUtils.buildErrorMessage("GraphBuilderEnrichmentService", "system.onObjectBatch",
                        ErrorUtils.MISSING_OR_BADLY_FORMED_FIELD, k, "not_long_or_object");
            }

            if (key.isObject()) { // user specified id, check its format is valid               
                if (!config.deduplication_fields().stream().allMatch(f -> key.has(f))) {
                    return ErrorUtils.buildErrorMessage("GraphBuilderEnrichmentService", "system.onObjectBatch",
                            ErrorUtils.MISSING_OR_BADLY_FORMED_FIELD, k, "missing_key_subfield");
                }
            }
            return null;
        }).filter(b -> null != b).findFirst();

        return first_error.<Validation<BasicMessageBean, ObjectNode>>map(b -> Validation.fail(b))
                .orElseGet(() -> Validation.success(o));
    });
}

From source file:com.redhat.lightblue.Request.java

/**
 * Parses the entity, client identification and execution options from the
 * given json object//from ww  w. j  a  v  a  2 s  .com
 */
protected void parse(ObjectNode node) {
    entityVersion = new EntityVersion();
    JsonNode x = node.get("entity");
    if (x != null) {
        entityVersion.setEntity(x.asText());
    }
    x = node.get("entityVersion");
    if (x != null) {
        entityVersion.setVersion(x.asText());
    }
    // TODO: clientIdentification
    x = node.get("execution");
    if (x != null) {
        execution = ExecutionOptions.fromJson((ObjectNode) x);
    }
}

From source file:org.createnet.raptor.models.objects.Action.java

protected void parse(JsonNode json) {

    if (json.isTextual()) {
        name = json.asText();
    } else {//from  www.jav  a  2  s .c o  m

        if (json.has("id")) {
            id = json.get("id").asText();
        }

        if (json.has("status")) {
            status = json.get("status").asText();
        }

        if (json.has("name")) {
            name = json.get("name").asText();
        }

        if (json.has("description")) {
            description = json.get("description").asText();
        }
    }
}

From source file:net.solarnetwork.node.reactor.io.json.JsonReactorSerializationService.java

private String getStringFieldValue(JsonNode node, String fieldName, String placeholder) {
    JsonNode child = node.get(fieldName);
    return (child == null ? placeholder : child.asText());
}