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:org.comicwiki.Repository.java

public void print() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(System.out, cache.values());
}

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

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

    final boolean authenticated = WebUtils.checkAuthenticated(request, application);
    final AuthResult result = new AuthResult(authenticated);

    final ObjectMapper jsonMapper = new ObjectMapper();

    response.reset();// w  ww  . j  ava 2 s .c  o m
    response.setContentType("application/json");
    final PrintWriter writer = response.getWriter();

    jsonMapper.writeValue(writer, result);

}

From source file:com.github.helenusdriver.driver.tools.Tool.java

/**
 * Creates all defined Json schemas based on the provided command line
 * information.//w  ww . j av  a2  s .c o m
 *
 * @author paouelle
 *
 * @param  line the command line information
 * @throws Exception if an error occurs while creating schemas
 * @throws LinkageError if the linkage fails for one of the specified entity
 *         class
 * @throws ExceptionInInitializerError if the initialization provoked by one
 *         of the specified entity class fails
 * @throws IllegalArgumentException if no pojos are found in any of the
 *         specified packages
 */
private static void createJsonSchemas(CommandLine line) throws Exception {
    final String[] opts = line.getOptionValues(Tool.jsons.getLongOpt());
    @SuppressWarnings({ "cast", "unchecked", "rawtypes" })
    final Map<String, String> suffixes = (Map<String, String>) (Map) line
            .getOptionProperties(Tool.suffixes.getOpt());
    final boolean matching = line.hasOption(Tool.matches_only.getLongOpt());
    final Map<Class<?>, JsonSchema> schemas = new LinkedHashMap<>();

    System.out.print(
            Tool.class.getSimpleName() + ": searching for Json schema definitions in " + Arrays.toString(opts));
    if (!suffixes.isEmpty()) {
        System.out.print(" with " + (matching ? "matching " : "") + "suffixes " + suffixes);
    }
    System.out.println();
    // start by assuming we have classes; if we do they will be nulled from the array
    Tool.createJsonSchemasFromClasses(opts, suffixes, matching, schemas);
    // now deal with the rest as if they were packages
    Tool.createJsonSchemasFromPackages(opts, suffixes, matching, schemas);
    if (schemas.isEmpty()) {
        System.out.println(
                Tool.class.getSimpleName() + ": no Json schemas found matching the specified criteria");
    } else {
        final String output = line.getOptionValue(Tool.output.getLongOpt(), "." // defaults to current directory
        );
        final File dir = new File(output);

        if (!dir.exists()) {
            dir.mkdirs();
        }
        org.apache.commons.lang3.Validate.isTrue(dir.isDirectory(), "not a directory: %s", dir);
        final ObjectMapper m = new ObjectMapper();

        m.enable(SerializationFeature.INDENT_OUTPUT);
        for (final Map.Entry<Class<?>, JsonSchema> e : schemas.entrySet()) {
            m.writeValue(new File(dir, e.getKey().getName() + ".json"), e.getValue());
            //System.out.println(s.getType() + " = " + m.writeValueAsString(s));
        }
    }
}

From source file:org.lockss.crawljax.TestRequestResponse.java

public void testFromJson() throws Exception {
    File outFile = new File("test.json");
    outFile.deleteOnExit();/*w ww.  ja v a2s . com*/
    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(outFile, mReqResp);
    Request req = mReqResp.getRequest();
    Response resp = mReqResp.getResponse();

    // now test our streaming reader...
    JsonParser parser = factory.createParser(outFile);
    AjaxRequestResponse rr = AjaxRequestResponse.fromJson(parser);
    // same request data
    AjaxRequestResponse.Request rr_req = rr.getRequest();
    AjaxRequestResponse.Response rr_resp = rr.getResponse();

    assertEquals(rr_req.getMethod(), req.getMethod());
    assertEquals(rr_req.getUrl(), req.getUrl());
    assertEquals(rr_req.getVersion(), req.getVersion());

    // same response data
    assertEquals(rr_resp.getMessage(), resp.getMessage());
    assertEquals(rr_resp.getStatus(), resp.getStatus());
    assertEquals(new String(rr_resp.getContent()), new String(resp.getContent()));

}

From source file:org.abondar.experimental.eventsearch.EventFinder.java

public void formJson(Event eb) {

    File fil = new File("/home/abondar/EventSearch/jsons/" + eb.getEventID() + ".json");
    try {/*from   w w  w.  ja  v  a2 s.c  om*/
        FileOutputStream fos = new FileOutputStream(fil);
        ObjectMapper om = new ObjectMapper();
        om.writeValue(fos, eb);

    } catch (IOException ex) {
        Logger.getLogger(EventFinder.class.getName()).log(Level.SEVERE, null, ex);

    }

}

From source file:MappingTest.java

public void legacyMappingTest() {
    String json = "{\"_id\":{\"$oid\":\"53934d3530047a8c9f648517\"},\"timestamp\":1402162485485,\"appId\":\"Idea\",\"nodeId\":\"MyMac3\",\"data\":{\"ps\":[{\"user\":\"mmacias\",\"pid\":\"815\",\"%cpu\":\"76.7\",\"%mem\":\"15.8\",\"vsz\":\"4484280\",\"rss\":\"1322276\",\"tt\":\"??\",\"stat\":\"R\",\"started\":\"8:23PM\",\"time\":\"176:30.48\",\"command\":\"/Applications/IntelliJ IDEA 13.app/Contents/MacOS/idea\"}],\"iostat\":{\"disk0\":{\"KB/t\":\"35.16\",\"tps\":\"8\",\"MB/s\":\"0.26\"},\"cpu\":{\"us\":\"15\",\"sy\":\"5\",\"id\":\"80\"},\"load\":{\"1m\":\"2.54\",\"5m\":\"2.39\",\"15m\":\"2.25\"}}}}";
    ObjectMapper om = new ObjectMapper();
    try {/* w ww.jav  a 2  s .  c o m*/
        Event e = om.readValue(json.getBytes(), Event.class);
        assertThat(e.getId()).isEqualToIgnoringCase("53934d3530047a8c9f648517");
        om.writeValue(System.out, e);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.sonian.elasticsearch.http.jetty.HttpClient.java

@SuppressWarnings({ "unchecked" })
public HttpClientResponse request(String method, String path, Map<String, Object> data) {
    ObjectMapper mapper = new ObjectMapper();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {//from   ww  w . j  a  v a 2s.c  o  m
        mapper.writeValue(out, data);
    } catch (IOException e) {
        throw new ElasticsearchException("", e);
    }
    return request(method, path, out.toByteArray());
}

From source file:com.hxh.websocket.service.UserOnlineService.java

/**
 * ???/*from   w  ww  .jav  a 2 s  .c  o m*/
 * ???WebSocketSession???
 * @param msg 
 */
private void pushMessageToWebClient(JsonMessage msg) {
    System.out.println("?");
    System.out.println(":" + sessions.size());
    synchronized (sessions) {
        for (WebSocketSession s : sessions) {
            ObjectMapper mapper = new ObjectMapper();
            StringWriter sw = new StringWriter();
            try {
                mapper.writeValue(sw, msg);
                String jsonmsg = sw.toString();
                System.out.println("?:" + jsonmsg);
                s.sendMessage(new TextMessage(jsonmsg));
            } catch (IOException ex) {
                Logger.getLogger(UserOnlineService.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:com.webtide.jetty.load.generator.web.MonitorServlet.java

protected void sendResponse(HttpServletResponse response) throws IOException {
    //start./*from  w  w  w .j  a va  2s  .  co  m*/
    //stop.

    try {
        Map<String, Object> run = new LinkedHashMap<>();
        Map<String, Object> config = new LinkedHashMap<>();
        run.put("config", config);
        config.put("cores", start.cores);
        config.put("totalMemory", new Result(start.gibiBytes(start.totalMemory), "GiB"));
        config.put("os", start.os);
        config.put("jvm", start.jvm);
        config.put("totalHeap", new Result(start.gibiBytes(start.heap.getMax()), "GiB"));
        config.put("date", new Date(start.date).toString());
        Map<String, Object> results = new LinkedHashMap<>();
        run.put("results", results);
        results.put("cpu", new Result(stop.percent(stop.cpuTime, stop.time) / start.cores, "%"));
        results.put("jitTime", new Result(stop.jitTime, "ms"));
        Map<String, Object> gc = new LinkedHashMap<>();
        results.put("gc", gc);
        gc.put("youngCount", stop.youngCount);
        gc.put("youngTime", new Result(stop.youngTime, "ms"));
        gc.put("oldCount", stop.oldCount);
        gc.put("oldTime", new Result(stop.oldTime, "ms"));
        gc.put("youngGarbage", new Result(stop.mebiBytes(stop.edenBytes + stop.survivorBytes), "MiB"));
        gc.put("oldGarbage", new Result(stop.mebiBytes(stop.tenuredBytes), "MiB"));

        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.writeValue(response.getOutputStream(), run);
    } catch (Exception e) {
        e.printStackTrace(response.getWriter());
        throw new IOException(e.getMessage(), e);
    }

}

From source file:kishida.cnn.NeuralNetwork.java

public void writeAsJson(Writer writer) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.writeValue(writer, this);
}