List of usage examples for com.fasterxml.jackson.databind ObjectMapper ObjectMapper
public ObjectMapper()
From source file:edu.mit.lib.mama.Mama.java
public static void main(String[] args) { Properties props = findConfig(args); DBI dbi = new DBI(props.getProperty("dburl"), props); // Advanced instrumentation/metrics if requested if (System.getenv("MAMA_DB_METRICS") != null) { dbi.setTimingCollector(new InstrumentedTimingCollector(metrics)); }/* ww w.ja va2s.com*/ // reassign default port 4567 if (System.getenv("MAMA_SVC_PORT") != null) { port(Integer.valueOf(System.getenv("MAMA_SVC_PORT"))); } // if API key given, use exception monitoring service if (System.getenv("HONEYBADGER_API_KEY") != null) { reporter = new HoneybadgerReporter(); } get("/ping", (req, res) -> { res.type("text/plain"); res.header("Cache-Control", "must-revalidate,no-cache,no-store"); return "pong"; }); get("/metrics", (req, res) -> { res.type("application/json"); res.header("Cache-Control", "must-revalidate,no-cache,no-store"); ObjectMapper objectMapper = new ObjectMapper() .registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, true)); try (ServletOutputStream outputStream = res.raw().getOutputStream()) { objectMapper.writer().withDefaultPrettyPrinter().writeValue(outputStream, metrics); } return ""; }); get("/shutdown", (req, res) -> { boolean auth = false; try { if (!isNullOrEmpty(System.getenv("MAMA_SHUTDOWN_KEY")) && !isNullOrEmpty(req.queryParams("key")) && System.getenv("MAMA_SHUTDOWN_KEY").equals(req.queryParams("key"))) { auth = true; return "Shutting down"; } else { res.status(401); return "Not authorized"; } } finally { if (auth) { stop(); } } }); get("/item", (req, res) -> { if (isNullOrEmpty(req.queryParams("qf")) || isNullOrEmpty(req.queryParams("qv"))) { halt(400, "Must supply field and value query parameters 'qf' and 'qv'"); } itemReqs.mark(); Timer.Context context = respTime.time(); try (Handle hdl = dbi.open()) { if (findFieldId(hdl, req.queryParams("qf")) != -1) { List<String> results = findItems(hdl, req.queryParams("qf"), req.queryParams("qv"), req.queryParamsValues("rf")); if (results.size() > 0) { res.type("application/json"); return "{ " + jsonValue("field", req.queryParams("qf"), true) + ",\n" + jsonValue("value", req.queryParams("qv"), true) + ",\n" + jsonValue("items", results.stream().collect(Collectors.joining(",", "[", "]")), false) + "\n" + " }"; } else { res.status(404); return "No items found for: " + req.queryParams("qf") + "::" + req.queryParams("qv"); } } else { res.status(404); return "No such field: " + req.queryParams("qf"); } } catch (Exception e) { if (null != reporter) reporter.reportError(e); res.status(500); return "Internal system error: " + e.getMessage(); } finally { context.stop(); } }); awaitInitialization(); }
From source file:com.basistech.rosette.dm.json.array.CompareJsons.java
public static void main(String[] args) throws Exception { File plenty = new File(args[0]); System.out.println(String.format("Original file length %d", plenty.length())); ObjectMapper inputMapper = AnnotatedDataModelModule.setupObjectMapper(new ObjectMapper()); AnnotatedText[] texts = inputMapper.readValue(plenty, AnnotatedText[].class); System.out.println(String.format("%d documents", texts.length)); runWithFormat(texts, new FactoryFactory() { @Override// www . j a v a 2 s.co m public JsonFactory newFactory() { return new JsonFactory(); } }, "Plain"); runWithFormat(texts, new FactoryFactory() { @Override public JsonFactory newFactory() { return new SmileFactory(); } }, "SMILE"); runWithFormat(texts, new FactoryFactory() { @Override public JsonFactory newFactory() { return new CBORFactory(); } }, "CBOR"); }
From source file:org.alex73.osm.validators.vioski.Export.java
public static void main(String[] args) throws Exception { RehijonyLoad.load(Env.readProperty("dav") + "/Rehijony.xml"); osm = new Belarus(); String dav = Env.readProperty("dav") + "/Nazvy_nasielenych_punktau.csv"; List<Miesta> daviednik = new CSV('\t').readCSV(dav, Miesta.class); Map<String, List<Mdav>> rajony = new TreeMap<>(); for (Miesta m : daviednik) { String r = m.rajon.startsWith("<") ? m.rajon : m.rajon + " "; List<Mdav> list = rajony.get(r); if (list == null) { list = new ArrayList<>(); rajony.put(r, list);//from w w w .jav a 2 s . c o m } Mdav mm = new Mdav(); mm.osmID = m.osmID; mm.ss = m.sielsaviet; mm.why = m.osmComment; mm.nameBe = m.nazvaNoStress; mm.nameRu = m.ras; mm.varyjantBe = m.varyjantyBel; mm.varyjantRu = m.rasUsedAsOld; list.add(mm); } placeTag = osm.getTagsPack().getTagCode("place"); osm.byTag("place", o -> o.isNode() && !o.getTag(placeTag).equals("island") && !o.getTag(placeTag).equals("islet"), o -> processNode((IOsmNode) o)); String outDir = Env.readProperty("out.dir"); File foutDir = new File(outDir + "/vioski"); foutDir.mkdirs(); Map<String, String> padzielo = new TreeMap<>(); for (Voblasc v : RehijonyLoad.kraina.getVoblasc()) { for (Rajon r : v.getRajon()) { padzielo.put(r.getNameBe(), osm.getObject(r.getOsmID()).getTag("name", osm)); } } ObjectMapper om = new ObjectMapper(); String o = "var data={};\n"; o += "data.dav=" + om.writeValueAsString(rajony) + "\n"; o += "data.map=" + om.writeValueAsString(map) + "\n"; o += "data.padziel=" + om.writeValueAsString(padzielo) + "\n"; FileUtils.writeStringToFile(new File(outDir + "/vioski/data.js"), o); FileUtils.copyFileToDirectory(new File("vioski/control.js"), foutDir); FileUtils.copyFileToDirectory(new File("vioski/vioski.html"), foutDir); }
From source file:ratpack.spark.jobserver.Main.java
public static void main(String... args) throws Exception { RatpackServer ratpackServer = RatpackServer.start(spec -> spec.serverConfig(builder -> { Path basePath = BaseDir.find("application.properties"); LOGGER.debug("BASE DIR: {}", basePath.toString()); builder.baseDir(BaseDir.find("application.properties")).env().sysProps(); Path localAppProps = Paths.get("../../config/application.properties"); if (Files.exists(localAppProps)) { LOGGER.debug("LOCALLY OVERLOADED application.properties: {}", localAppProps.toUri().toString()); builder.props(localAppProps); } else {/*from w ww .j a v a 2s .com*/ URL cpAppProps = Main.class.getClassLoader().getResource("config/application.properties"); LOGGER.debug("CLASSPATH OVERLOADED application.properties: {}", cpAppProps != null ? cpAppProps.toString() : "DEFAULT LOCATION"); builder.props(cpAppProps != null ? cpAppProps : Main.class.getClassLoader().getResource("application.properties")); } Path localSparkJobsProps = Paths.get("../../config/sparkjobs.properties"); if (Files.exists(localSparkJobsProps)) { LOGGER.debug("LOCALLY OVERLOADED sparkjobs.properties: {}", localSparkJobsProps.toUri().toString()); builder.props(localSparkJobsProps); } else { URL cpSparkJobsProps = Main.class.getClassLoader().getResource("config/sparkjobs.properties"); LOGGER.debug("CLASSPATH OVERLOADED SPARKJOBS.PROPS: {}", cpSparkJobsProps != null ? cpSparkJobsProps.toString() : "DEFAULT LOCATION"); builder.props(cpSparkJobsProps != null ? cpSparkJobsProps : Main.class.getClassLoader().getResource("sparkjobs.properties")); } builder.require("/spark", SparkConfig.class).require("/job", SparkJobsConfig.class); }).registry(Guice.registry(bindingsSpec -> bindingsSpec.bindInstance(ResponseTimer.decorator()) .module(ContainersModule.class).module(SparkModule.class) .bindInstance(new ObjectMapper().writerWithDefaultPrettyPrinter()))) .handlers(chain -> chain.all(ctx -> { LOGGER.debug("ALL"); MDC.put("clientIP", ctx.getRequest().getRemoteAddress().getHostText()); RequestId.Generator generator = ctx.maybeGet(RequestId.Generator.class) .orElse(UuidBasedRequestIdGenerator.INSTANCE); RequestId requestId = generator.generate(ctx.getRequest()); ctx.getRequest().add(RequestId.class, requestId); MDC.put("requestId", requestId.toString()); ctx.next(); }).prefix("v1", chain1 -> chain1.all(RequestLogger.ncsa()).get("api-def", ctx -> { LOGGER.debug("GET API_DEF.JSON"); SparkJobsConfig config = ctx.get(SparkJobsConfig.class); LOGGER.debug("SPARK JOBS CONFIG: " + config.toString()); ctx.render(ctx.file("public/apidef/apidef.json")); }).prefix("spark", JobsEndpoints.class)))); LOGGER.debug("STARTED: {}://{}:{}", ratpackServer.getScheme(), ratpackServer.getBindHost(), ratpackServer.getBindPort()); }
From source file:es.upv.grc.grcbox.server.GrcBoxServerApplication.java
/** * Launches the application with an HTTP server. * // ww w . ja va 2 s. c o m * @param args * The arguments. * @throws Exception */ public static void main(String[] args) throws Exception { //Load Config File LOG.info("Working Directory = " + System.getProperty("user.dir")); File file = new File("./config.json"); ObjectMapper mapper = new ObjectMapper(); config = mapper.readValue(file, GrcBoxConfig.class); if (!Collections.disjoint(config.getInnerInterfaces(), config.getOuterInterfaces())) { System.err.print("InnerInterfaces and Outerinterfaces has elements in common. Aborting execution."); System.exit(-1); } LinkedList<String> innerInterfaces = config.getInnerInterfaces(); RulesDB.setInnerInterfaces(innerInterfaces); RulesDB.initialize(); for (String string : innerInterfaces) { startServer(string); } }
From source file:com.amazonaws.services.iot.client.sample.shadowEcho.ShadowEchoSample.java
public static void main(String args[]) throws IOException, AWSIotException, AWSIotTimeoutException, InterruptedException { CommandArguments arguments = CommandArguments.parse(args); initClient(arguments);/*from ww w . jav a 2 s . c o m*/ String thingName = arguments.getNotNull("thingName", SampleUtil.getConfig("thingName")); AWSIotDevice device = new AWSIotDevice(thingName); awsIotClient.attach(device); awsIotClient.connect(); // Delete existing document if any device.delete(); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); Thing thing = new Thing(); while (true) { long desired = thing.state.desired.counter; thing.state.reported.counter = desired; thing.state.desired.counter = desired + 1; String jsonState = objectMapper.writeValueAsString(thing); try { // Send updated document to the shadow device.update(jsonState); System.out.println(System.currentTimeMillis() + ": >>> " + jsonState); } catch (AWSIotException e) { System.out.println(System.currentTimeMillis() + ": update failed for " + jsonState); continue; } try { // Retrieve updated document from the shadow String shadowState = device.get(); System.out.println(System.currentTimeMillis() + ": <<< " + shadowState); thing = objectMapper.readValue(shadowState, Thing.class); } catch (AWSIotException e) { System.out.println(System.currentTimeMillis() + ": get failed for " + jsonState); continue; } Thread.sleep(1000); } }
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. * /*from w w w. j a v a2s .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:it.uniroma2.sag.kelp.examples.main.SerializationExample.java
public static void main(String[] args) { try {//from w w w .j a va2 s.c o m // Read a dataset into a trainingSet variable SimpleDataset trainingSet = new SimpleDataset(); trainingSet.populate("src/main/resources/iris_dataset/iris_train.klp"); SimpleDataset testSet = new SimpleDataset(); testSet.populate("src/main/resources/iris_dataset/iris_test.klp"); // print some statistics System.out.println("Training set statistics"); System.out.print("Examples number "); System.out.println(trainingSet.getNumberOfExamples()); List<Label> classes = trainingSet.getClassificationLabels(); for (Label l : classes) { System.out.println( "Training Label " + l.toString() + " " + trainingSet.getNumberOfPositiveExamples(l)); System.out.println( "Training Label " + l.toString() + " " + trainingSet.getNumberOfNegativeExamples(l)); System.out.println("Test Label " + l.toString() + " " + testSet.getNumberOfPositiveExamples(l)); System.out.println("Test Label " + l.toString() + " " + testSet.getNumberOfNegativeExamples(l)); } // Kernel for the first representation (0-index) Kernel linear = new LinearKernel("0"); // Normalize the linear kernel NormalizationKernel normalizedKernel = new NormalizationKernel(linear); // instantiate an svmsolver BinaryCSvmClassification svmSolver = new BinaryCSvmClassification(); svmSolver.setKernel(normalizedKernel); svmSolver.setCp(2); svmSolver.setCn(1); OneVsAllLearning ovaLearner = new OneVsAllLearning(); ovaLearner.setBaseAlgorithm(svmSolver); ovaLearner.setLabels(classes); // One can serialize the learning algorihtm ObjectSerializer serializer = new JacksonSerializerWrapper(); String algoDescr = serializer.writeValueAsString(ovaLearner); System.out.println(algoDescr); // If the learning algorithm is specifified in the Json syntax // it is possible to load it in this way: ObjectMapper mapper = new ObjectMapper(); ovaLearner = (OneVsAllLearning) mapper.readValue(algoDescr, OneVsAllLearning.class); // the ovaLearner object is the one loaded from the Json description // refer to the api documentation to read a learning algorithm from a file // learn and get the prediction function ovaLearner.learn(trainingSet); Classifier f = ovaLearner.getPredictionFunction(); // it is possible also to serialize a classification function // that includes the model (e.g. the support vectors). String classificationFunctionDescr = serializer.writeValueAsString(f); System.out.println(classificationFunctionDescr); // and obiovously a classification function can be loaded in memory from // its json representation f = (Classifier) mapper.readValue(classificationFunctionDescr, Classifier.class); // classify examples and compute some statistics int correct = 0; for (Example e : testSet.getExamples()) { ClassificationOutput p = f.predict(testSet.getNextExample()); // System.out.println(p.getPredictedClasses()); if (e.isExampleOf(p.getPredictedClasses().get(0))) { correct++; } } System.out.println("Accuracy: " + ((float) correct / (float) testSet.getNumberOfExamples())); } catch (Exception e1) { e1.printStackTrace(); } }
From source file:uk.ac.surrey.ee.iot.fiware.ngsi9.semantic.SemanticConverter.java
public static void main(String[] args) throws JAXBException { SemanticConverter ri = new SemanticConverter(); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); RegisterContextRequest rcr = new RegisterContextRequest(); try {/* www . ja v a 2 s . c o m*/ rcr = objectMapper.readValue(ri.NGSI_FILE, RegisterContextRequest.class); } catch (Exception e) { } ri.createJenaModel(rcr); // //hMap.put("class", "OnDeviceResource"); //// hMap.put("class", new String[]{"ResourceService"}); // hMap.put("class", new String[]{"VirtualEntity"}); //// hMap.put("hasID", new String[]{"Resource_1"}); // hMap.put("hasID", new String[]{"VirtualEntity_1"}); // hMap.put("hasAttributeType", new String[]{"http://purl.oclc.org/NET/ssnx/qu/quantity#temperature"}); //// hMap.put("isHostedOn", "PloggBoard_49_BA_01_light"); //// hMap.put("hasType", "Sensor"); //// hMap.put("hasName", "lightsensor49_BA_01"); //// hMap.put("isExposedThroughService", "http://www.surrey.ac.uk/ccsr/ontologies/ServiceModel.owl#49_BA_01_light_sensingService"); //// hMap.put("hasTag", "light sensor 49,1st,BA,office"); // hMap.put("hasLatitude", new String[]{"51.243455"}); //// hMap.put("hasGlobalLocation", "http://www.geonames.org/2647793/"); //// hMap.put("hasResourceID", "Resource_53_BA_power_sensor"); //// hMap.put("hasLocalLocation", "http://www.surrey.ac.uk/ccsr/ontologies/LocationModel.owl#U49"); // hMap.put("hasAltitude", new String[]{""}); // hMap.put("hasLongitude", new String[]{"-0.588088"}); //// hMap.put("hasTimeOffset", "20"); // // //ri.ONT_URL = "http://www.surrey.ac.uk/ccsr/ontologies/ServiceModel.owl#"; // //ri.ONT_URL = "http://www.surrey.ac.uk/ccsr/ontologies/VirtualEntityModel.owl#"; // //ri.ONT_FILE = "web/IoTA-Models/VirtualEntityModel.owl"; // ri.createJenaModel(hMap); }
From source file:org.jaqpot.core.model.Report.java
public static void main(String[] args) throws JsonProcessingException { Report report = new Report(); LinkedHashMap<String, Object> single = new LinkedHashMap<>(); single.put("calculation1", 325.15); single.put("calculation2", "A"); single.put("calculation3", "whatever"); single.put("calculation4", 15); LinkedHashMap<String, ArrayCalculation> arrays = new LinkedHashMap<>(); ArrayCalculation a1 = new ArrayCalculation(); a1.setColNames(Arrays.asList("column A", "column B", "column C")); LinkedHashMap<String, List<Object>> v1 = new LinkedHashMap<>(); v1.put("row1", Arrays.asList(5.0, 1, 30)); v1.put("row2", Arrays.asList(6.0, 12, 34)); v1.put("row3", Arrays.asList(7.0, 11, 301)); a1.setValues(v1);//from w w w .ja va 2 s . co m ArrayCalculation a2 = new ArrayCalculation(); a2.setColNames(Arrays.asList("column 1", "column 2", "column 3")); LinkedHashMap<String, List<Object>> v2 = new LinkedHashMap<>(); v2.put("row1", Arrays.asList(5.0, 1, 30)); v2.put("row2", Arrays.asList(6.0, 12, 34)); v2.put("row3", Arrays.asList(7.0, 11, 301)); a2.setValues(v2); arrays.put("calculation 5", a1); arrays.put("calcluation 6", a2); LinkedHashMap<String, String> figures = new LinkedHashMap<>(); figures.put("figure1", "fa9ifj2ifjaspldkfjapwodfjaspoifjaspdofijaf283jfo2iefj"); figures.put("figure2", "1okwejf-o2eifj-2fij2e-fijeflksdjfksdjfpskdfjspdokfjsdpf"); report.setSingleCalculations(single); report.setArrayCalculations(arrays); report.setFigures(figures); ObjectMapper mapper = new ObjectMapper(); String reportString = mapper.writeValueAsString(report); System.out.println(reportString); }