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

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

Introduction

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

Prototype

public ObjectWriter writerWithDefaultPrettyPrinter() 

Source Link

Document

Factory method for constructing ObjectWriter that will serialize objects using the default pretty printer for indentation

Usage

From source file:com.google.openrtb.json.OpenRtbJsonTest.java

static void testRequestWithNative(String input, String result, boolean rootNative, boolean nativeAsObject,
        boolean ignoreIdField) throws IOException {
    OpenRtbJsonFactory jsonFactory = newJsonFactory().setForceNativeAsObject(nativeAsObject);
    OpenRtb.BidRequest bidRequest = jsonFactory.newReader().readBidRequest(input);
    String jsonRequestNativeStr = jsonFactory.setRootNativeField(rootNative).newWriter()
            .writeBidRequest(bidRequest);
    ObjectMapper mapper = new ObjectMapper();
    Object json = mapper.readValue(jsonRequestNativeStr, Object.class);
    jsonRequestNativeStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);

    if (ignoreIdField) {
        assertThat(cleanupIdField(jsonRequestNativeStr)).isEqualTo(cleanupIdField(result));
    } else {// w w w. j a va 2 s .  c  o m
        assertThat(jsonRequestNativeStr).isEqualTo(result);
    }
}

From source file:com.google.openrtb.json.OpenRtbJsonTest.java

private static String cleanupIdField(final String jsonString) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode json = mapper.readValue(jsonString, ObjectNode.class);
    json.put("id", "1");
    return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
}

From source file:com.google.openrtb.json.OpenRtbJsonTest.java

static void testResponseWithNative(String input, String result, boolean rootNative, boolean nativeAsObject,
        boolean ignoreIdField) throws IOException {
    OpenRtbJsonFactory jsonFactory = newJsonFactory().setForceNativeAsObject(nativeAsObject);
    OpenRtb.BidResponse bidResponse1 = jsonFactory.newReader().readBidResponse(input);
    String jsonResponseNativeStr = jsonFactory.setRootNativeField(rootNative).newWriter()
            .writeBidResponse(bidResponse1);
    ObjectMapper mapper = new ObjectMapper();
    Object json = mapper.readValue(jsonResponseNativeStr, Object.class);
    jsonResponseNativeStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);

    if (ignoreIdField) {
        assertThat(cleanupIdField(jsonResponseNativeStr)).isEqualTo(cleanupIdField(result));
    } else {//from w ww . j a va2s  .c  o  m
        assertThat(jsonResponseNativeStr).isEqualTo(result);
    }
}

From source file:org.helm.notation2.tools.HELM2NotationUtils.java

/**
 * method to generate a JSON-Object from the given HELM2Notation
 *
 * @param helm2notation HELM2Notation object
 * @return NotationContainer in JSON-Format
 * @throws JsonProcessingException/*from w w  w.  j  a  va 2  s  .c om*/
 */
public final static String toJSON(HELM2Notation helm2notation) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    String jsonINString = mapper.writeValueAsString(helm2notation);
    jsonINString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(helm2notation);
    return jsonINString;
}

From source file:Main.java

public static String takeDumpJSON(ThreadMXBean threadMXBean) throws IOException {
    ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(true, true);
    List<Map<String, Object>> threads = new ArrayList<>();

    for (ThreadInfo thread : threadInfos) {
        Map<String, Object> threadMap = new HashMap<>();
        threadMap.put("name", thread.getThreadName());
        threadMap.put("id", thread.getThreadId());
        threadMap.put("state", thread.getThreadState().name());
        List<String> stacktrace = new ArrayList<>();
        for (StackTraceElement element : thread.getStackTrace()) {
            stacktrace.add(element.toString());
        }/* ww  w  .  j  a v a2 s .c om*/
        threadMap.put("stack", stacktrace);

        if (thread.getLockName() != null) {
            threadMap.put("lock_name", thread.getLockName());
        }
        if (thread.getLockOwnerId() != -1) {
            threadMap.put("lock_owner_id", thread.getLockOwnerId());
        }
        if (thread.getBlockedTime() > 0) {
            threadMap.put("blocked_time", thread.getBlockedTime());
        }
        if (thread.getBlockedCount() > 0) {
            threadMap.put("blocked_count", thread.getBlockedCount());
        }
        if (thread.getLockedMonitors().length > 0) {
            threadMap.put("locked_monitors", thread.getLockedMonitors());
        }
        if (thread.getLockedSynchronizers().length > 0) {
            threadMap.put("locked_synchronizers", thread.getLockedSynchronizers());
        }
        threads.add(threadMap);
    }
    ObjectMapper om = new ObjectMapper();
    ObjectNode json = om.createObjectNode();
    json.put("date", new Date().toString());
    json.putPOJO("threads", threads);

    long[] deadlockedThreads = threadMXBean.findDeadlockedThreads();
    long[] monitorDeadlockedThreads = threadMXBean.findMonitorDeadlockedThreads();
    if (deadlockedThreads != null && deadlockedThreads.length > 0) {
        json.putPOJO("deadlocked_thread_ids", deadlockedThreads);
    }
    if (monitorDeadlockedThreads != null && monitorDeadlockedThreads.length > 0) {
        json.putPOJO("monitor_deadlocked_thread_ids", monitorDeadlockedThreads);
    }
    om.enable(SerializationFeature.INDENT_OUTPUT);
    return om.writerWithDefaultPrettyPrinter().writeValueAsString(json);
}

From source file:com.csc.fi.ioapi.utils.JerseyJsonLDClient.java

public static Response getExportGraph(String graph, boolean raw, String lang, String ctype) {

    try {/*from   w w  w  .  j a  v a  2s  . c  o  m*/

        ContentType contentType = ContentType.create(ctype);

        Lang rdfLang = RDFLanguages.contentTypeToLang(contentType);

        if (rdfLang == null) {
            logger.info("Unknown RDF type: " + ctype);
            return JerseyResponseManager.notFound();
        }

        DatasetAccessor accessor = DatasetAccessorFactory.createHTTP(services.getCoreReadAddress());
        Model model = accessor.getModel(graph);

        OutputStream out = new ByteArrayOutputStream();

        Response response = JerseyJsonLDClient.getGraphResponseFromService(graph + "#ExportGraph",
                services.getCoreReadAddress(), ctype);

        if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
            return JerseyResponseManager.unexpected();
        }

        /* TODO: Remove builders */
        ResponseBuilder rb;
        RDFDataMgr.write(out, model, rdfLang);

        if (rdfLang.equals(Lang.JSONLD)) {

            Map<String, Object> jsonModel = null;
            try {
                jsonModel = (Map<String, Object>) JsonUtils.fromString(out.toString());
            } catch (IOException ex) {
                Logger.getLogger(ExportModel.class.getName()).log(Level.SEVERE, null, ex);
                return JerseyResponseManager.unexpected();
            }

            Map<String, Object> frame = new HashMap<String, Object>();
            //Map<String,Object> frame = (HashMap<String,Object>) LDHelper.getExportContext();

            Map<String, Object> context = (Map<String, Object>) jsonModel.get("@context");

            context.putAll(LDHelper.CONTEXT_MAP);

            frame.put("@context", context);
            frame.put("@type", "owl:Ontology");

            Object data;

            try {
                data = JsonUtils.fromInputStream(response.readEntity(InputStream.class));

                rb = Response.status(response.getStatus());

                try {
                    JsonLdOptions options = new JsonLdOptions();
                    Object framed = JsonLdProcessor.frame(data, frame, options);

                    ObjectMapper mapper = new ObjectMapper();

                    rb.entity(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(framed));

                } catch (NullPointerException ex) {
                    logger.log(Level.WARNING, null, "DEFAULT GRAPH IS NULL!");
                    return rb.entity(JsonUtils.toString(data)).build();
                } catch (JsonLdError ex) {
                    logger.log(Level.SEVERE, null, ex);
                    return JerseyResponseManager.serverError();
                }

            } catch (IOException ex) {
                logger.log(Level.SEVERE, null, ex);
                return JerseyResponseManager.serverError();
            }

        } else {
            rb = Response.status(response.getStatus());
            rb.entity(response.readEntity(InputStream.class));
        }

        if (!raw) {
            rb.type(contentType.getContentType());
        } else {
            rb.type("text/plain");
        }

        return rb.build();

    } catch (Exception ex) {
        logger.log(Level.WARNING, "Expect the unexpected!", ex);
        return JerseyResponseManager.serverError();
    }

}

From source file:org.datakurator.data.ffdq.DQReport.java

/**
 * Serialize the report as json/*from   w w w  .  j a  va 2 s .  com*/
 *
 * @throws IOException
 */
public String toJson() throws IOException {
    ObjectMapper mapper = new ObjectMapper();

    return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(this);
}

From source file:puma.application.evaluation.metrics.MetricsController.java

@RequestMapping(value = "/metrics/results", method = RequestMethod.GET, produces = "text/plain")
public @ResponseBody String results() {
    try {/*from ww  w  .j  a v  a 2  s .c o  m*/
        ObjectMapper mapper = new ObjectMapper();
        ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
        return writer.writeValueAsString(TimerFactory.getInstance().getMetricRegistry());
    } catch (JsonProcessingException e) {
        return e.getMessage();
    }
}

From source file:com.samlikescode.stackoverflow.questions.q31034850.ParentSerializationTest.java

@Test
public void testIsSecure() throws JsonProcessingException {

    Parent parent = new Parent();
    Child child = new Child();
    child.someValue = "a sweet value";
    parent.child = child;//from w w w . j a va 2s  .  c  om
    parent.isSecure = true;

    Parent parent2 = new Parent();
    Child child2 = new Child();
    child.someValue = "a BAD VALUE";
    parent2.child = child2;
    parent2.isSecure = false;

    ArrayList<Parent> parents = Lists.newArrayList(parent, parent2);

    ObjectMapper om = new ObjectMapper();

    String output = om.writerWithDefaultPrettyPrinter().writeValueAsString(parents);

    System.out.println(output);
}

From source file:com.orange.clara.cloud.servicedbdumper.utiltest.TestListener.java

private void createReportFile() throws IOException, URISyntaxException {
    Date d = new Date();
    SimpleDateFormat form = new SimpleDateFormat(FILE_FORMAT);
    File jsonFile = new File(DIRECTORY_REPORTS + File.separator + form.format(d) + ".json");

    File dir = jsonFile.getParentFile();
    if (!dir.isDirectory()) {
        dir.mkdirs();//from w w w  . ja  v a  2  s  .c  om
    }
    ObjectMapper mapper = new ObjectMapper();
    mapper.writerWithDefaultPrettyPrinter().writeValue(jsonFile, ReportManager.getAllReports());
}