Java Code Examples for com.fasterxml.jackson.core.JsonProcessingException

The following are top voted examples for showing how to use com.fasterxml.jackson.core.JsonProcessingException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: athena   File: ObjectMapperUtil.java   View source code 8 votes vote down vote up
/**
 * convert Object into String.
 * @param obj Object
 * @return String
 */
public static String convertToString(Object obj) {
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        return objectMapper.writeValueAsString(obj);
    } catch (JsonProcessingException e) {
        log.error("JsonProcessingException while converting Entity into string", e);
    }
    return null;
}
 
Example 2
Project: PepSIIrup-2017   File: EventController.java   View source code 7 votes vote down vote up
/**
 * method to get all the events type 
 * @param id
 * @return
 * @throws JsonProcessingException
 */
@RabbitListener(queues = "#{getAllEventTypeQueue.name}")
public String getAllEventType(byte[] id){
	String res = "";
	List<EventType> eventsType = eventTypeRepository.findAll();
	ObjectMapper mapper = new ObjectMapper();
	Log
	.forContext("MemberName", "getAllEventType")
	.forContext("Service", appName)
	.information("RabbitMQ : getAllEventType");
	try {
		res = mapper.writeValueAsString(eventsType);
	} catch (JsonProcessingException e1) {
		Log
		.forContext("MemberName", "getAllEventType")
		.forContext("Service", appName)
		.error(e1,"JsonProcessingException");
	}
	return res;
}
 
Example 3
Project: spark-examples   File: ApiGatewayResponse.java   View source code 6 votes vote down vote up
public ApiGatewayResponse build() {
    String body = null;
    if (rawBody != null) {
        body = rawBody;
    } else if (objectBody != null) {
        try {
            body = objectMapper.writeValueAsString(objectBody);
        } catch (JsonProcessingException e) {
            LOG.error("failed to serialize object", e);
            throw new RuntimeException(e);
        }
    } else if (binaryBody != null) {
        body = new String(Base64.getEncoder().encode(binaryBody), StandardCharsets.UTF_8);
    }
    return new ApiGatewayResponse(statusCode, body, headers, base64Encoded);
}
 
Example 4
Project: TOSCAna   File: ResourceFileCreatorTest.java   View source code 6 votes vote down vote up
@Test
public void testReplicationControllerCreation() {
    ResourceFileCreator resourceFileCreator = new ResourceFileCreator(Pod.getPods(TestNodeStacks.getLampNodeStacks(log)));

    HashMap<String, String> result = null;
    try {
        result = resourceFileCreator.create();
    } catch (JsonProcessingException e) {
        e.printStackTrace();
        fail();
    }

    String service = result.get(appServiceName);
    String deployment = result.get(appDeploymentName);
    Yaml yaml = new Yaml();
    serviceTest((Map) yaml.load(service));
    deploymentTest((Map) yaml.load(deployment));
}
 
Example 5
Project: tdd-pingpong   File: FakeSandboxRestService.java   View source code 6 votes vote down vote up
private HttpEntity<MultiValueMap<String, String>> buildResponseEntity(
    Submission submission, HttpHeaders headers) {
  logger.debug("Building response entity");
  MultiValueMap<String, String> map = new LinkedMultiValueMap<>();

  try {
    map.add("test_output", new ObjectMapper().writeValueAsString(
        submission.getTestOutput()));
  } catch (JsonProcessingException ex) {
    logger.debug("POJO deserialization failed");
  }
  map.add("stdout", submission.getStdout());
  map.add("stderr", submission.getStderr());
  map.add("validations", submission.getValidations());
  map.add("vm_log", submission.getVmLog());
  map.add("token", submission.getId().toString());
  map.add("status", submission.getStatus().toString());
  map.add("exit_code", submission.getExitCode().toString());

  return new HttpEntity<>(map, headers);
}
 
Example 6
Project: verify-hub   File: SamlMessageReceiverApiResourceTest.java   View source code 6 votes vote down vote up
private SamlRequestDto createAuthnRequest(String issuer, String relayState, String publicCert, String privateKey) throws JsonProcessingException {
    String id = AuthnRequestIdGenerator.generateRequestId();
    Optional<Boolean> forceAuthentication = Optional.of(false);
    Optional<Integer> assertionConsumerServiceIndex = Optional.of(1);
    Optional<URI> assertionConsumerServiceUrl = Optional.empty();
    String anAuthnRequest = authnRequestFactory.anAuthnRequest(
            id,
            issuer,
            forceAuthentication,
            assertionConsumerServiceUrl,
            assertionConsumerServiceIndex,
            publicCert,
            privateKey,
            Endpoints.SSO_REQUEST_ENDPOINT,
            Optional.empty());
    SamlRequestDto authnRequestWrapper = new SamlRequestDto(anAuthnRequest, relayState, "ipAddress");
    return authnRequestWrapper;
}
 
Example 7
Project: GitHub   File: AdditionalPropertiesIT.java   View source code 6 votes vote down vote up
@Test
public void additionalPropertiesWorkWithAllVisibility() throws ClassNotFoundException, SecurityException, NoSuchMethodException, JsonProcessingException, IOException {
    mapper.configure(MapperFeature.AUTO_DETECT_GETTERS, false);
    mapper.configure(MapperFeature.AUTO_DETECT_SETTERS, false);
    mapper.setVisibility(mapper.getVisibilityChecker().with(Visibility.ANY));

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/additionalProperties/defaultAdditionalProperties.json", "com.example");

    Class<?> classWithAdditionalProperties = resultsClassLoader.loadClass("com.example.DefaultAdditionalProperties");
    String jsonWithAdditionalProperties = "{\"a\":1, \"b\":2};";
    Object instanceWithAdditionalProperties = mapper.readValue(jsonWithAdditionalProperties, classWithAdditionalProperties);

    JsonNode jsonNode = mapper.readTree(mapper.writeValueAsString(instanceWithAdditionalProperties));

    assertThat(jsonNode.path("a").asText(), is("1"));
    assertThat(jsonNode.path("b").asInt(), is(2));
    assertThat(jsonNode.has("additionalProperties"), is(false));
}
 
Example 8
Project: beaker-notebook-archive   File: TextSerializer.java   View source code 6 votes vote down vote up
@Override
public void serialize(Text text, JsonGenerator jgen, SerializerProvider sp)
  throws IOException, JsonProcessingException {

  boolean isNanoPlot = NanoPlot.class.equals(text.getPlotType());
  jgen.writeStartObject();
  jgen.writeObjectField("type", text.getClass().getSimpleName());
  jgen.writeObjectField("x", isNanoPlot ? processLargeNumber(text.getX()) : text.getX());
  jgen.writeObjectField("y", text.getY());
  jgen.writeObjectField("show_pointer", text.getShowPointer());
  jgen.writeObjectField("text", text.getText());
  jgen.writeObjectField("pointer_angle", text.getPointerAngle());
  jgen.writeObjectField("color", text.getColor());
  jgen.writeObjectField("size", text.getSize());
  jgen.writeEndObject();
}
 
Example 9
Project: GitHub   File: GeneratorFailFromReaderTest.java   View source code 6 votes vote down vote up
private void _testFailOnWritingStringFromNullReader(JsonFactory f, boolean useReader) throws Exception{
    JsonGenerator gen;
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    if (useReader) {
        gen = f.createGenerator(ObjectWriteContext.empty(), new OutputStreamWriter(bout, "UTF-8"));
    } else {
        gen = f.createGenerator(ObjectWriteContext.empty(), bout, JsonEncoding.UTF8);
    }
    gen.writeStartObject();

    try {
        gen.writeFieldName("a");
        gen.writeString(null, -1);
        gen.flush();
        String json = bout.toString("UTF-8");
        fail("Should not have let "+gen.getClass().getName()+".writeString() ': output = "+json);
    } catch (JsonProcessingException e) {
        verifyException(e, "null reader");
    }
    gen.close();
}
 
Example 10
Project: saluki   File: OAuth2RefreshTokenJackson2SerializerDeserializer.java   View source code 6 votes vote down vote up
@Override
public OAuth2RefreshToken deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {

    String tokenValue = null;
    Long expiration = null;

    while (p.nextToken() != JsonToken.END_OBJECT) {
        String name = p.getCurrentName();
        p.nextToken();
        if (TOKEN_VALUE.equals(name)) {
            tokenValue = p.getText();
        } else if (EXPIRATION.equals(name)) {
            try {
                expiration = p.getLongValue();
            } catch (JsonParseException e) {
                expiration = Long.valueOf(p.getText());
            }
        }
    }

    if (expiration != null) {
        return new DefaultExpiringOAuth2RefreshToken(tokenValue, new Date(expiration));
    } else {
        return new DefaultOAuth2RefreshToken(tokenValue);
    }
}
 
Example 11
Project: sf-java-ui   File: PasswordFormTest.java   View source code 6 votes vote down vote up
@Test
public void testGenerate_Password_WithFieldAddonLeft() throws JsonProcessingException {
	UiForm ui = UiFormSchemaGenerator.get().generate(PasswordForm3.class);
	
	String json = new ObjectMapper().writeValueAsString(ui);
	Assert.assertThat(json, hasJsonPath("$.schema.properties.password.title",equalTo("Password")));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='password')]",hasSize(1)));
	Assert.assertThat(json, hasJsonPath("$.schema.properties.password.pattern", equalTo("[a-z]")));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='password')].description",hasItem("This is password")));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='password')].placeholder",hasItem("Please set you password")));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='password')].validationMessage",hasItem("this is a validation msg")));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='password')].type",hasItem("password")));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='password')].notitle",hasItem(true)));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='password')].readonly",hasItem(true)));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='password')].fieldAddonLeft",hasItem("@")));

}
 
Example 12
Project: cf2pojo   File: SubFunction.java   View source code 6 votes vote down vote up
@Override
public void serialize(SubFunction value, JsonGenerator gen, SerializerProvider serializers)
    throws IOException, JsonProcessingException {
    gen.writeStartObject();
    gen.writeFieldName("Fn::Sub");

    if (value.getVariableMap() == null) {
        gen.writeString(value.getStringTemplate());
    } else {
        gen.writeStartArray();
        gen.writeString(value.getStringTemplate());
        serializers.defaultSerializeValue(value.getVariableMap(), gen);
        gen.writeEndArray();
    }

    gen.writeEndObject();
}
 
Example 13
Project: beaker-notebook-archive   File: BeakerCodeCell.java   View source code 6 votes vote down vote up
@Override
public void serialize(BeakerCodeCell value,
    JsonGenerator jgen,
    SerializerProvider provider)
    throws IOException, JsonProcessingException {

  synchronized (value) {
    jgen.writeStartObject();
    jgen.writeStringField("type", "BeakerCodeCell");
    jgen.writeStringField("execution_count", value.executionCount);
    jgen.writeStringField("cell_type", value.cellType);
    jgen.writeFieldName("outputs");
    if (!getObjectSerializer().writeObject(value.outputs, jgen, true))
      jgen.writeString(value.outputs.toString());
    jgen.writeFieldName("metadata");
    if (!getObjectSerializer().writeObject(value.metadata, jgen, true))
      jgen.writeString(value.metadata.toString());
    jgen.writeStringField("source", value.source);
    jgen.writeEndObject();
  }
}
 
Example 14
Project: Equella   File: BrightspaceConnectorServiceImpl.java   View source code 6 votes vote down vote up
private String getAuthorisationUrl(BrightspaceAppContext appContext, String forwardUrl, @Nullable String postfixKey)
{
	final ObjectMapper mapper = new ObjectMapper();
	final ObjectNode stateJson = mapper.createObjectNode();
	stateJson.put(BrightspaceConnectorConstants.STATE_KEY_FORWARD_URL, forwardUrl);
	if( postfixKey != null )
	{
		stateJson.put(BrightspaceConnectorConstants.STATE_KEY_POSTFIX_KEY, postfixKey);
	}

	URI uri;
	try
	{
		uri = appContext.createWebUrlForAuthentication(
			URI.create(institutionService.institutionalise(BrightspaceConnectorConstants.AUTH_URL)),
			encrypt(mapper.writeValueAsString(stateJson)));
	}
	catch( JsonProcessingException e )
	{
		throw Throwables.propagate(e);
	}
	return uri.toString();
}
 
Example 15
Project: rate-limiting   File: ConfigurationLoader.java   View source code 6 votes vote down vote up
public ConfigLoadResult loadConfig(FilterConfig filterConfig) throws JsonProcessingException, IOException {
	if (result == null) {
		result = new ConfigLoadResult();
		result.settingsFile = findConfigFile(filterConfig);

		if (result.settingsFile != null) {
			result.settings = loadConfigFromFile(result.settingsFile, filterId);
		}

		if (result.settings == null) {
			result.settingsFile = null;
			result.settings = readConfigFromFilter(filterConfig);
		}
	}

	return result;
}
 
Example 16
Project: OpenLRW   File: EntityTest.java   View source code 6 votes vote down vote up
@Test
public void whenFullyPopulatedJsonContainsEverything() throws JsonProcessingException {
  
  Entity entity
  = new Entity.Builder()
    .withId("id1")
    .withType("type1")
    .withName("name1")
    .withDescription("description1")
    .withExtensions(Collections.singletonMap("foo", "bar"))
    .withDateCreated(LocalDateTime.now())
    .withDateModified(LocalDateTime.now())
    .build();
  
  String result = mapper.writeValueAsString(entity);
  assertThat(result, containsString("@id"));
  assertThat(result, containsString("@type"));
  assertThat(result, containsString("type1"));
  assertThat(result, containsString("id1"));
  assertThat(result, containsString("name1"));
  assertThat(result, containsString("description1"));
  assertThat(result, containsString("foo"));
  assertThat(result, containsString("bar"));
}
 
Example 17
Project: cloud-app   File: JsonFactory.java   View source code 6 votes vote down vote up
public String toJSon(Object o) {

		//jackson object mapper
		ObjectMapper mapper = new ObjectMapper();

		//enable json pretty printing
		//mapper.enable(SerializationFeature.INDENT_OUTPUT);

		try {
			return mapper.writeValueAsString(o);

		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return null;
	}
 
Example 18
Project: drinkwater-java   File: AbstractEventLogger.java   View source code 6 votes vote down vote up
protected String serializeEvent(BaseEvent event) throws JsonProcessingException {
    StringBuilder builder = new StringBuilder();
    builder.append(event.getTime().toEpochMilli());
    builder.append("-");
    builder.append(event.getName());
    builder.append("-");
    builder.append(event.getCorrelationId());
    builder.append("-");
    builder.append(event.getDescription());
    builder.append(" -> START_PAYLOAD");
    int counter = 1;
    for (Object obj :
            event.getPayload().getTarget()) {
        builder.append("-[" + counter++ + ":");
        builder.append(serializeObject(obj));
        builder.append("]");

    }
    builder.append("END_PAYLOAD");
    return trimString(builder.toString());
}
 
Example 19
Project: nohibernate-core   File: NoHibernateUtils.java   View source code 6 votes vote down vote up
/**
 * Serialize object to JSON with two sections: HEAD (containing JAVA_CLASS) and BODY (containing object itself)
 * @param o uncomplicated object you want to serialize
 * @return object serialized to JSON
 */
public static String object2CustomString(Object o) {
    if (o == null) {
        throw new IllegalArgumentException("Object cannot be null");
    }
    ObjectNode objectNode = OBJECT_MAPPER.createObjectNode();
    ObjectNode headNode = OBJECT_MAPPER.createObjectNode();
    headNode.put(NoHibernate.Field.Head.JAVA_CLASS, o.getClass().getName());
    ObjectNode bodyNode = OBJECT_MAPPER.convertValue(o, ObjectNode.class);
    objectNode.set(NoHibernate.Field.HEAD, headNode);
    objectNode.set(NoHibernate.Field.BODY, bodyNode);
    try {
        return OBJECT_MAPPER.writeValueAsString(objectNode);
    } catch (JsonProcessingException e) {
        throw new IllegalArgumentException("Object \"" + o + "\" cannot be translated to string");
    }
}
 
Example 20
Project: sf-java-ui   File: ComboBoxFormTest.java   View source code 6 votes vote down vote up
@Test
public void testGenerate_ComboBox_WithCustomValuesContainer() throws JsonProcessingException {
	UiForm ui = UiFormSchemaGenerator.get().generate(ComboBoxForm2.class);

	String json = new ObjectMapper().writeValueAsString(ui);
	Assert.assertThat(json, hasJsonPath("$.schema.properties.gender.title", equalTo("Gender")));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='gender')]", hasSize(1)));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='gender')].disabled", hasItem(false)));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='gender')].multiple", hasItem(false)));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='gender')].required", hasItem(false)));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='gender')].autofocus", hasItem(false)));
	Assert.assertThat(json,
			hasJsonPath("$.form[?(@.key=='gender')].titleMap[?(@.name=='Male')].value", hasItem("male")));
	Assert.assertThat(json,
			hasJsonPath("$.form[?(@.key=='gender')].titleMap[?(@.name=='Female')].value", hasItem("female")));

}
 
Example 21
Project: gchange-pod   File: RegistryIndexDaoImpl.java   View source code 6 votes vote down vote up
@Override
protected void createIndex() throws JsonProcessingException {
    logger.info(String.format("Creating index [%s]", INDEX));

    CreateIndexRequestBuilder createIndexRequestBuilder = client.admin().indices().prepareCreate(INDEX);
    org.elasticsearch.common.settings.Settings indexSettings = org.elasticsearch.common.settings.Settings.settingsBuilder()
            .put("number_of_shards", 3)
            .put("number_of_replicas", 1)
            //.put("analyzer", createDefaultAnalyzer())
            .build();
    createIndexRequestBuilder.setSettings(indexSettings);
    createIndexRequestBuilder.addMapping(recordDao.getType(), recordDao.createTypeMapping());
    createIndexRequestBuilder.addMapping(commentDao.getType(), commentDao.createTypeMapping());
    createIndexRequestBuilder.addMapping(RegistryIndexDao.CATEGORY_TYPE, createCategoryTypeMapping());
    createIndexRequestBuilder.execute().actionGet();

    // Fill categories
    fillRecordCategories();
}
 
Example 22
Project: etomica   File: ParmedStructure.java   View source code 6 votes vote down vote up
/**
 * Gets the (single, rectangular) box found in this Structure.
 *
 * @return a Box object with the same boundary coordinates as the box in the Structure.
 */
public Box getBox() {
    JsonNode boxNode = root.get("_box");
    double[] boxGeometry;
    try {
        boxGeometry = mapper.treeToValue(boxNode.get(0), double[].class);
    } catch (JsonProcessingException e) {
        throw new RuntimeException("Error during JSON processing");
    }
    double[] boxCoordinates = Arrays.copyOf(boxGeometry, 3);

    Box box = new Box(SPACE);
    Boundary bound = new BoundaryRectangularPeriodic(SPACE, boxCoordinates);
    box.setBoundary(bound);
    return box;
}
 
Example 23
Project: soundwave   File: StringArrayOrElementStringDeserializer.java   View source code 6 votes vote down vote up
@Override
public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
    throws IOException, JsonProcessingException {
  ObjectCodec oc = jsonParser.getCodec();
  JsonNode node = oc.readTree(jsonParser);
  if (node instanceof ArrayNode) {
    ArrayNode arrayNode = (ArrayNode) node;
    ArrayList<String> ret = new ArrayList<>();
    for (int i = 0; i < arrayNode.size(); i++) {
      ret.add(arrayNode.get(i).textValue());
    }
    return ret.toArray(new String[0]);
  } else {
    return new String[]{node.textValue()};
  }

}
 
Example 24
Project: csap-core   File: Load_Working_Models_Test.java   View source code 6 votes vote down vote up
@Test
public void verify_platform_score_from_csaptools ()
		throws JsonProcessingException, IOException {
	logger.info( InitializeLogging.TC_HEAD );

	File csapApplicationDefinition = new File(
		getClass().getResource( "/org/csap/test/data/clusterConfigManager.json" ).getPath() );

	assertThat( csapApplication.loadDefinitionForJunits( false, csapApplicationDefinition ) )
		.as( "No Errors or warnings" )
		.isTrue();

	CSAP.setLogToDebug( Application.class.getName() );
	ObjectNode score = csapApplication.getPlatformScore( true );

	logger.info( "Score: {}", CSAP.jsonPrint( jacksonMapper, score ) );

	assertThat( score.get( Application.AGENT_ID ).asText() )
		.as( "Platform scorecards on landing page" )
		.contains( " of 8" );

	CSAP.setLogToInfo( Application.class.getName() );
}
 
Example 25
Project: rate-limiting   File: ConfigurationLoader.java   View source code 6 votes vote down vote up
private String findConfigFile(FilterConfig filterConfig) throws IOException, JsonProcessingException {

		String filename = System.getProperty(SystemConfigFileProperty);

		if (isFileValid(filename)) {
			logger.info("Using configuration file '" + filename + "' specified by system property '"
					+ SystemConfigFileProperty + "'");
			return filename;
		}

		filename = filterConfig.getInitParameter(SystemConfigFileProperty);
		if (isFileValid(filename)) {
			logger.info("Using configuration file '" + filename + "' specified in web.xml");
			return filename;
		}

		return null;
	}
 
Example 26
Project: fluid   File: SourceAndSinkBuilder.java   View source code 6 votes vote down vote up
private static Source buildSource(ObjectMapper mapper, Vertx vertx, String name, JsonNode config) {
  String type = config.get("type").asText(null);
  if (type == null) {
    throw new NullPointerException("Invalid configuration, the config " + name + " has no `type`");
  }

  SourceFactory factory = lookupForSourceFactory(type);
  if (factory == null) {
    throw new NullPointerException("Invalid configuration, the source type " + type + " is unknown");
  }

  try {
    String json = mapper.writeValueAsString(config);
    return factory.create(vertx, new JsonObject(json).put("name", name)).blockingGet();
  } catch (JsonProcessingException e) {
    throw new IllegalArgumentException("Invalid configuration for " + name, e);
  }
}
 
Example 27
Project: TOSCAna   File: Connection.java   View source code 6 votes vote down vote up
/**
 Method to get the service credentials which depends on the CloudFoundry instance.
 Therefore a connection to a CF instance is needed
 and the application has to be deployed and binded to the given service
 You can get special credentials in this way: JSONObject.getString("port")

 @return JSONObject with credentials of the given serviceId
 */
public JSONObject getServiceCredentials(String serviceName, String applicationName)
    throws JSONException, JsonProcessingException {

    ApplicationEnvironments environments = cloudFoundryOperations.applications()
        .getEnvironments(GetApplicationEnvironmentsRequest.builder()
            .name(applicationName)
            .build()).block();

    Object env = environments.getSystemProvided();
    ObjectMapper mapper = new ObjectMapper();
    String serviceCredentials = mapper.writeValueAsString(env);
    JSONObject jsonObject = new JSONObject(serviceCredentials).getJSONObject("VCAP_SERVICES");

    return jsonObject.getJSONArray(serviceName)
        .getJSONObject(0) //TODO: Check if always on the same index
        .getJSONObject("credentials");
}
 
Example 28
Project: centraldogma   File: ChangeConverter.java   View source code 6 votes vote down vote up
@Override
protected Change doForward(com.linecorp.centraldogma.common.Change<?> value) {
    Change change = new Change(value.path(), convertChangeType(value.type()));
    switch (change.getType()) {
        case UPSERT_JSON:
        case APPLY_JSON_PATCH:
            try {
                change.setContent(Jackson.writeValueAsString(value.content()));
            } catch (JsonProcessingException e) {
                throw new ChangeFormatException("failed to read a JSON tree", e);
            }
            break;
        case UPSERT_TEXT:
        case APPLY_TEXT_PATCH:
        case RENAME:
            change.setContent((String) value.content());
            break;
        case REMOVE:
            break;
    }
    return change;
}
 
Example 29
Project: kafka-0.11.0.0-src-with-comment   File: VerifiableSinkTask.java   View source code 6 votes vote down vote up
@Override
public void put(Collection<SinkRecord> records) {
    long nowMs = System.currentTimeMillis();
    for (SinkRecord record : records) {
        Map<String, Object> data = new HashMap<>();
        data.put("name", name);
        data.put("task", record.key()); // VerifiableSourceTask's input task (source partition)
        data.put("sinkTask", id);
        data.put("topic", record.topic());
        data.put("time_ms", nowMs);
        data.put("seqno", record.value());
        data.put("offset", record.kafkaOffset());
        String dataJson;
        try {
            dataJson = JSON_SERDE.writeValueAsString(data);
        } catch (JsonProcessingException e) {
            dataJson = "Bad data can't be written as json: " + e.getMessage();
        }
        System.out.println(dataJson);
        unflushed.add(data);
    }
}
 
Example 30
Project: liferay-service-builder-dsl   File: TxRequiredMethodSerializerTest.java   View source code 5 votes vote down vote up
@Test
public void testSerialize() throws JsonProcessingException {
	TxRequiredMethod txRequiredMethod = new TxRequiredMethod.Builder(
		"getFoo").build();

	XMLSerializer serializer = new TxRequiredMethodSerializer(
		txRequiredMethod);

	String xml = serializer.serialize();

	Assert.assertEquals("<tx-required>getFoo</tx-required>", xml);
}
 
Example 31
Project: kafka-0.11.0.0-src-with-comment   File: VerifiableConsumer.java   View source code 5 votes vote down vote up
private void printJson(Object data) {
    try {
        out.println(mapper.writeValueAsString(data));
    } catch (JsonProcessingException e) {
        out.println("Bad data can't be written as json: " + e.getMessage());
    }
}
 
Example 32
Project: verify-hub   File: ConfigStubRule.java   View source code 5 votes vote down vote up
public void setupStubForCertificates(String issuer) throws JsonProcessingException {
    String signingCertificateUri = UriBuilder.fromPath(Urls.ConfigUrls.SIGNATURE_VERIFICATION_CERTIFICATES_RESOURCE).buildFromEncoded(StringEncoding.urlEncode(issuer)).toASCIIString();
    CertificateDto signingCertificate = CertificateDtoBuilder.aCertificateDto().withIssuerId(issuer).withKeyUse(CertificateDto.KeyUse.Signing).build();
    Collection<CertificateDto> signingCertificates = new ArrayList<>();
    signingCertificates.add(signingCertificate);
    register(signingCertificateUri, Response.Status.OK.getStatusCode(), signingCertificates);

    String encryptionCertificateUri = UriBuilder.fromPath(Urls.ConfigUrls.ENCRYPTION_CERTIFICATES_RESOURCE).buildFromEncoded(StringEncoding.urlEncode(issuer)).toASCIIString();
    CertificateDto encryptionCertificate = CertificateDtoBuilder.aCertificateDto().withIssuerId(issuer).withKeyUse(CertificateDto.KeyUse.Encryption).build();
    register(encryptionCertificateUri, Response.Status.OK.getStatusCode(), encryptionCertificate);
}
 
Example 33
Project: holon-json   File: ExampleJackson.java   View source code 5 votes vote down vote up
public void serializeAndDeserialize() throws JsonProcessingException {
	ObjectMapper mapper = new ObjectMapper();
	JacksonConfiguration.configure(mapper); // <1>

	PropertyBox box = PropertyBox.builder(PROPERTY_SET).set(ID, 1L).set(DESCRIPTION, "Test").build(); // <2>

	// serialize
	String json = mapper.writer().writeValueAsString(box); // <3>
	// deserialize
	box = PROPERTY_SET.execute(() -> mapper.reader().forType(PropertyBox.class).readValue(json)); // <4>
}
 
Example 34
Project: loom   File: DeltaAdapterTest.java   View source code 5 votes vote down vote up
private String toJson(final Object object) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    String jsonRep = "";
    jsonRep = mapper.writeValueAsString(object);
    return jsonRep;
}
 
Example 35
Project: amv-access-api-poc   File: DeviceCertClientTest.java   View source code 5 votes vote down vote up
@Test
public void itShouldReturnDeserializedErrorTransferObjectOnFailure() throws JsonProcessingException {
    ErrorResponseDto errorDto = ErrorResponseDtoObjectMother.random();

    String errorDtoAsJson = Clients.defaultObjectMapper.writeValueAsString(errorDto);

    MockClient mockClient = new MockClient()
            .add(HttpMethod.POST, "/api/v1/device_certificates", Response.builder()
                    .status(HttpStatus.INTERNAL_SERVER_ERROR.value())
                    .reason(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
                    .headers(Collections.<String, Collection<String>>emptyMap())
                    .body(errorDtoAsJson, Charsets.UTF_8));

    Target<DeviceCertClient> mockTarget = new MockTarget<DeviceCertClient>(DeviceCertClient.class);

    DeviceCertClient sut = Clients.simpleFeignBuilder()
            .client(mockClient)
            .build()
            .newInstance(mockTarget);

    CreateDeviceCertificateRequestDto request = CreateDeviceCertificateRequestDto.builder()
            .build();
    HystrixCommand<CreateDeviceCertificateResponseDto> deviceCertificateRequest = sut
            .createDeviceCertificate(RANDOM_APP_ID, RANDOM_API_KEY, request);

    try {
        deviceCertificateRequest.execute();
        Assert.fail("Should have thrown exception");
    } catch (Exception e) {
        assertThat(e, is(notNullValue()));
        assertThat(e.getCause(), is(notNullValue()));

        Throwable cause = e.getCause();
        assertThat(cause, is(instanceOf(AccessApiException.class)));

        AccessApiException accessApiException = (AccessApiException) cause;
        ErrorResponseDto error = accessApiException.getError();
        assertThat(error, is(errorDto));
        assertThat(error.getErrors(), hasSize(errorDto.getErrors().size()));
    }
}
 
Example 36
Project: spring-boot-seed   File: JsonUtil.java   View source code 5 votes vote down vote up
/**
 * 转换分页查询结果
 *
 * @param list  结果集
 * @param total 记录数
 * @return the string
 */
public static String writePageJson(Object list, Object total) {
    Map<String, Object> map = new HashMap<>();
    map.put("list", list);
    map.put("total", total);
    try {
        return mapper.writeValueAsString(map);
    } catch (JsonProcessingException e) {
        (new JsonUtil()).logger.error(e.getMessage(), e);
        return null;
    }
}
 
Example 37
Project: holon-json   File: JacksonJsonPropertyBoxProvider.java   View source code 5 votes vote down vote up
@Override
public void writeTo(PropertyBox t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
		MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
		throws IOException, WebApplicationException {
	try (final Writer writer = new OutputStreamWriter(entityStream, CHARSET)) {
		try {
			getObjectWriter().writeValue(writer, t);
		} catch (JsonProcessingException e) {
			throw new WebApplicationException(e.getMessage(), e, Status.BAD_REQUEST);
		}
	}
}
 
Example 38
Project: verify-hub   File: SamlSoapProxyProxyStubRule.java   View source code 5 votes vote down vote up
public void setUpStubForSendHubMatchingServiceRequest(SessionId sessionId) throws JsonProcessingException {
    URI uri = UriBuilder
            .fromPath(Urls.SamlSoapProxyUrls.MATCHING_SERVICE_REQUEST_SENDER_RESOURCE)
            .queryParam(Urls.SharedUrls.SESSION_ID_PARAM, sessionId)
            .build();
    Response response = Response.status(Response.Status.ACCEPTED).build();
    register(uri.getPath(), Response.Status.ACCEPTED.getStatusCode(), response);
}
 
Example 39
Project: athena   File: ConfigFileBasedClusterMetadataProvider.java   View source code 5 votes vote down vote up
@Override
public void serialize(ControllerNode node, JsonGenerator jgen, SerializerProvider provider)
  throws IOException, JsonProcessingException {
    jgen.writeStartObject();
    jgen.writeStringField(ID, node.id().toString());
    jgen.writeStringField(IP, node.ip().toString());
    jgen.writeNumberField(PORT, node.tcpPort());
    jgen.writeEndObject();
}
 
Example 40
Project: beaker-notebook-archive   File: TableDisplayAlignmentSerializer.java   View source code 5 votes vote down vote up
@Override
public void serialize(TableDisplayAlignmentProvider value,
                      JsonGenerator jgen,
                      SerializerProvider provider)
  throws IOException, JsonProcessingException {

  synchronized (value) {
    jgen.writeString(value.getCode());
  }
}