Java Code Examples for org.codehaus.jackson.map.ObjectMapper#setSerializationInclusion()

The following examples show how to use org.codehaus.jackson.map.ObjectMapper#setSerializationInclusion() . 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: WriteJsonServletHandler.java    From uflo with Apache License 2.0 6 votes vote down vote up
protected void writeObjectToJson(HttpServletResponse resp,Object obj) throws ServletException, IOException{
	resp.setHeader("Access-Control-Allow-Origin", "*");
	resp.setContentType("text/json");
	resp.setCharacterEncoding("UTF-8");
	ObjectMapper mapper=new ObjectMapper();
	mapper.setSerializationInclusion(Inclusion.NON_NULL);
	mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false);
	mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
	OutputStream out = resp.getOutputStream();
	try {
		mapper.writeValue(out, obj);
	} finally {
		out.flush();
		out.close();
	}
}
 
Example 2
Source File: JSONRPCEncoder.java    From bitcoin-transaction-explorer with MIT License 5 votes vote down vote up
public static String getRequestStringWithParameters(final String method, final ArrayList<Object> parameters) throws JsonGenerationException, JsonMappingException, IOException {
  final JSONRPCRequest req = new JSONRPCRequest(method);
  req.setParams(parameters);

  final StringWriter writer = new StringWriter();

  final ObjectMapper mapper = new ObjectMapper();
  mapper.setSerializationInclusion(Inclusion.NON_EMPTY);
  mapper.writeValue(writer, req);

  return writer.toString();
}
 
Example 3
Source File: TaggerServiceImpl.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public boolean removeAttributeFromCrises(Integer modelFamilyID)
		throws AidrException {
	Client client = ClientBuilder.newBuilder()
			.register(JacksonFeature.class).build();
	try {
		/**
		 * Rest call to Tagger
		 */
		deletePybossaApp(modelFamilyID);
		WebTarget webResource = client.target(taggerMainUrl
				+ "/modelfamily/" + new Long(modelFamilyID));

		ObjectMapper objectMapper = JacksonWrapper.getObjectMapper();
		objectMapper
				.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
		Response clientResponse = webResource.request(
				MediaType.APPLICATION_JSON).delete();

		String jsonResponse = clientResponse.readEntity(String.class);

		TaggerStatusResponse response = objectMapper.readValue(
				jsonResponse, TaggerStatusResponse.class);
		if (response != null && response.getStatusCode() != null) {
			if ("SUCCESS".equals(response.getStatusCode())) {
				logger.info("Classifier was remove from crises by modelFamilyID: "
						+ modelFamilyID);
				return true;
			} else {
				return false;
			}
		}
		return false;
	} catch (Exception e) {
		logger.error("Error while removing classifier from crisis ", e);
		throw new AidrException(
				"Error while removing classifier from crisis in Tagger", e);
	}
}
 
Example 4
Source File: TaggerServiceImpl.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public TaggerAttribute updateAttribute(TaggerAttribute attribute)
		throws AidrException {
	Client client = ClientBuilder.newBuilder()
			.register(JacksonFeature.class).build();
	try {
		WebTarget webResource = client.target(taggerMainUrl + "/attribute");

		ObjectMapper objectMapper = JacksonWrapper.getObjectMapper();
		objectMapper
				.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);

		Response clientResponse = webResource.request(
				MediaType.APPLICATION_JSON).put(
				Entity.json(objectMapper.writeValueAsString(attribute
						.toDTO())), Response.class);

		String jsonResponse = clientResponse.readEntity(String.class);
		NominalAttributeDTO dto = objectMapper.readValue(jsonResponse,
				NominalAttributeDTO.class);
		TaggerAttribute updatedAttribute = new TaggerAttribute(dto);
		if (updatedAttribute != null) {
			logger.info("Attribute with id "
					+ updatedAttribute.getNominalAttributeID()
					+ " was updated in Tagger");
		} else {
			return null;
		}

		return attribute;
	} catch (Exception e) {
		logger.error("Error while updating attribute: "+attribute.getCode(), e);
		throw new AidrException("Error while updating attribute in Tagger",
				e);
	}
}
 
Example 5
Source File: TaggerServiceImpl.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
private void deletePybossaApp(Integer modelFamilyID) {
	Client client = ClientBuilder.newBuilder()
			.register(JacksonFeature.class).build();
	try {

		//System.out.print("removeAttributeFromCrises: starting ......................................");
		WebTarget webResource = client.target(taggerMainUrl
				+ "/modelfamily/" + modelFamilyID);

		ObjectMapper objectMapper = JacksonWrapper.getObjectMapper();
		objectMapper
				.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);

		Response resp = webResource.request(MediaType.APPLICATION_JSON)
				.get();
		String jsonResp = resp.readEntity(String.class);
		TaggerModelFamily tm = objectMapper.readValue(jsonResp,
				TaggerModelFamily.class);
		if (tm != null && tm.getCrisis() != null
				&& tm.getNominalAttribute() != null) {
			String crisisCode = tm.getCrisis().getCode();
			String attributeCode = tm.getNominalAttribute().getCode();

			logger.info("crisisCode: " + crisisCode + " attributeCode: " + attributeCode);

			WebTarget webResp = client.target(crowdsourcingAPIMainUrl
					+ "/clientapp/delete/" + crisisCode + "/"
					+ attributeCode);

			Response clientResp = webResource.request(
					MediaType.APPLICATION_JSON).get();
			//logger.info("deactivated - clientResponse : " + clientResp);
		} else {
			logger.info("No modelfamily found for id = " + modelFamilyID);
		}
	} catch (Exception e) {
		logger.error("deactivated - deletePybossaApp : " + e);
	}
}
 
Example 6
Source File: TaggerServiceImpl.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public TaggerAttribute createNewAttribute(TaggerAttribute attribute)
		throws AidrException {
	Client client = ClientBuilder.newBuilder()
			.register(JacksonFeature.class).build();
	try {
		WebTarget webResource = client.target(taggerMainUrl + "/attribute");

		ObjectMapper objectMapper = JacksonWrapper.getObjectMapper();
		objectMapper
				.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);

		Response clientResponse = webResource.request(
				MediaType.APPLICATION_JSON).post(
				Entity.json(objectMapper.writeValueAsString(attribute
						.toDTO())), Response.class);

		// String jsonResponse = clientResponse.getEntity(String.class);
		String jsonResponse = clientResponse.readEntity(String.class);
		NominalAttributeDTO dto = objectMapper.readValue(jsonResponse,
				NominalAttributeDTO.class);
		TaggerAttribute newAttribute = dto != null ? new TaggerAttribute(
				dto) : null;
		if (newAttribute != null) {
			logger.info("Attribute with ID "
					+ newAttribute.getNominalAttributeID()
					+ " was created in Tagger");
		}
		return newAttribute;
	} catch (Exception e) {
		logger.error("Error while creating new attribute", e);
		throw new AidrException(
				"Error while creating new attribute in Tagger", e);
	}
}
 
Example 7
Source File: ObjectMapperHelper.java    From bintray-client-java with Apache License 2.0 5 votes vote down vote up
private static ObjectMapper buildDetailsMapper() {
    ObjectMapper mapper = new ObjectMapper(new JsonFactory());

    // TODO: when moving to Jackson 2.x these can be replaced with JodaModule
    mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.configure(SerializationConfig.Feature.WRITE_DATE_KEYS_AS_TIMESTAMPS, false);

    //Don't include keys with null values implicitly, only explicitly set values should be sent over
    mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, false);
    mapper.configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, false);
    mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    return mapper;
}
 
Example 8
Source File: BaseService.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
public BaseService(String dockerApiRoot, String endPointPath) {
    objectMapper = new ObjectMapper();
    // Only send properties that are actually set, default values are often wrong
    objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    // If the API changes, we might get new properties that we do not know
    DeserializationConfig deserializationConfig = objectMapper.getDeserializationConfig()
            .without(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
    objectMapper.setDeserializationConfig(deserializationConfig);
    serviceEndPoint = createDockerTarget(dockerApiRoot)
            .path(TARGET_DOCKER_API_VERSION)
            .path(endPointPath);
}
 
Example 9
Source File: ObjectMapperFactory.java    From Bats with Apache License 2.0 5 votes vote down vote up
public static ObjectMapper getOperatorValueSerializer()
{
  ObjectMapper returnVal = new ObjectMapper();
  returnVal.setVisibilityChecker(new VC());
  returnVal.configure(org.codehaus.jackson.map.SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
  returnVal.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, As.WRAPPER_OBJECT);
  returnVal.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
  return returnVal;
}
 
Example 10
Source File: TestRailService.java    From TestRailSDK with MIT License 5 votes vote down vote up
/**
   * Posts the given String to the given TestRails end-point
   *
   * @param apiCall The end-point that expects to receive the entities (e.g. "add_result")
   * @param urlParams The remainder of the URL required for the POST. It is up to you to get this part right
   * @param entity The BaseEntity object to use at the POST body
   * @param returnEntityType The Class of the return type you wish to receive (helps avoid casting from the calling method)
   * @return The Content of the HTTP Response
   */
  private <T extends BaseEntity> T postRESTBodyReturn(String apiCall, String urlParams, BaseEntity entity, Class<T> returnEntityType) {
      HttpClient httpClient = new DefaultHttpClient();
      String completeUrl = buildRequestURL( apiCall, urlParams );

      try {
          HttpPost request = new HttpPost( completeUrl );
          String authentication = utils.encodeAuthenticationBase64(username, password);
          request.addHeader("Authorization", "Basic " + authentication);
          request.addHeader("Content-Type", "application/json");
          request.addHeader("Encoding", "UTF-8");

          ObjectMapper mapper = new ObjectMapper();
          mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
          byte[] body = mapper.writeValueAsBytes(entity);
          request.setEntity(new ByteArrayEntity(body));

          HttpResponse response = executeRequestWithRetry(request, 2);
          int responseStatusCode = response.getStatusLine().getStatusCode();
          if (responseStatusCode == 200) {
              log.info("Returning a JSON mapped object from calling api integration point");
              T mappedJsonObject = JSONUtils.getMappedJsonObject(returnEntityType, utils.getContentsFromHttpResponse(response));
              mappedJsonObject.setTestRailService(this);
              return mappedJsonObject;
          } else {
              Error error = JSONUtils.getMappedJsonObject(Error.class, utils.getContentsFromHttpResponse(response));
              log.error("Response code: {}", responseStatusCode);
              log.error("TestRails reported an error message: {}", error.getError());
          }
      }
      catch (IOException e) {
          log.error(String.format("An IOException was thrown while trying to process a REST Request against URL: [%s]", completeUrl), e);
          throw new RuntimeException(String.format("Connection is null, check URL: %s", completeUrl), e);
      } finally {
          httpClient.getConnectionManager().shutdown();
      }
return null;
  }
 
Example 11
Source File: TestRailService.java    From TestRailSDK with MIT License 5 votes vote down vote up
/**
 * Posts the given String to the given TestRails end-point
 * @param apiCall The end-point that expects to receive the entities (e.g. "add_result")
 * @param urlParams The remainder of the URL required for the POST. It is up to you to get this part right
 * @param entity The BaseEntity object to use at the POST body
 * @return The Content of the HTTP Response
 */
private HttpResponse postRESTBody(String apiCall, String urlParams, BaseEntity entity) {
    HttpClient httpClient = new DefaultHttpClient();
    String completeUrl = buildRequestURL( apiCall, urlParams );

    try {
        HttpPost request = new HttpPost( completeUrl );
        String authentication = utils.encodeAuthenticationBase64(username, password);
        request.addHeader("Authorization", "Basic " + authentication);
        request.addHeader("Content-Type", "application/json");

        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
        byte[] body = mapper.writeValueAsBytes(entity);
        request.setEntity(new ByteArrayEntity(body));

        HttpResponse response = executeRequestWithRetry(request, 2);
        if (response.getStatusLine().getStatusCode() != 200) {
            Error error = JSONUtils.getMappedJsonObject(Error.class, utils.getContentsFromHttpResponse(response));
            log.error("Response code: {}", response.getStatusLine().getStatusCode());
            log.error("TestRails reported an error message: {}", error.getError());
            request.addHeader("Encoding", "UTF-8");
        }
        return response;
    }
    catch (IOException e) {
        log.error(String.format("An IOException was thrown while trying to process a REST Request against URL: [%s]", completeUrl), e.toString());
        throw new RuntimeException(String.format("Connection is null, check URL: %s", completeUrl));
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example 12
Source File: ObjectMapperFactory.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
public static ObjectMapper getOperatorValueSerializer()
{
  ObjectMapper returnVal = new ObjectMapper();
  returnVal.setVisibilityChecker(new VC());
  returnVal.configure(org.codehaus.jackson.map.SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
  returnVal.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, As.WRAPPER_OBJECT);
  returnVal.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
  return returnVal;
}
 
Example 13
Source File: WriteJsonServletAction.java    From ureport with Apache License 2.0 5 votes vote down vote up
protected void writeObjectToJson(HttpServletResponse resp,Object obj) throws ServletException, IOException{
	resp.setContentType("text/json");
	resp.setCharacterEncoding("UTF-8");
	ObjectMapper mapper=new ObjectMapper();
	mapper.setSerializationInclusion(Inclusion.NON_NULL);
	mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false);
	mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
	OutputStream out = resp.getOutputStream();
	try {
		mapper.writeValue(out, obj);
	} finally {
		out.flush();
		out.close();
	}
}
 
Example 14
Source File: TaggerServiceImpl.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public TaggerLabel createNewLabel(TaggerLabelRequest label)
		throws AidrException {
	Client client = ClientBuilder.newBuilder()
			.register(JacksonFeature.class).build();
	try {
		/**
		 * Rest call to Tagger
		 */
		WebTarget webResource = client.target(taggerMainUrl + "/label");

		ObjectMapper objectMapper = JacksonWrapper.getObjectMapper();
		objectMapper
				.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);

		Response clientResponse = webResource.request(
				MediaType.APPLICATION_JSON)
				.post(Entity.json(objectMapper.writeValueAsString(label
						.toDTO())), Response.class);

		String jsonResponse = clientResponse.readEntity(String.class);
		NominalLabelDTO dto = objectMapper.readValue(jsonResponse,
				NominalLabelDTO.class);
		TaggerLabel response = new TaggerLabel(dto);
		if (response != null) {
			logger.info("Label with ID " + response.getNominalLabelID()
					+ " was created in Tagger");
			return response;
		} else {
			logger.error("Error while creating new label: "+label.getName());
			throw new AidrException(
					"Error while creating new label in Tagger");
		}
	} catch (Exception e) {
		logger.error("Error while creating new label: "+label.getName(), e);
		throw new AidrException("Error while creating new label in Tagger",
				e);
	}
}
 
Example 15
Source File: TaggerServiceImpl.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public TaggerLabel updateLabel(TaggerLabelRequest label)
		throws AidrException {
	Client client = ClientBuilder.newBuilder()
			.register(JacksonFeature.class).build();
	try {
		/**
		 * Rest call to Tagger
		 */
		// WebResource webResource = client.resource(taggerMainUrl +
		// "/label");
		WebTarget webResource = client.target(taggerMainUrl + "/label");

		ObjectMapper objectMapper = JacksonWrapper.getObjectMapper();
		objectMapper
				.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);

		Response clientResponse = webResource.request(
				MediaType.APPLICATION_JSON)
				.put(Entity.json(objectMapper.writeValueAsString(label
						.toDTO())), Response.class);

		String jsonResponse = clientResponse.readEntity(String.class);
		NominalLabelDTO dto = objectMapper.readValue(jsonResponse,
				NominalLabelDTO.class);
		TaggerLabel updatedLabel = new TaggerLabel(dto);
		if (updatedLabel != null) {
			logger.info("Label with id " + updatedLabel.getNominalLabelID()
					+ " was updated in Tagger");
		} else {
			return null;
		}

		return updatedLabel;
	} catch (Exception e) {
		logger.error("Error while updating label: "+label.getName(), e);
		throw new AidrException("Error while updating label in Tagger", e);
	}
}
 
Example 16
Source File: ApiObjectMapperContextResolver.java    From primecloud-controller with GNU General Public License v2.0 4 votes vote down vote up
public ApiObjectMapperContextResolver() {
    objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    objectMapper.disable(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS);
}
 
Example 17
Source File: BulkV2Connection.java    From components with Apache License 2.0 4 votes vote down vote up
static String serializeToJson(Object value) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Inclusion.NON_NULL);
    mapper.setDateFormat(CalendarCodec.getDateFormat());
    return mapper.writeValueAsString(value);
}
 
Example 18
Source File: TaggerServiceImpl.java    From AIDR with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Integer addNewUser(TaggerUser taggerUser) throws AidrException {
	Client client = ClientBuilder.newBuilder()
			.register(JacksonFeature.class).build();
	try {
		/**
		 * Rest call to Tagger
		 */
		WebTarget webResource = client.target(taggerMainUrl + "/user");

		ObjectMapper objectMapper = JacksonWrapper.getObjectMapper();
		objectMapper
				.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
		objectMapper.configure(
				DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
				false);
		Response clientResponse = webResource.request(
				MediaType.APPLICATION_JSON).post(
				Entity.json(objectMapper.writeValueAsString(taggerUser
						.toDTO())), Response.class);

		String jsonResponse = clientResponse.readEntity(String.class);

		UsersDTO dto = objectMapper.readValue(jsonResponse, UsersDTO.class);
		if (dto != null) {
			TaggerUser createdUser = new TaggerUser(dto);
			if (createdUser != null && createdUser.getUserID() != null) {
				logger.info("User with ID " + createdUser.getUserID()
						+ " was created in Tagger");
				return createdUser.getUserID();
			} else {
				return null;
			}
		} else {
			return null;
		}
	} catch (Exception e) {
		logger.error("Error while adding new user to Tagger", e);
		throw new AidrException("Error while adding new user to Tagger", e);
	}
}
 
Example 19
Source File: TaggerServiceImpl.java    From AIDR with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Integer addAttributeToCrisis(TaggerModelFamily modelFamily)
		throws AidrException {
	Client client = ClientBuilder.newBuilder()
			.register(JacksonFeature.class).build();
	try {
		/**
		 * Rest call to Tagger
		 */
		logger.info("Received add Attirbute request for crisis = "
				+ modelFamily.getCrisis().getCrisisID() + ", attribute = "
				+ modelFamily.getNominalAttribute().getNominalAttributeID());
		WebTarget webResource = client.target(taggerMainUrl
				+ "/modelfamily");

		ObjectMapper objectMapper = JacksonWrapper.getObjectMapper();
		objectMapper
				.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
		objectMapper.configure(
				DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
				false);

		Response clientResponse = webResource.request(
				MediaType.APPLICATION_JSON).post(
				Entity.json(objectMapper.writeValueAsString(modelFamily
						.toDTO())), Response.class);

		String jsonResponse = clientResponse.readEntity(String.class);
		TaggerResponseWrapper responseWrapper = objectMapper.readValue(
				jsonResponse, TaggerResponseWrapper.class);
		if (responseWrapper != null) {
			Long modelFamilyIDLong = responseWrapper.getEntityID();
			Integer modelFamilyID = new Long(modelFamilyIDLong).intValue();
			if (modelFamilyID.intValue() > 0) {
				logger.info("Attribute was added to crises: "
						+ modelFamilyID);
				return modelFamilyID;
			} else {
				logger.info("Attribute was NOT added to crises: ");
				logger.info("Received message from tagger-api: "
						+ responseWrapper.getStatusCode() + "\n"
						+ responseWrapper.getMessage());
				return null;
			}
		} else {
			logger.info("Attribute was NOT added to crises: ");
			return null;
		}
	} catch (Exception e) {
		logger.error("Error while adding attribute to crises", e);
		throw new AidrException("Error while adding attribute to crises", e);
	}
}
 
Example 20
Source File: YarnJacksonJaxbJsonProvider.java    From big-c with Apache License 2.0 4 votes vote down vote up
public static void configObjectMapper(ObjectMapper mapper) {
  AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
  mapper.setAnnotationIntrospector(introspector);
  mapper.setSerializationInclusion(Inclusion.NON_NULL);
}