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

The following examples show how to use com.fasterxml.jackson.core.JsonProcessingException. These examples are extracted from open source projects.
Example 1
Project: newts   File: SampleDTOSerializer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(SampleDTO value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
    jgen.writeStartObject();
    jgen.writeStringField("name", value.getName());
    jgen.writeNumberField("timestamp", value.getTimestamp());
    jgen.writeStringField("type", value.getType().toString());
    jgen.writeObjectField("value", value.getValue());

    // Since attributes is optional, be compact and omit from JSON output when unused.
    if (value.getAttributes() != null && !value.getAttributes().isEmpty()) {
        jgen.writeObjectField("attributes", value.getAttributes());
    }

    // Omit the context field when it is set to the default
    if (!Context.DEFAULT_CONTEXT.equals(value.getContext())) {
        jgen.writeStringField("context", value.getContext().getId());
    }

    jgen.writeEndObject();
}
 
Example 2
Project: api-layer   File: InstanceRetrievalServiceTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testGetAllInstancesFromDiscovery_whenNeedApplicationsWithoutFilter() throws JsonProcessingException {
    Map<String, InstanceInfo> instanceInfoMap = createInstances();


    Applications expectedApplications = new Applications();
    instanceInfoMap.forEach((key, value) -> expectedApplications.addApplication(new Application(value.getAppName(), Collections.singletonList(value))));

    ObjectMapper mapper = new ObjectMapper();
    String bodyAll = mapper.writeValueAsString(new ApplicationsWrapper(expectedApplications));
    mockRetrieveApplicationService(discoveryServiceAllAppsUrl, bodyAll);

    Applications actualApplications = instanceRetrievalService.getAllInstancesFromDiscovery(false);

    assertEquals(expectedApplications.size(), actualApplications.size());

    List<Application> actualApplicationList =
        new ArrayList<>(actualApplications.getRegisteredApplications());


    expectedApplications
        .getRegisteredApplications()
        .forEach(expectedApplication ->
            assertThat(actualApplicationList, hasItem(hasProperty("name", equalTo(expectedApplication.getName()))))
        );
}
 
Example 3
Project: android-viewer-for-khan-academy   File: UserVideoDeserializerModule.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public UserVideo deserialize(JsonParser jp, DeserializationContext ctxt)
		throws IOException, JsonProcessingException {
	
    TreeNode tree = defaultMapper.readTree(jp);
    
   	ObjectNode root = (ObjectNode) tree;
    Iterator<String> keys = root.fieldNames();
    
    while (keys.hasNext()) {
    	String key = keys.next();
    	if ("video".equals(key)) {
    		JsonNode value = root.get(key);
    		if (value.isObject()) {
    			root.set(key, value.get("readable_id"));
    		}
    	}
    }
	
    UserVideo video = defaultMapper.treeToValue(tree, UserVideo.class);
	return video;
}
 
Example 4
Project: metron   File: StringFunctions.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object apply(List<Object> strings) {

  if (strings == null || strings.size() == 0) {
    throw new IllegalArgumentException("[TO_JSON_OBJECT] incorrect arguments. Usage: TO_JSON_OBJECT <String>");
  }
  String var = (strings.get(0) == null) ? null : (String) strings.get(0);
  if (var == null) {
    return null;
  } else if (var.length() == 0) {
    return var;
  } else {
    if (!(strings.get(0) instanceof String)) {
      throw new ParseException("Valid JSON string not supplied");
    }
    // Return JSON Object
    try {
      return JSONUtils.INSTANCE.load((String) strings.get(0), Object.class);
    } catch (JsonProcessingException ex) {
      throw new ParseException("Valid JSON string not supplied", ex);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  return new ParseException("Unable to parse JSON string");
}
 
Example 5
Project: docker-java   File: Ports.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(Ports ports, JsonGenerator jsonGen,
                      SerializerProvider serProvider) throws IOException, JsonProcessingException {

    jsonGen.writeStartObject();//{
    for(String portKey : ports.getAllPorts().keySet()){
        Port p = ports.getAllPorts().get(portKey);
        jsonGen.writeFieldName(p.getPort() + "/" + p.getScheme());
        jsonGen.writeStartArray();
        jsonGen.writeStartObject();
        jsonGen.writeStringField("HostIp", p.hostIp);
        jsonGen.writeStringField("HostPort", p.hostPort);
        jsonGen.writeEndObject();
        jsonGen.writeEndArray();
    }
    jsonGen.writeEndObject();//}
}
 
Example 6
Project: proxyee-down   File: HttpHandlerUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static FullHttpResponse buildJson(Object obj, Include include) {
  FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
  response.headers().set(HttpHeaderNames.CONTENT_TYPE, AsciiString.cached("application/json; charset=utf-8"));
  if (obj != null) {
    try {
      ObjectMapper objectMapper = new ObjectMapper();
      if (include != null) {
        objectMapper.setSerializationInclusion(include);
      }
      String content = objectMapper.writeValueAsString(obj);
      response.content().writeBytes(content.getBytes(Charset.forName("utf-8")));
    } catch (JsonProcessingException e) {
      response.setStatus(HttpResponseStatus.SERVICE_UNAVAILABLE);
    }
  }
  response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
  return response;
}
 
Example 7
Project: judgels   File: QueueService.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void sendMessage(String sourceJid, String targetJid, String type, String content)
        throws IOException, TimeoutException {

    ClientMessage clientMessage = new ClientMessage.Builder()
            .sourceJid(sourceJid)
            .type(type)
            .content(content)
            .build();

    String message;
    try {
        message = objectMapper.writeValueAsString(clientMessage);
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    }

    QueueChannel channel = queue.createChannel();
    channel.declareQueue(targetJid);
    channel.pushMessage(targetJid, message);
}
 
Example 8
Project: tutorials   File: JsonUnwrappedUnitTest.java    License: MIT License 6 votes vote down vote up
@Test
public void whenSerializingUsingJsonUnwrapped_thenCorrect() throws JsonProcessingException {

    // arrange
    Order.Type preorderType = new Order.Type();
    preorderType.id = 10;
    preorderType.name = "pre-order";

    Order order = new Order(preorderType);

    // act
    String result = new ObjectMapper().writeValueAsString(order);

    // assert
    assertThat(from(result).getInt("id")).isEqualTo(10);
    assertThat(from(result).getString("name")).isEqualTo("pre-order");

    /*
        {
          "id": 10,
          "name": "pre-order"
        }
    */

}
 
Example 9
Project: cloudbreak   File: SdxRepairService.java    License: Apache License 2.0 6 votes vote down vote up
protected AttemptResult<StackV4Response> checkClusterStatusDuringRepair(SdxCluster sdxCluster) throws JsonProcessingException {
    LOGGER.info("Repair polling cloudbreak for stack status: '{}' in '{}' env", sdxCluster.getClusterName(), sdxCluster.getEnvName());
    try {
        if (PollGroup.CANCELLED.equals(DatalakeInMemoryStateStore.get(sdxCluster.getId()))) {
            LOGGER.info("Repair polling cancelled in inmemory store, id: " + sdxCluster.getId());
            return AttemptResults.breakFor("Repair polling cancelled in inmemory store, id: " + sdxCluster.getId());
        }
        FlowState flowState = cloudbreakFlowService.getLastKnownFlowState(sdxCluster);
        if (RUNNING.equals(flowState)) {
            LOGGER.info("Repair polling will continue, cluster has an active flow in Cloudbreak, id: " + sdxCluster.getId());
            return AttemptResults.justContinue();
        } else {
            return getStackResponseAttemptResult(sdxCluster, flowState);
        }
    } catch (NotFoundException e) {
        LOGGER.debug("Stack not found on CB side " + sdxCluster.getClusterName(), e);
        return AttemptResults.breakFor("Stack not found on CB side " + sdxCluster.getClusterName());
    }
}
 
Example 10
Project: foxtrot   File: TrendActionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testTrendActionNullTable() throws FoxtrotException, JsonProcessingException {
    TrendRequest trendRequest = new TrendRequest();
    trendRequest.setTable(null);
    BetweenFilter betweenFilter = new BetweenFilter();
    betweenFilter.setFrom(1L);
    betweenFilter.setTo(System.currentTimeMillis());
    betweenFilter.setTemporal(true);
    betweenFilter.setField("_timestamp");
    trendRequest.setField("os");
    trendRequest.setFilters(Collections.<Filter>singletonList(betweenFilter));
    try {
        getQueryExecutor().execute(trendRequest);
        fail();
    } catch (FoxtrotException ex) {
        assertEquals(ErrorCode.MALFORMED_QUERY, ex.getCode());
    }
}
 
Example 11
Project: pacbot   File: AuditUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creating the JSON for audit.
 *
 * @param ds the ds
 * @param type the type
 * @param status the status
 * @param id the id
 * @return the string
 */

private static String createAuditTrail(String ds, String type, String status, String id) {
    String date = CommonUtils.getCurrentDateStringWithFormat(PacmanSdkConstants.PAC_TIME_ZONE,
            PacmanSdkConstants.DATE_FORMAT);
    Map<String, String> auditTrail = new LinkedHashMap<>();
    auditTrail.put(PacmanSdkConstants.DATA_SOURCE_ATTR, ds);
    auditTrail.put(PacmanSdkConstants.TARGET_TYPE, type);
    auditTrail.put(PacmanSdkConstants.ANNOTATION_PK, id);
    auditTrail.put(PacmanSdkConstants.STATUS_KEY, status);
    auditTrail.put(PacmanSdkConstants.AUDIT_DATE, date);
    auditTrail.put(PacmanSdkConstants._AUDIT_DATE, date.substring(0, date.indexOf('T')));
    String _auditTrail = null;
    try {
        _auditTrail = new ObjectMapper().writeValueAsString(auditTrail);
    } catch (JsonProcessingException e) {
        logger.error(e.getMessage());
    }
    return _auditTrail;
}
 
Example 12
Project: scava   File: JiraRestClient.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public static void main(String[] args) throws UnirestException,
		JsonProcessingException, IOException {
	// System.out.println(UriBuilder.fromUri("http://a.com").path("ffff").path("fff"));
	JiraRestClient jira = new JiraRestClient("http://jira.codehaus.org/");
	// jira.getIssue("MNG-5649");
	// jira.getIssue("MNG-122");
	// jira.getIssue("GROOVY-6845");
	// jira.getComment("MNG-2205", "162059");

	JiraIssue issue = jira.getIssue("MNG-122");
	System.out.println(issue.getDescription());

	JiraComment comment = jira.getComment("MNG-220", "38768");
	System.out.println(comment.getText());

	/*
	 * for (JiraIssue issue : jira.getIssues("MNG", new DateTime(2014, 6,
	 * 20, 0, 0).toDate())) { System.out.println(issue.getDescription()); }
	 */

	JiraRestClient.shutdown();

}
 
Example 13
Project: octarine   File: SerialisationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test public void
reflectively_serialise_multiple_records() throws JsonProcessingException {
    Record me = $$(
            Person.name.of("Dominic"),
            Person.age.of(39),
            Person.favouriteColour.of(Color.RED),
            Person.address.of(Address.addressLines.of("13 Rue Morgue", "PO3 1TP")));

    Record you = $$(
            Person.name.of("Doppelganger"),
            Person.age.of(40),
            Person.favouriteColour.of(Color.BLUE),
            Person.address.of(Address.addressLines.of("23 Acacia Avenue", "VB6 5UX")));

    String json = ReflectiveRecordSerialiser.toJson(Stream.of(me, you), new ColorJsonSerializer());

    List<Record> people = ListDeserialiser.readingItemsWith(Person.deserialiser).fromString(json);

    assertThat(people, equalTo(Arrays.asList(me, you)));
}
 
Example 14
Project: sunbird-lms-service   File: OrganisationMetricsUtil.java    License: MIT License 6 votes vote down vote up
public static String getOrgMetricsRequest(
    Request actorMessage, String periodStr, String orgHashId, String userId, String channel)
    throws JsonProcessingException {
  Request request = new Request();
  request.setId(actorMessage.getId());
  Map<String, Object> requestObject = new HashMap<>();
  requestObject.put(JsonKey.PERIOD, BaseMetricsActor.getEkstepPeriod(periodStr));
  Map<String, Object> filterMap = new HashMap<>();
  filterMap.put(JsonKey.TAG, orgHashId);
  if (!StringUtils.isBlank(userId)) {
    filterMap.put(BaseMetricsActor.USER_ID, userId);
  }
  requestObject.put(JsonKey.FILTER, filterMap);
  requestObject.put(JsonKey.CHANNEL, channel);
  request.setRequest(requestObject);
  String requestStr = mapper.writeValueAsString(request);
  return requestStr;
}
 
Example 15
Project: besu   File: MultiTenancyAcceptanceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void privGetEeaTransactionCountSuccessShouldReturnExpectedTransactionCount()
    throws JsonProcessingException {
  final PrivateTransaction validSignedPrivateTransaction =
      getValidSignedPrivateTransaction(senderAddress);
  final String accountAddress = validSignedPrivateTransaction.getSender().toHexString();
  final String senderAddressBase64 = Base64.encode(Bytes.wrap(accountAddress.getBytes(UTF_8)));
  final BytesValueRLPOutput rlpOutput = getRLPOutput(validSignedPrivateTransaction);
  final List<PrivacyGroup> groupMembership =
      List.of(testPrivacyGroup(emptyList(), PrivacyGroup.Type.LEGACY));

  retrievePrivacyGroupEnclaveStub();
  sendEnclaveStub(KEY1);
  receiveEnclaveStub(validSignedPrivateTransaction);
  findPrivacyGroupEnclaveStub(groupMembership);

  node.verify(priv.getTransactionCount(accountAddress, PRIVACY_GROUP_ID, 0));
  final Hash transactionHash =
      node.execute(privacyTransactions.sendRawTransaction(rlpOutput.encoded().toHexString()));

  node.verify(priv.getTransactionReceipt(transactionHash));

  final String privateFrom = ENCLAVE_KEY;
  final String[] privateFor = {senderAddressBase64};
  node.verify(priv.getEeaTransactionCount(accountAddress, privateFrom, privateFor, 1));
}
 
Example 16
Project: edison-hal   File: HalRepresentationLinkingTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRenderNestedCuriedRelAsArrayWithCuriAtTopLevel() throws JsonProcessingException {
    // given
    final HalRepresentation representation = new HalRepresentation(
            linkingTo()
                    .curi("ex", "http://example.org/rels/{rel}")
                    .build(),
            embedded("http://example.org/rels/nested", asList(new HalRepresentation(
                    linkingTo()
                            .array(
                                    link("ex:foo", "http://example.org/items/1"),
                                    link("http://example.org/rels/bar", "http://example.org/items/2"))
                            .build()
            )))
    );
    // when
    final String json = new ObjectMapper().writeValueAsString(representation);
    // then
    assertThat(json, is("{" +
            "\"_links\":{" +
            "\"curies\":[{\"href\":\"http://example.org/rels/{rel}\",\"templated\":true,\"name\":\"ex\"}]}," +
            "\"_embedded\":{\"ex:nested\":[{\"_links\":{" +
            "\"ex:foo\":[{\"href\":\"http://example.org/items/1\"}]," +
            "\"ex:bar\":[{\"href\":\"http://example.org/items/2\"}]}}" +
            "]}}"));
}
 
Example 17
Project: q   File: ElasticsearchSearcher.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Set<String> getResultsFromServerResponse(String output) throws JsonProcessingException, IOException
{
	Set<String> results = Sets.newHashSet();
	ObjectMapper mapper = new ObjectMapper();
	JsonNode actualObj = mapper.readTree(output);
	JsonNode arrNode = actualObj.get("hits").get("hits");
	if (arrNode.isArray())
	{
		for (final JsonNode objNode : arrNode)
		{
			results.add(objNode.get("_id").textValue());
		}
	}
	return results;
	
}
 
Example 18
Project: databricks-rest-client   File: AbstractDatabricksRestClientImpl.java    License: Apache License 2.0 6 votes vote down vote up
protected HttpRequestBase makeHttpMethod(RequestMethod requestMethod, String path,
    Map<String, Object> data)
    throws UnsupportedEncodingException, JsonProcessingException {

  switch (requestMethod) {
    case POST:
      return makePostMethod(path, data);
    case GET:
      return makeGetMethod(path, data);
    case PATCH:
      return makePatchMethod(path, data);
    case DELETE:
      return makeDeleteMethod(path);
    case PUT:
      return makePutMethod(path, data);
    default:
      throw new IllegalArgumentException(requestMethod + " is not a valid request method");
  }
}
 
Example 19
Project: Cognizant-Intelligent-Test-Scripter   File: ImageCommand.java    License: Apache License 2.0 6 votes vote down vote up
public List<String> getObjectAreas(Object target, String name) {
    List<Map<String, String>> objectList = new ArrayList<>();
    if (target instanceof Region) {
        Region region = (Region) target;
        Map<String, String> obMap = new HashMap<>();
        obMap.put("name", name);
        obMap.put("area", "[" + region.x + "," + region.y + "," + region.w + "," + region.h + "]");
        objectList.add(obMap);
    }
    try {
        if (!objectList.isEmpty()) {
            return Arrays.asList(new ObjectMapper().writeValueAsString(objectList));
        }
    } catch (JsonProcessingException ex) {
        Logger.getLogger(ImageCommand.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}
 
Example 20
Project: raml-module-builder   File: PojoEventBusCodec.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void encodeToWire(Buffer buffer, Object pojo) {

  try {
    String value = MAPPER.writeValueAsString(pojo);
    String clazz = pojo.getClass().getName();
    int clazzLength = clazz.getBytes().length;
    buffer.appendInt(clazzLength);
    buffer.appendString(clazz);
    if(value != null){
      int dataLength = value.getBytes().length;
      // Write data into given buffer
      buffer.appendInt(dataLength);
      buffer.appendString(value);
    }
  } catch (JsonProcessingException e) {
    log.error(e.getMessage(), e);
  }
}
 
Example 21
Project: strimzi-kafka-operator   File: KafkaTopic.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    YAMLMapper mapper = new YAMLMapper();
    try {
        return mapper.writeValueAsString(this);
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    }
}
 
Example 22
Project: Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud   File: IsSameEvent.java    License: MIT License 5 votes vote down vote up
private String convertObjectToJsonString(Object object) {
	try {
		return mapper.writeValueAsString(object);
	} catch (JsonProcessingException e) {
		throw new RuntimeException(e);
	}
}
 
Example 23
Project: Poseidon   File: AbstractServiceClient.java    License: Apache License 2.0 5 votes vote down vote up
protected String encodeUrl(Object url) throws JsonProcessingException {
    if (url == null) {
        return "";
    }

    if (url instanceof String) {
        return encodeUrl((String) url);
    } else if (ClassUtils.isPrimitiveOrWrapper(url.getClass()) || url.getClass().isEnum()) {
        return String.valueOf(url);
    } else {
        return encodeUrl(objectMapper.writeValueAsString(url));
    }
}
 
Example 24
Project: search-spring-boot-starter   File: JsonUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String stringify(Object pojo) {
    try {
        return mapper.writeValueAsString(pojo);
    } catch (JsonProcessingException e) {
        throw new OpenSystemException(ErrorCode.JSON_SERIALIZE_FAIL).setCause(e);
    }
}
 
Example 25
Project: logsniffer   File: EsLogPointerSerializer.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void serialize(final LogPointer value, final JsonGenerator gen, final SerializerProvider serializers)
		throws IOException, JsonProcessingException {
	gen.writeStartObject();
	gen.writeStringField("_json", value.getJson());
	gen.writeEndObject();
}
 
Example 26
Project: controller-advice-exception-handler   File: ApplicationConfiguration.java    License: MIT License 5 votes vote down vote up
public JsonSerializer<LocalDate> localDateSerializer() {
    return new JsonSerializer<LocalDate>() {
        @Override
        public void serialize(LocalDate localDate, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
            jsonGenerator.writeString(localDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
        }
    };
}
 
Example 27
Project: TeaStore   File: ShaSecurityProvider.java    License: Apache License 2.0 5 votes vote down vote up
private String blobToString(SessionBlob blob) {
  ObjectMapper o = new ObjectMapper();
  try {
    return URLEncoder.encode(o.writeValueAsString(blob), "UTF-8");
  } catch (JsonProcessingException | UnsupportedEncodingException e) {
    throw new IllegalStateException("Could not save blob!");
  }
}
 
Example 28
Project: web-budget   File: AbstractChartModel.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Method used to transform this model into JSON
 *
 * @return this model as JSON
 */
public String toJson() {
    try {
        return JsonUtils.serialize(this);
    } catch (JsonProcessingException ex) {
        throw new RuntimeException("Can't parse this chart model to JSON due to unknown errors", ex);
    }
}
 
Example 29
Project: webtau   File: JsonUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String serialize(Object json) {
    if (json == null) {
        return "null";
    }

    try {
        return mapper.writeValueAsString(json);
    } catch (JsonProcessingException e) {
        throw new RuntimeException();
    }
}
 
Example 30
Project: jlineup   File: JobConfig.java    License: Apache License 2.0 5 votes vote down vote up
public static String prettyPrintWithAllFields(JobConfig jobConfig) {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objectMapper.addMixIn(JobConfig.class, JobConfigMixIn.class);
    objectMapper.addMixIn(UrlConfig.class, UrlConfigMixIn.class);
    try {
        return objectMapper.writeValueAsString(jobConfig);
    } catch (JsonProcessingException e) {
        throw new RuntimeException("There is a problem while writing the " + jobConfig.getClass().getCanonicalName() + " with Jackson.", e);
    }
}
 
Example 31
Project: backstopper   File: SampleResource.java    License: Apache License 2.0 5 votes vote down vote up
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response postSampleModel(SampleModel model) throws JsonProcessingException {
    // If the caller didn't pass us a payload we throw a MISSING_EXPECTED_CONTENT error.
    if (model == null) {
        throw ApiException.newBuilder()
                          .withExceptionMessage("Caller did not pass any request payload")
                          .withApiErrors(SampleCoreApiError.MISSING_EXPECTED_CONTENT)
                          .build();
    }
    // Run the object through our JSR 303 validation service, which will automatically throw an appropriate error
    //      if the validation fails that will get translated to the desired error contract.
    validationService.validateObjectsFailFast(model);

    // Manually check the throwManualError query param (normally you'd do this with JSR 303 annotations on the
    // object, but this shows how you can manually throw exceptions to be picked up by the error handling system).
    if (Boolean.TRUE.equals(model.throw_manual_error)) {
        throw ApiException.newBuilder()
                          .withExceptionMessage("Manual error throw was requested")
                          .withApiErrors(SampleProjectApiError.MANUALLY_THROWN_ERROR)
                          .withExtraDetailsForLogging(Pair.of("rgb_color_value", model.rgb_color))
                          .withExtraResponseHeaders(
                              Pair.of("rgbColorValue", singletonList(model.rgb_color)),
                              Pair.of("otherExtraMultivalueHeader", Arrays.asList("foo", "bar"))
                          )
                          .build();
    }

    return Response.status(201).entity(model).build();
}
 
Example 32
Project: spring-analysis-note   File: Jackson2ObjectMapperFactoryBeanTests.java    License: MIT License 5 votes vote down vote up
@Test
public void setFilters() throws JsonProcessingException {
	this.factory.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false));
	this.factory.afterPropertiesSet();
	ObjectMapper objectMapper = this.factory.getObject();

	JacksonFilteredBean bean = new JacksonFilteredBean("value1", "value2");
	String output = objectMapper.writeValueAsString(bean);
	assertThat(output, containsString("value1"));
	assertThat(output, containsString("value2"));
}
 
Example 33
Project: replicator   File: ConsoleApplier.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Boolean apply(Collection<AugmentedEvent> events) {
    try {
        for (AugmentedEvent event : events) {
            ConsoleApplier.LOG.info(ConsoleApplier.MAPPER.writeValueAsString(event));
        }

        return true;
    } catch (JsonProcessingException exception) {
        ConsoleApplier.LOG.error("error converting to json", exception);

        return false;
    }
}
 
Example 34
Project: metron   File: EnrichmentConfigFunctionsTest.java    License: Apache License 2.0 5 votes vote down vote up
public static String emptyTransformationsConfig() {
  SensorEnrichmentConfig config = new SensorEnrichmentConfig();
  try {
    return JSONUtils.INSTANCE.toJSON(config, true);
  } catch (JsonProcessingException e) {
    throw new IllegalStateException(e);
  }
}
 
Example 35
Project: pinpoint   File: ApplicationAgentsListSerializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(ApplicationAgentsList applicationAgentsList, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
    jgen.writeStartObject();
    List<ApplicationAgentList> applicationAgentLists = applicationAgentsList.getApplicationAgentLists();
    for (ApplicationAgentList applicationAgentList : applicationAgentLists) {
        jgen.writeFieldName(applicationAgentList.getGroupName());
        writeAgentList(jgen, applicationAgentList.getAgentInfos());
    }
    jgen.writeEndObject();
}
 
Example 36
Project: bonita-ui-designer   File: ContractDeserializer.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public Contract deserialize(JsonParser parser, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    ObjectCodec oc = parser.getCodec();
    ObjectNode treeNode = oc.readTree(parser);
    Contract contract = new Contract();
    parseNodeContractInput(childInput(treeNode), contract);
    return contract;
}
 
Example 37
Project: onos   File: OvsdbSetSerializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(OvsdbSet set, JsonGenerator generator,
                      SerializerProvider provider)
        throws IOException, JsonProcessingException {
    generator.writeStartArray();
    generator.writeString("set");
    generator.writeStartArray();
    Set javaSet = set.set();
    for (Object key : javaSet) {
        generator.writeObject(key);
    }
    generator.writeEndArray();
    generator.writeEndArray();
}
 
Example 38
Project: jdk9-jigsaw   File: MonitorServer.java    License: Creative Commons Zero v1.0 Universal 5 votes vote down vote up
private static String toJson(Statistics stats) {
	try {
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(StatisticsEntity.from(stats));
	} catch (JsonProcessingException ex) {
		// don't do this in real live
		return ex.toString();
	}
}
 
Example 39
Project: docker-java   File: CacheFromEncoder.java    License: Apache License 2.0 5 votes vote down vote up
public static String jsonEncode(Collection<String> imageIds) {
    try {
        return MAPPER.writeValueAsString(imageIds);
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    }
}
 
Example 40
Project: bce-sdk-java   File: GetStatFlowRequest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * (non-Javadoc)
 * @see java.lang.Object#toString()
 */
@Override
public String toString() {
    try {
        return JsonUtils.toJsonPrettyString(this);
    } catch (JsonProcessingException e) {
        return "";
    }
}