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.venice.beachfront.bfapi.BfApiConfig.java

@Bean
public ObjectMapper getJacksonObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JodaModule());
    return mapper;
}

From source file:cc.arduino.contributions.packages.ContributionsIndexer.java

private ContributionsIndex parseIndex(File indexFile) throws IOException {
    InputStream inputStream = null;
    try {/*  www . j  a  va2  s.  c  om*/
        inputStream = new FileInputStream(indexFile);
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new MrBeanModule());
        mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        mapper.configure(DeserializationFeature.EAGER_DESERIALIZER_FETCH, true);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper.readValue(inputStream, ContributionsIndex.class);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:org.apache.nifi.controller.druid.DruidTranquilityController.java

private List<AggregatorFactory> getAggregatorList(String aggregatorJSON) {
    ComponentLog log = getLogger();//from www  .  ja  v a 2 s.c  o  m
    ObjectMapper mapper = new ObjectMapper(null);
    mapper.registerModule(new AggregatorsModule());
    mapper.registerModules(Lists.newArrayList(new SketchModule().getJacksonModules()));
    mapper.registerModules(Lists.newArrayList(new ApproximateHistogramDruidModule().getJacksonModules()));

    try {
        return mapper.readValue(aggregatorJSON, new TypeReference<List<AggregatorFactory>>() {
        });
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        return null;
    }
}

From source file:com.spotify.ffwd.AgentCore.java

private AgentConfig readConfig(Injector early) throws IOException {
    final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    final SimpleModule module = early
            .getInstance(Key.get(SimpleModule.class, Names.named("application/yaml+config")));

    mapper.registerModule(module);

    try (final InputStream input = Files.newInputStream(this.config)) {
        return mapper.readValue(input, AgentConfig.class);
    } catch (JsonParseException e) {
        throw new IOException("Failed to parse configuration", e);
    }/*ww w .j  ava 2s.c  o m*/
}

From source file:com.basho.riak.client.api.commands.itest.ITestORM.java

@Test
public void storeParamterizedTypeJSON()
        throws ExecutionException, InterruptedException, JsonProcessingException {
    RiakClient client = new RiakClient(cluster);
    Namespace ns = new Namespace(Namespace.DEFAULT_BUCKET_TYPE, bucketName.toString());
    Location loc = new Location(ns, "test_ORM_key1");

    GenericPojo<Foo> gpf = new GenericPojo<Foo>();
    List<Foo> fooList = new ArrayList<Foo>();
    fooList.add(new Foo("Foo in list value"));
    gpf.value = new Foo("Foo in gp value");
    gpf.list = fooList;/*  ww  w .  ja  v a2s  .  co  m*/

    StoreValue sv = new StoreValue.Builder(gpf).withLocation(loc).withOption(Option.RETURN_BODY, true).build();

    StoreValue.Response resp = client.execute(sv);

    TypeReference<GenericPojo<Foo>> tr = new TypeReference<GenericPojo<Foo>>() {
    };
    GenericPojo<Foo> gpf2 = resp.getValue(tr);

    assertNotNull(gpf2);
    assertNotNull(gpf2.value);
    assertEquals(gpf.value, gpf2.value);
    assertNotNull(gpf2.list);
    assertTrue(gpf.list.containsAll(gpf2.list));

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new RiakJacksonModule());
    String json = mapper.writeValueAsString(gpf2);
    RiakObject ro = resp.getValue(RiakObject.class);
    assertEquals(json, ro.getValue().toString());

}

From source file:com.basho.riak.client.api.commands.itest.ITestORM.java

@Test
public void updateParameterizedTypeJSON()
        throws ExecutionException, InterruptedException, JsonProcessingException {
    RiakClient client = new RiakClient(cluster);
    Namespace ns = new Namespace(Namespace.DEFAULT_BUCKET_TYPE, bucketName.toString());
    Location loc = new Location(ns, "test_ORM_key3");

    MyUpdate update = new MyUpdate();
    TypeReference<GenericPojo<Integer>> tr = new TypeReference<GenericPojo<Integer>>() {
    };//from   w ww.  j av a 2  s  . c o  m

    UpdateValue uv = new UpdateValue.Builder(loc).withUpdate(update, tr)
            .withStoreOption(Option.RETURN_BODY, true).build();

    UpdateValue.Response resp = client.execute(uv);

    GenericPojo<Integer> gpi = resp.getValue(tr);

    assertNotNull(gpi);
    assertNotNull(gpi.value);
    assertEquals(1, gpi.value.intValue());

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new RiakJacksonModule());
    String json = mapper.writeValueAsString(gpi);
    RiakObject ro = resp.getValue(RiakObject.class);
    assertEquals(json, ro.getValue().toString());

    resp = client.execute(uv);
    gpi = resp.getValue(tr);
    assertNotNull(gpi);
    assertNotNull(gpi.value);
    assertEquals(2, gpi.value.intValue());
}

From source file:com.basho.riak.client.api.commands.itest.ITestORM.java

@Test
public void storeAndFetchParamterizedTypeJSON()
        throws ExecutionException, InterruptedException, JsonProcessingException {
    RiakClient client = new RiakClient(cluster);
    Namespace ns = new Namespace(Namespace.DEFAULT_BUCKET_TYPE, bucketName.toString());
    Location loc = new Location(ns, "test_ORM_key2");

    GenericPojo<Foo> gpf = new GenericPojo<Foo>();
    List<Foo> fooList = new ArrayList<Foo>();
    fooList.add(new Foo("Foo in list value"));
    gpf.value = new Foo("Foo in gp value");
    gpf.list = fooList;//from w  w  w  . ja v  a  2s.co m

    StoreValue sv = new StoreValue.Builder(gpf).withLocation(loc).build();

    client.execute(sv);

    FetchValue fv = new FetchValue.Builder(loc).build();
    FetchValue.Response resp = client.execute(fv);

    TypeReference<GenericPojo<Foo>> tr = new TypeReference<GenericPojo<Foo>>() {
    };
    GenericPojo<Foo> gpf2 = resp.getValue(tr);

    assertNotNull(gpf2);
    assertNotNull(gpf2.value);
    assertEquals(gpf.value, gpf2.value);
    assertNotNull(gpf2.list);
    assertTrue(gpf.list.containsAll(gpf2.list));

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new RiakJacksonModule());
    String json = mapper.writeValueAsString(gpf2);
    RiakObject ro = resp.getValue(RiakObject.class);
    assertEquals(json, ro.getValue().toString());

}

From source file:com.basho.riak.client.api.commands.itest.ITestORM.java

@Test
public void updateAndResolveRawTypeJSON()
        throws ExecutionException, InterruptedException, JsonProcessingException {
    RiakClient client = new RiakClient(cluster);
    Namespace ns = new Namespace(Namespace.DEFAULT_BUCKET_TYPE, bucketName.toString());
    Location loc = new Location(ns, "test_ORM_key6");
    ConflictResolverFactory.getInstance().registerConflictResolver(Foo.class, new MyFooResolver());
    MyFooUpdate update = new MyFooUpdate();

    UpdateValue uv = new UpdateValue.Builder(loc).withUpdate(update).build();

    client.execute(uv);/*from  w  w w .  j  a  va  2 s . c  o m*/

    // Create a sibling 
    Foo f = update.apply(null);
    StoreValue sv = new StoreValue.Builder(f).withLocation(loc).build();

    client.execute(sv);

    uv = new UpdateValue.Builder(loc).withUpdate(update).withStoreOption(Option.RETURN_BODY, true).build();

    UpdateValue.Response uvResp = client.execute(uv);

    f = uvResp.getValue(Foo.class);
    assertNotNull(f);
    assertEquals("Little bunny", f.fooValue);

    uv = new UpdateValue.Builder(loc).withUpdate(update).withStoreOption(Option.RETURN_BODY, true).build();

    uvResp = client.execute(uv);

    f = uvResp.getValue(Foo.class);
    assertNotNull(f);
    assertEquals("Little bunny foo foo.", f.fooValue);

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new RiakJacksonModule());
    String json = mapper.writeValueAsString(f);
    RiakObject ro = uvResp.getValue(RiakObject.class);
    assertEquals(json, ro.getValue().toString());

}

From source file:io.seldon.api.state.ClientAlgorithmStore.java

@Override
public void configUpdated(String client, String configKey, String configValue) {
    SimpleModule module = new SimpleModule("StrategyDeserializerModule");
    module.addDeserializer(Strategy.class, new StrategyDeserializer());
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(module);
    if (configKey.equals(ALG_KEY)) {
        logger.info("Received new algorithm config for " + client + ": " + configValue);
        try {/*from   w  w  w  .j a va2s .c  om*/
            List<AlgorithmStrategy> strategies = new ArrayList<>();
            Map<String, AlgorithmStrategy> stratMap = new HashMap<>();
            AlgorithmConfig config = mapper.readValue(configValue, AlgorithmConfig.class);
            for (Algorithm algorithm : config.algorithms) {
                AlgorithmStrategy strategy = toAlgorithmStrategy(algorithm);
                strategies.add(strategy);
            }
            AlgorithmResultsCombiner combiner = applicationContext.getBean(config.combiner,
                    AlgorithmResultsCombiner.class);
            Map<Integer, Double> actionWeightMap = toActionWeightMap(config.actionWeights);
            store.put(client, new SimpleClientStrategy(Collections.unmodifiableList(strategies), combiner,
                    config.diversityLevel, ClientStrategy.DEFAULT_NAME, actionWeightMap));
            storeMap.put(client, Collections.unmodifiableMap(stratMap));
            logger.info("Successfully added new algorithm config for " + client);
        } catch (IOException | BeansException e) {
            logger.error("Couldn't update algorithms for client " + client, e);
        }
    } else if (configKey.equals(TESTING_SWITCH_KEY)) {
        // not json as its so simple
        Boolean onOff = BooleanUtils.toBooleanObject(configValue);
        if (onOff == null) {
            logger.error("Couldn't set testing switch for client " + client + ", input was " + configValue);
        } else {
            logger.info("Testing switch for client " + client + " moving from '"
                    + BooleanUtils.toStringOnOff(testingOnOff.get(client)) + "' to '"
                    + BooleanUtils.toStringOnOff(onOff) + "'");
            testingOnOff.put(client, BooleanUtils.toBooleanObject(configValue));
        }
    } else if (configKey.equals(TEST)) {
        logger.info("Received new testing config for " + client + ":" + configValue);
        try {
            TestConfig config = mapper.readValue(configValue, TestConfig.class);
            List<VariationTestingClientStrategy.Variation> variations = new ArrayList<>();
            for (TestVariation var : config.variations) {
                List<AlgorithmStrategy> strategies = new ArrayList<>();
                for (Algorithm alg : var.config.algorithms) {
                    AlgorithmStrategy strategy = toAlgorithmStrategy(alg);
                    strategies.add(strategy);
                }
                AlgorithmResultsCombiner combiner = applicationContext.getBean(var.config.combiner,
                        AlgorithmResultsCombiner.class);
                Map<Integer, Double> actionWeightMap = toActionWeightMap(var.config.actionWeights);
                variations.add(new VariationTestingClientStrategy.Variation(
                        new SimpleClientStrategy(Collections.unmodifiableList(strategies), combiner,
                                var.config.diversityLevel, var.label, actionWeightMap),
                        new BigDecimal(var.ratio)));

            }
            tests.put(client, VariationTestingClientStrategy.build(variations));
            logger.info("Succesfully added " + variations.size() + " variation test for " + client);
        } catch (NumberFormatException | IOException e) {
            logger.error("Couldn't add test for client " + client, e);
        }
    } else if (configKey.equals(RECTAG)) {
        logger.info("Received new rectag config for " + client + ": " + configValue);
        try {
            RecTagConfig config = mapper.readValue(configValue, RecTagConfig.class);
            if (config.defaultStrategy == null) {
                logger.error("Couldn't read rectag config as there was no default alg");
                return;
            }

            ClientStrategy defStrategy = toStrategy(config.defaultStrategy);
            Map<String, ClientStrategy> recTagStrats = new HashMap<>();
            for (Map.Entry<String, Strategy> entry : config.recTagToStrategy.entrySet()) {
                recTagStrats.put(entry.getKey(), toStrategy(entry.getValue()));
            }
            recTagStrategies.put(client, new RecTagClientStrategy(defStrategy, recTagStrats));
            logger.info("Successfully added rec tag strategy for " + client);
        } catch (NumberFormatException | IOException e) {
            logger.error("Couldn't add rectag strategy for client " + client, e);
        }

    }
}

From source file:com.basistech.AfterburnerOopsTest.java

@Test
public void oops() throws Exception {
    SmileFactory smileFactory = new SmileFactory();
    ObjectMapper mapper = new ObjectMapper(smileFactory);
    mapper = AnnotatedDataModelModule.setupObjectMapper(mapper);

    EntityMention em = new EntityMention();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    List<EntityMention> mentions = Lists.newArrayList();
    mentions.add(em);//from  w  ww.ja  v  a 2s . com
    mapper.writeValue(byteArrayOutputStream, mentions);

    mapper = AnnotatedDataModelModule.setupObjectMapper(new ObjectMapper(smileFactory));
    mapper.registerModule(new AfterburnerModule());
    JsonParser jp = smileFactory.createParser(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
    jp.setCodec(mapper);

    JsonToken current;
    current = jp.nextToken();
    if (current != JsonToken.START_ARRAY) {
        System.err.println("Error: root should be array: quiting.");
        return;
    }

    while (jp.nextToken() != JsonToken.END_ARRAY) {
        jp.readValueAs(EntityMention.class);
    }

}