Example usage for com.fasterxml.jackson.core.util DefaultPrettyPrinter DefaultPrettyPrinter

List of usage examples for com.fasterxml.jackson.core.util DefaultPrettyPrinter DefaultPrettyPrinter

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core.util DefaultPrettyPrinter DefaultPrettyPrinter.

Prototype

public DefaultPrettyPrinter() 

Source Link

Usage

From source file:org.apache.infra.reviewboard.ReviewBoard.java

public static void main(String... args) throws IOException {

    URL url = new URL(REVIEW_BOARD_URL);
    HttpHost host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());

    Executor executor = Executor.newInstance().auth(host, REVIEW_BOARD_USERNAME, REVIEW_BOARD_PASSWORD)
            .authPreemptive(host);//w  w w . j  av  a  2  s. c o m

    Request request = Request.Get(REVIEW_BOARD_URL + "/api/review-requests/");
    Response response = executor.execute(request);

    request = Request.Get(REVIEW_BOARD_URL + "/api/review-requests/");
    response = executor.execute(request);

    ObjectMapper mapper = new ObjectMapper();
    JsonNode json = mapper.readTree(response.returnResponse().getEntity().getContent());

    JsonFactory factory = new JsonFactory();
    JsonGenerator generator = factory.createGenerator(new PrintWriter(System.out));
    generator.setPrettyPrinter(new DefaultPrettyPrinter());
    mapper.writeTree(generator, json);
}

From source file:be.dnsbelgium.rdap.client.RDAPCLI.java

public static void main(String[] args) {

    LOGGER.debug("Create the command line parser");
    CommandLineParser parser = new GnuParser();

    LOGGER.debug("Create the options");
    Options options = new RDAPOptions(Locale.ENGLISH);

    try {//w  w  w . jav a2  s  . co m
        LOGGER.debug("Parse the command line arguments");
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help")) {
            printHelp(options);
            return;
        }

        if (line.getArgs().length == 0) {
            throw new IllegalArgumentException("You must provide a query");
        }
        String query = line.getArgs()[0];

        Type type = (line.getArgs().length == 2) ? Type.valueOf(line.getArgs()[1].toUpperCase())
                : guessQueryType(query);

        LOGGER.debug("Query: {}, Type: {}", query, type);

        try {
            SSLContextBuilder sslContextBuilder = SSLContexts.custom();
            if (line.hasOption(RDAPOptions.TRUSTSTORE)) {
                sslContextBuilder.loadTrustMaterial(
                        RDAPClient.getKeyStoreFromFile(new File(line.getOptionValue(RDAPOptions.TRUSTSTORE)),
                                line.getOptionValue(RDAPOptions.TRUSTSTORE_TYPE, RDAPOptions.DEFAULT_STORETYPE),
                                line.getOptionValue(RDAPOptions.TRUSTSTORE_PASS, RDAPOptions.DEFAULT_PASS)));
            }
            if (line.hasOption(RDAPOptions.KEYSTORE)) {
                sslContextBuilder.loadKeyMaterial(
                        RDAPClient.getKeyStoreFromFile(new File(line.getOptionValue(RDAPOptions.KEYSTORE)),
                                line.getOptionValue(RDAPOptions.KEYSTORE_TYPE, RDAPOptions.DEFAULT_STORETYPE),
                                line.getOptionValue(RDAPOptions.KEYSTORE_PASS, RDAPOptions.DEFAULT_PASS)),
                        line.getOptionValue(RDAPOptions.KEYSTORE_PASS, RDAPOptions.DEFAULT_PASS).toCharArray());
            }
            SSLContext sslContext = sslContextBuilder.build();

            final String url = line.getOptionValue(RDAPOptions.URL);
            final HttpHost host = Utils.httpHost(url);

            HashSet<Header> headers = new HashSet<Header>();
            headers.add(new BasicHeader("Accept-Language",
                    line.getOptionValue(RDAPOptions.LANG, Locale.getDefault().toString())));
            HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultHeaders(headers)
                    .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext,
                            (line.hasOption(RDAPOptions.INSECURE) ? new AllowAllHostnameVerifier()
                                    : new BrowserCompatHostnameVerifier())));

            if (line.hasOption(RDAPOptions.USERNAME) && line.hasOption(RDAPOptions.PASSWORD)) {
                BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()),
                        new UsernamePasswordCredentials(line.getOptionValue(RDAPOptions.USERNAME),
                                line.getOptionValue(RDAPOptions.PASSWORD)));
                httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }

            RDAPClient rdapClient = new RDAPClient(httpClientBuilder.build(), url);
            ObjectMapper mapper = new ObjectMapper();

            JsonNode json = null;
            switch (type) {
            case DOMAIN:
                json = rdapClient.getDomainAsJson(query);
                break;
            case ENTITY:
                json = rdapClient.getEntityAsJson(query);
                break;
            case AUTNUM:
                json = rdapClient.getAutNum(query);
                break;
            case IP:
                json = rdapClient.getIp(query);
                break;
            case NAMESERVER:
                json = rdapClient.getNameserver(query);
                break;
            }
            PrintWriter out = new PrintWriter(System.out, true);
            if (line.hasOption(RDAPOptions.RAW)) {
                mapper.writer().writeValue(out, json);
            } else if (line.hasOption(RDAPOptions.PRETTY)) {
                mapper.writer(new DefaultPrettyPrinter()).writeValue(out, json);
            } else if (line.hasOption(RDAPOptions.YAML)) {
                DumperOptions dumperOptions = new DumperOptions();
                dumperOptions.setPrettyFlow(true);
                dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
                dumperOptions.setSplitLines(true);
                Yaml yaml = new Yaml(dumperOptions);
                Map data = mapper.convertValue(json, Map.class);
                yaml.dump(data, out);
            } else {
                mapper.writer(new MinimalPrettyPrinter()).writeValue(out, json);
            }
            out.flush();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            System.exit(-1);
        }
    } catch (org.apache.commons.cli.ParseException e) {
        printHelp(options);
        System.exit(-1);
    }
}

From source file:com.mirth.connect.util.MirthJsonUtil.java

public static String prettyPrint(String input) {
    ObjectMapper mapper = new ObjectMapper(new JsonFactory());
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    try {//  ww  w.  j  a va  2s .  c o m
        // Modified Jackson's default pretty printer to separate each array element onto its own line
        DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
        prettyPrinter.indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE);
        JsonNode json = mapper.readTree(input);

        return mapper.writer(prettyPrinter).writeValueAsString(json);
    } catch (Exception e) {
        logger.warn("Error pretty printing json.", e);
    }

    return input;
}

From source file:org.wso2.carbon.apimgt.hostobjects.util.Json.java

public static ObjectWriter pretty() {
    return mapper().writer(new DefaultPrettyPrinter());
}

From source file:com.evanzeimet.queryinfo.QueryInfoTestUtils.java

@SuppressWarnings("deprecation")
public static ObjectWriter createObjectWriter() {
    ObjectMapper objectMapper = createObjectMapper();

    DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
    prettyPrinter.indentArraysWith(new DefaultPrettyPrinter.Lf2SpacesIndenter());

    return objectMapper.writer(prettyPrinter);
}

From source file:com.orange.ngsi2.model.EntityTest.java

@Test
public void serializationEntityTest() throws JsonProcessingException {
    ObjectWriter writer = Utils.objectMapper.writer(new DefaultPrettyPrinter());

    Entity entity = new Entity("Bcn-Welt", "Room");
    HashMap<String, Attribute> attributes = new HashMap<String, Attribute>();
    Attribute tempAttribute = new Attribute(21.7);
    attributes.put("temperature", tempAttribute);
    Attribute humidityAttribute = new Attribute(60);
    attributes.put("humidity", humidityAttribute);
    entity.setAttributes(attributes);/*from  w  w  w . j a v a 2 s .c om*/
    String json = writer.writeValueAsString(entity);
    String jsonString = "{\n" + "  \"id\" : \"Bcn-Welt\",\n" + "  \"type\" : \"Room\",\n"
            + "  \"temperature\" : {\n" + "    \"value\" : 21.7,\n" + "    \"metadata\" : { }\n" + "  },\n"
            + "  \"humidity\" : {\n" + "    \"value\" : 60,\n" + "    \"metadata\" : { }\n" + "  }\n" + "}";
    assertEquals(jsonString, json);
}

From source file:com.vsct.dt.strowgr.admin.nsq.payload.PayloadTest.java

private void assertSerialization(Object message, String file) throws IOException, URISyntaxException {
    String result = mapper/*  w w  w . j a v  a 2s  .  c  om*/
            .writer(new DefaultPrettyPrinter().withArrayIndenter(new DefaultPrettyPrinter.FixedSpaceIndenter()))
            .writeValueAsString(message);

    URL resource = getClass().getClassLoader().getResource(file);
    String expected = new String(Files.readAllBytes(Paths.get(resource.toURI())));
    assertEquals(expected.replaceAll("\r\n", "\n"), result.replaceAll("\r\n", "\n"));
}

From source file:com.orange.ngsi2.model.EntityTypeTest.java

@Test
public void serializationEntityTypeTest() throws JsonProcessingException {
    ObjectWriter writer = Utils.objectMapper.writer(new DefaultPrettyPrinter());

    EntityType entityType = new EntityType();
    Map<String, AttributeType> attrs = new HashMap<>();
    AttributeType tempAttribute = new AttributeType("urn:phenomenum:temperature");
    attrs.put("temperature", tempAttribute);
    AttributeType humidityAttribute = new AttributeType("percentage");
    attrs.put("humidity", humidityAttribute);
    AttributeType pressureAttribute = new AttributeType("null");
    attrs.put("pressure", pressureAttribute);
    entityType.setAttrs(attrs);//from  w  ww.j  a v  a2 s  .  c  om
    entityType.setCount(7);
    String json = writer.writeValueAsString(entityType);

    assertEquals(jsonString, json);
}

From source file:org.wrml.runtime.format.application.json.JsonModelPrinter.java

public JsonModelPrinter(final JsonGenerator jsonGenerator, final ModelWriteOptions writeOptions) {

    _JsonGenerator = jsonGenerator;/*from  w ww  .j  av a  2 s. co m*/
    _WriteOptions = writeOptions;

    if (_WriteOptions.isPrettyPrint()) {
        final DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
        prettyPrinter.indentObjectsWith(new DefaultPrettyPrinter.Lf2SpacesIndenter());
        prettyPrinter.indentArraysWith(new DefaultPrettyPrinter.Lf2SpacesIndenter());
        _JsonGenerator.setPrettyPrinter(prettyPrinter);

        // _JsonGenerator.useDefaultPrettyPrinter();
    }
}

From source file:com.orange.ngsi.model.RegisterContextResponseTest.java

@Test
public void serializationSimpleRegisterContextResponse() throws IOException {

    RegisterContextResponse registerContextResponse = new RegisterContextResponse("52a744b011f5816465943d58");
    registerContextResponse.setDuration("P1M");

    ObjectMapper mapper = new ObjectMapper();
    ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
    String json = writer.writeValueAsString(registerContextResponse);
    assertEquals("52a744b011f5816465943d58", JsonPath.read(json, "$.registrationId"));
    assertEquals("P1M", JsonPath.read(json, "$.duration"));
}