List of usage examples for com.fasterxml.jackson.databind ObjectMapper ObjectMapper
public ObjectMapper()
From source file:se.carlengstrom.internetonastick.samples.irc.IrcBot.java
public static void main(final String[] args) throws IOException, IrcException { if (args.length != 1) { System.out.println("Usage: java -jar internet-on-a-stick.jar <configfile>"); System.exit(0);//w w w . j a va 2s .c om } final ObjectMapper mapper = new ObjectMapper().registerModule(new AutoMatterModule()); final IrcConfig config = mapper.readValue(new File(args[0]), IrcConfig.class); final Configuration configuration = new Configuration.Builder().setName(config.name()) .setRealName(config.realname()).addServer(config.server(), config.port()) .setSocketFactory(new UtilSSLSocketFactory().trustAllCertificates()) .addAutoJoinChannels(config.autoJoinChannels()).addListener(new IrcBot(config)) .buildConfiguration(); //Create our bot with the configuration final PircBotX bot = new PircBotX(configuration); //Connect to the server bot.startBot(); }
From source file:com.sociesc.findasmartphonespark.Main.java
public static void main(String[] args) { String apiPrefix = "api/v1/"; //setIpAddress("192.168.56.1"); setPort(9010);// w ww . j a va 2 s . c o m try { Logger.getLogger(Main.class.getName()).log(Level.INFO, "Criando banco de dados"); DatabaseUtils.seedDatabase(); } catch (SQLException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } Dao<User> userDao = new Dao(User.class); get(apiPrefix + "/hello/:name", (request, response) -> { ObjectMapper objectMapper = new ObjectMapper(); /*ArrayList<AccessPoint> arrayAp = new ArrayList<AccessPoint>(); for (int i = 0; i < 10; i++) { AccessPoint ap = new AccessPoint(); ap.setBSSID("AP" + i); ap.setSSID("00:00:00:0" + i); ap.setRSSI(-50 + i); ap.setSala("Sala" + i); arrayAp.add(ap); //System.out.println("Nome: " + ap.getBSSID() + " - Mac: " + ap.getSSID() + " - Sinal: " + ap.getRSSI()); } String retornoJson = rwJson.writeJson(arrayAp);*/ //objectMapper.readValue(URLDecoder.decode(request.params(":name"), "UTF-8"), new TypeReference(String("lol"))); ArrayList<AccessPoint> arrayAp = null; try { arrayAp = rwJson.readJson(URLDecoder.decode(request.params(":name"), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return arrayAp.get(0).getBSSID(); //return "Hello: " + request.params(":name"); //return arrayAp[0].get; }); post(apiPrefix + "/findUser/:data", (request, response) -> { String userId = request.params(":data"); ArrayList<AccessPoint> aps = rwJson.readJson(userId.toString()); /*JsonObject json = new JsonObject(); try { json = JsonObject.readFrom(request.params(":data")); } catch (Exception ex) { System.out.println("erro no json:\n" + ex.getMessage()); Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); json.add("error", ex.getMessage()); response.status(500); }*/ try { for (int i = 0; i < aps.size(); i++) { System.out.println("Nome: " + aps.get(i).getBSSID() + " - Mac: " + aps.get(i).getSSID() + " - Sinal: " + aps.get(i).getRSSI() + " - Sala: " + aps.get(i).getSala()); } } catch (Exception ex) { System.out.println("erro no json:\n" + ex.getMessage()); Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); //json.add("error", ex.getMessage()); response.status(500); return ex.getMessage(); } return userId.toString(); }); /*post(apiPrefix + "/findUser/", (request, response) ->{ JsonObject json = new JsonObject(); // Informaes do roteador/AP String[] BSSID; // basic service set identifier - nome da conexo String[] SSID; // service set identifier - identificador nico da conexo int[] RSSI; // received signal strength indicator - potencia do sinal (-87 a -32) String sala; String jsonBody = request.body(); JsonObject reqJson = JsonObject.readFrom(jsonBody); JsonObject wifiJson = reqJson.get("wifi").asObject(); System.out.println("reqJson.size()" + reqJson.size() + "\nwifiJson.size()" + wifiJson.size()); RSSI = new int[wifiJson.size()]; BSSID = new String[wifiJson.size()]; SSID = new String[wifiJson.size()]; try{ for (int i = 0; i < wifiJson.size(); i++) { // recebe informaes das conexes encontradas BSSID[i] = wifiJson.get("BSSID").asString(); SSID[i] = wifiJson.get("SSID").asString(); RSSI[i] = wifiJson.get("RSSI").asInt(); } return json.toString(); }catch(Exception ex){ System.out.println("erro no json:\n" + ex.getMessage()); Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); json.add("error", ex.getMessage()); response.status(500); } return json.toString(); });*/ get(apiPrefix + "/users", (request, response) -> { JsonObject json = new JsonObject(); request.params(); try { List<User> users = userDao.findAll(); JsonArray usersJson = new JsonArray(); for (User u : users) { JsonObject uJson = new JsonObject(); uJson.add("id", u.getId()); uJson.add("name", u.getName()); uJson.add("email", u.getEmail()); usersJson.add(uJson); } json.add("users", usersJson); } catch (SQLException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); json.add("error", ex.getMessage()); response.status(500); } return json.toString(); }); /*get(apiPrefix + "/users/:id", (request, response) -> { Long userId = Long.parseLong(request.params(":id")); JsonObject json = new JsonObject(); try{ User user = userDao.findById(userId); if(user == null){ json.add("error", "user not found"); response.status(404); return json.toString(); } JsonObject userJson = new JsonObject(); userJson.add("id", user.getId()); userJson.add("name", user.getName()); userJson.add("email", user.getEmail()); json.add("user", userJson); return json.toString(); }catch(Exception ex){ Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); json.add("error", ex.getMessage()); response.status(500); } return json.toString(); });*/ delete(apiPrefix + "/users/:id", (request, response) -> { Long userId = Long.parseLong(request.params(":id")); JsonObject json = new JsonObject(); try { userDao.removeById(userId); json.add("message", "user removed"); response.status(200); return json.toString(); } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); json.add("error", ex.getMessage()); response.status(500); } return json.toString(); }); put(apiPrefix + "/users/:id", (request, response) -> { Long userId = Long.parseLong(request.params(":id")); JsonObject json = new JsonObject(); try { String jsonBody = request.body(); JsonObject reqJson = JsonObject.readFrom(jsonBody); JsonObject userJson = reqJson.get("user").asObject(); String name = userJson.get("name") != null ? userJson.get("name").asString() : null; String email = userJson.get("email") != null ? userJson.get("email").asString() : null; String password = userJson.get("password") != null ? userJson.get("password").asString() : null; User user = userDao.findById(userId); if (name != null) user.setName(name); if (email != null) user.setEmail(email); if (password != null) { String passwordDigest = DatabaseUtils.criptPass(password); user.setPasswordDigest(passwordDigest); } userDao.update(user); JsonObject resUserJson = new JsonObject(); resUserJson.add("id", user.getId()); resUserJson.add("name", user.getName()); resUserJson.add("email", user.getEmail()); json.add("user", resUserJson); return json.toString(); } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); json.add("error", ex.getMessage()); response.status(500); } return json.toString(); }); post(apiPrefix + "/users", (request, response) -> { JsonObject json = new JsonObject(); try { String jsonBody = request.body(); JsonObject reqJson = JsonObject.readFrom(jsonBody); JsonObject userJson = reqJson.get("user").asObject(); User user = new User(); user.setName(userJson.get("name").asString()); user.setEmail(userJson.get("email").asString()); user.setPasswordDigest(DatabaseUtils.criptPass("tempPass")); userDao.create(user); JsonObject resUserJson = new JsonObject(); resUserJson.add("id", user.getId()); resUserJson.add("name", user.getName()); resUserJson.add("email", user.getEmail()); resUserJson.add("passwordDigest", user.getPasswordDigest()); json.add("user", resUserJson); return json.toString(); } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); json.add("error", ex.getMessage()); response.status(500); } return json.toString(); }); }
From source file:fr.cvlaminck.merging.samples.contacts.Application.java
public static void main(String[] args) throws IOException { final ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true); objectMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); /**// w w w . j a v a 2s .c o m * The first entry only contains mailing address. */ final Contact entry1 = new Contact("John", "Doe", "777. Rainbow road", "777", "City"); System.out.println("/*-----------------------------------------*/"); System.out.println("/* Entry : John Doe */"); System.out.println("/*-----------------------------------------*/"); objectMapper.writeValue(System.out, entry1); System.out.println(); System.out.println(); /** * The second entry considered as duplicate contains some phone numbers * for the contact */ final Contact entry2 = new Contact("John", "Doe", "+33777777777"); System.out.println("/*-----------------------------------------*/"); System.out.println("/* Duplicated : John Doe */"); System.out.println("/*-----------------------------------------*/"); objectMapper.writeValue(System.out, entry2); System.out.println(); System.out.println(); /** * Before doing any merge operation, we need to configure the merging library. * To configure the library, you need to instantiate a ValueMergers. * The ValuesMergers is a collection ValueMerger. This collection defines which * type of field can be merged by the library and which merging strategy can be * used for this type of field. * * For the sample, we uses a PreConfiguredValueMergers that contains all ValueMerger * implemented in the core library. There is other implementation of ValueMergers that * you can use in your application. */ ValueMergers valueMergers = new DefaultValueMergers(); //TODO valueMergers.registerValueMerger(new UseRightIfLeftIsNullObjectValueMerger()); valueMergers.registerValueMerger(new AddInRightCollectionValueMerger()); /** * Then we instantiate the core element of the library. * The ObjectMerger is the object that will allow you to merge your objects. */ ObjectMerger objectMerger = new DefaultObjectMerger(valueMergers); /** * The last step before merging two objects together is to create an ObjectMergingStrategy. * This defines which merging strategy must be used to merge values contained in a field. * * For this sample, we will use MutableObjectMergingStrategy implementation that allow you to define * the strategy at runtime. */ MutableObjectMergingStrategy objectMergingStrategy = new MutableObjectMergingStrategy(Contact.class); objectMergingStrategy.setDefaultStrategyForType(Object.class, MergingStrategies.useRightIfLeftIsNull); objectMergingStrategy.setDefaultStrategyForType(Collection.class, MergingStrategies.addInRightCollection); /** * Finally, we merge both objects and take a look at the result. */ final Contact result = objectMerger.merge(entry1, entry2, objectMergingStrategy); System.out.println("/*-----------------------------------------*/"); System.out.println("/* Merged : John Doe */"); System.out.println("/*-----------------------------------------*/"); objectMapper.writeValue(System.out, result); }
From source file:ch.rasc.wampspring.demo.client.CallClientSockJs.java
public static void main(String[] args) throws InterruptedException { List<Transport> transports = new ArrayList<>(2); transports.add(new WebSocketTransport(new StandardWebSocketClient())); transports.add(new RestTemplateXhrTransport()); WebSocketClient webSocketClient = new SockJsClient(transports); JsonFactory jsonFactory = new MappingJsonFactory(new ObjectMapper()); CountDownLatch latch = new CountDownLatch(10_000); TestTextWebSocketHandler handler = new TestTextWebSocketHandler(jsonFactory, latch); Long[] start = new Long[1]; ListenableFuture<WebSocketSession> future = webSocketClient.doHandshake(handler, "ws://localhost:8080/wampOverSockJS"); future.addCallback(wss -> {// w ww.j a v a 2s . co m start[0] = System.currentTimeMillis(); for (int i = 0; i < 10_000; i++) { CallMessage callMessage = new CallMessage(UUID.randomUUID().toString(), "testService.sum", i, i + 1); try { wss.sendMessage(new TextMessage(callMessage.toJson(jsonFactory))); } catch (Exception e) { System.out.println("ERROR SENDING CALLMESSAGE" + e); latch.countDown(); } } }, t -> { System.out.println("DO HANDSHAKE ERROR: " + t); System.exit(1); }); if (!latch.await(3, TimeUnit.MINUTES)) { System.out.println("SOMETHING WENT WRONG"); } System.out.println((System.currentTimeMillis() - start[0]) / 1000 + " seconds"); System.out.println("SUCCESS: " + handler.getSuccess()); System.out.println("ERROR : " + handler.getError()); }
From source file:MondrianService.java
public static void main(String[] arg) { System.out.println("Starting Mondrian Connector for Infoveave"); Properties prop = new Properties(); InputStream input = null;//w ww . j ava 2 s . co m int listenPort = 9998; int threads = 100; try { System.out.println("Staring from :" + getSettingsPath()); input = new FileInputStream(getSettingsPath() + File.separator + "MondrianService.properties"); prop.load(input); listenPort = Integer.parseInt(prop.getProperty("port")); threads = Integer.parseInt(prop.getProperty("maxThreads")); if (input != null) { input.close(); } System.out.println("Found MondrianService.Properties"); } catch (FileNotFoundException e) { } catch (IOException e) { } port(listenPort); threadPool(threads); enableCORS("*", "*", "*"); ObjectMapper mapper = new ObjectMapper(); MondrianConnector connector = new MondrianConnector(); get("/ping", (request, response) -> { response.type("application/json"); return "\"Here\""; }); post("/cubes", (request, response) -> { response.type("application/json"); try { Query queryObject = mapper.readValue(request.body(), Query.class); response.status(200); return mapper.writeValueAsString(connector.GetCubes(queryObject)); } catch (JsonParseException ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } catch (Exception ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } }); post("/measures", (request, response) -> { response.type("application/json"); try { Query queryObject = mapper.readValue(request.body(), Query.class); response.status(200); return mapper.writeValueAsString(connector.GetMeasures(queryObject)); } catch (JsonParseException ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } catch (Exception ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } }); post("/dimensions", (request, response) -> { response.type("application/json"); try { Query queryObject = mapper.readValue(request.body(), Query.class); response.status(200); return mapper.writeValueAsString(connector.GetDimensions(queryObject)); } catch (JsonParseException ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } catch (Exception ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } }); post("/cleanCache", (request, response) -> { response.type("application/json"); try { Query queryObject = mapper.readValue(request.body(), Query.class); response.status(200); return mapper.writeValueAsString(connector.CleanCubeCache(queryObject)); } catch (JsonParseException ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } catch (Exception ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } }); post("/executeQuery", (request, response) -> { response.type("application/json"); try { Query queryObject = mapper.readValue(request.body(), Query.class); response.status(200); String content = mapper.writeValueAsString(connector.ExecuteQuery2(queryObject)); return content; } catch (JsonParseException ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } catch (Exception ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } }); }
From source file:com.nextdoor.bender.CreateSchema.java
public static void main(String[] args) throws ParseException, InterruptedException, IOException { /*/*from w w w . j av a 2s.com*/ * Parse cli arguments */ Options options = new Options(); options.addOption(Option.builder().longOpt("out-file").hasArg() .desc("Filename to output schema to. Default: schema.json").build()); options.addOption(Option.builder().longOpt("docson").hasArg(false) .desc("Create a schema that is able to be read by docson").build()); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); String filename = cmd.getOptionValue("out-file", "schema.json"); /* * Write schema */ BenderSchema schema = new BenderSchema(); ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); JsonNode node = schema.getSchema(); if (cmd.hasOption("docson")) { modifyNode(node); } mapper.writeValue(new File(filename), node); }
From source file:test.jackson.JacksonNsgiDiscover.java
public static void main(String[] args) throws IOException { ObjectMapper objectMapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); String ngsiRcr = new String(Files.readAllBytes(Paths.get(NGSI_FILE))); DiscoveryContextAvailabilityRequest dcar = objectMapper.readValue(ngsiRcr, DiscoveryContextAvailabilityRequest.class); // System.out.println(objectMapper.writeValueAsString(dcar)); System.out.println(dcar.getRestriction().getOperationScope().get(1).getScopeValue()); LinkedHashMap shapeHMap = (LinkedHashMap) dcar.getRestriction().getOperationScope().get(1).getScopeValue(); // Association assocObject = objectMapper.convertValue(shapeHMap, Association.class); // System.out.println(assocObject.getAttributeAssociation().get(0).getSourceAttribute()); Shape shape = objectMapper.convertValue(shapeHMap, Shape.class); System.out.println("Deserialized Class: " + shape.getClass().getSimpleName()); System.out.println("VALUE: " + shape.getPolygon().getVertices().get(2).getLatitude()); System.out.println("VALUE: " + shape.getCircle()); if (!(shape.getCircle() == null)) System.out.println("This is null"); Polygon polygon = shape.getPolygon(); int vertexSize = polygon.getVertices().size(); Coordinate[] coords = new Coordinate[vertexSize]; final ArrayList<Coordinate> points = new ArrayList<>(); for (int i = 0; i < vertexSize; i++) { Vertex vertex = polygon.getVertices().get(i); points.add(new Coordinate(Double.valueOf(vertex.getLatitude()), Double.valueOf(vertex.getLongitude()))); coords[i] = new Coordinate(Double.valueOf(vertex.getLatitude()), Double.valueOf(vertex.getLongitude())); }/*from www. j ava2 s . c o m*/ points.add(new Coordinate(Double.valueOf(polygon.getVertices().get(0).getLatitude()), Double.valueOf(polygon.getVertices().get(0).getLongitude()))); final GeometryFactory gf = new GeometryFactory(); final Coordinate target = new Coordinate(49, -0.6); final Point point = gf.createPoint(target); Geometry shapeGm = gf.createPolygon( new LinearRing(new CoordinateArraySequence(points.toArray(new Coordinate[points.size()])), gf), null); // Geometry shapeGm = gf.createPolygon(coords); System.out.println(point.within(shapeGm)); // System.out.println(rcr.getContextRegistration().get(0).getContextMetadata().get(0).getValue().getClass().getCanonicalName()); // String assocJson = objectMapper.writeValueAsString(association); // Value assocObject = objectMapper.readValue(objectMapper.writeValueAsString(association), Value.class); // System.out.println(association.values().toString()); // System.out.println(assocJson); }
From source file:de.hbz.lobid.helper.CompareJsonMaps.java
public static void main(String... args) { if (args.length < 2) CompareJsonMaps.logger/*from ww w . j av a 2 s. c o m*/ .info("Usage: <filename1> <filename2> {<false> if @context should be taken into acount}"); filename1 = args[0]; filename2 = args[1]; CompareJsonMaps.logger.info("\n" + filename1 + " may be referenced in the logs as 'actual'\n" + filename2 + " may be referenced as 'expected'"); if (args.length >= 3 && args[2].equals("false")) IGNORE_CONTEXT = false; try { if (new CompareJsonMaps().writeFileAndTestJson( new ObjectMapper().readValue(new File(args[0]), JsonNode.class), new ObjectMapper().readValue(new File(args[1]), JsonNode.class))) CompareJsonMaps.logger.info("OK. The content is equal."); else CompareJsonMaps.logger.info("Sadeness. The content differs."); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.cjwagner.InfoSecPriv.ExtensionServer.java
public static void main(String[] args) { initializeLogStore();/* w w w . jav a 2 s . c o m*/ get("/data", (request, response) -> { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.MINUTE, -5); Date tMinusDelta = cal.getTime(); Map<String, LoggerMessage> filtered = new HashMap<String, LoggerMessage>(); for (Map.Entry<String, LoggerMessage> entry : logStore.entrySet()) { String ip = entry.getKey(); LoggerMessage logmess = entry.getValue(); LoggerMessage logmessFiltered = new LoggerMessage(); logmessFiltered.setFirstLogTime(logmess.getFirstLogTime()); List<LogData> filteredData = new ArrayList<LogData>(); logmessFiltered.setLogs(filteredData); for (LogData data : logmess.getLogs()) { if (data.getDate().after(tMinusDelta)) { filteredData.add(data); } } filtered.put(ip, logmessFiltered); } ObjectMapper objMapper = new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true); String jsonResponse = objMapper.writeValueAsString(filtered); System.out.println("Responded to query for recent data from IP: " + request.ip()); return jsonResponse; }); post("/LicenseRegistry", (request, response) -> { if (storeSize >= MAXSTORESIZE) { response.status(507);//insufficient storage return "Server storage full!"; } String ip = request.ip().replace(':', '_'); String json = request.body(); try { LoggerMessage logMess = LoggerMessage.fromJSON(json); logMess.setFirstLogTime(new Date()); LoggerMessage rec = logStore.get(ip); if (rec == null) { logStore.put(ip, logMess); rec = logMess; } else { rec.getLogs().addAll(logMess.getLogs()); } updateLogFile(ip, rec); storeSize += logMess.getLogs().size(); response.status(200); System.out.println("Recieved log data from IP: " + ip); return "LicenseKey:<c706cfe7-b748-4d75-98b5-c6b32ab789cb>"; } catch (JsonParseException jpe) { response.status(HTTP_BAD_REQUEST); System.out.println("Failed to parse log data from IP: " + ip); return jpe.getMessage(); } }); }
From source file:carmen.demo.LocationResolverDemo.java
public static void main(String[] args) throws ParseException, FileNotFoundException, IOException, ClassNotFoundException { // Parse the command line. String[] manditory_args = { "input_file" }; createCommandLineOptions();/*from www . j ava 2 s . c o m*/ CommandLineUtilities.initCommandLineParameters(args, LocationResolverDemo.options, manditory_args); // Get options String inputFile = CommandLineUtilities.getOptionValue("input_file"); String outputFile = null; if (CommandLineUtilities.hasArg("output_file")) { outputFile = CommandLineUtilities.getOptionValue("output_file"); } logger.info("Creating LocationResolver."); LocationResolver resolver = LocationResolver.getLocationResolver(); Scanner scanner = Utils.createScanner(inputFile); Writer writer = null; if (outputFile != null) { writer = Utils.createWriter(outputFile); logger.info("Saving geolocated tweets to: " + outputFile); } ObjectMapper mapper = new ObjectMapper(); int numResolved = 0; int total = 0; while (scanner.hasNextLine()) { String line = scanner.nextLine(); @SuppressWarnings("unchecked") HashMap<String, Object> tweet = (HashMap<String, Object>) mapper.readValue(line, Map.class); total++; Location location = resolver.resolveLocationFromTweet(tweet); if (location != null) { logger.debug("Found location: " + location.toString()); numResolved++; } if (writer != null) { if (location != null) { tweet.put("location", Location.createJsonFromLocation(location)); } mapper.writeValue(writer, tweet); writer.write("\n"); } } scanner.close(); if (writer != null) writer.close(); logger.info("Resolved locations for " + numResolved + " of " + total + " tweets."); }