Java Code Examples for org.codehaus.jackson.map.module.SimpleModule

The following examples show how to use org.codehaus.jackson.map.module.SimpleModule. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: hadoop   Source File: JsonObjectMapperWriter.java    License: 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 Project: hadoop   Source File: StatePool.java    License: 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 3
Source Project: hadoop   Source File: StatePool.java    License: 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 4
Source Project: big-c   Source File: JsonObjectMapperWriter.java    License: 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 5
Source Project: big-c   Source File: StatePool.java    License: 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 6
Source Project: big-c   Source File: StatePool.java    License: 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 7
Source Project: samza   Source File: StartpointObjectMapper.java    License: Apache License 2.0 6 votes vote down vote up
static ObjectMapper getObjectMapper() {
  ObjectMapper objectMapper = new ObjectMapper();
  SimpleModule module = new SimpleModule("StartpointModule", new Version(1, 0, 0, ""));
  module.addSerializer(Instant.class, new CustomInstantSerializer());
  module.addDeserializer(Instant.class, new CustomInstantDeserializer());
  objectMapper.registerModule(module);

  // 1. To support polymorphism for serialization, the Startpoint subtypes must be registered here.
  // 2. The NamedType container class provides a logical name as an external identifier so that the full canonical
  //    class name is not serialized into the json type property.
  objectMapper.registerSubtypes(new NamedType(StartpointSpecific.class));
  objectMapper.registerSubtypes(new NamedType(StartpointTimestamp.class));
  objectMapper.registerSubtypes(new NamedType(StartpointUpcoming.class));
  objectMapper.registerSubtypes(new NamedType(StartpointOldest.class));

  return objectMapper;
}
 
Example 8
Source Project: projectforge-webapp   Source File: Json.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static String toJson(Object object) {
	ObjectMapper mapper = new ObjectMapper(new MyJsonFactory());
	SimpleModule module = new SimpleModule("fullcalendar", new Version(1, 0, 0, null));
	module.addSerializer(new DateTimeSerializer());
	module.addSerializer(new LocalTimeSerializer());
	mapper.registerModule(module);
	mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);

	String json = null;
	try {
		json = mapper.writeValueAsString(object);
	} catch (Exception e) {
		throw new RuntimeException("Error encoding object: " + object + " into JSON string", e);
	}
	return json;
}
 
Example 9
Source Project: Bats   Source File: StramWebServices.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
private void init()
{
  //clear content type
  httpResponse.setContentType(null);
  if (!initialized) {
    Map<Class<?>, Class<? extends StringCodec<?>>> codecs = dagManager.getApplicationAttributes().get(DAGContext.STRING_CODECS);
    StringCodecs.loadConverters(codecs);
    if (codecs != null) {
      SimpleModule sm = new SimpleModule("DTSerializationModule", new Version(1, 0, 0, null));
      for (Map.Entry<Class<?>, Class<? extends StringCodec<?>>> entry : codecs.entrySet()) {
        try {
          final StringCodec<Object> codec = (StringCodec<Object>)entry.getValue().newInstance();
          sm.addSerializer(new SerializerBase(entry.getKey())
          {
            @Override
            public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException
            {
              jgen.writeString(codec.toString(value));
            }

          });
        } catch (Exception ex) {
          LOG.error("Caught exception when instantiating codec for class {}", entry.getKey().getName(), ex);
        }
      }

      objectMapper.registerModule(sm);
    }
    initialized = true;
  }
}
 
Example 10
/**
 * Deserialize from JSON
 */
public static KafkaDatastreamStatesResponse fromJson(String json) {
  SimpleModule simpleModule = new SimpleModule("KafkaDatastreamStatesResponseModule", Version.unknownVersion());
  simpleModule.addKeyDeserializer(FlushlessEventProducerHandler.SourcePartition.class, SourcePartitionDeserializer.getInstance());
  simpleModule.addKeyDeserializer(TopicPartition.class, TopicPartitionKeyDeserializer.getInstance());
  simpleModule.addDeserializer(TopicPartition.class, TopicPartitionDeserializer.getInstance());
  ObjectMapper mapper = new ObjectMapper();
  mapper.registerModule(simpleModule);
  mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  return JsonUtils.fromJson(json, KafkaDatastreamStatesResponse.class, mapper);
}
 
Example 11
Source Project: attic-apex-core   Source File: StramWebServices.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
private void init()
{
  //clear content type
  httpResponse.setContentType(null);
  if (!initialized) {
    Map<Class<?>, Class<? extends StringCodec<?>>> codecs = dagManager.getApplicationAttributes().get(DAGContext.STRING_CODECS);
    StringCodecs.loadConverters(codecs);
    if (codecs != null) {
      SimpleModule sm = new SimpleModule("DTSerializationModule", new Version(1, 0, 0, null));
      for (Map.Entry<Class<?>, Class<? extends StringCodec<?>>> entry : codecs.entrySet()) {
        try {
          final StringCodec<Object> codec = (StringCodec<Object>)entry.getValue().newInstance();
          sm.addSerializer(new SerializerBase(entry.getKey())
          {
            @Override
            public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException
            {
              jgen.writeString(codec.toString(value));
            }

          });
        } catch (Exception ex) {
          LOG.error("Caught exception when instantiating codec for class {}", entry.getKey().getName(), ex);
        }
      }

      objectMapper.registerModule(sm);
    }
    initialized = true;
  }
}
 
Example 12
private static ObjectMapper createObjectMapper() {
  ObjectMapper objectMapper = new ObjectMapper();
  SimpleModule module = new SimpleModule("ContainerPlacementModule", new Version(1, 0, 0, ""));
  module.addSerializer(ContainerPlacementMessage.class,
      new ContainerPlacementMessageObjectMapper.ContainerPlacementMessageSerializer());
  module.addDeserializer(ContainerPlacementMessage.class,
      new ContainerPlacementMessageObjectMapper.ContainerPlacementMessageDeserializer());
  objectMapper.registerModule(module);
  objectMapper.registerSubtypes(new NamedType(ContainerPlacementResponseMessage.class));
  objectMapper.registerSubtypes(new NamedType(ContainerPlacementRequestMessage.class));
  return objectMapper;
}
 
Example 13
Source Project: Raigad   Source File: DefaultMasterNodeInfoMapper.java    License: Apache License 2.0 5 votes vote down vote up
public DefaultMasterNodeInfoMapper(JsonFactory factory) {
    super(factory);
    SimpleModule serializerModule = new SimpleModule("default serializers", new Version(1, 0, 0, null));
    registerModule(serializerModule);

    configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
}
 
Example 14
Source Project: Raigad   Source File: DefaultIndexMapper.java    License: Apache License 2.0 5 votes vote down vote up
public DefaultIndexMapper(JsonFactory factory) {
    super(factory);
    SimpleModule serializerModule = new SimpleModule("default serializers", new Version(1, 0, 0, null));
    registerModule(serializerModule);

    configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    configure(SerializationConfig.Feature.AUTO_DETECT_GETTERS, false);
    configure(SerializationConfig.Feature.AUTO_DETECT_FIELDS, false);
    configure(SerializationConfig.Feature.INDENT_OUTPUT, false);
}
 
Example 15
Source Project: hraven   Source File: ObjectMapperProvider.java    License: Apache License 2.0 5 votes vote down vote up
public static ObjectMapper createCustomMapper() {
  ObjectMapper result = new ObjectMapper();
  result.configure(Feature.INDENT_OUTPUT, true);
  SimpleModule module = createhRavenModule();
  addJobMappings(module);
  module.addSerializer(Flow.class, new FlowSerializer());
  module.addSerializer(AppSummary.class, new AppSummarySerializer());
  module.addSerializer(TaskDetails.class, new TaskDetailsSerializer());
  module.addSerializer(JobDetails.class, new JobDetailsSerializer());
  result.registerModule(module);
  return result;
}
 
Example 16
Source Project: hadoop   Source File: Anonymizer.java    License: Apache License 2.0 4 votes vote down vote up
private void initialize(String[] args) throws Exception {
  try {
    for (int i = 0; i < args.length; ++i) {
      if ("-trace".equals(args[i])) {
        anonymizeTrace = true;
        inputTracePath = new Path(args[i+1]);
        outputTracePath = new Path(args[i+2]);
        i +=2;
      }
      if ("-topology".equals(args[i])) {
        anonymizeTopology = true;
        inputTopologyPath = new Path(args[i+1]);
        outputTopologyPath = new Path(args[i+2]);
        i +=2;
      }
    }
  } catch (Exception e) {
    throw new IllegalArgumentException("Illegal arguments list!", e);
  }
  
  if (!anonymizeTopology && !anonymizeTrace) {
    throw new IllegalArgumentException("Invalid arguments list!");
  }
  
  statePool = new StatePool();
  // initialize the state manager after the anonymizers are registered
  statePool.initialize(getConf());
   
  outMapper = new ObjectMapper();
  // define a module
  SimpleModule module = new SimpleModule("Anonymization Serializer",  
                                         new Version(0, 1, 1, "FINAL"));
  // add various serializers to the module
  // use the default (as-is) serializer for default data types
  module.addSerializer(DataType.class, new DefaultRumenSerializer());
  // use a blocking serializer for Strings as they can contain sensitive 
  // information
  module.addSerializer(String.class, new BlockingSerializer());
  // use object.toString() for object of type ID
  module.addSerializer(ID.class, new ObjectStringSerializer<ID>());
  // use getAnonymizedValue() for data types that have the anonymizing 
  // feature
  module.addSerializer(AnonymizableDataType.class, 
      new DefaultAnonymizingRumenSerializer(statePool, getConf()));
  
  // register the module with the object-mapper
  outMapper.registerModule(module);
  
  outFactory = outMapper.getJsonFactory();
}
 
Example 17
Source Project: big-c   Source File: Anonymizer.java    License: Apache License 2.0 4 votes vote down vote up
private void initialize(String[] args) throws Exception {
  try {
    for (int i = 0; i < args.length; ++i) {
      if ("-trace".equals(args[i])) {
        anonymizeTrace = true;
        inputTracePath = new Path(args[i+1]);
        outputTracePath = new Path(args[i+2]);
        i +=2;
      }
      if ("-topology".equals(args[i])) {
        anonymizeTopology = true;
        inputTopologyPath = new Path(args[i+1]);
        outputTopologyPath = new Path(args[i+2]);
        i +=2;
      }
    }
  } catch (Exception e) {
    throw new IllegalArgumentException("Illegal arguments list!", e);
  }
  
  if (!anonymizeTopology && !anonymizeTrace) {
    throw new IllegalArgumentException("Invalid arguments list!");
  }
  
  statePool = new StatePool();
  // initialize the state manager after the anonymizers are registered
  statePool.initialize(getConf());
   
  outMapper = new ObjectMapper();
  // define a module
  SimpleModule module = new SimpleModule("Anonymization Serializer",  
                                         new Version(0, 1, 1, "FINAL"));
  // add various serializers to the module
  // use the default (as-is) serializer for default data types
  module.addSerializer(DataType.class, new DefaultRumenSerializer());
  // use a blocking serializer for Strings as they can contain sensitive 
  // information
  module.addSerializer(String.class, new BlockingSerializer());
  // use object.toString() for object of type ID
  module.addSerializer(ID.class, new ObjectStringSerializer<ID>());
  // use getAnonymizedValue() for data types that have the anonymizing 
  // feature
  module.addSerializer(AnonymizableDataType.class, 
      new DefaultAnonymizingRumenSerializer(statePool, getConf()));
  
  // register the module with the object-mapper
  outMapper.registerModule(module);
  
  outFactory = outMapper.getJsonFactory();
}
 
Example 18
Source Project: samza   Source File: SamzaObjectMapper.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * @return Returns a new ObjectMapper that's been configured to (de)serialize
 *         Samza's job data model, and simple data types such as TaskName,
 *         Partition, Config, and SystemStreamPartition.
 */
public static ObjectMapper getObjectMapper() {
  ObjectMapper mapper = new ObjectMapper();
  SimpleModule module = new SimpleModule("SamzaModule", new Version(1, 0, 0, ""));

  // Setup custom serdes for simple data types.
  module.addSerializer(Partition.class, new PartitionSerializer());
  module.addSerializer(SystemStreamPartition.class, new SystemStreamPartitionSerializer());
  module.addKeySerializer(SystemStreamPartition.class, new SystemStreamPartitionKeySerializer());
  module.addSerializer(TaskName.class, new TaskNameSerializer());
  module.addSerializer(TaskMode.class, new TaskModeSerializer());
  module.addDeserializer(TaskName.class, new TaskNameDeserializer());
  module.addDeserializer(Partition.class, new PartitionDeserializer());
  module.addDeserializer(SystemStreamPartition.class, new SystemStreamPartitionDeserializer());
  module.addKeyDeserializer(SystemStreamPartition.class, new SystemStreamPartitionKeyDeserializer());
  module.addDeserializer(Config.class, new ConfigDeserializer());
  module.addDeserializer(TaskMode.class, new TaskModeDeserializer());

  // Setup mixins for data models.
  mapper.getSerializationConfig().addMixInAnnotations(TaskModel.class, JsonTaskModelMixIn.class);
  mapper.getDeserializationConfig().addMixInAnnotations(TaskModel.class, JsonTaskModelMixIn.class);
  mapper.getSerializationConfig().addMixInAnnotations(ContainerModel.class, JsonContainerModelMixIn.class);
  mapper.getSerializationConfig().addMixInAnnotations(JobModel.class, JsonJobModelMixIn.class);
  mapper.getDeserializationConfig().addMixInAnnotations(JobModel.class, JsonJobModelMixIn.class);

  module.addDeserializer(ContainerModel.class, new JsonDeserializer<ContainerModel>() {
    @Override
    public ContainerModel deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
      ObjectCodec oc = jp.getCodec();
      JsonNode node = oc.readTree(jp);
      /*
       * Before Samza 0.13, "container-id" was used.
       * In Samza 0.13, "processor-id" was added to be the id to use and "container-id" was deprecated. However,
       * "container-id" still needed to be checked for backwards compatibility in case "processor-id" was missing
       * (i.e. from a job model corresponding to a version of the job that was on a pre Samza 0.13 version).
       * In Samza 1.0, "container-id" was further cleaned up from ContainerModel. This logic is still being left here
       * as a fallback for backwards compatibility with pre Samza 0.13. ContainerModel.getProcessorId was changed to
       * ContainerModel.getId in the Java API, but "processor-id" still needs to be used as the JSON key for backwards
       * compatibility with Samza 0.13 and Samza 0.14.
       */
      String id;
      if (node.get(JsonContainerModelMixIn.PROCESSOR_ID_KEY) == null) {
        if (node.get(JsonContainerModelMixIn.CONTAINER_ID_KEY) == null) {
          throw new SamzaException(
              String.format("JobModel was missing %s and %s. This should never happen. JobModel corrupt!",
                  JsonContainerModelMixIn.PROCESSOR_ID_KEY, JsonContainerModelMixIn.CONTAINER_ID_KEY));
        }
        id = String.valueOf(node.get(JsonContainerModelMixIn.CONTAINER_ID_KEY).getIntValue());
      } else {
        id = node.get(JsonContainerModelMixIn.PROCESSOR_ID_KEY).getTextValue();
      }
      Map<TaskName, TaskModel> tasksMapping =
          OBJECT_MAPPER.readValue(node.get(JsonContainerModelMixIn.TASKS_KEY),
              new TypeReference<Map<TaskName, TaskModel>>() { });
      return new ContainerModel(id, tasksMapping);
    }
  });

  // Convert camel case to hyphenated field names, and register the module.
  mapper.setPropertyNamingStrategy(new CamelCaseToDashesStrategy());
  mapper.registerModule(module);

  return mapper;
}
 
Example 19
Source Project: hraven   Source File: ObjectMapperProvider.java    License: Apache License 2.0 4 votes vote down vote up
private static SimpleModule addJobMappings(SimpleModule module) {
  module.addSerializer(Configuration.class, new ConfigurationSerializer());
  module.addSerializer(CounterMap.class, new CounterSerializer());
  module.addSerializer(HdfsStats.class, new HdfsStatsSerializer());
  return module;
}
 
Example 20
Source Project: hraven   Source File: ObjectMapperProvider.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * creates a new SimpleModule for holding the serializers
 * @return SimpleModule
 */
private static SimpleModule createhRavenModule() {
  return new SimpleModule("hRavenModule", new Version(0, 4, 0, null));
}