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

The following examples show how to use org.codehaus.jackson.map.ObjectMapper#configure() . 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: JsonObjectMapperWriter.java    From big-c with Apache License 2.0 6 votes vote down vote up
public JsonObjectMapperWriter(OutputStream output, boolean prettyPrint) throws IOException {
  ObjectMapper mapper = new ObjectMapper();
  mapper.configure(
      SerializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS, true);

  // define a module
  SimpleModule module = new SimpleModule("Default Serializer",  
                                         new Version(0, 1, 1, "FINAL"));
  // add various serializers to the module
  //   add default (all-pass) serializer for all rumen specific data types
  module.addSerializer(DataType.class, new DefaultRumenSerializer());
  //   add a serializer to use object.toString() while serializing
  module.addSerializer(ID.class, new ObjectStringSerializer<ID>());
  
  // register the module with the object-mapper
  mapper.registerModule(module);

  mapper.getJsonFactory();
  writer = mapper.getJsonFactory().createJsonGenerator(
      output, JsonEncoding.UTF8);
  if (prettyPrint) {
    writer.useDefaultPrettyPrinter();
  }
}
 
Example 2
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 3
Source File: StatePool.java    From hadoop with Apache License 2.0 6 votes vote down vote up
private void read(DataInput in) throws IOException {
  ObjectMapper mapper = new ObjectMapper();
  mapper.configure(
      DeserializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS, true);
  
  // define a module
  SimpleModule module = new SimpleModule("State Serializer",  
      new Version(0, 1, 1, "FINAL"));
  // add the state deserializer
  module.addDeserializer(StatePair.class, new StateDeserializer());

  // register the module with the object-mapper
  mapper.registerModule(module);

  JsonParser parser = 
    mapper.getJsonFactory().createJsonParser((DataInputStream)in);
  StatePool statePool = mapper.readValue(parser, StatePool.class);
  this.setStates(statePool.getStates());
  parser.close();
}
 
Example 4
Source File: StatePool.java    From hadoop with Apache License 2.0 6 votes vote down vote up
private void write(DataOutput out) throws IOException {
  // This is just a JSON experiment
  System.out.println("Dumping the StatePool's in JSON format.");
  ObjectMapper outMapper = new ObjectMapper();
  outMapper.configure(
      SerializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS, true);
  // define a module
  SimpleModule module = new SimpleModule("State Serializer",  
      new Version(0, 1, 1, "FINAL"));
  // add the state serializer
  //module.addSerializer(State.class, new StateSerializer());

  // register the module with the object-mapper
  outMapper.registerModule(module);

  JsonFactory outFactory = outMapper.getJsonFactory();
  JsonGenerator jGen = 
    outFactory.createJsonGenerator((DataOutputStream)out, JsonEncoding.UTF8);
  jGen.useDefaultPrettyPrinter();

  jGen.writeObject(this);
  jGen.close();
}
 
Example 5
Source File: RegistryChangeService.java    From occurrence with Apache License 2.0 5 votes vote down vote up
/**
 * We have to create our own object mapper in order to set FAIL_ON_UNKNOWN, without which we can't deser reg objects
 */
private ObjectMapper createObjectMapper() {
  ObjectMapper objectMapper = new ObjectMapper();
  objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  Mixins.getPredefinedMixins().forEach((key, value) -> {
    objectMapper.getSerializationConfig().addMixInAnnotations(key, value);
    objectMapper.getDeserializationConfig().addMixInAnnotations(key, value);
  });
  return objectMapper;
}
 
Example 6
Source File: JsonObjectMapperParser.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 * 
 * @param input
 *          The input stream for the JSON data.
 */
public JsonObjectMapperParser(InputStream input, Class<? extends T> clazz)
    throws IOException {
  mapper = new ObjectMapper();
  mapper.configure(
      DeserializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS, true);
  this.clazz = clazz;
  jsonParser = mapper.getJsonFactory().createJsonParser(input);
}
 
Example 7
Source File: JsonObjectMapperParser.java    From RDFS with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 * 
 * @param input
 *          The input stream for the JSON data.
 */
public JsonObjectMapperParser(InputStream input, Class<? extends T> clazz)
    throws IOException {
  mapper = new ObjectMapper();
  mapper.configure(
      DeserializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS, true);
  this.clazz = clazz;
  decompressor = null;
  jsonParser = mapper.getJsonFactory().createJsonParser(input);
}
 
Example 8
Source File: JsonObjectMapperParser.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 * 
 * @param path
 *          Path to the JSON data file, possibly compressed.
 * @param conf
 * @throws IOException
 */
public JsonObjectMapperParser(Path path, Class<? extends T> clazz,
    Configuration conf) throws IOException {
  mapper = new ObjectMapper();
  mapper.configure(
      DeserializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS, true);
  this.clazz = clazz;
  InputStream input = new PossiblyDecompressedInputStream(path, conf);
  jsonParser = mapper.getJsonFactory().createJsonParser(input);
}
 
Example 9
Source File: TaskManagerEntityMapper.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Deprecated
public <E> E deSerializeList(String jsonString, TypeReference<E> type) {
	ObjectMapper mapper = new ObjectMapper();
	mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	try {
		if (jsonString != null) {
			E docList = mapper.readValue(jsonString, type);
			return docList;
		}	
	} catch (Exception e) {
		logger.error("JSON deserialization exception",e);
	}
	return null;
}
 
Example 10
Source File: TaggerServiceImpl.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public TaggerResponseWrapper getHumanLabeledDocumentsByCrisisIDUserName(
		Long crisisID, String userName, Integer count) throws AidrException {
	Client client = ClientBuilder.newBuilder()
			.register(JacksonFeature.class).build();
	try {
		// Rest call to Tagger
		WebTarget webResource = client.target(taggerMainUrl
				+ "/misc/humanLabeled/crisisID/" + crisisID + "/userName/"
				+ userName + "?count=" + count);

		ObjectMapper objectMapper = JacksonWrapper.getObjectMapper();
		objectMapper.configure(
				DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
				false);
		Response clientResponse = webResource.request(
				MediaType.APPLICATION_JSON).get();

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

		TaggerResponseWrapper dtoList = objectMapper.readValue(
				jsonResponse, TaggerResponseWrapper.class);
		logger.info("Number of human labeled documents returned by Tagger: "
				+ (dtoList.getHumanLabeledItems() != null ? dtoList
						.getHumanLabeledItems().size() : 0));

		return dtoList;
	} catch (Exception e) {
		logger.error("Error while getting all human labeled documents for crisisID = "
						+ crisisID + ", user name = " + userName
						+ " from Tagger", e);
		throw new AidrException(
				"Error while getting all human labeled documents for crisisID = "
						+ crisisID + ", user name = " + userName
						+ " from Tagger", e);
	}
}
 
Example 11
Source File: StringCodec.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
@Override
public T fromString(String string)
{
  try {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    ObjectReader reader = mapper.reader(clazz);
    return reader.readValue(string);
  } catch (IOException e) {
    throw Throwables.propagate(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 List<TaggerCrisisType> getAllCrisisTypes() throws AidrException {
	Client client = ClientBuilder.newBuilder()
			.register(JacksonFeature.class).build();
	try {
		/**
		 * Rest call to Tagger
		 */
		logger.info("Received request to fetch all crisisTypes");
		WebTarget webResource = client.target(taggerMainUrl
				+ "/crisisType/all");

		ObjectMapper objectMapper = JacksonWrapper.getObjectMapper();
		objectMapper.configure(
				DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
				false);
		Response clientResponse = webResource.request(
				MediaType.APPLICATION_JSON).get();

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

		//logger.error("URL: " + taggerMainUrl + " " + jsonResponse);

		TaggerAllCrisesTypesResponse crisesTypesResponse = objectMapper
				.readValue(jsonResponse, TaggerAllCrisesTypesResponse.class);

		if (crisesTypesResponse.getCrisisTypes() != null) {
			logger.info("Tagger returned "
					+ crisesTypesResponse.getCrisisTypes().size()
					+ " crises types");
		}

		return crisesTypesResponse.getCrisisTypes();
	} catch (Exception e) {
		logger.error("Error while getting all crisis from Tagger", e);
		throw new AidrException(
				"Error while getting all crisis from 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 TaggerResponseWrapper getHumanLabeledDocumentsByCrisisID(
		Long crisisID, Integer count) throws AidrException {
	Client client = ClientBuilder.newBuilder()
			.register(JacksonFeature.class).build();
	try {
		// Rest call to Tagger
		WebTarget webResource = client.target(taggerMainUrl
				+ "/misc/humanLabeled/crisisID/" + crisisID + "?count="
				+ count);

		ObjectMapper objectMapper = JacksonWrapper.getObjectMapper();
		objectMapper.configure(
				DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
				false);
		Response clientResponse = webResource.request(
				MediaType.APPLICATION_JSON).get();

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

		TaggerResponseWrapper dtoList = objectMapper.readValue(
				jsonResponse, TaggerResponseWrapper.class);
		logger.info("Number of human labeled documents returned by Tagger: "
				+ (dtoList.getHumanLabeledItems() != null ? dtoList
						.getHumanLabeledItems().size() : 0));

		return dtoList;
	} catch (Exception e) {
		logger.error("Error while getting all human labeled documents for crisisID = "
						+ crisisID + " from Tagger", e);
		throw new AidrException(
				"Error while getting all human labeled documents for crisisID = "
						+ crisisID + " from 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 TaggerCrisisExist isCrisesExist(String code) throws AidrException {
	Client client = ClientBuilder.newBuilder()
			.register(JacksonFeature.class).build();
	try {
		WebTarget webResource = client.target(taggerMainUrl
				+ "/crisis/code/" + code);

		ObjectMapper objectMapper = JacksonWrapper.getObjectMapper();
		objectMapper.configure(
				DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
				false);

		Response clientResponse = webResource.request(
				MediaType.APPLICATION_JSON).get();

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

		TaggerCrisisExist crisisExist = objectMapper.readValue(
				jsonResponse, TaggerCrisisExist.class);

		if (crisisExist.getCrisisId() != null) {
			logger.info("Response from Tagger-API for Crises with the code "
					+ code+ ", found crisisID = "+ crisisExist.getCrisisId());
			return crisisExist;
		} else {
			return null;
		}
	} catch (Exception e) {
		logger.error("Error while checking if crisis exist in Tagger for collection: "+code, e);
		throw new AidrException(
				"Error while checking if crisis exist in Tagger", e);
	}
}
 
Example 15
Source File: JsonMarshaller.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
private JsonMarshaller()
{
    mapper = new ObjectMapper();
    mapper.configure(org.codehaus.jackson.JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    mapper.getSerializationConfig().setSerializationInclusion(org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion.NON_NULL);
    mapper.getDeserializationConfig().set(org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
 
Example 16
Source File: BulkV2Connection.java    From components with Apache License 2.0 4 votes vote down vote up
static <T> T deserializeJsonToObject(InputStream in, Class<T> tmpClass) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    return mapper.readValue(in, tmpClass);
}
 
Example 17
Source File: CoinbaseSource.java    From cloud-bigtable-examples with Apache License 2.0 4 votes vote down vote up
private static ObjectMapper initializeObjectMapper() {
  objectMapper = new ObjectMapper();
  objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  return objectMapper;
}
 
Example 18
Source File: RMRestClient.java    From scheduling with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public ObjectMapper getContext(Class<?> objectType) {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return objectMapper;
}
 
Example 19
Source File: TaggerServiceImpl.java    From AIDR with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Map<String, Object> downloadHumanLabeledDocumentsByCrisisUserName(
		String queryString, String crisisCode, String userName,
		Integer count, String fileType, String contentType)
		throws AidrException {
	Client client = ClientBuilder.newBuilder()
			.register(JacksonFeature.class).build();
	
	String targetURL = taggerMainUrl
			+ "/misc/humanLabeled/download/crisis/" + crisisCode
			+ "/userName/" + userName + "?count=" + count
			+ "&fileType=" + fileType + "&contentType=" + contentType;
	
	logger.info("Going to invoke REST API: " + targetURL + " POST body: " + queryString);
	try {
		// Rest call to Tagger
		WebTarget webResource = client.target(targetURL);

		ObjectMapper objectMapper = JacksonWrapper.getObjectMapper();
		objectMapper.configure(
				DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
				false);
		Response clientResponse = webResource.request(
				MediaType.APPLICATION_JSON).post(Entity.json(queryString),
				Response.class);
		String jsonResponse = clientResponse.readEntity(String.class);
		//logger.info("Response = " + jsonResponse);
		TaggerResponseWrapper response = objectMapper.readValue(
				jsonResponse, TaggerResponseWrapper.class);
		logger.info("Number of human labeled documents returned by Tagger: "
				+ response.getTotal());

		Map<String, Object> retVal = new HashMap<String, Object>();
		retVal.put("fileName", response.getMessage());
		retVal.put("total", response.getTotal());
		return retVal;
	} catch (Exception e) {
		logger.error("Error while getting download link for human labeled documents for crisis code = "
						+ crisisCode+ ", user name = "+ userName+ " from Tagger", e);
		throw new AidrException("Error while getting download link for human labeled documents for crisis code = "
				+ crisisCode+ ", user name = "+ userName+ " from Tagger", e);
	}
}
 
Example 20
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);
	}
}