org.codehaus.jackson.map.annotate.JsonSerialize Java Examples

The following examples show how to use org.codehaus.jackson.map.annotate.JsonSerialize. 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: JacksonUnionExtension.java    From raml-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public TypeSpec.Builder classCreated(UnionPluginContext unionPluginContext, UnionTypeDeclaration ramlType, TypeSpec.Builder incoming, EventType eventType) {

    ClassName deserializer =
            ClassName.get("", unionPluginContext.creationResult().getJavaName(EventType.INTERFACE).simpleName(),
                    Names.typeName(ramlType.name(), "deserializer"));

    ClassName serializer =
            ClassName.get("", unionPluginContext.creationResult().getJavaName(EventType.INTERFACE).simpleName(),
                    Names.typeName("serializer"));

    createSerializer(unionPluginContext, serializer, ramlType, incoming, eventType);
    createDeserializer(unionPluginContext, deserializer, ramlType, incoming, eventType);

    incoming.addAnnotation(AnnotationSpec.builder(JsonDeserialize.class)
            .addMember("using", "$T.class", deserializer).build());
    incoming.addAnnotation(AnnotationSpec.builder(JsonSerialize.class)
            .addMember("using", "$T.class", serializer).build());

    return incoming;
}
 
Example #2
Source File: JsonUtils.java    From fountain with Apache License 2.0 5 votes vote down vote up
public static byte[] toJsonBytes(Object object, boolean ignoreEmpty) {
    byte[] smileData = null;
    try {
        if(ignoreEmpty){
            smileData = objectMapperByte.writeValueAsBytes(object,JsonSerialize.Inclusion.NON_EMPTY);
        }else{
            smileData = objectMapperByte.writeValueAsBytes(object);
        }
    } catch (Exception e) {
        log.warn("json error:" + e.getMessage());
    }
    return smileData;

}
 
Example #3
Source File: JsonUtils.java    From fountain with Apache License 2.0 5 votes vote down vote up
public String writeValueAsString(Object value,
		JsonSerialize.Inclusion inc) throws IOException,
		JsonGenerationException, JsonMappingException {
	if (inc == null) {
		return super.writeValueAsString(value);
	}
	// alas, we have to pull the recycler directly here...
	SegmentedStringWriter sw = new SegmentedStringWriter(
			_jsonFactory._getBufferRecycler());
	writeValueWithConf(_jsonFactory.createJsonGenerator(sw), value,
			inc);
	return sw.getAndClear();
}
 
Example #4
Source File: JsonUtils.java    From fountain with Apache License 2.0 5 votes vote down vote up
public byte[] writeValueAsBytes(Object value,
        JsonSerialize.Inclusion inc) throws IOException,
        JsonGenerationException, JsonMappingException {
    if (inc == null) {
        return super.writeValueAsBytes(value);
    }
    // alas, we have to pull the recycler directly here...
    ByteArrayBuilder bb = new ByteArrayBuilder(_jsonFactory._getBufferRecycler());
    writeValueWithConf(_jsonFactory.createJsonGenerator(bb, JsonEncoding.UTF8), value,inc);
    byte[] result = bb.toByteArray();
    bb.release();
    return result;
}
 
Example #5
Source File: AbstractEntity.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Override
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public String getName() {
    Object value = getProperty( PROPERTY_NAME );

    if ( value instanceof UUID ) {
        // fixes existing data that uses UUID in USERGRID-2099
        return value.toString();
    }

    return ( String ) value;
}
 
Example #6
Source File: JsonUtils.java    From fountain with Apache License 2.0 5 votes vote down vote up
public static String toJson(Object object, boolean ignoreEmpty) {
	String jsonString = "";
	try {
		if(ignoreEmpty){
			jsonString = objectMapper.writeValueAsString(object,JsonSerialize.Inclusion.NON_EMPTY);
		}else{
			jsonString = objectMapper.writeValueAsString(object);
		}
		} catch (Exception e) {
		log.warn("json error:" + e.getMessage());
	}
	return jsonString;
	
}
 
Example #7
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 #8
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 #9
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 #10
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 #11
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 #12
Source File: TaggerServiceImpl.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public boolean deleteAttribute(Integer id) throws AidrException {
	Client client = ClientBuilder.newBuilder()
			.register(JacksonFeature.class).build();
	try {
		WebTarget webResource = client.target(taggerMainUrl + "/attribute/"
				+ id);

		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("Attribute with ID " + id
						+ " was deleted in Tagger");
				return true;
			} else {
				return false;
			}
		}
		return false;
	} catch (Exception e) {
		logger.error("Error while deleting a attribute for attributeId: "+id, e);
		throw new AidrException("Error while deleting attribute in Tagger",
				e);
	}
}
 
Example #13
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 #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
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 #16
Source File: JsonTopologySerializer.java    From libcrunch with Apache License 2.0 5 votes vote down vote up
private ObjectWriter getWriter() {
  ObjectMapper mapper = new ObjectMapper();

  // omit null fields from serialization
  mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
  // exclude certain fields and getter methods from node serialization via mixin
  mapper.getSerializationConfig().addMixInAnnotations(Node.class, MixIn.class);
  // register the module that suppresses the failed property if false
  mapper.registerModule(new IsFailedSuppressor());

  return mapper.writer().withDefaultPrettyPrinter();
}
 
Example #17
Source File: Api.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@JsonSerialize(include = NON_NULL)
public List<ApiOperation> getOperations() {
    return operations;
}
 
Example #18
Source File: ApiParam.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@JsonSerialize(include = NON_NULL)
public Boolean isAllowMultiple() {
    return allowMultiple;
}
 
Example #19
Source File: Api.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@JsonSerialize(include = NON_NULL)
public String getPath() {
    return path;
}
 
Example #20
Source File: ApiListing.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@JsonSerialize(include = NON_NULL)
public String getApiVersion() {
    return apiVersion;
}
 
Example #21
Source File: ApiListing.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@JsonSerialize(include = NON_NULL)
public String getSwaggerVersion() {
    return swaggerVersion;
}
 
Example #22
Source File: ApiListing.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@JsonSerialize(include = NON_NULL)
public String getBasePath() {
    return basePath;
}
 
Example #23
Source File: ApiListing.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@JsonSerialize(include = NON_NULL)
public List<Api> getApis() {
    return apis;
}
 
Example #24
Source File: ApiParam.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@JsonSerialize(include = NON_NULL)
public String getName() {
    return name;
}
 
Example #25
Source File: ApiParam.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@JsonSerialize(include = NON_NULL)
public String getDataType() {
    return dataType;
}
 
Example #26
Source File: ApiParam.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@JsonSerialize(include = NON_NULL)
public String getDescription() {
    return description;
}
 
Example #27
Source File: ApiParam.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@JsonSerialize(include = NON_NULL)
public String getDefaultValue() {
    return defaultValue;
}
 
Example #28
Source File: AggregateCounterSet.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public UUID getUser() {
    return user;
}
 
Example #29
Source File: ApiParam.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@JsonSerialize(include = NON_NULL)
public Boolean isRequired() {
    return required;
}
 
Example #30
Source File: Api.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@JsonSerialize(include = NON_NULL)
public String getDescription() {
    return description;
}