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. 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 Project: newts   Source 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
@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
@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
Source Project: metron   Source 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
Source Project: docker-java   Source 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
Source Project: proxyee-down   Source 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
Source Project: judgels   Source 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
Source Project: tutorials   Source 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
Source Project: cloudbreak   Source 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
Source Project: foxtrot   Source 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
Source Project: pacbot   Source 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
Source Project: scava   Source 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
Source Project: octarine   Source 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
Source Project: sunbird-lms-service   Source 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
Source Project: besu   Source 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
Source Project: edison-hal   Source 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
Source Project: q   Source 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
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
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
Source Project: raml-module-builder   Source 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
Source Project: strimzi-kafka-operator   Source 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
private String convertObjectToJsonString(Object object) {
	try {
		return mapper.writeValueAsString(object);
	} catch (JsonProcessingException e) {
		throw new RuntimeException(e);
	}
}
 
Example 23
Source Project: Poseidon   Source 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
Source Project: search-spring-boot-starter   Source 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
@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
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
Source Project: TeaStore   Source 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
/**
 * 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
Source Project: webtau   Source 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
Source Project: jlineup   Source 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);
    }
}