org.codehaus.jackson.map.ObjectWriter Java Examples

The following examples show how to use org.codehaus.jackson.map.ObjectWriter. 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: LTI2Servlet.java    From basiclti-util-java with Apache License 2.0 6 votes vote down vote up
protected void getToolConsumerProfile(HttpServletRequest request,
		HttpServletResponse response,String profile_id)
{
	// Map<String,Object> deploy = ltiService.getDeployForConsumerKeyDao(profile_id);
	Map<String,Object> deploy = null;

	ToolConsumer consumer = buildToolConsumerProfile(request, deploy, profile_id);

	ObjectMapper mapper = new ObjectMapper();
	try {
		// http://stackoverflow.com/questions/6176881/how-do-i-make-jackson-pretty-print-the-json-content-it-generates
		ObjectWriter writer = mapper.defaultPrettyPrintingWriter();
		// ***IMPORTANT!!!*** for Jackson 2.x use the line below instead of the one above:
		// ObjectWriter writer = mapper.writer().withDefaultPrettyPrinter();
		// System.out.println(mapper.writeValueAsString(consumer));
		response.setContentType(APPLICATION_JSON);
		PrintWriter out = response.getWriter();
		out.println(writer.writeValueAsString(consumer));
		// System.out.println(writer.writeValueAsString(consumer));
	}
	catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example #2
Source File: RumenToSLSConverter.java    From hadoop with Apache License 2.0 6 votes vote down vote up
private static void generateSLSLoadFile(String inputFile, String outputFile)
        throws IOException {
  Reader input = new FileReader(inputFile);
  try {
    Writer output = new FileWriter(outputFile);
    try {
      ObjectMapper mapper = new ObjectMapper();
      ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
      Iterator<Map> i = mapper.readValues(
              new JsonFactory().createJsonParser(input), Map.class);
      while (i.hasNext()) {
        Map m = i.next();
        output.write(writer.writeValueAsString(createSLSJob(m)) + EOL);
      }
    } finally {
      output.close();
    }
  } finally {
    input.close();
  }
}
 
Example #3
Source File: RumenToSLSConverter.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static void generateSLSNodeFile(String outputFile)
        throws IOException {
  Writer output = new FileWriter(outputFile);
  try {
    ObjectMapper mapper = new ObjectMapper();
    ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
    for (Map.Entry<String, Set<String>> entry : rackNodeMap.entrySet()) {
      Map rack = new LinkedHashMap();
      rack.put("rack", entry.getKey());
      List nodes = new ArrayList();
      for (String name : entry.getValue()) {
        Map node = new LinkedHashMap();
        node.put("node", name);
        nodes.add(node);
      }
      rack.put("nodes", nodes);
      output.write(writer.writeValueAsString(rack) + EOL);
    }
  } finally {
    output.close();
  }
}
 
Example #4
Source File: RumenToSLSConverter.java    From big-c with Apache License 2.0 6 votes vote down vote up
private static void generateSLSLoadFile(String inputFile, String outputFile)
        throws IOException {
  Reader input = new FileReader(inputFile);
  try {
    Writer output = new FileWriter(outputFile);
    try {
      ObjectMapper mapper = new ObjectMapper();
      ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
      Iterator<Map> i = mapper.readValues(
              new JsonFactory().createJsonParser(input), Map.class);
      while (i.hasNext()) {
        Map m = i.next();
        output.write(writer.writeValueAsString(createSLSJob(m)) + EOL);
      }
    } finally {
      output.close();
    }
  } finally {
    input.close();
  }
}
 
Example #5
Source File: RumenToSLSConverter.java    From big-c with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static void generateSLSNodeFile(String outputFile)
        throws IOException {
  Writer output = new FileWriter(outputFile);
  try {
    ObjectMapper mapper = new ObjectMapper();
    ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
    for (Map.Entry<String, Set<String>> entry : rackNodeMap.entrySet()) {
      Map rack = new LinkedHashMap();
      rack.put("rack", entry.getKey());
      List nodes = new ArrayList();
      for (String name : entry.getValue()) {
        Map node = new LinkedHashMap();
        node.put("node", name);
        nodes.add(node);
      }
      rack.put("nodes", nodes);
      output.write(writer.writeValueAsString(rack) + EOL);
    }
  } finally {
    output.close();
  }
}
 
Example #6
Source File: StateTransitionThrottleConfig.java    From helix with Apache License 2.0 6 votes vote down vote up
/**
 * Generate the JSON String for StateTransitionThrottleConfig.
 * @return Json String for this config.
 */
public String toJSON() {
  Map<String, String> configMap = new HashMap<>();
  configMap.put(ConfigProperty.REBALANCE_TYPE.name(), _rebalanceType.name());
  configMap.put(ConfigProperty.THROTTLE_SCOPE.name(), _throttleScope.name());
  configMap.put(ConfigProperty.MAX_PARTITION_IN_TRANSITION.name(),
      String.valueOf(_maxPartitionInTransition));

  String jsonStr = null;
  try {
    ObjectWriter objectWriter = OBJECT_MAPPER.writer();
    jsonStr = objectWriter.writeValueAsString(configMap);
  } catch (IOException e) {
    logger.error("Failed to convert config map to JSON object! {}", configMap);
  }

  return jsonStr;
}
 
Example #7
Source File: RedisPublisher.java    From onboard with Apache License 2.0 6 votes vote down vote up
private void broadcastByActivity(User owner, Activity activity, BaseProjectItem originalItem, BaseProjectItem updatedItem)
        throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
    ObjectWriter ow = objectMapper.writer().withDefaultPrettyPrinter();
    activity.setSubscribers(userService.getUserByProjectId(activity.getProjectId()));
    activity.setAttachObject((BaseProjectItem)identifiableManager.getIdentifiableByTypeAndId(activity.getAttachType(),
            activity.getAttachId()));
    String message = "";
    try {
        message = ow.writeValueAsString(activity);
    } catch (IOException e) {
        e.printStackTrace();
    }
    template.convertAndSend("channel", message);
}
 
Example #8
Source File: StringCodec.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
@Override
public String toString(T pojo)
{
  try {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    ObjectWriter writer = mapper.writer();
    return writer.writeValueAsString(pojo);
  } catch (IOException e) {
    throw Throwables.propagate(e);
  }
}
 
Example #9
Source File: JsonTopologySerializer.java    From libcrunch with Apache License 2.0 5 votes vote down vote up
private ObjectWriter getWriter() {
  ObjectMapper mapper = new ObjectMapper();

  // omit null fields from serialization
  mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
  // exclude certain fields and getter methods from node serialization via mixin
  mapper.getSerializationConfig().addMixInAnnotations(Node.class, MixIn.class);
  // register the module that suppresses the failed property if false
  mapper.registerModule(new IsFailedSuppressor());

  return mapper.writer().withDefaultPrettyPrinter();
}
 
Example #10
Source File: JacksonCodec.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(OutputStream out, T object, TypeDef<?> type) throws IOException {
    if (type == null) {
        mapper.writeValue(out, object);
    } else {
        ObjectWriter writer = mapper.writerWithType(new TypeTokenBasedReference(type));
        writer.writeValue(out, object);
    }
}
 
Example #11
Source File: ZKAssistedDiscovery.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
JacksonInstanceSerializer(ObjectReader objectReader, ObjectWriter objectWriter,
    TypeReference<ServiceInstance<T>> typeRef)
{
  this.objectReader = objectReader;
  this.objectWriter = objectWriter;
  this.typeRef = typeRef;
}
 
Example #12
Source File: WebSocketServiceImpl.java    From onboard with Apache License 2.0 5 votes vote down vote up
/**
 * 根据map生成json
 * 
 * @param actionMap
 * @return
 */
private String getJson(Object activity) {
    ObjectMapper objectMapper = new ObjectMapper();

    objectMapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
    ObjectWriter ow = objectMapper.writer().withDefaultPrettyPrinter();
    String message = "";
    try {
        message = ow.writeValueAsString(activity);
    } catch (IOException e) {
        logger.info("activity to json failure");
    }
    return message;
}
 
Example #13
Source File: StringCodec.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public String toString(T pojo)
{
  try {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    ObjectWriter writer = mapper.writer();
    return writer.writeValueAsString(pojo);
  } catch (IOException e) {
    throw Throwables.propagate(e);
  }
}
 
Example #14
Source File: PrettifyJSONExample.java    From Examples with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    try {
        String json = "{\"candidate\" : \"Vicky Thakor\", \"expertise\" : [\"Core Java\", \"J2EE\", \"Design Pattern\"]}";
        System.out.println("Unformatter json:" + json);
        /* Create required objects */
        ObjectMapper objectMapper = new ObjectMapper();
        Object object = objectMapper.readValue(json, Object.class);
        ObjectWriter objectWriter = objectMapper.writer().withDefaultPrettyPrinter();
        /* Get the formatted json */
        String formattedJSON = objectWriter.writeValueAsString(object);
        System.out.println("Formatter json:\n"+formattedJSON);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
 
Example #15
Source File: TbContentControllerTests.java    From spring-boot-samples with Apache License 2.0 5 votes vote down vote up
/**
 * 更新资源
 *
 * @throws Exception
 */
@Test
public void testUpdate() throws Exception {
    // 由于请求参数使用了 @RequestBody 注解,故需要将参数封装成 JSON 格式
    TbContent tbContent = new TbContent();
    tbContent.setId(43L);
    tbContent.setCategoryId(89L);
    tbContent.setTitle("来自 SpringMock 的编辑测试");
    ObjectMapper objectMapper = new ObjectMapper();
    ObjectWriter objectWriter = objectMapper.writer().withDefaultPrettyPrinter();
    String jsonParams = objectWriter.writeValueAsString(tbContent);

    // 模拟请求
    int status = this.mockMvc
            .perform(MockMvcRequestBuilders
                    .put("/update")
                    .header("Authorization", "Bearer 91317816-5036-4b76-86b7-05d96d55774d")
                    // 设置使用 JSON 方式传参
                    .contentType(MediaType.APPLICATION_JSON)
                    // 设置 JSON 参数内容
                    .content(jsonParams))
            .andDo(MockMvcResultHandlers.print())
            .andReturn().getResponse().getStatus();
    if (status == 200) {
        log.info("请求成功");
    } else {
        log.info("请求失败,状态码为:{}", status);
    }

    Assert.assertEquals(status, 200);
}
 
Example #16
Source File: TbContentControllerTests.java    From spring-boot-samples with Apache License 2.0 5 votes vote down vote up
/**
 * 新增资源
 */
@Test
public void testInsert() throws Exception {
    // 由于请求参数使用了 @RequestBody 注解,故需要将参数封装成 JSON 格式
    TbContent tbContent = new TbContent();
    tbContent.setCategoryId(89L);
    tbContent.setTitle("来自 SpringMock 的新增测试");
    ObjectMapper objectMapper = new ObjectMapper();
    ObjectWriter objectWriter = objectMapper.writer().withDefaultPrettyPrinter();
    String jsonParams = objectWriter.writeValueAsString(tbContent);

    // 模拟请求
    int status = this.mockMvc
            .perform(MockMvcRequestBuilders
                    .post("/insert")
                    .header("Authorization", "Bearer 91317816-5036-4b76-86b7-05d96d55774d")
                    // 设置使用 JSON 方式传参
                    .contentType(MediaType.APPLICATION_JSON)
                    // 设置 JSON 参数内容
                    .content(jsonParams))
            .andDo(MockMvcResultHandlers.print())
            .andReturn().getResponse().getStatus();
    if (status == 200) {
        log.info("请求成功");
    } else {
        log.info("请求失败,状态码为:{}", status);
    }

    Assert.assertEquals(status, 200);
}
 
Example #17
Source File: ZKAssistedDiscovery.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
InstanceSerializerFactory(ObjectReader objectReader, ObjectWriter objectWriter)
{
  this.objectReader = objectReader;
  this.objectWriter = objectWriter;
}
 
Example #18
Source File: ObjectMapperUtil.java    From dcs-sdk-java with Apache License 2.0 4 votes vote down vote up
public ObjectWriter getObjectWriter() {
    return objectMapper.writer();
}