List of usage examples for com.fasterxml.jackson.databind ObjectMapper setPropertyNamingStrategy
public ObjectMapper setPropertyNamingStrategy(PropertyNamingStrategy s)
From source file:io.rodeo.chute.ChuteMain.java
public static void main(String[] args) throws SQLException, JsonParseException, JsonMappingException, IOException { InputStream is = new FileInputStream(new File(CONFIG_FILENAME)); ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); ChuteConfiguration config = mapper.readValue(is, ChuteConfiguration.class); Map<String, Importer> importManagers = new HashMap<String, Importer>(config.importerConfigurations.size()); for (Entry<String, ImporterConfiguration> importerConfig : config.importerConfigurations.entrySet()) { importManagers.put(importerConfig.getKey(), importerConfig.getValue().createImporter()); }//from w w w . jav a 2s . c o m Map<String, Exporter> exportManagers = new HashMap<String, Exporter>(config.exporterConfigurations.size()); for (Entry<String, ExporterConfiguration> exporterConfig : config.exporterConfigurations.entrySet()) { exportManagers.put(exporterConfig.getKey(), exporterConfig.getValue().createExporter()); } for (Entry<String, ConnectionConfiguration> connectionConfig : config.connectionConfigurations.entrySet()) { importManagers.get(connectionConfig.getValue().in) .addProcessor(exportManagers.get(connectionConfig.getValue().out)); } for (Entry<String, Exporter> exportManager : exportManagers.entrySet()) { exportManager.getValue().start(); } for (Entry<String, Importer> importManager : importManagers.entrySet()) { importManager.getValue().start(); } }
From source file:com.nextdoor.bender.ValidateSchema.java
public static void main(String[] args) throws ParseException, InterruptedException, IOException { /*//from ww w . j ava 2 s.c om * Parse cli arguments */ Options options = new Options(); options.addOption(Option.builder().longOpt("schema").hasArg() .desc("Filename to output schema to. Default: schema.json").build()); options.addOption(Option.builder().longOpt("configs").hasArgs() .desc("List of config files to validate against schema.").build()); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); String schemaFilename = cmd.getOptionValue("schema", "schema.json"); String[] configFilenames = cmd.getOptionValues("configs"); /* * Validate config files against schema */ boolean hasFailures = false; for (String configFilename : configFilenames) { StringBuilder sb = new StringBuilder(); Files.lines(Paths.get(configFilename), StandardCharsets.UTF_8).forEach(p -> sb.append(p + "\n")); System.out.println("Attempting to validate " + configFilename); try { ObjectMapper mapper = BenderConfig.getObjectMapper(configFilename); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); BenderConfig.load(configFilename, sb.toString(), mapper, true); System.out.println("Valid"); BenderConfig config = BenderConfig.load(configFilename, sb.toString()); } catch (ConfigurationException e) { System.out.println("Invalid"); e.printStackTrace(); hasFailures = true; } } if (hasFailures) { System.exit(1); } }
From source file:edu.usf.cutr.siri.SiriParserJacksonExample.java
/** * Takes in a path to a JSON or XML file, parses the contents into a Siri object, * and prints out the contents of the Siri object. * /* www . ja v a 2 s . c o m*/ * @param args path to the JSON or XML file located on disk */ public static void main(String[] args) { if (args[0] == null) { System.out.println("Proper Usage is: java JacksonSiriParserExample path-to-siri-file-to-parse"); System.exit(0); } try { //Siri object we're going to instantiate based on JSON or XML data Siri siri = null; //Get example JSON or XML from file File file = new File(args[0]); System.out.println("Input file = " + file.getAbsolutePath()); /* * Alternately, instead of passing in a File, a String encoded in JSON or XML can be * passed into Jackson for parsing. Uncomment the below line to read the * JSON or XML into the String. */ //String inputExample = readFile(file); String extension = FilenameUtils.getExtension(args[0]); if (extension.equalsIgnoreCase("json")) { System.out.println("Parsing JSON..."); ObjectMapper mapper = null; try { mapper = (ObjectMapper) SiriUtils.readFromCache(SiriUtils.OBJECT_MAPPER); } catch (Exception e) { System.out.println("Error reading from cache: " + e); } if (mapper == null) { // instantiate ObjectMapper like normal if cache read failed mapper = new ObjectMapper(); //Jackson 2.0 configuration settings mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true); mapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true); mapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true); //Tell Jackson to expect the JSON in PascalCase, instead of camelCase mapper.setPropertyNamingStrategy(new PropertyNamingStrategy.PascalCaseStrategy()); } //Deserialize the JSON from the file into the Siri object siri = mapper.readValue(file, Siri.class); /* * Alternately, you can also deserialize the JSON from a String into the Siri object. * Uncomment the below line to parsing the JSON from a String instead of the File. */ //siri = mapper.readValue(inputExample, Siri.class); //Write the ObjectMapper to the cache, to speed up parsing for the next execution SiriUtils.forceCacheWrite(mapper); } if (extension.equalsIgnoreCase("xml")) { System.out.println("Parsing XML..."); //Use Aalto StAX implementation explicitly XmlFactory f = new XmlFactory(new InputFactoryImpl(), new OutputFactoryImpl()); JacksonXmlModule module = new JacksonXmlModule(); /** * Tell Jackson that Lists are using "unwrapped" style (i.e., * there is no wrapper element for list). This fixes the error * "com.fasterxml.jackson.databind.JsonMappingException: Can not * >> instantiate value of type [simple type, class >> * uk.org.siri.siri.VehicleMonitoringDelivery] from JSON String; * no >> single-String constructor/factory method (through * reference chain: >> * uk.org.siri.siri.Siri["ServiceDelivery"]-> * uk.org.siri.siri.ServiceDel >> * ivery["VehicleMonitoringDelivery"])" * * NOTE - This requires Jackson v2.1 */ module.setDefaultUseWrapper(false); /** * Handles "xml:lang" attribute, which is used in SIRI * NaturalLanguage String, and looks like: <Description * xml:lang="EN">b/d 1:00pm until f/n. loc al and express buses * run w/delays & detours. POTUS visit in MANH. Allow additional * travel time Details at www.mta.info</Description> * * Passing "Value" (to match expected name in XML to map, * considering naming strategy) will make things work. This is * since JAXB uses pseudo-property name of "value" for XML Text * segments, whereas Jackson by default uses "" (to avoid name * collisions). * * NOTE - This requires Jackson v2.1 * * NOTE - This still requires a CustomPascalCaseStrategy to * work. Please see the CustomPascalCaseStrategy in this app * that is used below. */ module.setXMLTextElementName("Value"); XmlMapper xmlMapper = null; try { xmlMapper = (XmlMapper) SiriUtils.readFromCache(SiriUtils.XML_MAPPER); } catch (Exception e) { System.out.println("Error reading from cache: " + e); } if (xmlMapper == null) { xmlMapper = new XmlMapper(f, module); xmlMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); xmlMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true); xmlMapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true); xmlMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true); /** * Tell Jackson to expect the XML in PascalCase, instead of camelCase * NOTE: We need the CustomPascalStrategy here to handle XML * namespace attributes such as xml:lang. See the comments in * CustomPascalStrategy for details. */ xmlMapper.setPropertyNamingStrategy(new CustomPascalCaseStrategy()); } //Parse the SIRI XML response siri = xmlMapper.readValue(file, Siri.class); //Write the XmlMapper to the cache, to speed up parsing for the next execution SiriUtils.forceCacheWrite(xmlMapper); } //If we successfully retrieved and parsed JSON or XML, print the contents if (siri != null) { SiriUtils.printContents(siri); } } catch (IOException e) { System.err.println("Error reading or parsing input file: " + e); } }
From source file:com.fizzed.stork.launcher.ConfigurationFactory.java
static public ObjectMapper createObjectMapper() { // create json deserializer ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); return mapper; }
From source file:com.nike.cerberus.server.config.CmsConfig.java
public static ObjectMapper configureObjectMapper() { final ObjectMapper om = new ObjectMapper(); om.findAndRegisterModules();//from w ww .ja va 2s. c o m om.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); om.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); om.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); om.enable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS); om.enable(SerializationFeature.INDENT_OUTPUT); return om; }
From source file:keywhiz.testing.JsonHelpers.java
/** * Customized ObjectMapper for common settings. * * @return customized object mapper/*from www . ja va 2s . c o m*/ */ private static ObjectMapper customizeObjectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new Jdk8Module()); mapper.registerModule(new GuavaModule()); mapper.registerModule(new LogbackModule()); mapper.registerModule(new GuavaExtrasModule()); mapper.registerModule(new FuzzyEnumModule()); mapper.setPropertyNamingStrategy(new AnnotationSensitivePropertyNamingStrategy()); mapper.setSubtypeResolver(new DiscoverableSubtypeResolver()); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return mapper; }
From source file:models.daos.DatasetDao.java
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 {//from w ww . j av a2 s .c om Map<String, Object> result = JdbcUtil.wherehowsNamedJdbcTemplate.queryForMap(GET_DATASET_BY_URN, params); updateDataset(dataset); } catch (EmptyResultDataAccessException e) { insertDataset(dataset); } } }
From source file:models.daos.DatasetDao.java
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()); }//from w ww . ja v a2 s . com } // 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(); }
From source file:models.daos.DatasetDao.java
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()); }/*ww w . j a v a2s . c o m*/ } // 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(); }
From source file:com.nextdoor.bender.config.BenderConfig.java
public static BenderConfig load(String filename, String data) { /*//w w w.j av a 2 s . c om * Configure Mapper and register polymorphic types */ ObjectMapper mapper = BenderConfig.getObjectMapper(filename); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); /* * Optionally don't validate the config. Assume user has already * done this. */ String v = System.getenv("BENDER_SKIP_VALIDATE"); if (v != null && v.equals("true")) { return BenderConfig.load(filename, data, mapper, false); } else { return BenderConfig.load(filename, data, mapper, true); } }