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

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper#writeValueAsString() . 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: TenantResourceDocumentationTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("Handles PUT request for settings values in tenant specific configuration. Required Permission: "
        + SpPermission.TENANT_CONFIGURATION)
public void putTenantConfigration() throws Exception {

    final MgmtSystemTenantConfigurationValueRequest bodyPut = new MgmtSystemTenantConfigurationValueRequest();
    bodyPut.setValue("exampleToken");
    final ObjectMapper mapper = new ObjectMapper();
    final String json = mapper.writeValueAsString(bodyPut);

    mockMvc.perform(put(MgmtRestConstants.SYSTEM_V1_REQUEST_MAPPING + "/configs/{keyName}/",
            TenantConfigurationKey.AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_KEY).content(json)
                    .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk()).andDo(MockMvcResultPrinter.print())
            .andDo(this.document.document(
                    pathParameters(parameterWithName("keyName").description(MgmtApiModelProperties.CONFIG_PARAM)),
                    requestFields(requestFieldWithPath("value").description(MgmtApiModelProperties.CONFIG_VALUE)),
                    responseFields(getTenantConfigurationValueResponseField())));
}
 
Example 2
Source File: NarrowcastTest.java    From line-bot-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerializeOperatorDemographicFilter() throws JsonProcessingException {
    ObjectMapper objectMapper = ModelObjectMapper.createNewObjectMapper();
    String json = objectMapper.writeValueAsString(
            OperatorDemographicFilter
                    .builder()
                    .and(Collections.singletonList(GenderDemographicFilter.builder()
                                                                          .oneOf(Collections.singletonList(
                                                                                  Gender.MALE))
                                                                          .build()))
                    .build()
    );
    System.out.println(json);
    assertThat(json).isEqualTo(
            "{\"type\":\"operator\","
            + "\"and\":[{\"type\":\"gender\",\"oneOf\":[\"male\"]}],"
            + "\"or\":null,"
            + "\"not\":null}");
}
 
Example 3
Source File: CaseExecutionRestServiceInteractionTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testPutSingleLocalSerializableVariableUnsupportedMediaType() throws Exception {

  ArrayList<String> serializable = new ArrayList<String>();
  serializable.add("foo");

  ObjectMapper mapper = new ObjectMapper();
  String jsonBytes = mapper.writeValueAsString(serializable);
  String typeName = TypeFactory.defaultInstance().constructType(serializable.getClass()).toCanonical();

  String variableKey = "aVariableKey";

  given()
    .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID)
    .pathParam("varId", variableKey)
    .multiPart("data", jsonBytes, "unsupported")
    .multiPart("type", typeName, MediaType.TEXT_PLAIN)
  .expect()
    .statusCode(Status.BAD_REQUEST.getStatusCode())
    .body(containsString("Unrecognized content type for serialized java type: unsupported"))
  .when()
    .post(SINGLE_CASE_EXECUTION_LOCAL_BINARY_VARIABLE_URL);

  verify(caseServiceMock, never()).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID);
}
 
Example 4
Source File: DurationDeserTest.java    From jackson-modules-java8 with Apache License 2.0 6 votes vote down vote up
@Test
public void testLenientDeserializeFromEmptyString() throws Exception {

    String key = "duration";
    ObjectMapper mapper = newMapper();
    ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);

    String dateValAsNullStr = null;
    String dateValAsEmptyStr = "";

    String valueFromNullStr = mapper.writeValueAsString(asMap(key, dateValAsNullStr));
    Map<String, Duration> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    Duration actualDateFromNullStr = actualMapFromNullStr.get(key);
    assertNull(actualDateFromNullStr);

    String valueFromEmptyStr = mapper.writeValueAsString(asMap(key, dateValAsEmptyStr));
    Map<String, Duration> actualMapFromEmptyStr = objectReader.readValue(valueFromEmptyStr);
    Duration actualDateFromEmptyStr = actualMapFromEmptyStr.get(key);
    assertEquals("empty string failed to deserialize to null with lenient setting", null, actualDateFromEmptyStr);
}
 
Example 5
Source File: ResultTest.java    From OpenLRW with Educational Community License v2.0 6 votes vote down vote up
@Test
public void whenMinimallyPopulatedAllGood() throws JsonProcessingException {
  Map<String, String> testMetadata = java.util.Collections.singletonMap("meta", "data");

  Result result
  = new Result.Builder()
  .withSourcedId("result-sid")
  .withMetadata(testMetadata)
  .withStatus(Status.active)
  .withDateLastModified(Instant.now())
  .withComment("that's awesome let me hire you at Unicon")
  .withLineitem(new Link.Builder().withSourcedId("122").withType("assessment").build())
  .withResultStatus("passed")
  .withScore(90.0)
  .withStudent(new Link.Builder().withSourcedId("user-111").withType("student").build())
  .build();


  ObjectMapper mapper = new ObjectMapper();
  String mapperResult = mapper.writeValueAsString(result);
  assertThat(mapperResult, containsString("passed"));
  assertThat(mapperResult, containsString("result-sid"));
  assertThat(mapperResult, containsString("90.0"));
  assertThat(mapperResult, containsString("meta"));
  assertThat(mapperResult, containsString("data"));
}
 
Example 6
Source File: MyAuthenticationSuccessHandler.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
@Override
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    String targetUrl = this.determineTargetUrl(request, response);
    if(response.isCommitted()) {
        this.logger.debug("Response has already been committed. Unable to redirect to " + targetUrl);
    } else {
        ObjectMapper mapper = new ObjectMapper();
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "X-Request-With, JWCQ, Origin,Content-Type");
        response.setContentType("text/plain;charset='utf-8'");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(200);

        // Our ajax request, redirect it to login web page
        Response response1 = new Response();
        response1.setSuccess(1);
        response1.setMessage("success");
        response1.setResult("登录成功");
        String responseStr = "";
        PrintWriter out = response.getWriter();
        try {
            responseStr = mapper.writeValueAsString(response1);
            out.append(responseStr);
        } catch (IOException ioe) {
            // FIXME: Add log here!
            out.append(ioe.toString());
        }
        out.close();
    }
}
 
Example 7
Source File: IpAddrControllerTest.java    From alcor with Apache License 2.0 5 votes vote down vote up
@Test
public void Test12_activateIpAddrStateBulkTest() throws Exception {
    IpAddrRequest ipAddrRequest1 = new IpAddrRequest(
            UnitTestConfig.ipVersion,
            UnitTestConfig.vpcId,
            UnitTestConfig.subnetId,
            UnitTestConfig.rangeId,
            UnitTestConfig.ip2,
            UnitTestConfig.activated);
    IpAddrRequest ipAddrRequest2 = new IpAddrRequest(
            UnitTestConfig.ipVersion,
            UnitTestConfig.vpcId,
            UnitTestConfig.subnetId,
            UnitTestConfig.rangeId,
            UnitTestConfig.ip3,
            UnitTestConfig.activated);

    List<IpAddrRequest> ipAddrRequests = new ArrayList<>();
    ipAddrRequests.add(ipAddrRequest1);
    ipAddrRequests.add(ipAddrRequest2);

    IpAddrRequestBulk ipAddrRequestBulk = new IpAddrRequestBulk();
    ipAddrRequestBulk.setIpRequests(ipAddrRequests);

    ObjectMapper objectMapper = new ObjectMapper();
    String ipAddrRequestBulkJson = objectMapper.writeValueAsString(ipAddrRequestBulk);

    this.mockMvc.perform(put(UnitTestConfig.ipAddrBulkUrl)
            .content(ipAddrRequestBulkJson)
            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(print());
}
 
Example 8
Source File: DingtalkFeignClient.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
@Override
@ApiOperation(httpMethod = "POST", value = "发送钉钉消息")
public Wrapper<Boolean> sendChatRobotMsg(@RequestBody ChatRobotMsgDto chatRobotMsgDto) {
	logger.info("sendChatRobotMsg - 钉钉机器人开始发送消息. chatRobotMsgDto = {}", chatRobotMsgDto);
	boolean result;
	try {
		checkChatReBotMsg(chatRobotMsgDto);
		HttpClient httpclient = HttpClients.createDefault();
		String webhookToken = "https://oapi.dingtalk.com/robot/send?access_token=" + chatRobotMsgDto.getWebhookToken();
		HttpPost httpPost = new HttpPost(webhookToken);
		ObjectMapper mapper = new ObjectMapper();
		String robotJson = mapper.writeValueAsString(chatRobotMsgDto);
		logger.info("robotJson = {}", robotJson);
		httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
		StringEntity se = new StringEntity(robotJson, "utf-8");
		httpPost.setEntity(se);
		logger.info("robotJson={}", robotJson);
		logger.info("httpPost={}", httpPost);
		HttpResponse response;
		response = httpclient.execute(httpPost);
		if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
			logger.info("钉钉机器人发送消息成功 response={}", response);
			result = true;
		} else {
			logger.error("钉钉机器人发送消息失败 response={}", response);
			result = false;
		}
	} catch (IOException e) {
		logger.error("发送钉钉消息,出现异常 ex={}", e.getMessage(), e);
		return WrapMapper.error("发送钉钉消息失败");
	}
	return WrapMapper.ok(result);
}
 
Example 9
Source File: TaskStatusUpdateEvent.java    From termd with Apache License 2.0 5 votes vote down vote up
public String toString() {
  ObjectMapper mapper = new ObjectMapper();
  try {
    return mapper.writeValueAsString(this);
  } catch (JsonProcessingException e) {
    log.error("Cannot serialize object.", e);
  }
  return null;
}
 
Example 10
Source File: AdvancedAnnotationsUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenUsingJsonIdentityReferenceAnnotation_thenCorrect() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    BeanWithIdentityReference bean = new BeanWithIdentityReference(1, "Bean With Identity Reference Annotation");
    String jsonString = mapper.writeValueAsString(bean);

    assertEquals("1", jsonString);
}
 
Example 11
Source File: JsonTestUtils.java    From spring-credhub with Apache License 2.0 5 votes vote down vote up
public static String toJson(Object object) {
	try {
		ObjectMapper mapper = JsonUtils.buildObjectMapper();
		return mapper.writeValueAsString(object);
	}
	catch (JsonProcessingException ex) {
		fail("Error creating JSON string from object: " + ex);
		throw new IllegalStateException(ex);
	}
}
 
Example 12
Source File: MetadataTest.java    From pegasus with Apache License 2.0 5 votes vote down vote up
@Test
public void serializationWithOnlyMetadata() throws IOException {
    ObjectMapper mapper =
            new ObjectMapper(
                    new YAMLFactory().configure(YAMLGenerator.Feature.INDENT_ARRAYS, true));
    mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false);

    // metadata serialization can only be tested by being enclosed in a ReplicaLocation
    // object as we don't have writeStartObject in the serializer implementatio of Metadata
    ReplicaLocation rl = new ReplicaLocation();
    rl.setLFN("test");

    Metadata m = new Metadata();
    rl.addMetadata("user", "vahi");
    rl.addMetadata("year", "2020");

    String expected =
            "---\n"
                    + "lfn: \"test\"\n"
                    + "metadata:\n"
                    + "  year: \"2020\"\n"
                    + "  user: \"vahi\"\n";

    String actual = mapper.writeValueAsString(rl);

    assertEquals(expected, actual);
}
 
Example 13
Source File: ExecutionRestServiceInteractionTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidationOnPutSingleLocalSerializableVariableFromJson() throws Exception {
  boolean previousIsValidationEnabled = processEngine.getProcessEngineConfiguration().isDeserializationTypeValidationEnabled();
  DeserializationTypeValidator previousValidator = processEngine.getProcessEngineConfiguration().getDeserializationTypeValidator();

  DeserializationTypeValidator validatorMock = mock(DeserializationTypeValidator.class);
  when(validatorMock.validate(anyString())).thenReturn(true);
  when(processEngine.getProcessEngineConfiguration().isDeserializationTypeValidationEnabled()).thenReturn(true);
  when(processEngine.getProcessEngineConfiguration().getDeserializationTypeValidator()).thenReturn(validatorMock);

  try {
    ObjectMapper mapper = new ObjectMapper();
    String jsonBytes = mapper.writeValueAsString("test");
    String typeName = TypeFactory.defaultInstance().constructType(String.class).toCanonical();

    String variableKey = "aVariableKey";

    given()
      .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey)
      .multiPart("data", jsonBytes, MediaType.APPLICATION_JSON)
      .multiPart("type", typeName, MediaType.TEXT_PLAIN)
    .expect()
      .statusCode(Status.NO_CONTENT.getStatusCode())
    .when()
      .post(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL);

    verify(validatorMock).validate("java.lang.String");
    verifyNoMoreInteractions(validatorMock);

    verify(runtimeServiceMock).setVariableLocal(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey),
        argThat(EqualsObjectValue.objectValueMatcher().isDeserialized().value("test")));
  } finally {
    when(processEngine.getProcessEngineConfiguration().isDeserializationTypeValidationEnabled()).thenReturn(previousIsValidationEnabled);
    when(processEngine.getProcessEngineConfiguration().getDeserializationTypeValidator()).thenReturn(previousValidator);
  }
}
 
Example 14
Source File: TnCControllerTest.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
public String mapToJson(Map map) {
  ObjectMapper mapperObj = new ObjectMapper();
  String jsonResp = "";

  if (map != null) {
    try {
      jsonResp = mapperObj.writeValueAsString(map);
    } catch (IOException e) {
      ProjectLogger.log(e.getMessage(), e);
    }
  }
  return jsonResp;
}
 
Example 15
Source File: DatabaseValidationTask.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
private void writeResult(ValidationResult result, PrintWriter output) {
  ObjectMapper objectMapper = new ObjectMapper();
  objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
  try {
    String content = objectMapper.writeValueAsString(result);
    output.write(content);
  } catch (JsonProcessingException e) {
    LOG.error("Failed to process ValidationResult as JSON", e);
  }
}
 
Example 16
Source File: JsonMapperProviderTest.java    From conductor with Apache License 2.0 5 votes vote down vote up
@Test
public void testWorkflowSerDe() throws IOException {
    WorkflowDef workflowDef = new WorkflowDef();
    workflowDef.setName("testDef");
    workflowDef.setVersion(2);

    Workflow workflow = new Workflow();
    workflow.setWorkflowDefinition(workflowDef);
    workflow.setWorkflowId("test-workflow-id");
    workflow.setStatus(Workflow.WorkflowStatus.RUNNING);
    workflow.setStartTime(10L);
    workflow.setInput(null);

    Map<String, Object> data = new HashMap<>();
    data.put("someKey", null);
    data.put("someId", "abc123");
    workflow.setOutput(data);

    ObjectMapper objectMapper = new JsonMapperProvider().get();

    String workflowPayload = objectMapper.writeValueAsString(workflow);

    Workflow workflow1 = objectMapper.readValue(workflowPayload, Workflow.class);

    assertTrue(workflow1.getOutput().containsKey("someKey"));
    assertNull(workflow1.getOutput().get("someKey"));
    assertNotNull(workflow1.getInput());
}
 
Example 17
Source File: TestPolymorphic.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
public void testAfterburner() throws Exception {
    ObjectMapper mapper = newAfterburnerMapper();
    Envelope envelope = new Envelope(new Payload("test"));
    String json = mapper.writeValueAsString(envelope);
    Envelope result = mapper.readValue(json, Envelope.class);

    assertNotNull(result);
    assertNotNull(result.payload);
    assertEquals(Payload.class, result.payload.getClass());
}
 
Example 18
Source File: EventTest.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@Test
public void commit() throws Exception {
  ObjectMapper mapper = new ObjectMapper().registerModule(Event.module());
  Map<Integer, Long> offsets = singletonMap(0, 1L);
  Event event = new Commit("correlationId", offsets);
  String json = mapper.writeValueAsString(event);
  Commit readValue = mapper.readValue(json, Commit.class);
  assertThat(readValue.getCorrelationId(), is("correlationId"));
  assertThat(readValue.getOffsets(), is(offsets));

  Event result = mapper.readValue(json, Event.class);
  assertThat(result, is(event));
}
 
Example 19
Source File: HttpDownAppCallback.java    From proxyee-down with Apache License 2.0 4 votes vote down vote up
private void commonHook(HttpDownBootstrap httpDownBootstrap, String event, boolean async) {
  DownInfo downInfo = findDownInfo(httpDownBootstrap);
  Map<String, Object> taskInfo = buildTaskInfo(downInfo);
  if (taskInfo != null) {
    //遍历扩展模块是否有对应的处理
    List<ExtensionInfo> extensionInfos = ExtensionContent.get();
    for (ExtensionInfo extensionInfo : extensionInfos) {
      if (extensionInfo.getMeta().isEnabled()) {
        if (extensionInfo.getHookScript() != null
            && !StringUtils.isEmpty(extensionInfo.getHookScript().getScript())) {
          Event e = extensionInfo.getHookScript().hasEvent(event, HttpDownUtil.getUrl(httpDownBootstrap.getRequest()));
          if (e != null) {
            try {
              //执行钩子函数
              Object result = ExtensionUtil.invoke(extensionInfo, e, taskInfo, async);
              if (result != null) {
                ObjectMapper objectMapper = new ObjectMapper();
                String temp = objectMapper.writeValueAsString(result);
                TaskForm taskForm = objectMapper.readValue(temp, TaskForm.class);
                if (taskForm.getRequest() != null) {
                  httpDownBootstrap.setRequest(
                      HttpDownUtil.buildRequest(taskForm.getRequest().getMethod(),
                          taskForm.getRequest().getUrl(),
                          taskForm.getRequest().getHeads(),
                          taskForm.getRequest().getBody())
                  );
                }
                if (taskForm.getResponse() != null) {
                  httpDownBootstrap.setResponse(taskForm.getResponse());
                }
                if (taskForm.getData() != null) {
                  downInfo.setData(taskForm.getData());
                }
                HttpDownContent.getInstance().save();
              }
            } catch (Exception ex) {
              LOGGER.error("An hook exception occurred while " + event + "()", ex);
            }
          }
        }
      }
    }
  }
}
 
Example 20
Source File: TestRestApiSession.java    From sdk-rest with MIT License 3 votes vote down vote up
@Test
public void testSessionSerialization() throws IOException {

	ObjectMapper mapper = new ObjectMapper();
	mapper.registerModule(new JodaModule());

	String json = mapper.writeValueAsString(restApiSession);

	System.out.println(json);

	final RestApiSession newSession = mapper.readValue(json, RestApiSession.class);
	assertNotNull(newSession);

}