Example usage for com.fasterxml.jackson.databind.module SimpleModule SimpleModule

List of usage examples for com.fasterxml.jackson.databind.module SimpleModule SimpleModule

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind.module SimpleModule SimpleModule.

Prototype

public SimpleModule() 

Source Link

Document

Constructors that should only be used for non-reusable convenience modules used by app code: "real" modules should use actual name and version number information.

Usage

From source file:com.rcv.ResultsWriter.java

private void generateSummaryJson(Map<Integer, Map<String, BigDecimal>> roundTallies, String precinct,
        String outputPath) throws IOException {

    // mapper converts java objects to json
    ObjectMapper mapper = new ObjectMapper();
    // set mapper to order keys alphabetically for more legible output
    mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
    // create a module to contain a serializer for BigDecimal serialization
    SimpleModule module = new SimpleModule();
    module.addSerializer(BigDecimal.class, new ToStringSerializer());
    // attach serializer to mapper
    mapper.registerModule(module);//  w w  w.j ava2 s  .c o m

    // jsonWriter writes those object to disk
    ObjectWriter jsonWriter = mapper.writer(new DefaultPrettyPrinter());
    // jsonPath for output json summary
    String jsonPath = outputPath + ".json";
    // log output location
    Logger.log(Level.INFO, "Generating summary JSON file: %s...", jsonPath);
    // outFile is the target file
    File outFile = new File(jsonPath);

    // root outputJson dict will have two entries:
    // results - vote totals, transfers, and candidates elected / eliminated
    // config - global config into
    HashMap<String, Object> outputJson = new HashMap<>();
    // config will contain contest configuration info
    HashMap<String, Object> configData = new HashMap<>();
    // add config header info
    configData.put("contest", config.getContestName());
    configData.put("jurisdiction", config.getContestJurisdiction());
    configData.put("office", config.getContestOffice());
    configData.put("date", config.getContestDate());
    configData.put("threshold", winningThreshold);
    if (precinct != null && !precinct.isEmpty()) {
        configData.put("precinct", precinct);
    }
    // results will be a list of round data objects
    ArrayList<Object> results = new ArrayList<>();
    // for each round create objects for json serialization
    for (int round = 1; round <= numRounds; round++) {
        // container for all json data this round:
        HashMap<String, Object> roundData = new HashMap<>();
        // add round number (this is implied by the ordering but for debugging we are explicit)
        roundData.put("round", round);
        // add actions if this is not a precinct summary
        if (precinct == null || precinct.isEmpty()) {
            // actions is a list of one or more action objects
            ArrayList<Object> actions = new ArrayList<>();
            addActionObjects("elected", roundToWinningCandidates.get(round), round, actions);
            // add any elimination actions
            addActionObjects("eliminated", roundToEliminatedCandidates.get(round), round, actions);
            // add action objects
            roundData.put("tallyResults", actions);
        }
        // add tally object
        roundData.put("tally", updateCandidateNamesInTally(roundTallies.get(round)));
        // add roundData to results list
        results.add(roundData);
    }
    // add config data to root object
    outputJson.put("config", configData);
    // add results to root object
    outputJson.put("results", results);
    // write results to disk
    try {
        jsonWriter.writeValue(outFile, outputJson);
    } catch (IOException exception) {
        Logger.log(Level.SEVERE, "Error writing to JSON file: %s\n%s", jsonPath, exception.toString());
        throw exception;
    }
}

From source file:org.openmhealth.shim.healthvault.HealthvaultShim.java

@Override
public ShimDataResponse getData(final ShimDataRequest shimDataRequest) throws ShimException {
    final HealthVaultDataType healthVaultDataType;
    try {/*from w  w w  .  ja v  a 2 s .c  o m*/
        healthVaultDataType = HealthVaultDataType
                .valueOf(shimDataRequest.getDataTypeKey().trim().toUpperCase());
    } catch (NullPointerException | IllegalArgumentException e) {
        throw new ShimException("Null or Invalid data type parameter: " + shimDataRequest.getDataTypeKey()
                + " in shimDataRequest, cannot retrieve data.");
    }

    final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'hh:mm:ss");

    /***
     * Setup default date parameters
     */
    DateTime today = new DateTime();

    DateTime startDate = shimDataRequest.getStartDate() == null ? today.minusDays(1)
            : shimDataRequest.getStartDate();
    String dateStart = startDate.toString(formatter);

    DateTime endDate = shimDataRequest.getEndDate() == null ? today.plusDays(1) : shimDataRequest.getEndDate();
    String dateEnd = endDate.toString(formatter);

    long numToReturn = shimDataRequest.getNumToReturn() == null || shimDataRequest.getNumToReturn() <= 0 ? 100
            : shimDataRequest.getNumToReturn();

    Request request = new Request();
    request.setMethodName("GetThings");
    request.setInfo("<info>" + "<group max=\"" + numToReturn + "\">" + "<filter>" + "<type-id>"
            + healthVaultDataType.getDataTypeId() + "</type-id>" + "<eff-date-min>" + dateStart
            + "</eff-date-min>" + "<eff-date-max>" + dateEnd + "</eff-date-max>" + "</filter>" + "<format>"
            + "<section>core</section>" + "<xml/>" + "</format>" + "</group>" + "</info>");

    RequestTemplate template = new RequestTemplate(connection);
    return template.makeRequest(shimDataRequest.getAccessParameters(), request,
            new Marshaller<ShimDataResponse>() {
                public ShimDataResponse marshal(InputStream istream) throws Exception {

                    /**
                     * XML Document mappings to JSON don't respect repeatable
                     * tags, they don't get properly serialized into collections.
                     * Thus, we pickup the 'things' via the 'group' root tag
                     * and create a new JSON document out of each 'thing' node.
                     */
                    XmlMapper xmlMapper = new XmlMapper();
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document doc = builder.parse(istream);
                    NodeList nodeList = doc.getElementsByTagName("thing");

                    /**
                     * Collect JsonNode from each 'thing' xml node.
                     */
                    List<JsonNode> thingList = new ArrayList<>();
                    for (int i = 0; i < nodeList.getLength(); i++) {
                        Node node = nodeList.item(i);
                        Document thingDoc = builder.newDocument();
                        Node newNode = thingDoc.importNode(node, true);
                        thingDoc.appendChild(newNode);
                        thingList.add(xmlMapper.readTree(convertDocumentToString(thingDoc)));
                    }

                    /**
                     * Rebuild JSON document structure to pass to deserializer.
                     */
                    String thingsJson = "{\"things\":[";
                    String thingsContent = "";
                    for (JsonNode thingNode : thingList) {
                        thingsContent += thingNode.toString() + ",";
                    }
                    thingsContent = "".equals(thingsContent) ? thingsContent
                            : thingsContent.substring(0, thingsContent.length() - 1);
                    thingsJson += thingsContent;
                    thingsJson += "]}";

                    /**
                     * Return raw re-built 'things' or a normalized JSON document.
                     */
                    ObjectMapper objectMapper = new ObjectMapper();
                    if (shimDataRequest.getNormalize()) {
                        SimpleModule module = new SimpleModule();
                        module.addDeserializer(ShimDataResponse.class, healthVaultDataType.getNormalizer());
                        objectMapper.registerModule(module);
                        return objectMapper.readValue(thingsJson, ShimDataResponse.class);
                    } else {
                        return ShimDataResponse.result(HealthvaultShim.SHIM_KEY,
                                objectMapper.readTree(thingsJson));
                    }
                }
            });
}

From source file:com.ikanow.aleph2.data_model.utils.BeanTemplateUtils.java

/** Configures a mapper with the desired properties for use in Aleph2
 * @param configure_me - leave this empty to create a new mapper, or add one to configure an existing mapper
 * @return//w  ww . j  av  a 2 s.c  o m
 */
public static ObjectMapper configureMapper(final Optional<ObjectMapper> configure_me) {
    final ObjectMapper mapper = configure_me.orElse(new ObjectMapper());
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE);

    final SimpleModule module = new SimpleModule();
    module.addDeserializer(Number.class, new NumberDeserializer());
    mapper.registerModule(module);

    return mapper;
}

From source file:de.undercouch.bson4jackson.BsonParserTest.java

/**
 * Check if org.bson.types.ObjectId can be serialized and deserialized as
 * a byte array. See issue #38//from www . j  av a  2 s .  com
 * @throws Exception if something goes wrong
 */
@Test
public void parseObjectId() throws Exception {
    class ObjectIdDeserializer extends StdDeserializer<org.bson.types.ObjectId> {
        private static final long serialVersionUID = 6934309887169924897L;

        protected ObjectIdDeserializer() {
            super(org.bson.types.ObjectId.class);
        }

        @Override
        public org.bson.types.ObjectId deserialize(JsonParser jp, DeserializationContext ctxt)
                throws IOException, JsonGenerationException {
            return new org.bson.types.ObjectId(jp.getBinaryValue());
        }
    }

    org.bson.types.ObjectId oid = new org.bson.types.ObjectId();
    BSONObject o = new BasicBSONObject();
    o.put("oid", oid.toByteArray());

    SimpleModule mod = new SimpleModule();
    mod.addDeserializer(org.bson.types.ObjectId.class, new ObjectIdDeserializer());

    ObjectIdClass res = parseBsonObject(o, ObjectIdClass.class, mod);
    assertEquals(oid, res.oid);
}

From source file:io.coala.json.DynaBean.java

/** */
public static <T> void registerType(final ObjectMapper om, final Class<T> type, final Properties... imports) {
    // TODO implement dynamic generic Converter(s) for JSON bean
    // properties ?

    // if (Config.class.isAssignableFrom(type))
    // {/*from w  w w. j  a  v  a  2s . co m*/
    // final Class<?> editorType = new
    // JsonPropertyEditor<T>().getClass();
    // PropertyEditorManager.registerEditor(type, editorType);
    // LOG.trace("Registered " + editorType + " - "
    // + PropertyEditorManager.findEditor(type));
    // }

    om.registerModule(new SimpleModule().addSerializer(type, createJsonSerializer(type)).addDeserializer(type,
            createJsonDeserializer(om, type, imports)));
}

From source file:org.apache.drill.exec.store.parquet.Metadata.java

/**
 * Serialize parquet metadata to json and write to a file
 *
 * @param parquetTableMetadata//from   w ww  . ja v  a  2 s. co m
 * @param p
 * @throws IOException
 */
private void writeFile(ParquetTableMetadata_v3 parquetTableMetadata, Path p) throws IOException {
    JsonFactory jsonFactory = new JsonFactory();
    jsonFactory.configure(Feature.AUTO_CLOSE_TARGET, false);
    jsonFactory.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
    ObjectMapper mapper = new ObjectMapper(jsonFactory);
    SimpleModule module = new SimpleModule();
    module.addSerializer(ColumnMetadata_v3.class, new ColumnMetadata_v3.Serializer());
    mapper.registerModule(module);
    FSDataOutputStream os = fs.create(p);
    mapper.writerWithDefaultPrettyPrinter().writeValue(os, parquetTableMetadata);
    os.flush();
    os.close();
}

From source file:org.apache.drill.exec.store.parquet.Metadata.java

private void writeFile(ParquetTableMetadataDirs parquetTableMetadataDirs, Path p) throws IOException {
    JsonFactory jsonFactory = new JsonFactory();
    jsonFactory.configure(Feature.AUTO_CLOSE_TARGET, false);
    jsonFactory.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
    ObjectMapper mapper = new ObjectMapper(jsonFactory);
    SimpleModule module = new SimpleModule();
    mapper.registerModule(module);/*from  w  ww. jav  a 2  s . c  om*/
    FSDataOutputStream os = fs.create(p);
    mapper.writerWithDefaultPrettyPrinter().writeValue(os, parquetTableMetadataDirs);
    os.flush();
    os.close();
}

From source file:org.apache.drill.exec.store.parquet.Metadata.java

/**
 * Read the parquet metadata from a file
 *
 * @param path/*from w ww  .  j a  v a 2s  .c o  m*/
 * @return
 * @throws IOException
 */
private void readBlockMeta(String path, boolean dirsOnly, MetadataContext metaContext) throws IOException {
    Stopwatch timer = Stopwatch.createStarted();
    Path p = new Path(path);
    Path parentDir = p.getParent(); // parent directory of the metadata file
    ObjectMapper mapper = new ObjectMapper();

    final SimpleModule serialModule = new SimpleModule();
    serialModule.addDeserializer(SchemaPath.class, new SchemaPath.De());
    serialModule.addKeyDeserializer(ColumnTypeMetadata_v2.Key.class,
            new ColumnTypeMetadata_v2.Key.DeSerializer());
    serialModule.addKeyDeserializer(ColumnTypeMetadata_v3.Key.class,
            new ColumnTypeMetadata_v3.Key.DeSerializer());

    AfterburnerModule module = new AfterburnerModule();
    module.setUseOptimizedBeanDeserializer(true);

    mapper.registerModule(serialModule);
    mapper.registerModule(module);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    FSDataInputStream is = fs.open(p);

    boolean alreadyCheckedModification = false;
    boolean newMetadata = false;

    if (metaContext != null) {
        alreadyCheckedModification = metaContext.getStatus(parentDir.toString());
    }

    if (dirsOnly) {
        parquetTableMetadataDirs = mapper.readValue(is, ParquetTableMetadataDirs.class);
        logger.info("Took {} ms to read directories from directory cache file",
                timer.elapsed(TimeUnit.MILLISECONDS));
        timer.stop();
        if (!alreadyCheckedModification
                && tableModified(parquetTableMetadataDirs.getDirectories(), p, parentDir, metaContext)) {
            parquetTableMetadataDirs = (createMetaFilesRecursively(
                    Path.getPathWithoutSchemeAndAuthority(p.getParent()).toString())).getRight();
            newMetadata = true;
        }
    } else {
        parquetTableMetadata = mapper.readValue(is, ParquetTableMetadataBase.class);
        logger.info("Took {} ms to read metadata from cache file", timer.elapsed(TimeUnit.MILLISECONDS));
        timer.stop();
        if (!alreadyCheckedModification
                && tableModified(parquetTableMetadata.getDirectories(), p, parentDir, metaContext)) {
            parquetTableMetadata = (createMetaFilesRecursively(
                    Path.getPathWithoutSchemeAndAuthority(p.getParent()).toString())).getLeft();
            newMetadata = true;
        }

        // DRILL-5009: Remove the RowGroup if it is empty
        List<? extends ParquetFileMetadata> files = parquetTableMetadata.getFiles();
        for (ParquetFileMetadata file : files) {
            List<? extends RowGroupMetadata> rowGroups = file.getRowGroups();
            for (Iterator<? extends RowGroupMetadata> iter = rowGroups.iterator(); iter.hasNext();) {
                RowGroupMetadata r = iter.next();
                if (r.getRowCount() == 0) {
                    iter.remove();
                }
            }
        }

    }

    if (newMetadata && metaContext != null) {
        // if new metadata files were created, invalidate the existing metadata context
        metaContext.clear();
    }

}

From source file:org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.java

/**
 * Configure an existing {@link ObjectMapper} instance with this builder's
 * settings. This can be applied to any number of {@code ObjectMappers}.
 * @param objectMapper the ObjectMapper to configure
 *//*w  w w  . j a va 2s  .com*/
public void configure(ObjectMapper objectMapper) {
    Assert.notNull(objectMapper, "ObjectMapper must not be null");

    if (this.findModulesViaServiceLoader) {
        // Jackson 2.2+
        objectMapper.registerModules(ObjectMapper.findModules(this.moduleClassLoader));
    } else if (this.findWellKnownModules) {
        registerWellKnownModulesIfAvailable(objectMapper);
    }

    if (this.modules != null) {
        for (Module module : this.modules) {
            // Using Jackson 2.0+ registerModule method, not Jackson 2.2+ registerModules
            objectMapper.registerModule(module);
        }
    }
    if (this.moduleClasses != null) {
        for (Class<? extends Module> module : this.moduleClasses) {
            objectMapper.registerModule(BeanUtils.instantiateClass(module));
        }
    }

    if (this.dateFormat != null) {
        objectMapper.setDateFormat(this.dateFormat);
    }
    if (this.locale != null) {
        objectMapper.setLocale(this.locale);
    }
    if (this.timeZone != null) {
        objectMapper.setTimeZone(this.timeZone);
    }

    if (this.annotationIntrospector != null) {
        objectMapper.setAnnotationIntrospector(this.annotationIntrospector);
    }
    if (this.propertyNamingStrategy != null) {
        objectMapper.setPropertyNamingStrategy(this.propertyNamingStrategy);
    }
    if (this.defaultTyping != null) {
        objectMapper.setDefaultTyping(this.defaultTyping);
    }
    if (this.serializationInclusion != null) {
        objectMapper.setSerializationInclusion(this.serializationInclusion);
    }

    if (this.filters != null) {
        objectMapper.setFilterProvider(this.filters);
    }

    for (Class<?> target : this.mixIns.keySet()) {
        objectMapper.addMixIn(target, this.mixIns.get(target));
    }

    if (!this.serializers.isEmpty() || !this.deserializers.isEmpty()) {
        SimpleModule module = new SimpleModule();
        addSerializers(module);
        addDeserializers(module);
        objectMapper.registerModule(module);
    }

    customizeDefaultFeatures(objectMapper);
    for (Object feature : this.features.keySet()) {
        configureFeature(objectMapper, feature, this.features.get(feature));
    }

    if (this.handlerInstantiator != null) {
        objectMapper.setHandlerInstantiator(this.handlerInstantiator);
    } else if (this.applicationContext != null) {
        objectMapper.setHandlerInstantiator(
                new SpringHandlerInstantiator(this.applicationContext.getAutowireCapableBeanFactory()));
    }
}