public static void insertDataset(JsonNode dataset) throws Exception { ObjectMapper om = new ObjectMapper(); om.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); DatasetRecord record = om.convertValue(dataset, DatasetRecord.class); if (record.getRefDatasetUrn() != null) { Map<String, Object> refDataset = getDatasetByUrn(record.getRefDatasetUrn()); // Find ref dataset id if (refDataset != null) { record.setRefDatasetId(((Long) refDataset.get("id")).intValue()); } } DatabaseWriter dw = new DatabaseWriter(JdbcUtil.wherehowsJdbcTemplate, "dict_dataset"); dw.append(record); dw.close(); }
public static void setDatasetRecord (JsonNode dataset) throws Exception { ObjectMapper om = new ObjectMapper(); om.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); DatasetRecord record = om.convertValue(dataset, DatasetRecord.class); if (record != null) { Map<String, Object> params = new HashMap<>(); params.put("urn", record.getUrn()); if (record.getUrn().indexOf(":///") == -1) { throw new Exception("improperly formatted urn: " + record.getUrn() + ", requires ':///'"); } try { Map<String, Object> result = JdbcUtil.wherehowsNamedJdbcTemplate.queryForMap(GET_DATASET_BY_URN, params); updateDataset(dataset); } catch (EmptyResultDataAccessException e) { insertDataset(dataset); } } }
public static void updateDataset(JsonNode dataset) throws Exception { ObjectMapper om = new ObjectMapper(); om.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); DatasetRecord record = om.convertValue(dataset, DatasetRecord.class); if (record.getRefDatasetUrn() != null) { Map<String, Object> refDataset = getDatasetByUrn(record.getRefDatasetUrn()); // Find ref dataset id if (refDataset != null) { record.setRefDatasetId(((Long) refDataset.get("id")).intValue()); } } DatabaseWriter dw = new DatabaseWriter(JdbcUtil.wherehowsJdbcTemplate, "dict_dataset"); dw.update(record.toUpdateDatabaseValue(), record.getUrn()); dw.close(); }
public static void insertDataset(JsonNode dataset) throws Exception { ObjectMapper om = new ObjectMapper(); om.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); DatasetRecord record = om.convertValue(dataset, DatasetRecord.class); if (record.getRefDatasetUrn() != null) { Map<String, Object> refDataset = getDatasetByUrn(record.getRefDatasetUrn()); // Find ref dataset id if (refDataset != null) { record.setRefDatasetId(((Long) refDataset.get("id")).intValue()); } } // Find layout id if (record.getSamplePartitionFullPath() != null) { PartitionPatternMatcher ppm = new PartitionPatternMatcher(PartitionLayoutDao.getPartitionLayouts()); record.setPartitionLayoutPatternId(ppm.analyze(record.getSamplePartitionFullPath())); } DatabaseWriter dw = new DatabaseWriter(JdbcUtil.wherehowsJdbcTemplate, "dict_dataset"); dw.append(record); dw.close(); }
public static void setDatasetRecord (JsonNode dataset) throws Exception { ObjectMapper om = new ObjectMapper(); om.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); DatasetRecord record = om.convertValue(dataset, DatasetRecord.class); if (record != null) { Map<String, Object> params = new HashMap<>(); params.put("urn", record.getUrn()); try { Map<String, Object> result = JdbcUtil.wherehowsNamedJdbcTemplate.queryForMap(GET_DATASET_BY_URN, params); updateDataset(dataset); } catch (EmptyResultDataAccessException e) { insertDataset(dataset); } } }
public static void updateDataset(JsonNode dataset) throws Exception { ObjectMapper om = new ObjectMapper(); om.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); DatasetRecord record = om.convertValue(dataset, DatasetRecord.class); if (record.getRefDatasetUrn() != null) { Map<String, Object> refDataset = getDatasetByUrn(record.getRefDatasetUrn()); // Find ref dataset id if (refDataset != null) { record.setRefDatasetId(((Long) refDataset.get("id")).intValue()); } } // Find layout id if (record.getSamplePartitionFullPath() != null) { PartitionPatternMatcher ppm = new PartitionPatternMatcher(PartitionLayoutDao.getPartitionLayouts()); record.setPartitionLayoutPatternId(ppm.analyze(record.getSamplePartitionFullPath())); } DatabaseWriter dw = new DatabaseWriter(JdbcUtil.wherehowsJdbcTemplate, "dict_dataset"); dw.update(record.toUpdateDatabaseValue(), record.getUrn()); dw.close(); }
protected void load(final String dataDir, final boolean update) { try { final File dir = new File("data/fixtures/" + dataDir); final File[] files = dir.listFiles((d, name) -> name.endsWith(".json")); if (files == null) { throw new IOException("No files found in " + dir.getAbsolutePath()); } final ObjectMapper mapper = new ObjectMapper(); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); for (File jsonFile : files) { final T entity = mapper.readValue(jsonFile, entityClass); if (update && entity.getId() != null) { update(entity); } else { create(entity); } } } catch (IOException ioex) { throw new RuntimeException(ioex); } }
public static ObjectMapper objectMapper() { return new ObjectMapper() // Property visibility .setDefaultPropertyInclusion(JsonInclude.Include.ALWAYS) .setDefaultVisibility(JsonAutoDetect.Value.construct(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.PROTECTED_AND_PUBLIC)) .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true) .setSerializationInclusion(JsonInclude.Include.NON_NULL) .configure(SerializationFeature.WRITE_NULL_MAP_VALUES, true) // Property naming and order .setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE) // Customised de/serializers // Formats, locals, encoding, binary data .setDateFormat(new SimpleDateFormat("MM/dd/yyyy")) .setDefaultPrettyPrinter(new DefaultPrettyPrinter()) .setLocale(Locale.CANADA); }
public Optional<Cluster> createCluster(String name, String region, Map<String, String> args) throws IOException { Map<String, String> createOptions = new HashMap<>(args); createOptions.put(SpydraArgument.OPTION_REGION, region); List<String> command = ImmutableList.of("--format=json", "beta", "dataproc", "clusters", "create", name); StringBuilder outputBuilder = new StringBuilder(); boolean success = ProcessHelper.executeForOutput( buildCommand(command, createOptions, Collections.emptyList()), outputBuilder); String output = outputBuilder.toString(); if (success) { Cluster cluster = JsonHelper.objectMapper() .setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE) .readValue(output, Cluster.class); return Optional.of(cluster); } else { LOGGER.error("Dataproc cluster creation call failed. Command line output:"); LOGGER.error(output); return Optional.empty(); } }
public static ObjectMapper createDefaultMapper() { final ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); mapper.configure(SerializationFeature.INDENT_OUTPUT, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); SimpleModule module = new SimpleModule(); module.addSerializer(Transaction.class, new TransactionSerializer()); module.addDeserializer(Transaction.class, new TransactionDeserializer()); module.addSerializer(Difficulty.class, new DifficultySerializer()); module.addDeserializer(Difficulty.class, new DifficultyDeserializer()); module.addSerializer(Block.class, new BlockSerializer()); module.addDeserializer(Block.class, new BlockDeserializer()); mapper.registerModule(module); return mapper; }
@Test public void fieldNamingStrategySerialize() throws IOException { final ObjectMapper mapper = new VPackMapper(); mapper.setPropertyNamingStrategy(new PropertyNamingStrategy() { private static final long serialVersionUID = 1L; @Override public String nameForGetterMethod( final MapperConfig<?> config, final AnnotatedMethod method, final String defaultName) { return "bla"; } }); final VPackSlice vpack = new VPackSlice(mapper.writeValueAsBytes(new TestEntityA())); assertThat(vpack, is(notNullValue())); assertThat(vpack.isObject(), is(true)); final VPackSlice bla = vpack.get("bla"); assertThat(bla.isString(), is(true)); assertThat(bla.getAsString(), is("a")); }
@Test public void fieldNamingStrategyDeserialize() throws IOException { final VPackBuilder builder = new VPackBuilder(); builder.add(ValueType.OBJECT); builder.add("bla", "test"); builder.close(); final ObjectMapper mapper = new VPackMapper(); mapper.setPropertyNamingStrategy(new PropertyNamingStrategy() { private static final long serialVersionUID = 1L; @Override public String nameForSetterMethod( final MapperConfig<?> config, final AnnotatedMethod method, final String defaultName) { return "bla"; } }); final TestEntityA entity = mapper.readValue(builder.slice().getBuffer(), TestEntityA.class); assertThat(entity, is(notNullValue())); assertThat(entity.a, is("test")); }
/** * Creates properly configured Jackson XML Mapper instances. * @return XmlMapper instance. */ public static XmlMapper newInstance() { // Create new mapper final JacksonXmlModule module = new JacksonXmlModule(); module.setDefaultUseWrapper(false); XmlMapper mapper = new XmlMapper(module); // Configure it mapper .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE) .registerModule(new JodaModule()) .setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); return mapper; }
public ObjectMapper provideObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); objectMapper.setSerializationInclusion(Include.NON_NULL); objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); objectMapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true); objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); objectMapper.setDateFormat(provideDateFormat()); return objectMapper; }
public WxAppUserInfoRes decryptUserInfo(String encryptedData, String iv, String sessionKey) { byte[] res = WechatAESUtils.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv)); if (null != res && res.length > 0) { try { String resStr = new String(res, "UTF8"); return getObjectMapper() .setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE) .readValue(resStr, WxAppUserInfoRes.class); } catch (IOException e) { logger.error(e.getMessage(), e); return null; } } return null; }
protected <T> T getResponse(Request request, Class<T> clazz) throws WxSnsException { try { Response response = getHttpClient().newCall(request).execute(); String resStr = response.body().string(); try { WxErrorRes error = getObjectMapper().readValue(resStr, WxErrorRes.class); if (null != error.getErrcode()) { throw new WxSnsException(error.getErrcode(), error.getErrmsg()); } } catch (IOException ignored) { } return getObjectMapper() .setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE) .readValue(resStr, clazz); } catch (IOException e) { logger.error(e.getMessage(), e); throw new WxSnsException(-1, e.getMessage()); } }
protected static BenderConfig load(String filename, String data) { String swappedData = swapEnvironmentVariables(data); /* * Configure Mapper and register polymorphic types */ ObjectMapper mapper = BenderConfig.getObjectMapper(filename); mapper.setPropertyNamingStrategy( PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); BenderConfig.validate(swappedData, mapper); BenderConfig config = null; try { config = mapper.readValue(swappedData, BenderConfig.class); } catch (IOException e) { throw new ConfigurationException("invalid config file", e); } return config; }
public static Converter.Factory getDefaultConverter() { if (defaultConverterFactory == null) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); objectMapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true); objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); objectMapper.setDateFormat(df); defaultConverterFactory = JacksonConverterFactory.create(objectMapper); } return defaultConverterFactory; }
public CloudFrontLogEventHandler(AmazonCloudFormationClient cloudFormationClient, AmazonS3Client amazonS3Client, AWSWAF awsWaf) { cloudFormationClient.setRegion(Region.getRegion(Regions.US_WEST_2)); this.amazonS3Client = amazonS3Client; objectMapper = new ObjectMapper(); objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); // New processors would need there own ip sets as there is a hard limit of 1000 ips and the // RateLimitingProcessor truncates the set and removes any ips from the set that it doesn't know about // see CloudFormationDefinedParams logEventProcessors.add(new RateLimitingProcessor(objectMapper, awsWaf, amazonS3Client)); logEventProcessors.add(new GoogleAnalyticsKPIProcessor()); logEventProcessors.add(new TlsVerificationProcessor()); }
private void configurePropertyNamingStrategyField( Jackson2ObjectMapperBuilder builder, String fieldName) { // Find the field (this way we automatically support new constants // that may be added by Jackson in the future) Field field = ReflectionUtils.findField(PropertyNamingStrategy.class, fieldName, PropertyNamingStrategy.class); Assert.notNull(field, "Constant named '" + fieldName + "' not found on " + PropertyNamingStrategy.class.getName()); try { builder.propertyNamingStrategy( (PropertyNamingStrategy) field.get(null)); } catch (Exception ex) { throw new IllegalStateException(ex); } }
@Inject public CreateCerberusBackupOperation(CerberusAdminClientFactory cerberusAdminClientFactory, ConfigStore configStore, MetricsService metricsService, EnvironmentMetadata environmentMetadata) { objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); objectMapper.enable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS); objectMapper.setDateFormat(new ISO8601DateFormat()); this.configStore = configStore; this.metricsService = metricsService; this.environmentMetadata = environmentMetadata; cerberusAdminClient = cerberusAdminClientFactory.createCerberusAdminClient( configStore.getCerberusBaseUrl()); }
public EnvironmentConfig getEnvironmentConfig() { if (environmentConfig != null) { return environmentConfig; } if (file == null) { return null; } File environmentConfigFile = new File(file); if (! environmentConfigFile.exists() || environmentConfigFile.isDirectory()) { throw new IllegalArgumentException(String.format("The file: %s does not exist or is a directory", file)); } ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE); try { environmentConfig = mapper.readValue(environmentConfigFile, EnvironmentConfig.class); } catch (IOException e) { throw new IllegalArgumentException("Failed to deserialize environment yaml", e); } return environmentConfig; }
@Produces @Omakase public ObjectMapper getObjectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); ImmutableSet<SimpleModule> modules = getModules(); if (getModules() != null) { modules.stream().forEach(mapper::registerModule); } mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.registerModule(new GuavaModule()); return mapper; }
public ObjectMapper getObjectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); ImmutableSet<SimpleModule> modules = getModules(); if (getModules() != null) { modules.stream().forEach(mapper::registerModule); } mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.registerModule(new GuavaModule()); return mapper; }
/** * Configure an existing object mapper to work with Archie RM and AOM Objects. * Indentation is enabled. Feel free to disable again in your own code. * @param objectMapper */ public static void configureObjectMapper(ObjectMapper objectMapper) { objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.enable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); objectMapper.disable(SerializationFeature.WRITE_NULL_MAP_VALUES); objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); objectMapper.enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); //objectMapper. objectMapper.registerModule(new JavaTimeModule()); TypeResolverBuilder typeResolverBuilder = new ArchieTypeResolverBuilder() .init(JsonTypeInfo.Id.NAME, new OpenEHRTypeNaming()) .typeProperty("@type") .typeIdVisibility(true) .inclusion(JsonTypeInfo.As.PROPERTY); objectMapper.setDefaultTyping(typeResolverBuilder); }
private PropertyNamingStrategy _findNamingStrategy() { Object localObject1; if (this._annotationIntrospector == null) localObject1 = null; else localObject1 = this._annotationIntrospector.findNamingStrategy(this._classDef); Object localObject2 = localObject1; if (localObject1 == null) return this._config.getPropertyNamingStrategy(); if ((localObject2 instanceof PropertyNamingStrategy)) return (PropertyNamingStrategy)localObject2; if (!(localObject2 instanceof Class)) throw new IllegalStateException("AnnotationIntrospector returned PropertyNamingStrategy definition of type " + localObject2.getClass().getName() + "; expected type PropertyNamingStrategy or Class<PropertyNamingStrategy> instead"); Class localClass = (Class)localObject2; if (!PropertyNamingStrategy.class.isAssignableFrom(localClass)) throw new IllegalStateException("AnnotationIntrospector returned Class " + localClass.getName() + "; expected Class<PropertyNamingStrategy>"); HandlerInstantiator localHandlerInstantiator = this._config.getHandlerInstantiator(); if (localHandlerInstantiator != null) { PropertyNamingStrategy localPropertyNamingStrategy = localHandlerInstantiator.namingStrategyInstance(this._config, this._classDef, localClass); if (localPropertyNamingStrategy != null) return localPropertyNamingStrategy; } return (PropertyNamingStrategy)ClassUtil.createInstance(localClass, this._config.canOverrideAccessModifiers()); }
public POJOPropertiesCollector collect() { this._properties.clear(); _addFields(); _addMethods(); _addCreators(); _addInjectables(); _removeUnwantedProperties(); _renameProperties(); PropertyNamingStrategy localPropertyNamingStrategy = _findNamingStrategy(); if (localPropertyNamingStrategy != null) _renameUsing(localPropertyNamingStrategy); Iterator localIterator1 = this._properties.values().iterator(); while (localIterator1.hasNext()) ((POJOPropertyBuilder)localIterator1.next()).trimByVisibility(); Iterator localIterator2 = this._properties.values().iterator(); while (localIterator2.hasNext()) ((POJOPropertyBuilder)localIterator2.next()).mergeAnnotations(this._forSerialization); if (this._config.isEnabled(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME)) _renameWithWrappers(); _sortProperties(); return this; }
@Override public String toString() { String rtn = null; try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); mapper.setDateFormat(new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")); rtn = mapper.writeValueAsString(this); } catch( Exception e ) { logger.error("toString() failed - " + e.getMessage(), e); } return rtn; }
public boolean authenticate(String username, String password) throws IOException, UnauthenticatedException { HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost method = new HttpPost(serverUrl + oauthUrl); List<NameValuePair> requestParams = new ArrayList<NameValuePair>(); requestParams.add(new BasicNameValuePair("grant_type", "password")); requestParams.add(new BasicNameValuePair("client_id", URLEncoder.encode(clientId, "UTF-8"))); requestParams.add(new BasicNameValuePair("client_secret", clientSecret)); requestParams.add(new BasicNameValuePair("username", username)); requestParams.add(new BasicNameValuePair("password", password)); method.setEntity(new UrlEncodedFormEntity(requestParams)); HttpResponse response = httpClient.execute(method); int responseStatus = response.getStatusLine().getStatusCode(); String body = EntityUtils.toString(response.getEntity(), "UTF-8"); if (responseStatus != 200) { throw new UnauthenticatedException(responseStatus + " " + body); } ObjectMapper mapper = new ObjectMapper(); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); oauthToken = mapper.readValue(body, AuthToken.class); return true; }
/** * Provides the serialization configurations required by the Eureka Server. JSON * content exchanged with eureka requires a root node matching the entity being * serialized or deserialized. Achived with * {@link SerializationFeature.WRAP_ROOT_VALUE} and * {@link DeserializationFeature.UNWRAP_ROOT_VALUE}. * {@link PropertyNamingStrategy.SnakeCaseStrategy} is applied to the underlying * {@link ObjectMapper}. * * * @return */ public MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter() { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); converter.setObjectMapper(new ObjectMapper() .setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)); SimpleModule jsonModule = new SimpleModule(); jsonModule.setSerializerModifier(createJsonSerializerModifier());//keyFormatter, compact)); converter.getObjectMapper().registerModule(jsonModule); converter.getObjectMapper().configure(SerializationFeature.WRAP_ROOT_VALUE, true); converter.getObjectMapper().configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); converter.getObjectMapper().addMixIn(Applications.class, ApplicationsJsonMixIn.class); converter.getObjectMapper().addMixIn(InstanceInfo.class, InstanceInfoJsonMixIn.class); // converter.getObjectMapper().addMixIn(DataCenterInfo.class, DataCenterInfoXmlMixIn.class); // converter.getObjectMapper().addMixIn(InstanceInfo.PortWrapper.class, PortWrapperXmlMixIn.class); // converter.getObjectMapper().addMixIn(Application.class, ApplicationXmlMixIn.class); // converter.getObjectMapper().addMixIn(Applications.class, ApplicationsXmlMixIn.class); return converter; }
@Override public void run(final CredentialStorageConfiguration configuration, final Environment environment) throws Exception { final JedisManaged jedisManaged = this.buildJedis(configuration.getRedis()); environment.lifecycle().manage(jedisManaged); final PetiteContainer petiteContainer = this.petite.getPetiteContainer(); this.registerExternalDependencies(configuration, environment, jedisManaged, petiteContainer); environment.getObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); environment.jersey().register(petiteContainer.getBean(CredentialResource.class)); // Admin resources. final JerseyEnvironment adminJerseyEnvironment = this.adminResourceBundle .getJerseyEnvironment(); adminJerseyEnvironment.register(petiteContainer.getBean(AuditResource.class)); // Health checks environment.healthChecks().register("redis", this.petite.getPetiteContainer().getBean(RedisHealthCheck.class)); }
public JacksonJson() { objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(Include.NON_NULL); objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true); SimpleModule module = new SimpleModule("GitLabApiJsonModule"); module.addSerializer(Date.class, new JsonDateSerializer()); module.addDeserializer(Date.class, new JsonDateDeserializer()); objectMapper.registerModule(module); }
@Test public void shouldHaveChannelIdAndRequestIdInjectedIntoExceptionMapper() throws Exception { HttpGet get = new HttpGet(ServiceConfiguration.SERVICE_URL + "/exception"); Future<HttpResponse> future = client.getClient().execute(get, null); HttpResponse response = future.get(); assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpStatus.SC_CONFLICT)); ObjectMapper mapper = new ObjectMapper(); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); ServiceError error = mapper.readValue(response.getEntity().getContent(), ServiceError.class); String tokens[] = error.getErrorText().split("-"); assertThat(tokens.length, equalTo(2)); assertThat(tokens[0].length(), greaterThan(0)); assertThat(tokens[1].length(), greaterThan(0)); // there's a channel id assertThat(tokens[0].length(), greaterThan(0)); // the request id in the body matches the one that's added by the underlying pipeline String requestId = tokens[1]; assertThat(requestId, equalTo(response.getFirstHeader(Headers.REQUEST_TRACING_HEADER).getValue())); }
public static ObjectMapper createDefaultMapper() { final ObjectMapper result = new ObjectMapper(); result.setSerializationInclusion(Include.NON_NULL); result.configure(SerializationFeature.INDENT_OUTPUT, false); result.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); result.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); SimpleModule module = new SimpleModule(); module.addDeserializer(Money.class, new MoneyDeserializer()); module.addDeserializer(CurrencyUnit.class, new CurrencyUnitDeserializer()); module.addSerializer(CurrencyUnit.class, new CurrencyUnitSerializer()); result.registerModule(module); result.registerModule(new JodaModule()); return result; }
@Override public void initialize(Bootstrap<SkidRoadDropwizardExampleConfiguration> bootstrap) { ObjectMapper om = bootstrap.getObjectMapper(); om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); om.registerModule(new JodaModule()); om.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); bootstrap.addBundle(new DBIExceptionsBundle()); bootstrap.addBundle(new MigrationsBundle<SkidRoadDropwizardExampleConfiguration>() { @Override public DataSourceFactory getDataSourceFactory(SkidRoadDropwizardExampleConfiguration configuration) { return configuration.getSkidRoad().getDatabaseConfiguration(); } }); bootstrap.addCommand(new GenerateRandomKey()); }
@Test public void roundtrip353() throws Exception { ObjectMapper mapper = new ObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); String json = mapper.writeValueAsString(ImmutableNamingStrategy.builder() .abraCadabra(1) .focusPocus(true) .build()); NamingStrategy info = mapper.readValue(json, NamingStrategy.class); check(info.abraCadabra()).is(1); check(info.focusPocus()); check(json).is("{'abra_cadabra':1,'focus_pocus':true}".replace('\'', '"')); }
@Override public void run(final DeviceUsageTrackerConfig configuration, final Environment environment) { ConfigurationHolder.set(configuration); environment.jersey().register(DeviceResource.class); environment.jersey().register(UserResource.class); environment.jersey().register(ProfileResource.class); environment.jersey().register(ClaimResource.class); environment.jersey().register(DeviceSlackResource.class); environment.jersey().register(DeviceClaimResource.class); // JSON property naming environment.getObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); environment.jersey().register(new CustomExceptionMapper()); // Enable CORS headers final FilterRegistration.Dynamic cors = environment.servlets() .addFilter("CORS", CrossOriginFilter.class); // Configure CORS parameters cors.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*"); cors.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin,Authorization"); cors.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "OPTIONS,GET,PUT,POST,DELETE,HEAD"); // Add URL mapping cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); // Auth environment.jersey().register( new AuthenticatorFeature(environment.metrics(), configuration.getAuthConfig())); }
public void init() { // 排除值为空属性 setSerializationInclusion(JsonInclude.Include.NON_NULL); // 进行缩进输出 configure(SerializationFeature.INDENT_OUTPUT, true); // 将驼峰转为下划线 if (camelCaseToLowerCaseWithUnderscores) { setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); } // 进行日期格式化 if (!StringUtils.isEmpty(dateFormatPattern)) { DateFormat dateFormat = new SimpleDateFormat(dateFormatPattern); setDateFormat(dateFormat); } }
@Provides @Singleton ObjectMapper provideObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setPropertyNamingStrategy( PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_ABSENT); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); return objectMapper; }