com.fasterxml.jackson.core.JsonProcessingException Java Examples

The following examples show how to use com.fasterxml.jackson.core.JsonProcessingException. 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: HttpHandlerUtil.java    From proxyee-down with 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 #2
Source File: InstanceRetrievalServiceTest.java    From api-layer with 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
Source File: UserVideoDeserializerModule.java    From android-viewer-for-khan-academy with 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
Source File: SampleDTOSerializer.java    From newts with 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 #5
Source File: Ports.java    From docker-java with 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 File: StringFunctions.java    From metron with 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 #7
Source File: ImageCommand.java    From Cognizant-Intelligent-Test-Scripter with 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 #8
Source File: PojoEventBusCodec.java    From raml-module-builder with 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 #9
Source File: AbstractDatabricksRestClientImpl.java    From databricks-rest-client with 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 #10
Source File: ElasticsearchSearcher.java    From q with 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 #11
Source File: QueueService.java    From judgels with 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 #12
Source File: HalRepresentationLinkingTest.java    From edison-hal with 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 #13
Source File: JsonUnwrappedUnitTest.java    From tutorials with 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 #14
Source File: MultiTenancyAcceptanceTest.java    From besu with 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 #15
Source File: SdxRepairService.java    From cloudbreak with 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 #16
Source File: TrendActionTest.java    From foxtrot with 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 #17
Source File: AuditUtils.java    From pacbot with 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 #18
Source File: OrganisationMetricsUtil.java    From sunbird-lms-service with 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 #19
Source File: SerialisationTest.java    From octarine with 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 #20
Source File: JiraRestClient.java    From scava with 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 #21
Source File: Jackson2ObjectMapperFactoryBeanTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void defaultModules() throws JsonProcessingException, UnsupportedEncodingException {
	this.factory.afterPropertiesSet();
	ObjectMapper objectMapper = this.factory.getObject();

	Long timestamp = 1322903730000L;
	DateTime dateTime = new DateTime(timestamp, DateTimeZone.UTC);
	assertEquals(timestamp.toString(), new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8"));
}
 
Example #22
Source File: JacksonUtil.java    From yshopmall with Apache License 2.0 5 votes vote down vote up
public static String toJson(Object data) {
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        return objectMapper.writeValueAsString(data);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #23
Source File: Descriptor.java    From helios with Apache License 2.0 5 votes vote down vote up
public byte[] toJsonBytes() {
  try {
    return Json.asBytes(this);
  } catch (JsonProcessingException e) {
    throw new RuntimeException(e);
  }
}
 
Example #24
Source File: SeaCloudsMonitoringInitializationPolicies.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
private void postSeaCloudsDcConfiguration(SeaCloudsDcRequestDto requestBody) {
    try {
        String jsonBody = new ObjectMapper().writeValueAsString(requestBody);
        postSeaCloudsDcConfiguration(jsonBody);
    } catch (JsonProcessingException e) {
        throw new RuntimeException("Something went wrong creating Request body to " +
                "configure the SeaCloudsDc for type" + requestBody.getType() + " and " +
                "url " + requestBody.getUrl() + ". Message: " + e.getMessage());
    }
}
 
Example #25
Source File: ObjectComposer.java    From jackson-jr with Apache License 2.0 5 votes vote down vote up
public ArrayComposer<ObjectComposer<PARENT>> startArrayField(SerializableString fieldName)
    throws IOException, JsonProcessingException
{
    _closeChild();
    _generator.writeFieldName(fieldName);
    return _startArray(this, _generator);
}
 
Example #26
Source File: RevisionHistoryEnricherTest.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testDefaultRevisionHistoryLimit() throws JsonProcessingException {
    // Given
    KubernetesListBuilder builder = new KubernetesListBuilder().addToItems(new DeploymentBuilder().build());

    RevisionHistoryEnricher enricher = new RevisionHistoryEnricher(context);

    // When
    enricher.create(PlatformMode.kubernetes, builder);

    // Then
    assertRevisionHistory(builder.build(), Configs.asInt(RevisionHistoryEnricher.Config.limit.def()));
}
 
Example #27
Source File: ElasticsearchTransactionRepository.java    From servicecomb-pack with Apache License 2.0 5 votes vote down vote up
private IndexQuery convert(GlobalTransaction transaction) throws JsonProcessingException {
  IndexQuery indexQuery = new IndexQuery();
  indexQuery.setId(transaction.getGlobalTxId());
  indexQuery.setSource(mapper.writeValueAsString(transaction));
  indexQuery.setIndexName(INDEX_NAME);
  indexQuery.setType(INDEX_TYPE);
  return indexQuery;
}
 
Example #28
Source File: GraphQLController.java    From graphql-java-examples with MIT License 5 votes vote down vote up
private String bodyToString() {
    try {
        return objectMapper.writeValueAsString(body);
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #29
Source File: IsSameEvent.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with 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 #30
Source File: PrecompiledWithSignService.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
/**
 * check node id
 */
private boolean isValidNodeID(int groupId, String _nodeID) throws IOException, JsonProcessingException {
	boolean flag = false;
	List<String> nodeIDs = web3ApiService.getWeb3j(groupId).getNodeIDList().send().getResult();
	for (String nodeID : nodeIDs) {
		if (_nodeID.equals(nodeID)) {
			flag = true;
			break;
		}
	}
	return flag;
}