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:com.redhat.lightblue.crud.validator.StringLengthChecker.java

@Override
public void checkConstraint(ConstraintValidator validator, FieldTreeNode fieldMetadata, Path fieldMetadataPath,
        FieldConstraint constraint, Path valuePath, JsonDoc doc, JsonNode fieldValue) {
    int value = ((StringLengthConstraint) constraint).getValue();
    String type = ((StringLengthConstraint) constraint).getType();
    int len = fieldValue.asText().length();
    if (StringLengthConstraint.MINLENGTH.equals(type)) {
        if (len < value) {
            validator.addDocError(Error.get(CrudConstants.ERR_TOO_SHORT, fieldValue.asText()));
        }//from   w w w .  j  a  v a2s  . c  om
    } else {
        if (len > value) {
            validator.addDocError(Error.get(CrudConstants.ERR_TOO_LONG, fieldValue.asText()));
        }
    }
}

From source file:org.thingsplode.synapse.serializers.jackson.adapters.MediaTypeDeserializer.java

@Override
public MediaType deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    JsonNode node = p.readValueAsTree();
    JsonNode mTypeNode = node.get("media_type");
    if (mTypeNode == null) {
        mTypeNode = node.get("content_type");
    }/* w  ww  .jav a2 s  .  com*/
    if (mTypeNode == null || Util.isEmpty(mTypeNode.asText())) {
        return null;
    } else {
        return new MediaType(mTypeNode.asText());
    }
}

From source file:org.activiti.rest.service.api.legacy.TaskOperationResource.java

@Put
public ObjectNode executeTaskOperation(Representation entity) {
    if (authenticate() == false)
        return null;

    String taskId = (String) getRequest().getAttributes().get("taskId");
    String operation = (String) getRequest().getAttributes().get("operation");

    if ("claim".equals(operation)) {
        try {/*w  w w .  j  a  v  a2  s. c  om*/
            ActivitiUtil.getTaskService().claim(taskId, loggedInUser);
        } catch (ActivitiTaskAlreadyClaimedException atece) {
            // Explicitally throw an exception that is not the ActivitiTaskAlreadyClaimedException, as this causes a 409 instead of a 500
            throw new IllegalStateException(atece);
        }
    } else if ("unclaim".equals(operation)) {
        ActivitiUtil.getTaskService().claim(taskId, null);
    } else if ("complete".equals(operation)) {

        Map<String, String> variables = new HashMap<String, String>();
        try {
            if (entity != null) {
                String startParams = entity.getText();
                if (StringUtils.isNotEmpty(startParams)) {
                    JsonNode startJSON = new ObjectMapper().readTree(startParams);
                    Iterator<String> itName = startJSON.fieldNames();
                    while (itName.hasNext()) {
                        String name = itName.next();
                        JsonNode valueNode = startJSON.path(name);
                        variables.put(name, valueNode.asText());
                    }
                }
            }
        } catch (Exception e) {
            if (e instanceof ActivitiException) {
                throw (ActivitiException) e;
            }
            throw new ActivitiException("Did not receive the operation parameters", e);
        }

        variables.remove("taskId");
        ActivitiUtil.getFormService().submitTaskFormData(taskId, variables);

    } else if ("assign".equals(operation)) {
        String userId = null;
        try {
            String startParams = entity.getText();
            JsonNode startJSON = new ObjectMapper().readTree(startParams);
            userId = startJSON.path("userId").textValue();
        } catch (Exception e) {
            throw new ActivitiException("Did not assign the operation parameters", e);
        }
        ActivitiUtil.getTaskService().setAssignee(taskId, userId);
    } else {
        throw new ActivitiIllegalArgumentException("'" + operation + "' is not a valid operation");
    }

    ObjectNode successNode = new ObjectMapper().createObjectNode();
    successNode.put("success", true);
    return successNode;
}

From source file:la.alsocan.jsonshapeshifter.transformations.AdvancedCollectionTransformationTest.java

@Test
public void embeddedCollectionBindingShouldProduceTheRightValues() throws IOException {

    Schema source = Schema.buildSchema(new ObjectMapper().readTree(DataSet.EMBEDDED_COLLECTION_SCHEMA));
    Schema target = Schema.buildSchema(new ObjectMapper().readTree(DataSet.EMBEDDED_COLLECTION_SCHEMA));
    Transformation t = new Transformation(source, target);

    Iterator<SchemaNode> it = t.toBind();
    t.bind(it.next(), new ArrayNodeBinding((SchemaArrayNode) source.at("/someArrayOfArray")));
    t.bind(it.next(), new ArrayNodeBinding((SchemaArrayNode) source.at("/someArrayOfArray/{i}")));
    t.bind(it.next(), new StringNodeBinding(source.at("/someArrayOfArray/{i}/{i}")));

    JsonNode payload = new ObjectMapper().readTree(DataSet.EMBEDDED_COLLECTION_PAYLOAD);
    JsonNode result = t.apply(payload);//  w  w w  . ja v a 2s  .co m

    int index = 0;
    String[] expectedStrings = new String[] { "a", "b", "c" };
    for (JsonNode node : (ArrayNode) result.at("/someArrayOfArray/0")) {
        assertThat(node.asText(), is(equalTo(expectedStrings[index++])));
    }

    index = 0;
    expectedStrings = new String[] { "d", "e" };
    for (JsonNode node : (ArrayNode) result.at("/someArrayOfArray/1")) {
        assertThat(node.asText(), is(equalTo(expectedStrings[index++])));
    }

    index = 0;
    expectedStrings = new String[] { "f" };
    for (JsonNode node : (ArrayNode) result.at("/someArrayOfArray/2")) {
        assertThat(node.asText(), is(equalTo(expectedStrings[index++])));
    }
}

From source file:com.redhat.lightblue.metadata.types.StringTypeTest.java

@Test
public void testToJson() {
    JsonNodeFactory jsonNodeFactory = new JsonNodeFactory(true);
    JsonNode jsonNode = stringType.toJson(jsonNodeFactory, "json");
    assertTrue(new Boolean(jsonNode.asText().equals("json")));
}

From source file:org.neo4j.ogm.drivers.http.response.AbstractHttpResponse.java

/**
 * Returns the first set of columns from the JSON response.
 * Note that the current implementation expects that columns be standard across all statements in a Cypher transaction.
 *
 * @return the first set of columns from a JSON response
 *//*from  ww  w  .  j av a 2s .c  o  m*/
public String[] columns() {
    if (columns == null) {
        List<String> columnsList = new ArrayList<>();
        List<JsonNode> columnsNodes = responseNode.findValues("columns");
        if (columnsNodes != null && columnsNodes.size() > 0) {
            JsonNode firstColumnsNode = columnsNodes.get(0);
            for (JsonNode columnNode : firstColumnsNode) {
                columnsList.add(columnNode.asText());
            }
            columns = new String[columnsList.size()];
            columns = columnsList.toArray(columns);
        }
    }
    return columns;
}

From source file:com.redhat.lightblue.mongo.config.MongoMetadataConfiguration.java

@Override
public void initializeFromJson(JsonNode node) {
    // init from super (gets hook configuration parsers and anything else that's common)
    super.initializeFromJson(node);

    if (node != null) {
        JsonNode x = node.get("dataSource");
        if (x != null) {
            datasource = x.asText();
        }/*from w  w  w .ja v a2 s .com*/
        x = node.get("collection");
        if (x != null) {
            collection = x.asText();
        }
    }
}

From source file:io.gravitee.definition.jackson.datatype.services.healthcheck.deser.HealthCheckDeserializer.java

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

    HealthCheck healthCheck = new HealthCheck();

    final JsonNode intervalNode = node.get("interval");
    if (intervalNode != null) {
        healthCheck.setInterval(intervalNode.asLong());
    } else {//w w w.j a v a 2 s  .  co  m
        throw ctxt.mappingException("[healthcheck] Interval is required");
    }

    final JsonNode unitNode = node.get("unit");
    if (unitNode != null) {
        healthCheck.setUnit(TimeUnit.valueOf(unitNode.asText().toUpperCase()));
    } else {
        throw ctxt.mappingException("[healthcheck] Unit is required");
    }

    final JsonNode requestNode = node.get("request");
    if (requestNode != null) {
        healthCheck.setRequest(requestNode.traverse(jp.getCodec()).readValueAs(Request.class));
    } else {
        throw ctxt.mappingException("[healthcheck] Request is required");
    }

    final JsonNode expectationNode = node.get("expectation");
    if (expectationNode != null) {
        healthCheck.setExpectation(expectationNode.traverse(jp.getCodec()).readValueAs(Expectation.class));
    } else {
        Expectation expectation = new Expectation();
        expectation.setAssertions(Collections.singletonList(Expectation.DEFAULT_ASSERTION));
        healthCheck.setExpectation(expectation);
    }

    final JsonNode healthCheckEnabledNode = node.get("enabled");
    if (healthCheckEnabledNode != null) {
        healthCheck.setEnabled(healthCheckEnabledNode.asBoolean(true));
    } else {
        healthCheck.setEnabled(true);
    }

    return healthCheck;
}

From source file:la.alsocan.jsonshapeshifter.transformations.HandlebarsBindingTransformationTest.java

@Test
public void nodeHandlebarsBindingShouldProduceRightResult() throws IOException {

    Schema source = Schema.buildSchema(new ObjectMapper().readTree(DataSet.SIMPLE_COLLECTION_SCHEMA));
    Schema target = Schema.buildSchema(new ObjectMapper().readTree(DataSet.SIMPLE_COLLECTION_SCHEMA));
    Transformation t = new Transformation(source, target);

    String template = "{{someString}} {{stringInArray}}";
    Map<String, Binding> params = new HashMap<>();
    params.put("someString", new StringNodeBinding(source.at("/someString")));
    params.put("stringInArray", new StringNodeBinding(source.at("/someStringArray/{i}")));

    Iterator<SchemaNode> it = t.toBind();
    it.next();/*w w w.ja  va 2s.  co  m*/
    t.bind(it.next(), new ArrayNodeBinding((SchemaArrayNode) source.at("/someStringArray")));
    t.bind(it.next(), new StringHandlebarsBinding(template, params));

    JsonNode payload = new ObjectMapper().readTree(DataSet.SIMPLE_COLLECTION_PAYLOAD);
    JsonNode result = t.apply(payload);

    String[] expectedStrings = new String[] { "string1 a", "string1 b", "string1 c", "string1 d", "string1 e" };
    for (int i = 0; i < 5; i++) {
        JsonNode node = result.at("/someStringArray/" + i);
        assertThat(node, is(not(nullValue())));
        assertThat(node.asText(), is(equalTo(expectedStrings[i])));
    }
}

From source file:net.proest.librepilot.web.handler.ObjectHandler.java

public void handlePost(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    PrintWriter out = response.getWriter();
    BufferedReader br = request.getReader();
    String json = "";
    while (br.ready()) {
        json += br.readLine();/*w ww.jav  a 2  s. c om*/
    }
    System.out.println(json);
    json = json.replaceFirst("json=", "");
    System.out.println(json);
    json = URLDecoder.decode(json, "utf-8");
    System.out.println(json);
    System.out.println();
    ObjectMapper mapper = new ObjectMapper();
    JsonNode actualObj = mapper.readTree(json);
    out.println(actualObj.asText());
    out.println(mapper.toString());
}