Example usage for com.fasterxml.jackson.databind ObjectMapper writeValue

List of usage examples for com.fasterxml.jackson.databind ObjectMapper writeValue

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper writeValue.

Prototype

public void writeValue(Writer w, Object value)
        throws IOException, JsonGenerationException, JsonMappingException 

Source Link

Document

Method that can be used to serialize any Java value as JSON output, using Writer provided.

Usage

From source file:net.roboconf.dm.rest.commons.json.JSonBindingUtilsTest.java

@Test
public void testInstanceBinding_4() throws Exception {

    final String result = "{\"name\":\"server\",\"path\":\"/server\",\"status\":\"STOPPING\",\"component\":{\"name\":\"server-component\"}}";
    ObjectMapper mapper = JSonBindingUtils.createObjectMapper();

    Component comp = new Component("server-component");
    Instance inst = new Instance("server").status(InstanceStatus.STOPPING).component(comp);

    StringWriter writer = new StringWriter();
    mapper.writeValue(writer, inst);
    String s = writer.toString();

    Assert.assertEquals(result, s);//from  w  ww .  j  a v a2 s  .c  o m
    Instance readInst = mapper.readValue(result, Instance.class);
    Assert.assertEquals(inst, readInst);
    Assert.assertEquals(inst.getName(), readInst.getName());
    Assert.assertEquals(inst.getStatus(), readInst.getStatus());
    Assert.assertEquals(inst.channels, readInst.channels);
    Assert.assertEquals(inst.getComponent().getName(), readInst.getComponent().getName());
}

From source file:com.github.jasonruckman.gzip.AbstractBenchmark.java

private void initializeJackson() {
    try {//from  w  ww  .  ja  v  a 2 s.com
        ObjectMapper mapper = new ObjectMapper();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPOutputStream gzos = new GZIPOutputStream(baos);
        mapper.writeValue(gzos, sampleData);
        gzos.close();
        serializedJacksonData = baos.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.opencb.opencga.app.cli.main.OpenCGAMainOld.java

private static void saveUserFile(SessionFile sessionFile) throws IOException {
    Path opencgaDirectoryPath = Paths.get(System.getProperty("user.home"), ".opencga");
    if (!opencgaDirectoryPath.toFile().exists()) {
        Files.createDirectory(opencgaDirectoryPath);
    }/*from w  w w.ja  v  a2  s.c o  m*/
    FileUtils.checkDirectory(opencgaDirectoryPath, true);
    java.io.File file = opencgaDirectoryPath.resolve("opencga.yml").toFile();
    ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
    objectMapper.writeValue(file, sessionFile);
}

From source file:fll.web.api.CategoryScheduleMappingServlet.java

@Override
protected final void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException, ServletException {
    final ServletContext application = getServletContext();

    final DataSource datasource = ApplicationAttributes.getDataSource(application);
    Connection connection = null;
    try {/*from  w w  w  .jav a  2  s.com*/
        connection = datasource.getConnection();

        final ObjectMapper jsonMapper = new ObjectMapper();

        response.reset();
        response.setContentType("application/json");
        final PrintWriter writer = response.getWriter();

        final int currentTournament = Queries.getCurrentTournament(connection);

        final Collection<CategoryColumnMapping> mappings = CategoryColumnMapping.load(connection,
                currentTournament);

        jsonMapper.writeValue(writer, mappings);
    } catch (final SQLException e) {
        LOGGER.fatal("Database Exception", e);
        throw new RuntimeException(e);
    } finally {
        SQLFunctions.close(connection);
    }

}

From source file:io.fabric8.maven.plugin.mojo.internal.HelmIndexMojo.java

@Override
public void executeInternal() throws MojoExecutionException, MojoFailureException {
    outputFile.getParentFile().mkdirs();

    log.info("Creating Helm Chart Index file at: %s", outputFile);
    List<ArtifactDTO> artifacts = searchMaven("?q=l:%22helm%22");

    ChartsRepository repository = new ChartsRepository();
    Map<String, ChartInfo> charts = new TreeMap<>();
    for (ArtifactDTO artifact : artifacts) {
        addChartInfo(repository, charts, artifact);
    }//from w w  w  . j a  va2 s. co m

    Set<Map.Entry<String, ChartInfo>> entries = charts.entrySet();
    for (Map.Entry<String, ChartInfo> entry : entries) {
        getLog().debug("" + entry.getKey() + " = " + entry.getValue());
    }
    try {
        ObjectMapper mapper = KubernetesHelper.createYamlObjectMapper();
        mapper.writeValue(outputFile, repository);
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to write results as YAML to: " + outputFile + ". " + e, e);
    }

    generateHTML(outputHtmlFile, charts);
}

From source file:com.cedarsoft.serialization.test.performance.JacksonTest.java

@Test
public void testMapper() throws Exception {
    ObjectMapper mapper = new ObjectMapper();

    com.cedarsoft.serialization.test.performance.jaxb.FileType fileType = new com.cedarsoft.serialization.test.performance.jaxb.FileType(
            "Canon Raw", new com.cedarsoft.serialization.test.performance.jaxb.Extension(".", "cr2", true),
            false);// w  w w .j av a2s. co  m
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    mapper.writeValue(out, fileType);

    JsonUtils.assertJsonEquals(JSON, out.toString());
}

From source file:org.fcrepo.auth.roles.common.integration.AbstractRolesIT.java

protected String makeJson(final Map<String, List<String>> roles) {
    final ObjectMapper mapper = new ObjectMapper();
    final StringWriter sw = new StringWriter();
    try {/* w ww  .  ja v  a  2 s . c  o  m*/
        mapper.writeValue(sw, roles);
        return sw.toString();
    } catch (final IOException e) {
        throw new Error(e);
    }
}

From source file:com.netflix.genie.common.client.TestBaseGenieClient.java

/**
 * Test to make sure if response is successful entity is returned.
 *
 * @throws GenieException  Random issues.
 * @throws ClientException A http client.
 * @throws IOException     IOException./*from   w w  w .  ja v a 2s  .c o  m*/
 */
@Test
public void testExecuteRequestSuccessSingleEntity() throws GenieException, ClientException, IOException {
    Mockito.when(this.response.isSuccess()).thenReturn(true);

    final ObjectMapper mapper = new ObjectMapper();
    final StringWriter writer = new StringWriter();
    mapper.writeValue(writer, APPLICATION);
    final String inputEntity = writer.toString();
    final InputStream is = new ByteArrayInputStream(inputEntity.getBytes(Charset.forName("UTF-8")));
    Mockito.when(this.response.getInputStream()).thenReturn(is);

    Mockito.when(this.restClient.executeWithLoadBalancer(this.request)).thenReturn(this.response);

    final Application outputEntity = (Application) this.client.executeRequest(this.request, null,
            Application.class);

    Assert.assertEquals(APPLICATION.getName(), outputEntity.getName());
    Assert.assertEquals(APPLICATION.getUser(), outputEntity.getUser());
    Assert.assertEquals(APPLICATION.getVersion(), outputEntity.getVersion());
    Assert.assertEquals(APPLICATION.getStatus(), outputEntity.getStatus());

    Mockito.verify(this.response, Mockito.times(1)).isSuccess();
    Mockito.verify(this.response, Mockito.times(1)).getInputStream();
}

From source file:de.undercouch.bson4jackson.BsonGeneratorTest.java

private BSONObject generateAndParse(Map<String, Object> data, BsonGenerator.Feature... featuresToEnable)
        throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BsonFactory bsonFactory = new BsonFactory();
    if (featuresToEnable != null) {
        for (BsonGenerator.Feature fe : featuresToEnable) {
            bsonFactory.enable(fe);/*from w w w  .  j av  a2 s  .  c  o  m*/
        }
    }
    ObjectMapper om = new ObjectMapper(bsonFactory);
    om.registerModule(new BsonModule());
    om.writeValue(baos, data);

    byte[] r = baos.toByteArray();
    ByteArrayInputStream bais = new ByteArrayInputStream(r);

    BSONDecoder decoder = new BasicBSONDecoder();
    return decoder.readObject(bais);
}

From source file:io.fabric8.maven.plugin.ManifestIndexMojo.java

@Override
public void executeInternal() throws MojoExecutionException, MojoFailureException {
    outputFile.getParentFile().mkdirs();

    log.info("Creating Manifest Index file at: %s", outputFile);
    List<ArtifactDTO> artifacts = searchMaven("?q=l:%22kubernetes%22");
    Map<String, ManifestInfo> manifests = new TreeMap<>();
    for (ArtifactDTO artifact : artifacts) {
        addManifestInfo(manifests, artifact);
    }//  www .  j  ava 2 s. c om

    Set<Map.Entry<String, ManifestInfo>> entries = manifests.entrySet();
    for (Map.Entry<String, ManifestInfo> entry : entries) {
        getLog().debug("" + entry.getKey() + " = " + entry.getValue());
    }
    try {
        ObjectMapper mapper = KubernetesHelper.createYamlObjectMapper();
        mapper.writeValue(outputFile, manifests);
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to write results as YAML to: " + outputFile + ". " + e, e);
    }

    generateHTML(new File(outputHtmlDir, "kubernetes.html"), manifests, true, kubernetesIntroductionHtmlFile,
            kubernetesHeadHtmlFile, kubernetesFooterHtmlFile);
    generateHTML(new File(outputHtmlDir, "openshift.html"), manifests, false, openshiftIntroductionHtmlFile,
            openshiftHeadHtmlFile, openshiftFooterHtmlFile);
}