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.ArrayRangeProjectorTest.java

@Test
public void one_$parent_array_range_projection_with_match() throws Exception {
    Projection p = EvalTestContext//from  ww w . ja v  a2 s.com
            .projectionFromJson("{'field':'field6.$parent.field7','range':[1,2],'project':{'field':'elemf3'}}");
    Projector projector = Projector.getInstance(p, md);
    JsonNode expectedNode = JsonUtils.json("{'field7':[{'elemf3':4},{'elemf3':5}]}".replace('\'', '\"'));

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

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

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

@Test
public void two_$parent_array_range_projection_with_match() throws Exception {
    Projection p = EvalTestContext.projectionFromJson(
            "{'field':'field6.nf7.$parent.$parent.field7','range':[1,2],'project':{'field':'elemf3'}}");
    Projector projector = Projector.getInstance(p, md);
    JsonNode expectedNode = JsonUtils.json("{'field7':[{'elemf3':4},{'elemf3':5}]}".replace('\'', '\"'));

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

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

From source file:windows.webservices.JsonDeserializer.Deserializer.java

@Override
public E deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {
    try {/*from  w  w w  .j  a v  a  2  s .  co m*/

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

        if (StringUtils.isEmpty(json.toString()) || json.toString().length() < 4) {
            return getNullValue(dc);
        }
        E instance = classChild.newInstance();
        ObjectMapper mapper = new ObjectMapper();
        SimpleModule modul = new SimpleModule("parroquia")
                .addDeserializer(Parroquia.class, new ParroquiaDeserializer())
                .addDeserializer(Semana.class, new SemanaDeserializer())
                .addDeserializer(Animal.class, new AnimalDeserializer())
                .addDeserializer(Semana.class, new SemanaDeserializer())
                .addDeserializer(Especie.class, new EspecieDeserializer())
                .addDeserializer(Persona.class, new PersonaDeserializer())
                .addDeserializer(Permiso.class, new PermisoDeserializer())
                .addDeserializer(Usuario.class, new UsuarioDeserializer())
                .addDeserializer(Cliente.class, new ClienteDeserializer())
                .addDeserializer(Municipio.class, new MunicipioDeserializer())
                .addDeserializer(Animal_has_Caso.class, new Animal_has_CasoDeserializer())
                .addDeserializer(Caso.class, new CasoDeserializer())
                .addDeserializer(Novedades.class, new NovedadesDeserializer())
                .addDeserializer(RegistroVacunacion.class, new RegistroVacunacionDeserializer())
                .addDeserializer(RegistroVacunacion_has_Animal.class,
                        new RegistroVacunacion_has_AnimalDeserializer())
                .addDeserializer(Vacunacion.class, new VacunacionDeserializer());
        mapper.registerModule(modul);

        for (Field field : ReflectionUtils.getAllFields(classChild)) {
            Object value = null;
            Iterator<String> it = json.fieldNames();
            String column = null;
            String fieldName = field.getName();
            JsonProperty property = field.getAnnotation(JsonProperty.class);
            if (property != null) {
                fieldName = property.value();
            }
            while (it.hasNext()) {
                String name = it.next();
                if (Objects.equals(name.trim(), fieldName)) {
                    column = name;
                    break;
                }
            }
            if (column == null) {
                System.out.println("No se reconoce la siguente columna : " + fieldName + " de : "
                        + classChild.getSimpleName());
                continue;
            }
            if (field.getType().equals(String.class)) {
                value = json.get(column).asText();
            } else if (Collection.class.isAssignableFrom(field.getType())) {
                if (StringUtils.isNotEmpty(json.get(column).toString())) {
                    ParameterizedType stringListType = (ParameterizedType) field.getGenericType();
                    Class<?> stringListClass = (Class<?>) stringListType.getActualTypeArguments()[0];
                    value = mapper.readValue(json.get(column).toString(),
                            mapper.getTypeFactory().constructCollectionType(List.class, stringListClass));
                } else {
                    value = null;
                }
            } else if (!field.getType().equals(Date.class)) {
                try {
                    value = mapper.convertValue(json.get(column), field.getType());
                } catch (IllegalArgumentException ex) {
                    value = null;
                }
            } else {
                String date = json.get(column).textValue();
                try {
                    if (date != null) {
                        value = d.parse(date.replace("-", "/"));
                    }
                } catch (ParseException ex) {
                    Logger.getLogger(Deserializer.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            ReflectionUtils.runSetter(field, instance, value);
        }
        return instance;
    } catch (InstantiationException | IllegalAccessException ex) {
        Logger.getLogger(Deserializer.class.getName()).log(Level.SEVERE, null, ex);
    }
    return getNullValue(dc);
}

From source file:com.pros.jsontransform.plugin.constraint.ConstraintTaxPercentRange.java

public static void validate(final JsonNode constraintNode, final JsonNode resultNode,
        final ObjectTransformer transformer) throws ObjectTransformerException {
    // expect price and tax nodes in sourceNode that is being processed
    JsonNode sourceNode = transformer.getSourceNode();
    double price = sourceNode.get("price").asDouble();
    double tax = sourceNode.get("tax").asDouble();
    double percentTax = tax * 100 / price;

    boolean ltRangeValid = true;
    boolean gtRangeValid = true;
    JsonNode rangeNode = constraintNode.get(CONSTRAINT_NAME);
    if (rangeNode.isObject()) {
        JsonNode ltNode = rangeNode.path("$less-than");
        if (!ltNode.isMissingNode()) {
            ltRangeValid = percentTax < ltNode.asDouble();
        }//from   w  w  w .j  a  va2  s.  c o m

        JsonNode gtNode = rangeNode.path("$greater-than");
        if (!gtNode.isMissingNode()) {
            gtRangeValid = percentTax > gtNode.asDouble();
        }
    }

    if (ltRangeValid == false || gtRangeValid == false) {
        throw new ObjectTransformerException("Constraint violation [" + CONSTRAINT_NAME + "]"
                + " on transform node " + transformer.getTransformNodeFieldName() + " on result node "
                + resultNode.toString() + " " + percentTax);
    }
}

From source file:nextflow.fs.dx.api.DxHttpClient.java

/**
 * Issues a request against the specified resource and returns the result
 * as a JSON object.//from ww  w  .java 2 s  . com
 */
public JsonNode request(String resource, JsonNode data) throws IOException {
    String dataAsString = data.toString();
    return requestImpl(resource, dataAsString, true).responseJson;
}

From source file:com.ikanow.aleph2.data_model.utils.TestJsonUtils.java

@Test
public void test_foldTuple() {
    final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty());

    LinkedHashMap<String, Object> test1 = new LinkedHashMap<String, Object>();
    test1.put("long", 10L);
    test1.put("double", 1.1);
    test1.put("string", "val");
    test1.put("json", "{\"misc\":true,\"long\":1, \"string\":\"\"}");

    final JsonNode j1 = JsonUtils.foldTuple(test1, mapper, Optional.empty());
    assertEquals("{\"misc\":true,\"long\":10,\"string\":\"val\",\"double\":1.1}", j1.toString());

    LinkedHashMap<String, Object> test2 = new LinkedHashMap<String, Object>();
    test2.put("misc", false);
    test2.put("long", 10L);
    test2.put("json", "{\"misc\":true,\"long\":1, \"string\":\"\"}");
    test2.put("double", 1.1);
    test2.put("string", "val");

    final JsonNode j2 = JsonUtils.foldTuple(test2, mapper, Optional.of("json"));
    assertEquals("{\"misc\":false,\"long\":10,\"string\":\"val\",\"double\":1.1}", j2.toString());

    LinkedHashMap<String, Object> test3 = new LinkedHashMap<String, Object>();
    test3.put("long", mapper.createObjectNode());
    test3.put("double", mapper.createArrayNode());
    test3.put("string", BeanTemplateUtils.build(TestBean.class).with("test1", 4).done().get());
    test3.put("json", "{\"misc\":true,\"long\":1, \"string\":\"\"}");

    final JsonNode j3 = JsonUtils.foldTuple(test3, mapper, Optional.of("json"));
    assertEquals("{\"misc\":true,\"long\":{},\"string\":{\"test1\":4},\"double\":[]}", j3.toString());

    LinkedHashMap<String, Object> test4 = new LinkedHashMap<String, Object>();
    test4.put("misc", BigDecimal.ONE);
    test4.put("long", (int) 10);
    test4.put("double", (float) 1.1);
    test4.put("json", "{\"misc\":true,\"long\":1, \"string\":\"\"}");
    test4.put("string", "val");

    final JsonNode j4 = JsonUtils.foldTuple(test4, mapper, Optional.of("json"));
    assertEquals("{\"misc\":1,\"long\":10,\"string\":\"val\",\"double\":1.1}",
            j4.toString().replaceFirst("1[.]1[0]{6,}[0-9]+", "1.1"));

    try {/*from  w w  w  . ja v a 2s  .c  om*/
        test4.put("json", "{\"misc\":true,\"long\":1, string\":\"\"}"); // (Added json error)
        JsonUtils.foldTuple(test4, mapper, Optional.of("json"));
        fail("Should have thrown JSON exception");
    } catch (Exception e) {
    } // json error, check

    new JsonUtils(); // (just for coverage)      
}

From source file:com.mapr.synth.samplers.RandomWalkSampler.java

@SuppressWarnings("UnusedDeclaration")
public void setPrecision(final JsonNode value) throws IOException {
    if (value.isObject()) {
        sd = new FieldSampler() {
            FieldSampler base = FieldSampler.newSampler(value.toString());

            @Override// www. ja  v  a2  s .  c  o m
            public JsonNode sample() {
                return new DoubleNode(Math.sqrt(1 / base.sample().asDouble()));
            }
        };
    } else {
        this.sd = constant(Math.sqrt(1 / value.asDouble()));
    }
    init();
}

From source file:com.mapr.synth.samplers.RandomWalkSampler.java

@SuppressWarnings("UnusedDeclaration")
public void setVariance(final JsonNode value) throws IOException {
    if (value.isObject()) {
        sd = new FieldSampler() {
            FieldSampler base = FieldSampler.newSampler(value.toString());

            @Override/*from   ww  w .  j a  v  a  2s  .co  m*/
            public JsonNode sample() {
                return new DoubleNode(Math.sqrt(base.sample().asDouble()));
            }
        };
    } else {
        this.sd = constant(Math.sqrt(value.asDouble()));
    }
    init();
}

From source file:com.infinities.keystone4j.admin.v3.group.GroupResourceTest.java

@Test
public void testUpdateGroup() throws ClientProtocolException, IOException {
    group.setDescription("updatedName");
    group.setDescription("updatedDescription");
    GroupWrapper wrapper = new GroupWrapper(group);
    String json = JsonUtils.toJson(wrapper, Views.Advance.class);
    System.err.println(json);/*w  ww.  jav  a  2  s .  c om*/

    PatchClient client = new PatchClient("http://localhost:9998/v3/groups/" + group.getId());
    JsonNode node = client.connect(wrapper);
    System.err.println(node.toString());
    JsonNode groupJ = node.get("group");
    assertEquals(group.getId(), groupJ.get("id").asText());
    assertEquals(group.getName(), groupJ.get("name").asText());
    assertEquals(group.getDescription(), groupJ.get("description").asText());
    assertEquals(group.getDomain().getId(), groupJ.get("domain_id").asText());
    assertNotNull(groupJ.get("links"));
    assertNotNull(groupJ.get("links").get("self").asText());
}

From source file:com.redhat.lightblue.util.ErrorTest.java

@Test
public void toJson_empty() throws Exception {
    Method method = Error.class.getMethod("get", String.class);
    Error e = (Error) method.invoke(null, new Object[] { null });
    JsonNode node = e.toJson();
    JSONAssert.assertEquals("{}", node.toString(), false);
}