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

The following examples show how to use com.fasterxml.jackson.databind.ObjectWriter#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: JaxrsReaderTest.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void createCommonParameters() throws Exception {
    reader = new JaxrsReader(new Swagger(), Mockito.mock(Log.class));
    Swagger result = reader.read(CommonParametersApi.class);
    Parameter headerParam = result.getParameter("headerParam");
    assertTrue(headerParam instanceof HeaderParameter);
    Parameter queryParam = result.getParameter("queryParam");
    assertTrue(queryParam instanceof QueryParameter);

    result = reader.read(ReferenceCommonParametersApi.class);
    Operation get = result.getPath("/apath").getGet();
    List<Parameter> parameters = get.getParameters();
    for (Parameter parameter : parameters) {
        assertTrue(parameter instanceof RefParameter);
    }

    ObjectMapper mapper = Json.mapper();
    ObjectWriter jsonWriter = mapper.writer(new DefaultPrettyPrinter());
    String json = jsonWriter.writeValueAsString(result);
    JsonNode expectJson = mapper.readTree(this.getClass().getResourceAsStream("/expectedOutput/swagger-common-parameters.json"));
    JsonAssert.assertJsonEquals(expectJson, json);
}
 
Example 2
Source File: HealthCheckResourceTest.java    From pay-publicapi with MIT License 6 votes vote down vote up
@Test
public void checkHealthCheck_isHealthy() throws JsonProcessingException {
    SortedMap<String,HealthCheck.Result> map = new TreeMap<>();
    map.put("ping", HealthCheck.Result.healthy());
    map.put("deadlocks", HealthCheck.Result.healthy());

    when(healthCheckRegistry.runHealthChecks()).thenReturn(map);

    Response response = resource.healthCheck();

    assertThat(response.getStatus(), is(200));

    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    String body = ow.writeValueAsString(response.getEntity());

    JsonAssert.with(body)
            .assertThat("$.*", hasSize(2))
            .assertThat("$.ping.healthy", is(true))
            .assertThat("$.deadlocks.healthy", is(true));
}
 
Example 3
Source File: ObjectReaderJDK7IT.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteValue() throws Exception {
    __POJO pojo = new __POJO();
    pojo.setName("Jackson");
    
    ObjectWriter writer = mapper.writer();

    String jsonStr = writer.writeValueAsString(pojo);
    byte[] jsonByte = writer.writeValueAsBytes(pojo);

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();

    Method writeval1 = ObjectWriter.class.getMethod("writeValueAsString", Object.class);
    Method writeval2 = ObjectWriter.class.getMethod("writeValueAsBytes", Object.class);

    verifier.verifyTrace(event("JACKSON", writeval1, annotation("jackson.json.length", jsonStr.length())));
    verifier.verifyTrace(event("JACKSON", writeval2, annotation("jackson.json.length", jsonByte.length)));

    verifier.verifyTraceCount(0);
}
 
Example 4
Source File: ExtensionSerializationTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerializeDeserialize() throws IOException {
    final ObjectReader reader = JsonUtils.reader();
    final ObjectWriter writer = JsonUtils.writer();

    try (InputStream source = getClass().getResourceAsStream("syndesis-extension-definition.json")) {
        final Extension read = reader.forType(Extension.class).readValue(source);

        final Extension recreated = new Extension.Builder()
            .createFrom(read)
            .build();

        final String written = writer.writeValueAsString(recreated);

        final Extension reRead = reader.forType(Extension.class).readValue(written);

        assertThat(reRead)
            .isEqualTo(read)
            .isEqualTo(recreated);
    }
}
 
Example 5
Source File: DefaultPagedMetaInformationTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void nonNullMustBeSerialized() throws JsonProcessingException {
	ObjectMapper mapper = new ObjectMapper();
	ObjectWriter writer = mapper.writerFor(DefaultPagedMetaInformation.class);

	DefaultPagedMetaInformation metaInformation = new DefaultPagedMetaInformation();
	metaInformation.setTotalResourceCount(12L);

	String json = writer.writeValueAsString(metaInformation);
	Assert.assertEquals("{\"totalResourceCount\":12}", json);
}
 
Example 6
Source File: RntbdResponseStatus.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
@Override
public String toString() {
    final ObjectWriter writer = RntbdObjectMapper.writer();
    try {
        return writer.writeValueAsString(this);
    } catch (final JsonProcessingException error) {
        throw new CorruptedFrameException(error);
    }
}
 
Example 7
Source File: SeqTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void test1() throws IOException {
    ObjectWriter writer = mapper().writer();
    Seq<?> src = of(1, null, 2.0, "s");
    String json = writer.writeValueAsString(src);
    Assertions.assertEquals(genJsonList(1, null, 2.0, "s"), json);
    Seq<?> dst = (Seq<?>) mapper().readValue(json, clz());
    Assertions.assertEquals(src, dst);
}
 
Example 8
Source File: CharSeqTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void test1() throws IOException {
    ObjectWriter writer = mapper().writer();
    CharSeq src = CharSeq.of("abc");
    String json = writer.writeValueAsString(src);
    Assertions.assertEquals("\"abc\"", json);
    CharSeq dst = mapper().readValue(json, CharSeq.class);
    Assertions.assertEquals(src, dst);
}
 
Example 9
Source File: JsonUtil.java    From cf-java-client-sap with Apache License 2.0 5 votes vote down vote up
private static String convertToJsonStringUsingWriter(ObjectWriter writer, Object value) {
    if (value == null || writer.canSerialize(value.getClass())) {
        try {
            return writer.writeValueAsString(value);
        } catch (IOException e) {
            logger.warn("Error while serializing " + value + " to JSON", e);
            return null;
        }

    } else {
        throw new IllegalArgumentException("Value of type " + value.getClass()
                                                                   .getName()
            + " can not be serialized to JSON.");
    }
}
 
Example 10
Source File: MonetaryAmountSerializerTest.java    From jackson-datatype-money with MIT License 5 votes vote down vote up
@ParameterizedTest
@MethodSource("amounts")
void shouldSerializeWithCustomName(final MonetaryAmount amount) throws IOException {
    final ObjectMapper unit = unit(module().withDefaultFormatting()
            .withAmountFieldName("value")
            .withCurrencyFieldName("unit")
            .withFormattedFieldName("pretty"));

    final String expected = "{\"value\":29.95,\"unit\":\"EUR\",\"pretty\":\"29,95 EUR\"}";

    final ObjectWriter writer = unit.writer().with(Locale.GERMANY);
    final String actual = writer.writeValueAsString(amount);

    assertThat(actual, is(expected));
}
 
Example 11
Source File: TrpTokenCreditSerializationTest.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void test() throws JAXBException, JsonProcessingException {
	TrpCreditProduct p = new TrpCreditProduct();
	p.setAvailableFrom(new Date());
	p.setAvailableUntil(new Date());
	p.setCreditType("HTR");
	p.setLabel("Test Product");
	p.setNrOfCredits(1543);
	p.setShareable(true);
	p.setSubscription("Monthly");
	
	TrpCreditPackage c = new TrpCreditPackage();
	c.setActive(true);
	c.setBalance(1543d);
	c.setExpirationDate(new Date());
	c.setPaymentReceived(new Date());
	c.setPurchaseDate(new Date());
	c.setUserId(43);
	
	c.setProduct(p);
	
	SSW sw = new SSW();
	sw.start();
	Gson gson = new GsonBuilder().setPrettyPrinting().create();
	String gsonOut = gson.toJson(c);
	long time = sw.stop(false);
	logger.info("GSON ({} ms) says:\n\n{}\n\n", time, gsonOut);
	
	sw.start();
	String moxyOut = JaxbUtils.marshalToJsonString(c, true);
	time = sw.stop(false);
	logger.info("Moxy ({} ms) says:\n\n{}\n\n", time, moxyOut);
	
	sw.start();
	ObjectWriter writer = new ObjectMapper().writerWithDefaultPrettyPrinter();
	String jacksonOut = writer.writeValueAsString(c);
	time = sw.stop(false);
	logger.info("Jackson ({} ms) says:\n\n{}\n\n", time, jacksonOut);
}
 
Example 12
Source File: LinkSerializerTest.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void testSerialize() throws Exception {
    AgentHistogramList list = new AgentHistogramList();
    AgentHistogram histogram = new AgentHistogram(new Application("test", ServiceType.STAND_ALONE));
    list.addAgentHistogram(histogram);
    Node node1 = new Node(new Application("test1", ServiceType.STAND_ALONE));
    Node node2 = new Node(new Application("test1", ServiceType.STAND_ALONE));

    Link link = new Link(CreateType.Source, node1, node2, Range.newRange(0, 1));
    ObjectWriter objectWriter = MAPPER.writerWithDefaultPrettyPrinter();
    String s = objectWriter.writeValueAsString(link);

    logger.debug(s);
}
 
Example 13
Source File: JsonParser.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
private static String toJson(ObjectWriter writer, Object o) {
    try {
        return writer.writeValueAsString(o);
    } catch (Exception e) {
        log.error("Error jsoning object.", e);
    }
    return "{}";
}
 
Example 14
Source File: PhysicalPlan.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/** Converts a physical plan to a string. (Opposite of {@link #parse}.) */
public String unparse(ObjectWriter writer) {
  try {
    return writer.writeValueAsString(this);
  } catch (JsonProcessingException e) {
    throw new RuntimeException(e);
  }
}
 
Example 15
Source File: QuickstarterApiControllerTest.java    From ods-provisioning-app with Apache License 2.0 4 votes vote down vote up
private String getBody() throws Exception {
  ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
  String json = ow.writeValueAsString(project);
  return json;
}
 
Example 16
Source File: ClusteringActionIT.java    From elasticsearch-carrot2 with Apache License 2.0 4 votes vote down vote up
public void testIncludeHits() throws IOException {
    // same search with and without hits
    SearchRequestBuilder req = client.prepareSearch()
            .setIndices(INDEX_TEST)
            .setSize(2)
            .setQuery(QueryBuilders.termQuery("content", "data"))
            .setFetchSource(new String[] {"content"}, null);

    // with hits (default)
    ClusteringActionResponse resultWithHits = new ClusteringActionRequestBuilder(client)
        .setQueryHint("data mining")
        .setAlgorithm(STCClusteringAlgorithm.NAME)
        .addSourceFieldMapping("title", LogicalField.TITLE)
        .setCreateUngroupedDocumentsCluster(true)
        .setSearchRequest(req)
        .execute().actionGet();
    checkValid(resultWithHits);
    checkJsonSerialization(resultWithHits);
    // get JSON output
    XContentBuilder builder = XContentFactory.jsonBuilder().prettyPrint();
    builder.startObject();
    resultWithHits.toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.endObject();

    ObjectNode jsonWithHits = (ObjectNode) new ObjectMapper().readTree(Strings.toString(builder));
    Assertions.assertThat(jsonWithHits.has("hits")).isTrue();

    // without hits
    ClusteringActionResponse resultWithoutHits = new ClusteringActionRequestBuilder(client)
        .setQueryHint("data mining")
        .setMaxHits(0)
        .setAlgorithm(STCClusteringAlgorithm.NAME)
        .addSourceFieldMapping("title", LogicalField.TITLE)
        .setCreateUngroupedDocumentsCluster(true)
        .setSearchRequest(req)
        .execute().actionGet();
    checkValid(resultWithoutHits);
    checkJsonSerialization(resultWithoutHits);

    // get JSON output
    builder = XContentFactory.jsonBuilder().prettyPrint();
    builder.startObject();
    resultWithoutHits.toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.endObject();
    ObjectNode jsonWithoutHits = (ObjectNode) new ObjectMapper().readTree(Strings.toString(builder));

    ObjectWriter ow = new ObjectMapper().writerWithDefaultPrettyPrinter();
    Assertions.assertThat(jsonWithoutHits.get("hits").get("hits").size()).isEqualTo(0);

    // insert hits into jsonWithoutHits
    jsonWithoutHits.set("hits", jsonWithHits.get("hits"));

    // 'took' can vary, so ignore it
    jsonWithoutHits.remove("took");
    jsonWithHits.remove("took");

    // info can vary (clustering-millis, output_hits), so ignore it
    jsonWithoutHits.remove("info");
    jsonWithHits.remove("info");

    // profile can vary
    jsonWithoutHits.remove("profile");
    jsonWithHits.remove("profile");

    // now they should match
    String json1 = ow.writeValueAsString(jsonWithHits);
    logger.debug("--> with:\n" + json1);
    String json2 = ow.writeValueAsString(jsonWithoutHits);
    logger.debug("--> without:\n" + json2);
    Assertions.assertThat(json1).isEqualTo(json2);
}
 
Example 17
Source File: HttpRestWb.java    From document-management-software with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static void find(CloseableHttpClient httpclient, WSSearchOptions wsso) throws Exception {

		System.out.println("find");
		//CloseableHttpClient httpclient = HttpClients.createDefault();
		
        HttpPost httppost = new HttpPost(BASE_PATH + "/services/rest/search/find");
        httppost.addHeader(new BasicHeader("Accept", "application/json"));

		//ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        ObjectMapper mapper = new ObjectMapper();
        ObjectWriter ow = mapper.writer();
		String jsonStr = ow.writeValueAsString(wsso);
		System.out.println(jsonStr);
		
		StringEntity entity = new StringEntity(jsonStr, ContentType.create("application/json", Consts.UTF_8));
		httppost.setEntity(entity);		

		CloseableHttpResponse response = httpclient.execute(httppost);
		
		int code = response.getStatusLine().getStatusCode();
		System.out.println("HTTPstatus code: "+ code);
		
		if (code == HttpStatus.SC_OK) {
		} else {
			//log.warn("status code is invalid: {}", code);
			System.err.println("status code is invalid: "+ code);
			throw new Exception(response.getStatusLine().getReasonPhrase());
		}			
		
		try {
			HttpEntity rent = response.getEntity();
			if (rent != null) {
				String respoBody = EntityUtils.toString(rent, "UTF-8");
				System.out.println(respoBody);
				
				//JSON from String to Object
				//WSSearchResult obj = mapper.readValue(respoBody, WSSearchResult.class);
				//System.out.println(ow.writeValueAsString(obj) );				
			}
		} finally {
			response.close();
		}
	}
 
Example 18
Source File: RestFidoActionsOnPolicy.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static void patch(String REST_URI,
                        String did,
                        String accesskey,
                        String secretkey,
                        String sidpid,
                        Long startdate,
                        Long enddate,
                        Integer version,
                        String status,
                        String notes,
                        String policy) throws Exception
{
    System.out.println("Patch policy test");
    System.out.println("******************************************");

    String apiversion = "2.0";

    //  Make API rest call and get response from the server
    String resourceLoc = REST_URI + Constants.REST_SUFFIX + did + Constants.PATCH_POLICY_ENDPOINT + "/" + sidpid;
    System.out.println("\nCalling update @ " + resourceLoc);

    PatchFidoPolicyRequest pfpr = new PatchFidoPolicyRequest();
    pfpr.setStartDate(startdate);
    if (enddate != null)
        pfpr.setEndDate(enddate);
    pfpr.setVersion(version);
    pfpr.setStatus(status);
    pfpr.setNotes(notes);
    pfpr.setPolicy(policy);

    ObjectWriter ow = new ObjectMapper().writer();
    String json = ow.writeValueAsString(pfpr);

    ContentType mimetype = ContentType.create("application/merge-patch+json");
    StringEntity body = new StringEntity(json, mimetype);

    String currentDate = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z").format(new Date());
    String contentSHA = common.calculateSha256(json);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPatch httpPatch = new HttpPatch(resourceLoc);
    httpPatch.setEntity(body);
    String requestToHmac = httpPatch.getMethod() + "\n"
            + contentSHA + "\n"
            + mimetype.getMimeType() + "\n"
            + currentDate + "\n"
            + apiversion + "\n"
            + httpPatch.getURI().getPath();

    String hmac = common.calculateHMAC(secretkey, requestToHmac);
    httpPatch.addHeader("Authorization", "HMAC " + accesskey + ":" + hmac);
    httpPatch.addHeader("strongkey-content-sha256", contentSHA);
    httpPatch.addHeader("Content-Type", mimetype.getMimeType());
    httpPatch.addHeader("Date", currentDate);
    httpPatch.addHeader("strongkey-api-version", apiversion);
    CloseableHttpResponse response = httpclient.execute(httpPatch);
    String result;
    try {
        StatusLine responseStatusLine = response.getStatusLine();
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity);
        EntityUtils.consume(entity);

        switch (responseStatusLine.getStatusCode()) {
            case 200:
                break;
            case 401:
                System.out.println("Error during patch fido policy : 401 HMAC Authentication Failed");
                return;
            case 404:
                System.out.println("Error during patch fido policy : 404 Resource not found");
                return;
            case 400:
            case 500:
            default:
                System.out.println("Error during patch fido policy : " + responseStatusLine.getStatusCode() + " " + result);
                return;
        }

    } finally {
        response.close();
    }

    System.out.println(" Response : " + result);

    System.out.println("\nPatch policy test complete.");
    System.out.println("******************************************");
}
 
Example 19
Source File: TestMapMessage.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
@Test
public void testMapMessageSerializationWithJson() throws IOException {
    MapMessage message = new MapMessage("namespace", "name");
    message.addField("boolean", true);
    message.addField("boolean_array", Arrays.asList(new Boolean[] { true, false }));
    message.addField("byte", (byte) 1);
    message.addField("byte_array", Arrays.asList(new Byte[] { 2, 3, 4 }));
    message.addField("short", (short) 5);
    message.addField("short_array", Arrays.asList(new Short[] { 6, 7, 8 }));
    message.addField("int", 9);
    message.addField("int_array", Arrays.asList(new Integer[] { 10, 11, 12 }));
    message.addField("long", 13l);
    message.addField("long_array", Arrays.asList(new Long[] { 14l, 15l, 16l }));
    message.addField("float", 17.1f);
    message.addField("float_array", Arrays.asList(new Float[] { 18.1f, 19.1f, 20.1f }));
    message.addField("double", 21.1d);
    message.addField("double_array", Arrays.asList(new Double[] { 22.1d, 23.1d, 24.1d }));
    message.addField("bigdecimal", new BigDecimal("25.1"));
    message.addField("bigdecimal_array", Arrays.asList(new BigDecimal[] { new BigDecimal("26.1"), new BigDecimal("27.1"), new BigDecimal("28.1") }));
    message.addField("char", 'a');
    message.addField("char_array", Arrays.asList(new Character[] { 'b', 'c', 'd' }));
    message.addField("string", "ef");
    message.addField("string_array", Arrays.asList(new String[] { "gh", "jk", "lm" }));
    message.addField("localdatetime", DateTimeUtility.nowLocalDateTime());
    message.addField("localdatetime_array", Arrays.asList(new LocalDateTime[] { DateTimeUtility.nowLocalDateTime(), DateTimeUtility.nowLocalDateTime(), DateTimeUtility.nowLocalDateTime() }));
    message.addField("localdate", DateTimeUtility.nowLocalDate());
    message.addField("localdate_array", Arrays.asList(new LocalDate[] { DateTimeUtility.nowLocalDate(), DateTimeUtility.nowLocalDate(), DateTimeUtility.nowLocalDate() }));
    message.addField("localtime", DateTimeUtility.nowLocalTime());
    message.addField("localtime_array", Arrays.asList(new LocalTime[] { DateTimeUtility.nowLocalTime(), DateTimeUtility.nowLocalTime(), DateTimeUtility.nowLocalTime() }));
    
    MsgMetaData metaData = message.getMetaData();
    metaData.setDictionaryURI(SailfishURI.unsafeParse("plugin.dictionary"));
    metaData.setFromService("fromService");
    metaData.setToService("toService");
    metaData.setRawMessage(new byte[] { 1, 2, 3, 4, 5 });
    metaData.setServiceInfo(new ServiceInfo("id", new ServiceName("env", "serviceName")));
    
    MapMessage subMessage = message.cloneMessage();
    message.addField("message", subMessage);
    message.addField("message_array", Arrays.asList(new MapMessage[] { subMessage, subMessage }));
    
    ObjectMapper objectMapper = new ObjectMapper().enableDefaultTyping(DefaultTyping.NON_FINAL)
            .registerModule(new JavaTimeModule());
    ObjectReader reader = objectMapper.reader(IMessage.class);
    ObjectWriter writer = objectMapper.writer();
    
    String json = writer.writeValueAsString(message);
    
    IMessage message2 = reader.readValue(json);
    
    Assert.assertEquals(message, message2);
}
 
Example 20
Source File: ObjectMapperIT.java    From pinpoint with Apache License 2.0 3 votes vote down vote up
@Test
public void testWriteValue() throws Exception {
    __POJO pojo = new __POJO();
    pojo.setName("Jackson");

    String jsonStr = mapper.writeValueAsString(pojo);
    byte[] jsonByte = mapper.writeValueAsBytes(pojo);
    
    ObjectWriter writer = mapper.writer();

    writer.writeValueAsString(pojo);
    writer.writeValueAsBytes(pojo);


    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();

    Method mapperWriteValueAsString = ObjectMapper.class.getMethod("writeValueAsString", Object.class);
    Method mapperWriteValueAsBytes = ObjectMapper.class.getMethod("writeValueAsBytes", Object.class);
    Method writerWriteValueAsString = ObjectWriter.class.getMethod("writeValueAsString", Object.class);
    Method writerWriteValueAsBytes = ObjectWriter.class.getMethod("writeValueAsBytes", Object.class);


    verifier.verifyTrace(event(SERVICE_TYPE, mapperWriteValueAsString, annotation(ANNOTATION_KEY, jsonStr.length())));
    verifier.verifyTrace(event(SERVICE_TYPE, mapperWriteValueAsBytes, annotation(ANNOTATION_KEY, jsonByte.length)));

    verifier.verifyTrace(event(SERVICE_TYPE, writerWriteValueAsString, annotation(ANNOTATION_KEY, jsonStr.length())));
    verifier.verifyTrace(event(SERVICE_TYPE, writerWriteValueAsBytes, annotation(ANNOTATION_KEY, jsonByte.length)));

    verifier.verifyTraceCount(0);
}