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:org.openepics.discs.ccdb.gui.ui.AuditManager.java

private String formatEntryDetails(AuditRecord record) {
    try {//ww w  .  j  av  a2 s.  c om
        final ObjectMapper mapper = new ObjectMapper();
        final Object json = mapper.readValue(record.getEntry(), Object.class);
        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
    } catch (IOException e) {
        LOGGER.log(Level.FINE, e.getMessage(), e);
        return "";
    }
}

From source file:com.cloudbees.clickstack.vertx.VertxConfigurationBuilder.java

public void fillVertxModuleConfiguration(Path vertxHome, Metadata metadata) throws IOException {
    Path jsonConfPath = vertxHome.resolve("conf/configuration.json");
    Preconditions.checkState(Files.exists(jsonConfPath), "Expected conf file file %s does not exist",
            jsonConfPath);//from w ww  .  j  ava 2s . co m
    ObjectMapper mapper = new ObjectMapper();
    JsonNodeFactory nodeFactory = mapper.getNodeFactory();
    ObjectNode conf = (ObjectNode) mapper.readValue(jsonConfPath.toFile(), JsonNode.class);

    new VertxConfigurationBuilder().fillVertxModuleConfiguration(metadata, nodeFactory, conf);

    mapper.writerWithDefaultPrettyPrinter().writeValue(jsonConfPath.toFile(), conf);
}

From source file:com.marosj.backend.BackendHttpServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("application/json");

    ObjectMapper mapper = new ObjectMapper();
    String greeting = req.getParameter("greeting");

    ResponseDTO response = new ResponseDTO();
    response.setGreeting(greeting + " from cluster Backend");
    response.setTime(System.currentTimeMillis());
    response.setIp(getIp());//w  w w.j a  va  2s .  c  om

    PrintWriter out = resp.getWriter();
    mapper.writerWithDefaultPrettyPrinter().writeValue(out, response);
}

From source file:uk.gov.nationalarchives.discovery.taxonomy.cli.CLIRunner.java

private void getEvaluationReport(String comments) throws JsonProcessingException {
    EvaluationReport report = evaluationService.getEvaluationReport(comments);
    ObjectMapper mapper = new ObjectMapper();
    logger.info("Report: {}", mapper.writerWithDefaultPrettyPrinter().writeValueAsString(report));

    List<String> listOfCategoriesNotFound = new ArrayList<String>();
    List<String> listOfCategoriesWithBadAccuracy = new ArrayList<String>();
    List<String> listOfCategoriesWithBadRecall = new ArrayList<String>();
    for (CategoryEvaluationResult categoryEvaluationResult : report.getResults()) {
        if (!categoryEvaluationResult.isFoundInTDocCat()
                && !categoryEvaluationResult.isFoundInTDocLegacyCat()) {
            listOfCategoriesNotFound.add(categoryEvaluationResult.getCategory());
            logger.debug(/*from   ww w  .  j av a 2  s .  com*/
                    "Category '{}' from current System was not found in any document among legacy and current cats",
                    categoryEvaluationResult.getCategory());
        }
        if (categoryEvaluationResult.getAccuracy() < 0.5d) {
            listOfCategoriesWithBadAccuracy.add(categoryEvaluationResult.getCategory());
            logger.debug("Category '{}' has bad accuracy: {}", categoryEvaluationResult.getCategory(),
                    categoryEvaluationResult.getAccuracy());

        }
        if (categoryEvaluationResult.getRecall() < 0.5d) {
            listOfCategoriesWithBadRecall.add(categoryEvaluationResult.getCategory());
            logger.debug("Category '{}' has bad recall: {}", categoryEvaluationResult.getCategory(),
                    categoryEvaluationResult.getRecall());

        }
    }
    logger.info("{} categories were processed", report.getResults().size());
    logger.info("{} categories from current system were not found anywhere: {}",
            listOfCategoriesNotFound.size(), Arrays.toString(listOfCategoriesNotFound.toArray()));
    logger.info("{} categories have accuracy < 0.5: {}", listOfCategoriesWithBadAccuracy.size(),
            Arrays.toString(listOfCategoriesWithBadAccuracy.toArray()));
    logger.info("{} categories have recall < 0.5: {}", listOfCategoriesWithBadRecall.size(),
            Arrays.toString(listOfCategoriesWithBadRecall.toArray()));
    logger.info("");
}

From source file:com.smartbear.collab.client.Client.java

public JsonrpcResponse sendRequest(List<JsonrpcCommand> methods) {
    JsonrpcResponse result = new JsonrpcResponse();

    List<LinkedHashMap<String, LinkedHashMap<String, String>>> results = new ArrayList<LinkedHashMap<String, LinkedHashMap<String, String>>>();

    ObjectMapper mapper = new ObjectMapper();
    try {//ww  w . j a v a 2s.  c  o m
        logger.info(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(methods));
    } catch (JsonProcessingException jpe) {
    }

    results = target.request(MediaType.APPLICATION_JSON_TYPE)
            .post(Entity.entity(methods, MediaType.APPLICATION_JSON_TYPE), List.class);

    try {
        logger.info(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(results));
    } catch (JsonProcessingException jpe) {
    }

    List<JsonrpcCommandResponse> commandResponses = new ArrayList<JsonrpcCommandResponse>();
    for (LinkedHashMap commandResultMap : results) {
        JsonrpcCommandResponse commandResponse = new JsonrpcCommandResponse();
        if (commandResultMap.get("result") != null) {
            JsonrpcResult commandResult = new JsonrpcResult();
            LinkedHashMap<String, String> commandResultValue = (LinkedHashMap<String, String>) commandResultMap
                    .get("result");
            if (commandResultValue.size() > 0) {
                commandResult.setCommand(commandResultValue.keySet().iterator().next());
                commandResult.setValue(commandResultValue.get(commandResult.getCommand()));
                commandResponse.setResult(commandResult);
            }
        }
        if (commandResultMap.get("errors") != null) {
            List<LinkedHashMap<String, String>> errors = (List<LinkedHashMap<String, String>>) commandResultMap
                    .get("errors");
            List<JsonrpcError> jsonrpcErrors = new ArrayList<JsonrpcError>();
            for (LinkedHashMap<String, String> error : errors) {
                JsonrpcError jsonrpcError = new JsonrpcError();
                jsonrpcError.setCode(error.get("code"));
                jsonrpcError.setMessage(error.get("message"));
                jsonrpcErrors.add(jsonrpcError);
            }
            commandResponse.setErrors(jsonrpcErrors);

        }

        commandResponses.add(commandResponse);
    }
    result.setResults(commandResponses);

    return result;
}

From source file:org.venice.piazza.servicecontroller.messaging.handlers.ExecuteServiceHandlerTest.java

/**
 * Tests executing web service with GET method
 *//*from  w w  w  .ja v a2  s.  co m*/
@Test
public void testHandleWithMapInputsGet() {
    ExecuteServiceData edata = new ExecuteServiceData();
    String serviceId = "a842aae2-bd74-4c4b-9a65-c45e8cd9060f";
    edata.setServiceId(serviceId);
    HashMap<String, DataType> dataInputs = new HashMap<String, DataType>();
    URLParameterDataType tdt = new URLParameterDataType();
    tdt.content = "Marge";

    dataInputs.put("name", tdt);
    edata.setDataInputs(dataInputs);

    ObjectMapper mapper = new ObjectMapper();
    try {
        String tsvc = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(edata);
        System.out.println(tsvc);
    } catch (JsonProcessingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    URI uri = URI.create("http://localhost:8087/jumpstart/moviequotewelcome?name=Marge");
    Mockito.when(serviceMock.getUrl()).thenReturn(uri.toString());
    Mockito.when(accessorMock.getServiceById(serviceId)).thenReturn(movieService);
    Mockito.doNothing().when(loggerMock).log(Mockito.anyString(), Mockito.anyString());
    Mockito.when(restTemplateMock.getForEntity(Mockito.eq(uri), Mockito.eq(String.class)))
            .thenReturn(new ResponseEntity<String>("testExecuteService", HttpStatus.FOUND));

    when(accessorMock.getServiceById(serviceId)).thenReturn(movieService);

    ResponseEntity<String> retVal = executeServiceHandler.handle(edata);
    assertTrue(retVal.getBody().contains("testExecuteService"));
}

From source file:com.groupon.odo.proxylib.models.History.java

public void setFormattedResponseData(String data) throws Exception {
    this.formattedResponseData = data;

    if (data != null && !data.equals("") && responseContentType != null
            && responseContentType.toLowerCase().indexOf("application/json") != -1) {
        // try to format it
        try {//from w  w  w  .j  av a  2 s  .c o m
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();
            Object json = objectMapper.readValue(data, Object.class);
            this.formattedResponseData = writer.withView(ViewFilters.Default.class).writeValueAsString(json);
        } catch (JsonParseException jpe) {
            // nothing to do here as this.formattedResponseData was already set to the appropriate data
        }
    }
}

From source file:com.groupon.odo.proxylib.models.History.java

public void setFormattedOriginalResponseData(String originalResponseData) throws Exception {
    this.formattedOriginalResponseData = originalResponseData;

    if (originalResponseData != null && !originalResponseData.equals("") && originalResponseContentType != null
            && originalResponseContentType.toLowerCase().indexOf("application/json") != -1) {
        try {// w  w w  .  ja  v  a2  s .  c o m
            // try to format it
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();
            Object json = objectMapper.readValue(originalResponseData, Object.class);
            this.formattedOriginalResponseData = writer.withView(ViewFilters.Default.class)
                    .writeValueAsString(json);
        } catch (JsonParseException jpe) {
            // nothing to do here as this.formattedResponseData was already set to the appropriate data
        }
    }
}

From source file:io.mandrel.common.schema.SchemaTest.java

@Test
public void test() throws JsonProcessingException {

    ObjectMapper m = new ObjectMapper();
    SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
    m.acceptJsonFormatVisitor(m.constructType(Spider.class), visitor);
    JsonSchema jsonSchema = visitor.finalSchema();

    System.err.println(m.writerWithDefaultPrettyPrinter().writeValueAsString(jsonSchema));
}

From source file:io.mandrel.OtherTest.java

@Test
public void test() throws JsonProcessingException {

    ObjectMapper objectMapper = new ObjectMapper();

    Class<?> clazz = LinkFilter.class;
    for (JsonSubTypes.Type type : clazz.getAnnotation(JsonSubTypes.class).value()) {
        System.err.println(objectMapper.writerWithDefaultPrettyPrinter()
                .writeValueAsString(new SchemaGenerator(objectMapper).getSchema(type.value())));
    }/*from   w  ww . j  a v  a 2s. co  m*/

}