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

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

Introduction

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

Prototype

public ObjectWriter writer() 

Source Link

Document

Convenience method for constructing ObjectWriter with default settings.

Usage

From source file:org.fusesource.restygwt.server.complex.DTOTypeResolverServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    DTO1 one = new DTO1();
    one.name = "Fred Flintstone";
    one.size = 1024;/*from  ww w.java  2  s. c  o m*/

    DTO2 two = new DTO2();
    two.name = "Barney Rubble";
    two.foo = "schmaltzy";

    DTO2 three = new DTO2();
    three.name = "BamBam Rubble";
    three.foo = "dorky";

    resp.setContentType("application/json");
    ObjectMapper om = new ObjectMapper();
    try {
        ObjectWriter writer = om.writer()
                .withType(om.constructType(getClass().getMethod("prototype").getGenericReturnType()));
        writer.writeValue(resp.getOutputStream(), Lists.newArrayList(one, two, three));
    } catch (Exception e) {
        throw new ServletException(e);
    }
}

From source file:tachyon.master.RawTablesTest.java

@Test
public void writeImageTest() throws IOException, TachyonException {
    // crate the RawTables, byte buffers, and output streams
    RawTables rt = new RawTables(new TachyonConf());
    ByteBuffer bb1 = ByteBuffer.allocate(1);
    ByteBuffer bb2 = ByteBuffer.allocate(1);
    ByteBuffer bb3 = ByteBuffer.allocate(1);

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(os);
    ObjectMapper mapper = JsonObject.createObjectMapper();
    ObjectWriter writer = mapper.writer();

    // add elements to the RawTables
    rt.addRawTable(0, 1, bb1);//from   w  w w . ja v a2s  .  c o m
    rt.addRawTable(1, 1, bb2);
    rt.addRawTable(2, 1, bb3);

    // write the image
    rt.writeImage(writer, dos);

    List<Integer> ids = Arrays.asList(0, 1, 2);
    List<Integer> columns = Arrays.asList(1, 1, 1);
    List<ByteBuffer> data = Arrays.asList(bb1, bb2, bb3);

    // decode the written bytes
    ImageElement decoded = mapper.readValue(os.toByteArray(), ImageElement.class);

    // test the decoded ImageElement
    Assert.assertEquals(ids, decoded.get("ids", new TypeReference<List<Integer>>() {
    }));
    Assert.assertEquals(columns, decoded.get("columns", new TypeReference<List<Integer>>() {
    }));
    Assert.assertEquals(data, decoded.get("data", new TypeReference<List<ByteBuffer>>() {
    }));
}

From source file:com.stackify.api.common.AppIdentityServiceTest.java

/**
 * testGetAppIdentity/*w  w  w.  ja v a  2  s  .  c o m*/
 * @throws Exception
 */
@Test
public void testGetAppIdentity() throws Exception {

    final EnvironmentDetail envDetail = EnvironmentDetail.newBuilder().deviceName("device").appName("app")
            .build();

    final AppIdentity appIdentity = AppIdentity.newBuilder().deviceId(123).deviceAppId(789).appNameId("456")
            .appName("app").build();

    final ObjectMapper objectMapper = new ObjectMapper();

    String appIdentityResponse = objectMapper.writer().writeValueAsString(appIdentity);

    final HttpClient httpClient = PowerMockito.mock(HttpClient.class);
    PowerMockito.whenNew(HttpClient.class).withAnyArguments().thenReturn(httpClient);
    PowerMockito.when(httpClient.post(Mockito.anyString(), (byte[]) Mockito.any()))
            .thenReturn(appIdentityResponse);

    ApiConfiguration apiConfig = ApiConfiguration.newBuilder().apiUrl("url").apiKey("key").application("app")
            .envDetail(envDetail).build();

    AppIdentityService service = new AppIdentityService(apiConfig, objectMapper);

    AppIdentity rv = service.getAppIdentity();

    Assert.assertNotNull(rv);
    Assert.assertEquals(Integer.valueOf(123), rv.getDeviceId());
    Assert.assertEquals("456", rv.getAppNameId());
}

From source file:com.basistech.rosette.dm.json.array.ExtendedPropertyTest.java

@Test
public void textExtendedRoundTrip() throws Exception {
    Token.Builder builder = new Token.Builder(0, 5, "abcdefg");
    builder.extendedProperty("veloci", "raptor");
    Token token = builder.build();//  w  w w. j a va  2s  .c  o m
    ObjectMapper mapper = objectMapper();
    ObjectWriter writer = mapper.writer().withDefaultPrettyPrinter();
    ByteArrayOutputStream jsonBlob = new ByteArrayOutputStream();
    writer.writeValue(jsonBlob, token);

    ObjectReader reader = mapper.readerFor(Token.class);
    // just see if we get an exception for now.
    Token token2 = reader.readValue(jsonBlob.toByteArray());
    assertEquals("abcdefg", token2.getText());
    assertEquals(0, token2.getStartOffset());
    assertEquals(5, token2.getEndOffset());
    assertEquals("raptor", token2.getExtendedProperties().get("veloci"));
}

From source file:edu.usd.btl.toolTree.OntoToTree.java

public String jsonToJava(String input) throws Exception {
    try {/*  www  . j  a  v a 2s  .co  m*/
        //File input = new File("C:\\Users\\Tyler\\Documents\\GitHub\\BTL\\src\\ontology_files\\testEdam.json");

        /*
         CONVERT JSON TO JAVA OBJECTS
         */
        //map EDAM ontology JSON to List of objects
        ObjectMapper treeMapper = new ObjectMapper(); //create new Jackson Mapper
        ObjectWriter treeWriter = treeMapper.writer().withDefaultPrettyPrinter();
        List<EDAMNode> ontologyNodes = treeMapper.readValue(input,
                treeMapper.getTypeFactory().constructCollectionType(List.class, EDAMNode.class));
        System.out.println("********SIZE OF ontologyNodes*********" + ontologyNodes.size());
        for (EDAMNode node : ontologyNodes) { //for each ontology node
            System.out.println(node.getName());
            //build tree from ontology nodes

        }
        JsonNode rootNode = treeMapper.readValue(getOntoJson(), JsonNode.class);
        JsonNode tool = rootNode.get("name");

        System.out.println("\n\n\n\n****************************" + tool.toString());
        System.out.println("**** ONTOLOGY SIZE *****" + ontologyNodes.size());
        String jsonOutput = treeWriter.writeValueAsString(ontologyNodes.get(0));
        System.out.println("\n\n****ONTOLOGY JSON OUPUT*****+\n" + jsonOutput);

        //            IplantV1 iplantOutput = BETSConverter.toIplant(betsTool);
        //            String iplantOutputJson = iplantWriter.writeValueAsString(iplantOutput); //write Json as String
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
    return "jsonToJava success";
}

From source file:edu.slu.tpen.transfer.JsonLDExporter.java

public String export() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    return mapper.writer().withDefaultPrettyPrinter().writeValueAsString(manifestData);
}

From source file:controllers.BundlesController.java

public Result export() {
    final Form<ExportBundleRequest> form = Tools.bindMultiValueFormFromRequest(ExportBundleRequest.class);

    if (form.hasErrors()) {
        BreadcrumbList bc = new BreadcrumbList();
        bc.addCrumb("System", routes.SystemController.index(0));
        bc.addCrumb("Content packs", routes.BundlesController.index());
        bc.addCrumb("Create", routes.BundlesController.exportForm());

        Map<String, List> data = getListData();

        flash("error", "Please correct the fields marked in red to export the bundle");
        return badRequest(views.html.system.bundles.export.render(form, currentUser(), bc,
                (List<Input>) data.get("inputs"), (List<Output>) data.get("outputs"),
                (List<Stream>) data.get("streams"), (List<Dashboard>) data.get("dashboards")));
    }/* www.  j  a va 2 s . co  m*/

    try {
        final ExportBundleRequest exportBundleRequest = form.get();
        ConfigurationBundle bundle = bundleService.export(exportBundleRequest);

        response().setContentType(MediaType.JSON_UTF_8.toString());
        response().setHeader("Content-Disposition", "attachment; filename=content_pack.json");
        ObjectMapper m = new ObjectMapper();
        ObjectWriter ow = m.writer().withDefaultPrettyPrinter();
        return ok(ow.writeValueAsString(bundle));
    } catch (IOException e) {
        flash("error", "Could not reach Graylog server");
    } catch (Exception e) {
        flash("error", "Unexpected error exporting configuration bundle, please try again later");
    }

    return redirect(routes.BundlesController.exportForm());
}

From source file:com.auth0.api.internal.SimpleRequest.java

public SimpleRequest(Handler handler, HttpUrl url, OkHttpClient client, ObjectMapper mapper, String httpMethod,
        Class<T> clazz) {//w w  w. j  a  v  a2 s  . c o  m
    super(handler, url, client, mapper.reader(clazz), mapper.writer());
    this.errorReader = mapper.reader(new TypeReference<Map<String, Object>>() {
    });
    this.method = httpMethod;
}

From source file:tachyon.master.DependencyIntegrationTest.java

@Test
public void writeImageTest() throws IOException {
    // create the dependency, output streams, and associated objects
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(os);
    ObjectMapper mapper = JsonObject.createObjectMapper();
    ObjectWriter writer = mapper.writer();

    String cmd = "java test.jar $master:$port";
    List<Integer> parents = new ArrayList<Integer>();
    List<Integer> children = new ArrayList<Integer>();
    List<ByteBuffer> data = new ArrayList<ByteBuffer>();
    Collection<Integer> parentDependencies = new ArrayList<Integer>();
    Dependency dep = new Dependency(0, parents, children, cmd, data, "Dependency Test", "Tachyon Tests", "0.4",
            DependencyType.Narrow, parentDependencies, 0L, mMasterTachyonConf);

    // write the image
    dep.writeImage(writer, dos);//from  www . j  a v a2s.  c  om

    // decode the written bytes
    ImageElement decoded = mapper.readValue(os.toByteArray(), ImageElement.class);
    TypeReference<List<Integer>> intListRef = new TypeReference<List<Integer>>() {
    };
    TypeReference<DependencyType> depTypeRef = new TypeReference<DependencyType>() {
    };
    TypeReference<List<ByteBuffer>> byteListRef = new TypeReference<List<ByteBuffer>>() {
    };

    // test the decoded ImageElement
    // can't use equals(decoded) because ImageElement doesn't have an equals method and can have
    // variable fields
    Assert.assertEquals(0, decoded.getInt("depID").intValue());
    Assert.assertEquals(parents, decoded.get("parentFiles", intListRef));
    Assert.assertEquals(children, decoded.get("childrenFiles", intListRef));
    Assert.assertEquals(data, decoded.get("data", byteListRef));
    Assert.assertEquals(parentDependencies, decoded.get("parentDeps", intListRef));
    Assert.assertEquals(cmd, decoded.getString("commandPrefix"));
    Assert.assertEquals("Dependency Test", decoded.getString("comment"));
    Assert.assertEquals("Tachyon Tests", decoded.getString("framework"));
    Assert.assertEquals("0.4", decoded.getString("frameworkVersion"));
    Assert.assertEquals(DependencyType.Narrow, decoded.get("depType", depTypeRef));
    Assert.assertEquals(0L, decoded.getLong("creationTimeMs").longValue());
    Assert.assertEquals(dep.getUncheckpointedChildrenFiles(),
            decoded.get("unCheckpointedChildrenFiles", intListRef));
}

From source file:com.redhat.jenkins.plugins.ci.messaging.data.FedmsgMessage.java

public String toJson() {
    try {/*from  ww w  . j  av  a 2  s.  co m*/
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ObjectMapper mapper = new ObjectMapper();
        ObjectWriter writer = mapper.writer();
        writer.with(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS).writeValue(os, this);
        os.close();
        return new String(os.toByteArray(), "UTF-8");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}