Example usage for com.fasterxml.jackson.databind ObjectWriter writeValueAsString

List of usage examples for com.fasterxml.jackson.databind ObjectWriter writeValueAsString

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectWriter writeValueAsString.

Prototype

@SuppressWarnings("resource")
public String writeValueAsString(Object value) throws JsonProcessingException 

Source Link

Document

Method that can be used to serialize any Java value as a String.

Usage

From source file:org.osiam.resource_server.resources.helper.AttributesRemovalHelper.java

private <T extends Resource> SCIMSearchResult<T> getJsonResponseWithAdditionalFields(
        SCIMSearchResult<T> scimSearchResult, Map<String, Object> parameterMap) {

    ObjectMapper mapper = new ObjectMapper();

    String[] fieldsToReturn = (String[]) parameterMap.get("attributes");
    ObjectWriter writer = getObjectWriter(mapper, fieldsToReturn);

    try {/*from  www  .  j a  va2s.co  m*/
        String resourcesString = writer.writeValueAsString(scimSearchResult.getResources());
        JsonNode resourcesNode = mapper.readTree(resourcesString);

        String schemasString = writer.writeValueAsString(scimSearchResult.getSchemas());
        JsonNode schemasNode = mapper.readTree(schemasString);

        ObjectNode rootNode = mapper.createObjectNode();
        rootNode.put("totalResults", scimSearchResult.getTotalResults());
        rootNode.put("itemsPerPage", scimSearchResult.getItemsPerPage());
        rootNode.put("startIndex", scimSearchResult.getStartIndex());
        rootNode.put("schemas", schemasNode);
        rootNode.put("Resources", resourcesNode);

        return mapper.readValue(rootNode.toString(), SCIMSearchResult.class);
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:de.tudarmstadt.ukp.clarin.webanno.crowdflower.CrowdJob.java

/**
 * Serialize the template to a JSON string
 * @return//from w  w w  . ja  va  2 s .  com
 * @throws JsonGenerationException
 * @throws JsonMappingException
 * @throws IOException
 */

String getTemplateAsString() throws JsonGenerationException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    ObjectWriter writer = mapper.writer().withDefaultPrettyPrinter();
    return writer.writeValueAsString(template);
}

From source file:cern.jarrace.controller.rest.controller.AgentContainerControllerTest.java

private String getJson(Object object) throws JsonProcessingException {
    ObjectWriter writer = new ObjectMapper().writer();
    return writer.writeValueAsString(object);
}

From source file:io.fabric8.cxf.endpoint.JsonSchemaLookup.java

public String getSchemaForClass(Class<?> clazz) {
    LOG.info("Looking up schema for " + clazz.getCanonicalName());
    String name = clazz.getName();
    try {/*from   w w  w. ja  va2  s.  co  m*/
        ObjectWriter writer = mapper.writer().with(new FourSpacePrettyPrinter());
        JsonSchemaGenerator jsg = new JsonSchemaGenerator(mapper);
        JsonSchema jsonSchema = jsg.generateSchema(clazz);
        return writer.writeValueAsString(jsonSchema);
    } catch (Exception e) {
        LOG.log(Level.FINEST, "Failed to generate JSON schema for class " + name, e);
        return "";
    }
}

From source file:org.apereo.portal.events.aggr.JpaStatisticalSummaryTest.java

public void testStorelessUnivariateStatistic(StorelessUnivariateStatistic sus, double expected)
        throws Exception {

    assertEquals(expected, sus.getResult(), 0.1);

    final ObjectMapper mapper = new ObjectMapper();
    mapper.findAndRegisterModules();//from w w  w .  j av  a  2 s  . c  om

    //Configure Jackson to just use fields
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    mapper.setVisibility(PropertyAccessor.GETTER, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.IS_GETTER, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.SETTER, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.CREATOR, Visibility.NONE);

    mapper.addMixInAnnotations(Object.class, IgnoreTypeMixIn.class);

    final FilterProvider filters = new SimpleFilterProvider().addFilter("storedDataFilter",
            SimpleBeanPropertyFilter.serializeAllExcept("storedData"));

    final ObjectWriter ssWriter = mapper.writer(filters);
    final ObjectReader ssReader = mapper.reader(sus.getClass());

    final String susString = ssWriter.writeValueAsString(sus);
    System.out.println(susString);
    final StorelessUnivariateStatistic newSus = ssReader.readValue(susString);

    assertEquals(expected, newSus.getResult(), 0.1);
}

From source file:com.linecorp.armeria.server.grpc.GrpcDocServiceTest.java

@Test
public void testOk() throws Exception {
    List<ServiceEntry> entries = ImmutableList.of(
            new ServiceEntry(TEST_SERVICE_DESCRIPTOR,
                    ImmutableList.of(new EndpointInfo("*", "/test/armeria.grpc.testing.TestService/", "",
                            GrpcSerializationFormats.PROTO.mediaType(),
                            ImmutableSet.of(GrpcSerializationFormats.PROTO.mediaType(),
                                    GrpcSerializationFormats.JSON.mediaType(),
                                    GrpcSerializationFormats.PROTO_WEB.mediaType(),
                                    GrpcSerializationFormats.JSON_WEB.mediaType(),
                                    MediaType.PROTOBUF.withParameter("protocol", "gRPC"),
                                    MediaType.JSON_UTF_8.withParameter("protocol", "gRPC"))))),
            new ServiceEntry(RECONNECT_SERVICE_DESCRIPTOR, ImmutableList.of(new EndpointInfo("*",
                    "/armeria.grpc.testing.ReconnectService/", "", GrpcSerializationFormats.PROTO,
                    ImmutableSet.of(GrpcSerializationFormats.PROTO, GrpcSerializationFormats.PROTO_WEB)))));
    final ObjectMapper mapper = new ObjectMapper();

    final JsonNode expectedJson = mapper.valueToTree(new GrpcDocServicePlugin().generate(entries));

    // The specification generated by GrpcDocServicePlugin does not include the examples specified
    // when building a DocService, so we add them manually here.
    addExamples(expectedJson);//from ww w  . j  a va  2 s .com

    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        final HttpGet req = new HttpGet(specificationUri());

        try (CloseableHttpResponse res = hc.execute(req)) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
            final JsonNode actualJson = mapper.readTree(EntityUtils.toString(res.getEntity()));

            // The specification generated by ThriftDocServicePlugin does not include the docstrings
            // because it's injected by the DocService, so we remove them here for easier comparison.
            removeDocStrings(actualJson);

            // Convert to the prettified strings for human-readable comparison.
            final ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
            final String actualJsonString = writer.writeValueAsString(actualJson);
            final String expectedJsonString = writer.writeValueAsString(expectedJson);
            assertThat(actualJsonString).isEqualTo(expectedJsonString);
        }
    }
}

From source file:com.orange.cepheus.broker.persistence.RegistrationsRepository.java

/**
 * Update a registration.//from ww  w  . j  a v  a  2  s.  c  o m
 * @param registration
 * @throws RegistrationPersistenceException
 */
public void updateRegistration(Registration registration) throws RegistrationPersistenceException {
    try {
        //serialization
        ObjectWriter writer = mapper.writer();
        RegisterContext registerContext = registration.getRegisterContext();
        String registerContextString = writer.writeValueAsString(registerContext);
        String expirationDate = registration.getExpirationDate().toString();
        jdbcTemplate.update("update t_registrations set expirationDate=? , registerContext=? where id=?",
                expirationDate, registerContextString, registerContext.getRegistrationId());
    } catch (Exception e) {
        throw new RegistrationPersistenceException(e);
    }
}

From source file:com.orange.cepheus.broker.persistence.RegistrationsRepository.java

/**
 * Save a registration.//  www  .j  ava  2  s. c om
 * @param registration
 * @throws RegistrationPersistenceException
 */
public void saveRegistration(Registration registration) throws RegistrationPersistenceException {
    try {
        //Mapping from model to database model
        ObjectWriter writer = mapper.writer();
        RegisterContext registerContext = registration.getRegisterContext();
        String registerContextString = writer.writeValueAsString(registerContext);
        String expirationDate = registration.getExpirationDate().toString();
        //insert into database
        jdbcTemplate.update("insert into t_registrations(id,expirationDate,registerContext) values(?,?,?)",
                registerContext.getRegistrationId(), expirationDate, registerContextString);
    } catch (Exception e) {
        throw new RegistrationPersistenceException(e);
    }
}

From source file:org.usd.edu.btl.cli.ConvertBets.java

public void toBld(String inputS, String output) {
    ObjectMapper mapper = new ObjectMapper(); //create new Jackson Mapper
    File input = new File(inputS);
    //mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); //ignore the extra BETS fields
    BETSV1 betsTool;/*from w  w w.  j  a  v  a  2  s  .c  o m*/

    try {
        //map input json files to iplant class
        betsTool = mapper.readValue(input, BETSV1.class);

        //convert bets to BioExtract
        BLDV1 bExtOutput = BETSConverter.toBld(betsTool); //pass the iplant tool spec, convert to bets

        ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();

        if (output == null) {
            /*===============PRINT JSON TO CONSOLE AND FILES =================== */
            ObjectWriter bExtWriter = mapper.writer().withDefaultPrettyPrinter();
            String bExtJson = bExtWriter.writeValueAsString(bExtOutput); //write Json as String

            System.err.println("=== BETS TO BLD JSON === \n");
            System.out.println(bExtJson);
        } else {
            //write to files
            ow.writeValue(new File(output), bExtOutput);
            System.err.println(output + " has been created successfully");
        }
    } catch (IOException e) {
        System.err.println(e.getMessage());
    }
}

From source file:org.usd.edu.btl.cli.ConvertBets.java

public void toBioextract(String inputS, String output) {
    ObjectMapper mapper = new ObjectMapper(); //create new Jackson Mapper
    File input = new File(inputS);

    //mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); //ignore the extra BETS fields
    BETSV1 betsTool;/*  www. ja  v  a  2  s  .c  om*/

    try {
        //map input json files to iplant class
        betsTool = mapper.readValue(input, BETSV1.class);

        //convert bets to BioExtract
        BioExtV1 bExtOutput = BETSConverter.toBioExtract(betsTool); //pass the iplant tool spec, convert to bets
        ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();

        if (output == null) {
            /*===============PRINT JSON TO CONSOLE AND FILES =================== */
            ObjectWriter bExtWriter = mapper.writer().withDefaultPrettyPrinter();
            String bExtJson = bExtWriter.writeValueAsString(bExtOutput); //write Json as String

            System.err.println("=== BETS TO BioExtract JSON === \n");
            System.out.println(bExtJson);
        } else {
            //write to files
            ow.writeValue(new File(output), bExtOutput);
            System.err.println(output + " has been created successfully");
        }
    } catch (IOException e) {
        System.err.println(e.getMessage());
    }
}