Java Code Examples for com.fasterxml.jackson.databind.ObjectMapper#writerWithDefaultPrettyPrinter()

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper#writerWithDefaultPrettyPrinter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestsMultiRowParse.java    From foxtrot with Apache License 2.0 6 votes vote down vote up
@Test
public void parseTable() throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();
    final String json = "[{\"name\":\"60\",\"ttl\":15},{\"name\":\"aprameya\",\"ttl\":15},{\"name\":\"athena\",\"ttl\":7}," +
                        "{\"name\":\"callisto\",\"ttl\":30},{\"name\":\"cart-service\",\"ttl\":15}," +
                        "{\"name\":\"digital-ingestion-pipeline\",\"ttl\":60},{\"name\":\"ebooks-delivery\",\"ttl\":15}," +
                        "{\"name\":\"europa\",\"ttl\":60},{\"name\":\"fk-w3-co-prezente\",\"ttl\":15}," +
                        "{\"name\":\"fk-w3-uss\",\"ttl\":60},{\"name\":\"flip-sync\",\"ttl\":30},{\"name\":\"flipcast\"," +
                        "\"ttl\":30},{\"name\":\"flipkart-ebook\",\"ttl\":60},{\"name\":\"flipkart-ebooks\",\"ttl\":30}," +
                        "{\"name\":\"flipkartretailapp\",\"ttl\":30},{\"name\":\"flipkartretailapp-referral\",\"ttl\":60}," +
                        "{\"name\":\"ganymede\",\"ttl\":30},{\"name\":\"santa\",\"ttl\":30},{\"name\":\"selfserve\"," +
                        "\"ttl\":15},{\"name\":\"warehouse\",\"ttl\":30},{\"name\":\"webreader\",\"ttl\":60}]";
    JsonNode root = objectMapper.readTree(json);
    FlatRepresentation representation = FlatteningUtils.genericMultiRowParse(root, null, "name");
    System.out.println(writer.writeValueAsString(representation));
    Assert.assertEquals(2, representation.getHeaders()
            .size());
}
 
Example 2
Source File: History.java    From odo with Apache License 2.0 6 votes vote down vote up
public void setFormattedOriginalResponseData(String originalResponseData) throws Exception {
    this.formattedOriginalResponseData = originalResponseData;

    if (originalResponseData != null && !originalResponseData.equals("") &&
            originalResponseContentType != null && originalResponseContentType.toLowerCase().indexOf("application/json") != -1) {
        try {
            // 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
        }
    }
}
 
Example 3
Source File: History.java    From odo with Apache License 2.0 6 votes vote down vote up
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 {
            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
        }
    }
}
 
Example 4
Source File: ElasticBaseTestQuery.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
public static void compareJson(String expected, String actual) throws IOException {
  if(ElasticsearchCluster.USE_EXTERNAL_ES5){
    // ignore json comparison for now
    return;
  }

  ObjectMapper m = new ObjectMapper();
  JsonNode expectedRootNode = m.readTree(expected);
  JsonNode actualRootNode = m.readTree(actual);
  if (!expectedRootNode.equals(actualRootNode)) {
    ObjectWriter writer = m.writerWithDefaultPrettyPrinter();
    String message = String.format("Comparison between JSON values failed.\nExpected:\n%s\nActual:\n%s", expected, actual);
    // assertEquals gives a better diff
    assertEquals(message, writer.writeValueAsString(expectedRootNode), writer.writeValueAsString(actualRootNode));
    throw new RuntimeException(message);
  }
}
 
Example 5
Source File: BackupController.java    From odo with Apache License 2.0 6 votes vote down vote up
/**
 * API call to backup active overides and active server group for a client
 * Also backs up entire odo configuration
 *
 * @param model
 * @param response
 * @param profileIdentifier Id of profile to backup
 * @param clientUUID Client Id to backup
 * @param oldExport Flag if this is exporting old configuration on a new import, used to change name of file
 * @return
 * @throws Exception
 */

@SuppressWarnings("deprecation")
@RequestMapping(value = "/api/backup/profile/{profileIdentifier}/{clientUUID}", method = RequestMethod.GET)
public
@ResponseBody
String getSingleProfileConfiguration(Model model, HttpServletResponse response,
                                     @PathVariable String profileIdentifier,
                                     @PathVariable String clientUUID,
                                     @RequestParam(value = "oldExport", defaultValue = "false") boolean oldExport) throws Exception {
    int profileID = ControllerUtils.convertProfileIdentifier(profileIdentifier);
    response.setContentType("application/json");

    ObjectMapper objectMapper = new ObjectMapper();
    ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();

    if (oldExport) {
        response.addHeader("Content-Disposition", "attachment; filename=Config_and_Profile_OLD.json");
    } else {
        response.addHeader("Content-Disposition", "attachment; filename=Config_and_Profile_Backup.json");
    }
    ConfigAndProfileBackup configAndProfileBackup = BackupService.getInstance().
        getConfigAndProfileData(profileID, clientUUID);
    return writer.withView(ViewFilters.Default.class).writeValueAsString(configAndProfileBackup);
}
 
Example 6
Source File: TestsMultiRowParse.java    From foxtrot with Apache License 2.0 5 votes vote down vote up
@Test
public void parseMeta() throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();
    final String json = "{\"table\":\"europa\",\"mappings\":[{\"field\":\"data.checkoutId\",\"type\":\"STRING\"}," +
                        "{\"field\":\"data.errorMessage\",\"type\":\"STRING\"},{\"field\":\"data.startTime\"," +
                        "\"type\":\"LONG\"},{\"field\":\"data.error\",\"type\":\"STRING\"},{\"field\":\"data" + ".pin\"," +
                        "\"type\":\"LONG\"},{\"field\":\"data.version\",\"type\":\"STRING\"},{\"field\":\"data" +
                        ".invalidationReason\",\"type\":\"STRING\"},{\"field\":\"data.request.clientHostName\"," +
                        "\"type\":\"STRING\"},{\"field\":\"data.storedValueType\",\"type\":\"STRING\"}," + "{\"field\":\"data" +
                        ".request.clientTraceId\",\"type\":\"STRING\"},{\"field\":\"data.accountId\"," + "\"type\":\"STRING\"}," +
                        "{\"field\":\"header.profile\",\"type\":\"STRING\"},{\"field\":\"data.endTime\"," + "\"type\":\"LONG\"}," +
                        "{\"field\":\"data.channel.sessionId\",\"type\":\"STRING\"},{\"field\":\"data.channel" + ".salesChannel\"," +
                        "\"type\":\"STRING\"},{\"field\":\"data.storedValue\",\"type\":\"STRING\"}," + "{\"field\":\"data" +
                        ".duration\",\"type\":\"LONG\"},{\"field\":\"data.invalidationMessage\"," + "\"type\":\"STRING\"}," +
                        "{\"field\":\"data.channel.terminalId\",\"type\":\"STRING\"},{\"field\":\"data.email\"," +
                        "\"type\":\"STRING\"},{\"field\":\"data.channel.channelSource\",\"type\":\"STRING\"}," +
                        "{\"field\":\"header.configName\",\"type\":\"STRING\"},{\"field\":\"header.appName\"," +
                        "\"type\":\"STRING\"},{\"field\":\"data.errorCode\",\"type\":\"STRING\"}," + "{\"field\":\"header" +
                        ".timestamp\",\"type\":\"DATE\"},{\"field\":\"data.request.requestId\"," + "\"type\":\"STRING\"}," +
                        "{\"field\":\"data.request.clientAppIPAddress\",\"type\":\"STRING\"},{\"field\":\"data" + ".key\"," +
                        "\"type\":\"STRING\"},{\"field\":\"data.channel.createdBy\",\"type\":\"STRING\"}," + "{\"field\":\"data" +
                        ".callistoAPI\",\"type\":\"STRING\"},{\"field\":\"data.addressId\",\"type\":\"STRING\"}," +
                        "{\"field\":\"data.channel.userAgent\",\"type\":\"STRING\"},{\"field\":\"data" + ".salesChannel\"," +
                        "\"type\":\"STRING\"},{\"field\":\"header.instanceId\",\"type\":\"STRING\"}," + "{\"field\":\"data.request" +
                        ".checkoutId\",\"type\":\"STRING\"},{\"field\":\"data.checkoutType\"," + "\"type\":\"STRING\"}," +
                        "{\"field\":\"data.channel.userIp\",\"type\":\"STRING\"},{\"field\":\"data.tenant\"," +
                        "\"type\":\"STRING\"},{\"field\":\"header.eventId\",\"type\":\"STRING\"}," + "{\"field\":\"data.actionType" +
                        ".type\",\"type\":\"STRING\"},{\"field\":\"data.request.client\",\"type\":\"STRING\"}," +
                        "{\"field\":\"data.dataFlow\",\"type\":\"STRING\"}]}";
    JsonNode root = objectMapper.readTree(json);
    FlatRepresentation representation = FlatteningUtils.genericMultiRowParse(root.get("mappings"), null, "field");
    System.out.println(writer.writeValueAsString(representation));
    Assert.assertEquals(2, representation.getHeaders()
            .size());
}
 
Example 7
Source File: BackupController.java    From odo with Apache License 2.0 5 votes vote down vote up
/**
 * Get all backup data
 *
 * @param model
 * @return
 * @throws Exception
 */
@SuppressWarnings("deprecation")
@RequestMapping(value = "/api/backup", method = RequestMethod.GET)
public
@ResponseBody
String getBackup(Model model, HttpServletResponse response) throws Exception {
    response.addHeader("Content-Disposition", "attachment; filename=backup.json");
    response.setContentType("application/json");

    Backup backup = BackupService.getInstance().getBackupData();
    ObjectMapper objectMapper = new ObjectMapper();
    ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();

    return writer.withView(ViewFilters.Default.class).writeValueAsString(backup);
}
 
Example 8
Source File: JsonSecurityAnalysisParameters.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Writes parameters as JSON to an output stream.
 */
public static void write(SecurityAnalysisParameters parameters, OutputStream outputStream) {
    try {
        ObjectMapper objectMapper = createObjectMapper();
        ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();
        writer.writeValue(outputStream, parameters);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 9
Source File: SecurityAnalysisResultSerializer.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
public static void write(SecurityAnalysisResult result, Writer writer) throws IOException {
    Objects.requireNonNull(result);
    Objects.requireNonNull(writer);

    ObjectMapper objectMapper = JsonUtil.createObjectMapper()
            .registerModule(new SecurityAnalysisJsonModule());

    ObjectWriter objectWriter = objectMapper.writerWithDefaultPrettyPrinter();
    objectWriter.writeValue(writer, result);
}
 
Example 10
Source File: ContingencyJsonTest.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
private static void write(Contingency object, Path jsonFile) {
    Objects.requireNonNull(object);
    Objects.requireNonNull(jsonFile);

    try (OutputStream os = Files.newOutputStream(jsonFile)) {
        ObjectMapper mapper = JsonUtil.createObjectMapper();
        ContingencyJsonModule module = new ContingencyJsonModule();
        mapper.registerModule(module);

        ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
        writer.writeValue(os, object);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 11
Source File: JsonDynamicSimulationParameters.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Writes parameters as JSON to an output stream.
 */
public static void write(DynamicSimulationParameters parameters, OutputStream outputStream) {
    try {
        ObjectMapper objectMapper = createObjectMapper();
        ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();
        writer.writeValue(outputStream, parameters);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 12
Source File: JacksonUtil.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public static String prettyPrint(Object obj)
		throws com.fasterxml.jackson.core.JsonProcessingException {
	ObjectMapper mapper = new ObjectMapper();

	// ***IMPORTANT!!!*** for Jackson 2.x use the line below instead of the one above: 
	// ObjectWriter writer = mapper.writer().withDefaultPrettyPrinter();
	// return mapper.writeValueAsString(obj);
	ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
	return writer.writeValueAsString(obj);
}
 
Example 13
Source File: JacksonUtil.java    From jpmml-model with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static
public void write(PMMLObject object, OutputStream os) throws IOException {
	ObjectMapper objectMapper = createObjectMapper(null);

	ObjectWriter objectWriter = objectMapper.writerWithDefaultPrettyPrinter();

	objectWriter.writeValue(os, object);
}
 
Example 14
Source File: JsonUtil.java    From multiapps with Apache License 2.0 5 votes vote down vote up
public static ObjectWriter getObjectWriter(boolean indentedOutput) {
    ObjectMapper objectMapper = getObjectMapper();
    if (indentedOutput) {
        return objectMapper.writerWithDefaultPrettyPrinter();
    }
    return objectMapper.writer();
}
 
Example 15
Source File: ParseTest.java    From foxtrot with Apache License 2.0 4 votes vote down vote up
@Test
public void test() throws Exception {
    //TODO
    /*ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();
    {
        String sql = "select abc.xyz, def from europa order by test.name limit 20 offset 5";
        QueryTranslator queryTranslator = new QueryTranslator();
        ActionRequest request = queryTranslator.translate(sql);
        System.out.println(writer.writeValueAsString(request));
    }
    {
        String sql = "select * from europa order by test.name limit 20 offset 5";
        QueryTranslator queryTranslator = new QueryTranslator();
        ActionRequest request = queryTranslator.translate(sql);
        System.out.println(writer.writeValueAsString(request));
    }
    {
        String sql = "select * from europa group by test.name, test.surname";
        QueryTranslator queryTranslator = new QueryTranslator();
        ActionRequest request = queryTranslator.translate(sql);
        System.out.println(writer.writeValueAsString(request));
    }
    {
        //String sql = "select trend(header.configName) from europa";
        //String sql = "select trend(header.configName, 'minutes') from europa";
        String sql = "select trend(header.configName, 'minutes', 'header.timestamp') from europa";
        QueryTranslator queryTranslator = new QueryTranslator();
        ActionRequest request = queryTranslator.translate(sql);
        System.out.println(writer.writeValueAsString(request));
    }
    {
        //String sql = "select statstrend(header.configName) from europa";
        String sql = "select statstrend(header.configName, 'minutes') from europa";
        QueryTranslator queryTranslator = new QueryTranslator();
        ActionRequest request = queryTranslator.translate(sql);
        System.out.println(writer.writeValueAsString(request));
    }
    {
        //String sql = "select statstrend(header.configName) from europa";
        String sql = "select stats(header.configName) from europa";
        QueryTranslator queryTranslator = new QueryTranslator();
        ActionRequest request = queryTranslator.translate(sql);
        System.out.println(writer.writeValueAsString(request));
    }
    {
        //String sql = "select statstrend(header.configName) from europa";
        //String sql = "select histogram() from europa";
        //String sql = "select histogram('hours') from europa";
        String sql = "select histogram('minutes', 'header.timestamp') from europa";
        QueryTranslator queryTranslator = new QueryTranslator();
        ActionRequest request = queryTranslator.translate(sql);
        System.out.println(writer.writeValueAsString(request));
    }
    {
        String sql = "select * from europa where a = 'b' and c=2.5 and temporal(e) between 10 and 30 and x > 99
        order by test.name limit 20 offset 5";
        QueryTranslator queryTranslator = new QueryTranslator();
        ActionRequest request = queryTranslator.translate(sql);
        System.out.println(writer.writeValueAsString(request));
    }*/


    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();
    {
        String sql = "select * from europa where a is null";
        QueryTranslator queryTranslator = new QueryTranslator();
        //FqlQuery query = queryTranslator.translate(sql);
        Query query = new Query();
        query.setTable("europa");
        query.setFrom(0);
        query.setLimit(10);
        query.setSort(null);
        ImmutableList filters = ImmutableList.of(new MissingFilter("a"));
        query.setFilters(filters);
        FqlActionQuery fqlActionQuery = new FqlActionQuery(query, new ArrayList<>());
        Assert.assertEquals(writer.writeValueAsString(fqlActionQuery), writer.writeValueAsString(queryTranslator.translate(sql)));

    }
}
 
Example 16
Source File: JsonConfigurationWriter.java    From nifi with Apache License 2.0 4 votes vote down vote up
public JsonConfigurationWriter(ObjectMapper objectMapper, File file) {
    this.objectWriter = objectMapper.writerWithDefaultPrettyPrinter();
    this.file = file;
}
 
Example 17
Source File: Json.java    From StubbornJava with MIT License 4 votes vote down vote up
private Json(ObjectMapper mapper) {
    this.mapper = mapper;
    this.writer = mapper.writer();
    this.prettyWriter = mapper.writerWithDefaultPrettyPrinter();
}
 
Example 18
Source File: ClusterTopicManipulationServiceTest.java    From kafka-monitor with Apache License 2.0 4 votes vote down vote up
@Test(invocationCount = 2)
void serviceStartTest() throws JsonProcessingException {
  ClusterTopicManipulationService clusterTopicManipulationService =
      Mockito.mock(ClusterTopicManipulationService.class);

  Mockito.doCallRealMethod()
      .when(clusterTopicManipulationService)
      .processBroker(Mockito.anyMap(), Mockito.any(), Mockito.anyString());

  Mockito.doCallRealMethod()
      .when(clusterTopicManipulationService)
      .setExpectedPartitionsCount(Mockito.anyInt());

  Mockito.doCallRealMethod()
      .when(clusterTopicManipulationService)
      .expectedPartitionsCount();

  List<Node> brokers = new ArrayList<>();
  for (int id = 1; id < 3; id++) {
    brokers.add(new Node(id, "kafka-broker-host", 8000));
  }

  Map<Integer, Map<String, DescribeLogDirsResponse.LogDirInfo>> logDirectoriesResponseMap1 = new HashMap<>();
  Map<Integer, Map<String, DescribeLogDirsResponse.LogDirInfo>> logDirectoriesResponseMap2 = new HashMap<>();

  Map<Node, Map<Integer, Map<String, DescribeLogDirsResponse.LogDirInfo>>> brokerMapHashMap = new HashMap<>();
  brokerMapHashMap.putIfAbsent(brokers.get(0), logDirectoriesResponseMap1);
  brokerMapHashMap.putIfAbsent(brokers.get(1), logDirectoriesResponseMap2);

  Map<String, DescribeLogDirsResponse.LogDirInfo> logDirInfoMap1 = new HashMap<>();
  Map<String, DescribeLogDirsResponse.LogDirInfo> logDirInfoMap2 = new HashMap<>();

  logDirectoriesResponseMap1.put(brokers.get(0).id(), logDirInfoMap1);
  logDirectoriesResponseMap2.put(brokers.get(1).id(), logDirInfoMap2);

  Map<TopicPartition, DescribeLogDirsResponse.ReplicaInfo> replicaInfos1 = new HashMap<>();
  Map<TopicPartition, DescribeLogDirsResponse.ReplicaInfo> replicaInfos2 = new HashMap<>();

  for (int topicPartition = 0; topicPartition < 3; topicPartition++) {
    replicaInfos1.put(new TopicPartition(SERVICE_TEST_TOPIC, topicPartition),
        new DescribeLogDirsResponse.ReplicaInfo(235, 0, false));

    replicaInfos2.put(new TopicPartition(SERVICE_TEST_TOPIC, topicPartition),
        new DescribeLogDirsResponse.ReplicaInfo(235, 0, false));
  }

  int totalPartitions = brokers.size() * replicaInfos1.size();
  System.out.println(totalPartitions);
  clusterTopicManipulationService.setExpectedPartitionsCount(totalPartitions);
  System.out.println(clusterTopicManipulationService.expectedPartitionsCount());

  logDirInfoMap1.put(XinfraMonitorConstants.KAFKA_LOG_DIRECTORY + "-1",
      new DescribeLogDirsResponse.LogDirInfo(null, replicaInfos1));
  logDirInfoMap2.put(XinfraMonitorConstants.KAFKA_LOG_DIRECTORY + "-2",
      new DescribeLogDirsResponse.LogDirInfo(null, replicaInfos2));

  ObjectMapper objectMapper = new ObjectMapper();
  ObjectWriter objectWriter = objectMapper.writerWithDefaultPrettyPrinter();

  for (Map.Entry<Node, Map<Integer, Map<String, DescribeLogDirsResponse.LogDirInfo>>> nodeMapEntry : brokerMapHashMap.entrySet()) {
    System.out.println(objectWriter.writeValueAsString(nodeMapEntry.getValue()));
  }

  for (Node broker : brokers) {
    clusterTopicManipulationService.processBroker(brokerMapHashMap.get(broker), broker, SERVICE_TEST_TOPIC);
  }

  Assert.assertEquals(totalPartitions, clusterTopicManipulationService.expectedPartitionsCount());
  System.out.println();
}
 
Example 19
Source File: JsonConfigurationWriter.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
public JsonConfigurationWriter(ObjectMapper objectMapper, File file) {
    this.objectWriter = objectMapper.writerWithDefaultPrettyPrinter();
    this.file = file;
}
 
Example 20
Source File: GetMongo.java    From nifi with Apache License 2.0 4 votes vote down vote up
private ObjectWriter getObjectWriter(ObjectMapper mapper, String ppSetting) {
    return ppSetting.equals(YES_PP.getValue()) ? mapper.writerWithDefaultPrettyPrinter()
            : mapper.writer();
}