List of usage examples for com.fasterxml.jackson.databind.module SimpleModule SimpleModule
public SimpleModule()
From source file:io.swagger.test.examples.ExampleBuilderTest.java
@Test public void testComplexArrayWithExample() throws Exception { Map<String, Model> definitions = new HashMap<String, Model>(); Model address = new ModelImpl().example("{\"foo\":\"bar\"}").xml(new Xml().name("address")) .property("street", new StringProperty().example("12345 El Monte Blvd")) .property("city", new StringProperty().example("Los Altos Hills")) .property("state", new StringProperty().example("CA").minLength(2).maxLength(2)) .property("zip", new StringProperty().example("94022")); definitions.put("Address", address); // register the JSON serializer SimpleModule simpleModule = new SimpleModule(); simpleModule.addSerializer(new JsonNodeExampleSerializer()); simpleModule.addDeserializer(Example.class, new JsonExampleDeserializer()); Json.mapper().registerModule(simpleModule); Example rep = (Example) ExampleBuilder.fromProperty(new StringProperty("hello").example("fun"), definitions);//from www . j ava 2 s . com assertEqualsIgnoreLineEnding(Json.pretty(rep), "\"fun\""); }
From source file:org.lbogdanov.poker.web.AppInitializer.java
/** * {@inheritDoc}// w w w . j a v a 2 s. c o m */ @Override protected Injector getInjector() { SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); try { InputStream settings = Resources.newInputStreamSupplier(Resources.getResource("settings.properties")) .getInput(); Properties props = new Properties(); try { props.load(settings); } finally { settings.close(); } Settings.init(Maps.fromProperties(props)); } catch (IOException ioe) { throw Throwables.propagate(ioe); } final boolean isDevel = DEVELOPMENT_MODE.asBool().or(false); Module shiroModule = new ShiroWebModule(servletContext) { @Override @SuppressWarnings("unchecked") protected void configureShiroWeb() { bind(String.class).annotatedWith(Names.named(InjectableOAuthFilter.FAILURE_URL_PARAM)) .toInstance("/"); // TODO simple ini-based realm for development bindRealm().toInstance(new IniRealm(IniFactorySupport.loadDefaultClassPathIni())); bindRealm().to(InjectableOAuthRealm.class).in(Singleton.class); addFilterChain("/" + Constants.OAUTH_CLBK_FILTER_URL, Key.get(InjectableOAuthFilter.class)); addFilterChain("/" + Constants.OAUTH_FILTER_URL, config(CallbackUrlSetterFilter.class, Constants.OAUTH_CLBK_FILTER_URL), Key.get(InjectableOAuthUserFilter.class)); } @Provides @Singleton private OAuthProvider getOAuthProvider() { Google2Provider provider = new Google2Provider(); provider.setKey(GOOGLE_OAUTH_KEY.asString().get()); provider.setSecret(GOOGLE_OAUTH_SECRET.asString().get()); provider.setCallbackUrl("example.com"); // fake URL, will be replaced by CallbackUrlSetterFilter provider.setScope(Google2Scope.EMAIL_AND_PROFILE); return provider; } }; Module appModule = new ServletModule() { @Override protected void configureServlets() { ServerConfig dbConfig = new ServerConfig(); String jndiDataSource = DB_DATA_SOURCE.asString().orNull(); if (Strings.isNullOrEmpty(jndiDataSource)) { // use direct JDBC connection DataSourceConfig dsConfig = new DataSourceConfig(); dsConfig.setDriver(DB_DRIVER.asString().get()); dsConfig.setUrl(DB_URL.asString().get()); dsConfig.setUsername(DB_USER.asString().orNull()); dsConfig.setPassword(DB_PASSWORD.asString().orNull()); dbConfig.setDataSourceConfig(dsConfig); } else { dbConfig.setDataSourceJndiName(jndiDataSource); } dbConfig.setName("PlanningPoker"); dbConfig.setDefaultServer(true); dbConfig.addClass(Session.class); dbConfig.addClass(User.class); bind(EbeanServer.class).toInstance(EbeanServerFactory.create(dbConfig)); bind(SessionService.class).to(SessionServiceImpl.class); bind(UserService.class).to(UserServiceImpl.class); bind(WebApplication.class).to(PokerWebApplication.class); bind(MeteorServlet.class).in(Singleton.class); bind(ObjectMapper.class).toProvider(new Provider<ObjectMapper>() { @Override public ObjectMapper get() { SimpleModule module = new SimpleModule().addSerializer(UserSerializer.get()); return new ObjectMapper().registerModule(module); } }).in(Singleton.class); String wicketConfig = (isDevel ? RuntimeConfigurationType.DEVELOPMENT : RuntimeConfigurationType.DEPLOYMENT).toString(); ImmutableMap.Builder<String, String> params = ImmutableMap.builder(); params.put(ApplicationConfig.FILTER_CLASS, WicketFilter.class.getName()) .put(ApplicationConfig.PROPERTY_SESSION_SUPPORT, Boolean.TRUE.toString()) .put(ApplicationConfig.BROADCAST_FILTER_CLASSES, TrackMessageSizeFilter.class.getName()) .put(ApplicationConfig.BROADCASTER_CACHE, UUIDBroadcasterCache.class.getName()) .put(ApplicationConfig.SHOW_SUPPORT_MESSAGE, Boolean.FALSE.toString()) .put(WicketFilter.FILTER_MAPPING_PARAM, "/*") .put(WebApplication.CONFIGURATION, wicketConfig) .put(WicketFilter.APP_FACT_PARAM, GuiceWebApplicationFactory.class.getName()) .put("injectorContextAttribute", Injector.class.getName()).build(); serve("/*").with(MeteorServlet.class, params.build()); } }; Stage stage = isDevel ? Stage.DEVELOPMENT : Stage.PRODUCTION; return Guice.createInjector(stage, ShiroWebModule.guiceFilterModule(), shiroModule, appModule); }
From source file:whitespell.net.websockets.socketio.parser.JacksonJsonSupport.java
protected void init(ObjectMapper objectMapper) { SimpleModule module = new SimpleModule(); module.addDeserializer(Event.class, eventDeserializer); module.addDeserializer(JsonObject.class, jsonObjectDeserializer); module.addDeserializer(AckArgs.class, ackArgsDeserializer); objectMapper.registerModule(module); objectMapper.setSerializationInclusion(Include.NON_NULL); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // TODO If jsonObjectDeserializer will be not enough // TypeResolverBuilder<?> typer = new DefaultTypeResolverBuilder(DefaultTyping.NON_FINAL); // typer.init(JsonTypeInfo.Id.CLASS, null); // typer.inclusion(JsonTypeInfo.As.PROPERTY); // typer.typeProperty(configuration.getJsonTypeFieldName()); // objectMapper.setDefaultTyping(typer); }
From source file:craterdog.smart.SmartObjectMapperTest.java
/** * This unit test method tests a polymorphic object. * * @throws IOException/* w w w . jav a2 s .c o m*/ */ @Test public void testPolymorphicObject() throws IOException { logger.info("Testing polymorphic objects..."); SimpleModule module = new SimpleModule(); module.addAbstractTypeMapping(SmartObject.class, PolymorphicTestObject.class); mapper.registerModule(module); PolymorphicTestObject polyObject = polymorphicReader(mapper); assertEquals("success", polyObject.testAttribute); logger.info("Polymorphic objects testing completed.\n"); }
From source file:de.upb.wdqa.wdvd.test.JsonNormalizerTest.java
private void testWDTKParsing(String filename) throws IOException { String jsonString = readFile(filename, StandardCharsets.UTF_8); SimpleModule module = new SimpleModule(); module.setDeserializerModifier(new MapDeserializerModifier()); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(module);/* w ww . j av a 2 s . c om*/ // JsonNode root = mapper.readTree(jsonString); // mapper.readValue(mapper.treeAsTokens(root), JacksonItemDocument.class); JacksonItemDocument itemDocument = mapper.readValue(jsonString, JacksonItemDocument.class); itemDocument.setSiteIri(Datamodel.SITE_WIKIDATA); itemDocument.toString(); // raises an exception if information is missing }
From source file:eu.trentorise.opendata.semtext.jackson.test.SemTextModuleTest.java
@Test public void testMapper() throws IOException { SemTextModule.registerMetadata(Meaning.class, "a", Dict.class); SemTextModule.registerMetadata(Meaning.class, "b", Dict.class); SemTextModule.registerMetadata(Term.class, "c", Integer.class); SemTextModule.registerMetadata(Sentence.class, "a", MyMetadata.class); SemTextModule.registerMetadata(SemText.class, "a", Integer.class); objectMapper.registerModule(new SimpleModule() { {/*from w w w . j av a 2s . co m*/ setMixInAnnotation(MyMetadata.class, MyMetadataJackson.class); } }); try { objectMapper.readValue("{\"start\":2, \"end\":1}", Term.class); Assert.fail("Should have failed because of missing attributes!"); } catch (Exception ex) { } Meaning m1 = Meaning.of("a", MeaningKind.ENTITY, 0.2, Dict.of(Locale.ITALIAN, "a"), Dict.of(Locale.FRENCH, "b"), ImmutableMap.of("a", Dict.of("s"))); Meaning m2 = Meaning.of("b", MeaningKind.ENTITY, 0.2, Dict.of(Locale.ITALIAN, "a"), Dict.of(Locale.FRENCH, "b"), ImmutableMap.of("b", Dict.of("s"))); testJsonConv(objectMapper, LOG, Meaning.of("a", MeaningKind.CONCEPT, 0.2)); Term term = Term.of(0, 2, MeaningStatus.SELECTED, m1, ImmutableList.of(m1, m2), ImmutableMap.of("c", 3)); testJsonConv(objectMapper, LOG, SemText.ofSentences(Locale.ITALIAN, "abcdefghilmno", ImmutableList.of( Sentence.of(0, 7, ImmutableList.of(term), ImmutableMap.of("a", MyMetadata.of("hello")))), ImmutableMap.of("a", 9))); }
From source file:org.springframework.yarn.integration.support.Jackson2ObjectMapperFactoryBean.java
public void afterPropertiesSet() throws FatalBeanException { if (this.objectMapper == null) { this.objectMapper = new ObjectMapper(); }//from w w w. j a v a 2s . co m if (this.dateFormat != null) { this.objectMapper.setDateFormat(this.dateFormat); } if (this.serializers != null || this.deserializers != null) { SimpleModule module = new SimpleModule(); addSerializers(module); addDeserializers(module); this.objectMapper.registerModule(module); } if (this.annotationIntrospector != null) { this.objectMapper.setAnnotationIntrospector(this.annotationIntrospector); } for (Object feature : this.features.keySet()) { configureFeature(feature, this.features.get(feature)); } }
From source file:DataTools.ConvertObjectToJson.java
private void addCustomSerializing(ObjectMapper mapper) { //custom serializer to help parsing dates class dateSerializer extends JsonSerializer<DateTime> { @Override/*from w w w . j a v a 2 s. c om*/ public void serialize(DateTime dateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeString(cleanupDate(dateTime)); } } //custom serializer to help parsing dates class zoneDateSerializer extends JsonSerializer<ZonedDateTime> { @Override public void serialize(ZonedDateTime dateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeString(cleanupDate(dateTime)); } } class utilDateSerializer extends JsonSerializer<Date> { @Override public void serialize(Date dateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeString(dateTime.toString()); } } class JsonObjectSerializer extends JsonSerializer<JSONObject> { @Override public void serialize(JSONObject jsonObject, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeString(jsonObject.toString()); } } class JsonArraySerializer extends JsonSerializer<JSONArray> { @Override public void serialize(JSONArray jsonArray, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeString(jsonArray.toString()); } } class StorageSerializer extends JsonSerializer<Storage> { @Override public void serialize(Storage storage, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeString(storage.toString()); } } //setup new serializer SimpleModule simpleModule = new SimpleModule(); simpleModule.addSerializer(DateTime.class, new dateSerializer()); simpleModule.addSerializer(ZonedDateTime.class, new zoneDateSerializer()); simpleModule.addSerializer(Date.class, new utilDateSerializer()); simpleModule.addSerializer(JSONObject.class, new JsonObjectSerializer()); simpleModule.addSerializer(JSONArray.class, new JsonArraySerializer()); simpleModule.addSerializer(Storage.class, new StorageSerializer()); mapper.registerModule(simpleModule); }
From source file:org.hawkular.alerts.api.JsonTest.java
@Test public void jsonToAlertTest() throws Exception { String jsonAlert = "{\"tenantId\":\"jdoe\"," + "\"id\":\"trigger-test|1436964192878\"," + "\"eventType\":\"ALERT\"," + "\"trigger\":{\"tenantId\":\"jdoe\"," + "\"id\":\"trigger-test\"," + "\"name\":\"trigger-test\"," + "\"description\":\"trigger-test\"," + "\"context\":{\"n1\":\"v1\",\"n2\":\"v2\"}" + "}," + "\"ctime\":1436964192878," + "\"context\":{\"n1\":\"v1\",\"n2\":\"v2\"}," + "\"text\":\"trigger-test\"," + "\"evalSets\":[" + "[{\"evalTimestamp\":1436964294055," + "\"dataTimestamp\":2," + "\"type\":\"THRESHOLD\"," + "\"condition\":{\"tenantId\":\"jdoe\"," + "\"triggerId\":\"trigger-test\"," + "\"triggerMode\":\"FIRING\"," + "\"type\":\"THRESHOLD\"," + "\"conditionId\":\"my-organization-trigger-test-FIRING-1-1\"," + "\"dataId\":\"Default\"," + "\"operator\":\"LTE\"," + "\"threshold\":50.0" + "}," + "\"value\":25.5}," + "{\"evalTimestamp\":1436964284965," + "\"dataTimestamp\":1," + "\"type\":\"AVAILABILITY\"," + "\"condition\":{\"tenantId\":\"jdoe\"," + "\"triggerId\":\"trigger-test\"," + "\"triggerMode\":\"FIRING\"," + "\"type\":\"AVAILABILITY\"," + "\"conditionId\":\"my-organization-trigger-test-FIRING-1-1\"," + "\"dataId\":\"Default\"," + "\"operator\":\"UP\"" + "}," + "\"value\":\"UP\"}]" + "]," + "\"severity\":\"MEDIUM\"," + "\"status\":\"OPEN\"," + "\"ackTime\":0," + "\"ackBy\":null," + "\"resolvedTime\":0," + "\"resolvedBy\":null," + "\"notes\":[{\"user\":\"user1\",\"ctime\":1,\"text\":\"The comment 1\"}," + "{\"user\":\"user2\",\"ctime\":2,\"text\":\"The comment 2\"}" + "]," + "\"context\":{\"n1\":\"v1\",\"n2\":\"v2\"}}"; ObjectMapper mapper = new ObjectMapper(); Alert alert = mapper.readValue(jsonAlert, Alert.class); assertNotNull(alert);/* w ww.ja v a 2s. co m*/ assertNotNull(alert.getEvalSets()); assertEquals(1, alert.getEvalSets().size()); assertEquals(2, alert.getEvalSets().get(0).size()); assertTrue(alert.getContext() != null); assertTrue(alert.getContext().size() == 2); assertTrue(alert.getContext().get("n1").equals("v1")); assertTrue(alert.getContext().get("n2").equals("v2")); assertEquals("trigger-test", alert.getText()); /* Testing thin deserializer */ SimpleModule simpleModule = new SimpleModule(); simpleModule.setDeserializerModifier(new JacksonDeserializer.AlertThinDeserializer()); mapper = new ObjectMapper(); mapper.registerModule(simpleModule); alert = mapper.readValue(jsonAlert, Alert.class); assertNull(alert.getEvalSets()); }