Example usage for com.fasterxml.jackson.databind ObjectMapper registerModule

List of usage examples for com.fasterxml.jackson.databind ObjectMapper registerModule

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper registerModule.

Prototype

public ObjectMapper registerModule(Module module) 

Source Link

Document

Method for registering a module that can extend functionality provided by this mapper; for example, by adding providers for custom serializers and deserializers.

Usage

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

/**
 * Serialize parquet metadata to json and write to a file.
 *
 * @param parquetTableMetadata parquet table metadata
 * @param p file path//from  w w w  .  j a  v  a 2s. c  o  m
 */
private void writeFile(ParquetTableMetadata_v3 parquetTableMetadata, Path p, FileSystem fs) 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:com.jkoolcloud.tnt4j.streams.custom.kafka.interceptors.reporters.metrics.MetricsReporter.java

protected void reportMetrics(Map<String, TopicMetrics> mRegistry) {
    String metricsCorrelator = tracker.newUUID();

    try {//w ww  .j a va2s .  com
        if (InterceptionsManager.getInstance().isProducerIntercepted()) {
            TrackingActivity metricsJMX = collectKafkaProducerMetricsJMX(tracker);
            metricsJMX.setCorrelator(metricsCorrelator);
            prepareAndSend(metricsJMX);
        }
        if (InterceptionsManager.getInstance().isConsumerIntercepted()) {
            TrackingActivity metricsJMX = collectKafkaConsumerMetricsJMX(tracker);
            metricsJMX.setCorrelator(metricsCorrelator);
            prepareAndSend(metricsJMX);
        }

        TrackingActivity metricsJMX = collectJVMMetricsJMX(tracker);
        metricsJMX.setCorrelator(metricsCorrelator);
        prepareAndSend(metricsJMX);
    } catch (UnsupportedOperationException exc) {
        LOGGER.log(OpLevel.WARNING, StreamsResources.getBundle(KafkaStreamConstants.RESOURCE_BUNDLE_NAME),
                "MetricsReporter.clients.jmx.unsupported", Utils.getExceptionMessages(exc));
    } catch (Exception exc) {
        Utils.logThrowable(LOGGER, OpLevel.WARNING,
                StreamsResources.getBundle(KafkaStreamConstants.RESOURCE_BUNDLE_NAME),
                "MetricsReporter.clients.jmx.fail", exc);
    }

    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, false));
        mapper.registerModule(new MetricsRegistryModule());
        for (Map.Entry<String, TopicMetrics> metrics : mRegistry.entrySet()) {
            TopicMetrics topicMetrics = metrics.getValue();
            topicMetrics.correlator = metricsCorrelator;
            String msg = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(topicMetrics);
            topicMetrics.reset();
            tracker.log(OpLevel.INFO, msg);
        }
    } catch (JsonProcessingException exc) {
        Utils.logThrowable(LOGGER, OpLevel.ERROR,
                StreamsResources.getBundle(KafkaStreamConstants.RESOURCE_BUNDLE_NAME),
                "MetricsReporter.report.metrics.fail", exc);
    }
}

From source file:capital.scalable.restdocs.jackson.FieldDocumentationGeneratorTest.java

@Test
public void testGenerateDocumentationForExternalSerializer() throws Exception {
    // given/*from  ww w.  j  a  va 2 s  .  c om*/
    ObjectMapper mapper = createMapper();

    JavadocReader javadocReader = mock(JavadocReader.class);
    when(javadocReader.resolveFieldComment(ExternalSerializer.class, "bigDecimal")).thenReturn("A decimal");

    ConstraintReader constraintReader = mock(ConstraintReader.class);

    SimpleModule testModule = new SimpleModule("TestModule");
    testModule.addSerializer(new BigDecimalSerializer());
    mapper.registerModule(testModule);

    FieldDocumentationGenerator generator = new FieldDocumentationGenerator(mapper.writer(), javadocReader,
            constraintReader);
    Type type = ExternalSerializer.class;

    // when
    List<ExtendedFieldDescriptor> fieldDescriptions = cast(
            generator.generateDocumentation(type, mapper.getTypeFactory()));

    // then
    assertThat(fieldDescriptions.size(), is(1));
    assertThat(fieldDescriptions.get(0), is(descriptor("bigDecimal", "Decimal", "A decimal", "true")));
}

From source file:com.thinkbiganalytics.integration.IntegrationTestBase.java

@Before
public void setupRestAssured() throws URISyntaxException {
    UserContext.setUser(UserContext.User.ADMIN);

    RestAssured.baseURI = kyloConfig.getProtocol() + kyloConfig.getHost();
    RestAssured.port = kyloConfig.getPort();
    RestAssured.basePath = kyloConfig.getBasePath();

    RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();

    Jackson2ObjectMapperFactory factory = (aClass, s) -> {
        ObjectMapper om = new ObjectMapper();
        om.registerModule(new JodaModule());
        om.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
        om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        configureObjectMapper(om);/*from w  w  w  .  ja v  a  2  s  . c  o m*/

        return om;
    };
    com.jayway.restassured.mapper.ObjectMapper objectMapper = new Jackson2Mapper(factory);
    RestAssured.objectMapper(objectMapper);

    startClean();
}

From source file:org.apache.druid.query.aggregation.AggregationTestHelper.java

private AggregationTestHelper(ObjectMapper mapper, IndexMerger indexMerger, IndexIO indexIO,
        QueryToolChest toolchest, QueryRunnerFactory factory, TemporaryFolder tempFolder,
        List<? extends Module> jsonModulesToRegister, Closer resourceCloser) {
    this.mapper = mapper;
    this.indexMerger = indexMerger;
    this.indexIO = indexIO;
    this.toolChest = toolchest;
    this.factory = factory;
    this.tempFolder = tempFolder;
    this.resourceCloser = resourceCloser;

    for (Module mod : jsonModulesToRegister) {
        mapper.registerModule(mod);
    }//from  w ww .  j  av  a  2s  .c  om
}

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

@Override
public ShimDataResponse getData(final ShimDataRequest shimDataRequest) throws ShimException {
    final HealthVaultDataType healthVaultDataType;
    try {//from   w ww  .  ja v  a 2 s  .  com
        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:org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration.java

/**
 * The Jackson {@link ObjectMapper} used internally.
 * /* ww  w .  jav a 2  s  .c  o  m*/
 * @return
 */
@Bean
public ObjectMapper objectMapper() {

    ObjectMapper mapper = basicObjectMapper();
    mapper.registerModule(persistentEntityJackson2Module());

    return mapper;
}

From source file:com.basho.riak.client.api.commands.mapreduce.MapReduce.java

/**
 * Creates the JSON string of the M/R job for submitting to the client
 * <p/>//from   ww w. j av  a 2  s.  co m
 * Uses Jackson to write out the JSON string. I'm not very happy with this method, it is a candidate for change.
 * <p/>
 * TODO re-evaluate this method, look for something smaller and more elegant.
 *
 * @return a String of JSON
 * @throws RiakException if, for some reason, we can't create a JSON string.
 */
String writeSpec() throws RiakException {

    final ByteArrayOutputStream out = new ByteArrayOutputStream();

    try {
        JsonGenerator jg = new JsonFactory().createGenerator(out, JsonEncoding.UTF8);

        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule specModule = new SimpleModule("SpecModule", Version.unknownVersion());
        specModule.addSerializer(LinkPhase.class, new LinkPhaseSerializer());
        specModule.addSerializer(FunctionPhase.class, new FunctionPhaseSerializer());
        specModule.addSerializer(BucketInput.class, new BucketInputSerializer());
        specModule.addSerializer(SearchInput.class, new SearchInputSerializer());
        specModule.addSerializer(BucketKeyInput.class, new BucketKeyInputSerializer());
        specModule.addSerializer(IndexInput.class, new IndexInputSerializer());
        objectMapper.registerModule(specModule);

        jg.setCodec(objectMapper);

        List<MapReducePhase> phases = spec.getPhases();
        phases.get(phases.size() - 1).setKeep(true);
        jg.writeObject(spec);

        jg.flush();

        return out.toString("UTF8");

    } catch (IOException e) {
        throw new RiakException(e);
    }
}

From source file:org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration.java

@Bean
public ObjectMapper halObjectMapper() {

    RelProvider defaultedRelProvider = this.relProvider != null ? this.relProvider
            : new EvoInflectorRelProvider();

    HalHandlerInstantiator instantiator = new HalHandlerInstantiator(defaultedRelProvider, curieProvider,
            resourceDescriptionMessageSourceAccessor());

    ObjectMapper mapper = basicObjectMapper();
    mapper.registerModule(persistentEntityJackson2Module());
    mapper.registerModule(new Jackson2HalModule());
    mapper.setHandlerInstantiator(instantiator);

    return mapper;
}