List of usage examples for com.fasterxml.jackson.databind ObjectMapper ObjectMapper
public ObjectMapper()
From source file:com.metamx.datatypes.ExampleWriteNewLineJson.java
public static void main(String[] args) throws Exception { final MmxAuctionSummary sampleAuction1 = MmxAuctionSummary.builder() .timestamp(new DateTime("2014-01-01T00:00:00.000Z")).auctionType(2).build(); final MmxAuctionSummary sampleAuction2 = MmxAuctionSummary.builder() .timestamp(new DateTime("2014-01-01T01:00:00.000Z")).auctionType(1).build(); List<MmxAuctionSummary> auctionList = Arrays.asList(sampleAuction1, sampleAuction2); final String separator = "\n"; final ObjectMapper objectMapper = new ObjectMapper(); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); final OutputStream outStream = new ByteArrayOutputStream(); for (MmxAuctionSummary auction : auctionList) { outStream.write(objectMapper.writeValueAsBytes(auction)); outStream.write(separator.getBytes()); }/*from ww w . ja va 2 s . c o m*/ System.out.println(outStream.toString()); }
From source file:rpex.hadoop.Main.java
public static void main(String... args) throws Exception { LOGGER.debug("STARTING..."); ObjectMapper objectMapper = new ObjectMapper(); RatpackServer/* w w w .j a va 2 s .co m*/ .start(spec -> spec .serverConfig(builder -> builder.baseDir(BaseDir.find("application.properties")) .props(Main.class.getClassLoader().getResource("application.properties")).env() .sysProps().require("/hadoop", MapReduceConfig.class)) .registry(Guice.registry(bindingsSpec -> { bindingsSpec.bindInstance(ResponseTimer.decorator()).module(MapReduceModule.class, config -> config .copyOf(bindingsSpec.getServerConfig().get(MapReduceConfig.class))); Jackson.Init.register(bindingsSpec, objectMapper, objectMapper.writerWithDefaultPrettyPrinter()); })).handlers(chain -> chain.all(new Handler() { @Override public void handle(Context ctx) throws Exception { MDC.put("clientIP", ctx.getRequest().getRemoteAddress().getHostText()); RequestId.Generator generator = ctx.maybeGet(RequestId.Generator.class) .orElse(UuidBasedRequestIdGenerator.INSTANCE); RequestId requestId = generator.generate(ctx); ctx.getRequest().add(RequestId.class, requestId); MDC.put("requestId", requestId.getId()); LOGGER.debug("ALL CALLED"); ctx.next(); } }).prefix("v1", chain1 -> chain1.get("api-def", ctx -> { LOGGER.debug("GET API_DEF.JSON"); ctx.render(ctx.file("public/apidef/api-def.json")); }).prefix("mr", MapReduceEndpoints.class)))); }
From source file:com.metamx.datatypes.ExampleMain.java
public static void main(String[] args) throws Exception { final ObjectMapper objectMapper = new ObjectMapper(); final MmxAuctionSummary auctionSummary = MmxAuctionSummary.builder() .timestamp(new DateTime("2014-01-01T00:00:00.000Z")).auctionType(2) .bcat(Arrays.asList("IAB26", "IAB25")).requestId("AFEWSEBD5EB5FI32DASFCD452BB78DVE") .ext(Ext.builder().put("custFlag", 3).put("custStr", "Unicorns are the best!").build()) .app(App.builder().bundle("bundlename").cat(Arrays.asList("IAB1")).domain("unicornssay.com") .id("12312312").name("Unicornssay") .publisher(Publisher.builder().id("DSA1394D42D3").name("Unicornssay").build()).build()) .site(Site.builder().cat(Arrays.asList("IAB1", "IAB2")).domain("unicornssay.com").id("1345135123") .name("Unicornssay") .publisher(Publisher.builder().id("pub12345").name("Publisher A").build()).build()) .impressions(Arrays.asList(Imp.builder().tagId("231").bidFloor(0.1).secure(0) .banner(Banner.builder().height(320).width(50).pos(3).api(Arrays.asList(3, 4)).build()) .displayManager("MyRenderer").displayManagerVer("v2").build())) .device(Device.builder().carrier("Verizon").connectionType(2).deviceType(1).didmd5("AA003") .didsha1("AA023").dnt(0).dpidmd5("A400FABFB5").dpidsha1("AA0").flashVer("2.1").ifa("123") .ip("192.168.1.8").jsSupport(1).language("en").macsha1("E50BB11").macmd5("BB11") .make("Apple").model("iPhone 3GS").osVer("4.2.1").os("iOS").ua("Crazy UA String!") .geo(Geo.builder().city("US-SFO").country("USA").lat(37.790148).lon(-122.434103) .metro("807").region("CA").type(1).zip("94107").build()) .ext(Ext.builder().put("customField", "sam").build()).build()) .user(User.builder().id("456789876567897654678987656789").yob(1987).gender("M") .data(Arrays.asList(Data.builder().id("123").name("bluesky") .segment(Arrays .asList(Segment.builder().id("abc1").name("gender").value("male").build())) .build()))//from w w w.j a v a2 s . c o m .build()) .responses(Arrays.asList(MmxBidResponse.builder() .timestamp(new DateTime("2014-03-05T04:58:23.200Z")).status(1).totalDuration(43L) .bidderId("1921").bidderName("RealAds").cur("USD") .seatBid(Arrays.asList(MmxSeatBid.builder().seat("512") .bid(Arrays.asList(MmxBid.builder().id("1").impId("102").status(1).price(5.43) .clearPrice(1.1).adId("314").attr(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 12)) .crId("1234").cId("229").adomain(Arrays.asList("realtime4real.mmx.org")) .iUrl("http://adserver.com/pathtosampleimage").build())) .build())) .build())) .build(); System.out.println(objectMapper.writeValueAsString(auctionSummary)); }
From source file:com.vethrfolnir.TestJsonAfterUnmarshal.java
public static void main(String[] args) throws Exception { ArrayList<TestThing> tsts = new ArrayList<>(); for (int i = 0; i < 21; i++) { final int nr = i; tsts.add(new TestThing() { {//from w ww.ja v a2 s . co m id = 1028 * nr + 256; name = "Name-" + nr; } }); } ObjectMapper mp = new ObjectMapper(); mp.setVisibilityChecker(mp.getDeserializationConfig().getDefaultVisibilityChecker() .withCreatorVisibility(JsonAutoDetect.Visibility.NONE) .withFieldVisibility(JsonAutoDetect.Visibility.ANY) .withGetterVisibility(JsonAutoDetect.Visibility.NONE) .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE) .withSetterVisibility(JsonAutoDetect.Visibility.NONE)); mp.configure(SerializationFeature.INDENT_OUTPUT, true); ByteArrayOutputStream br = new ByteArrayOutputStream(); mp.writeValue(System.err, tsts); mp.writeValue(br, tsts); ByteArrayInputStream in = new ByteArrayInputStream(br.toByteArray()); tsts = mp.readValue(in, new TypeReference<ArrayList<TestThing>>() { }); System.err.println(); System.out.println("Got: " + tsts); }
From source file:org.hcmut.emr.SessionBuilder.java
public static void main(String[] args) throws FileNotFoundException, IOException { try (BufferedReader br = new BufferedReader( new FileReader("/home/sinhlk/myspace/emr/src/main/resources/patern"))) { ObjectMapper jsonMapper = new ObjectMapper(); String line = br.readLine(); Map<String, String> result = new HashMap<String, String>(); List<NameValuePair> list = new ArrayList<>(); while (line != null) { if (line != null && line != "") { list.add(new BasicNameValuePair(line.trim().toLowerCase(), SessionBuilder.buildValue(line))); result.put(line.trim().toLowerCase(), SessionBuilder.buildValue(line)); line = br.readLine();/*w w w . jav a 2s .c om*/ } } System.out.println(jsonMapper.writeValueAsString(list)); File file = new File("/home/sinhlk/myspace/emr/src/main/resources/session.js"); jsonMapper.writeValue(file, list); } }
From source file:ch.rasc.wampspring.demo.client.Publisher.java
public static void main(String[] args) throws InterruptedException { WebSocketClient webSocketClient = new StandardWebSocketClient(); final JsonFactory jsonFactory = new MappingJsonFactory(new ObjectMapper()); final CountDownLatch welcomeLatch = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(1_000_000); TextWebSocketHandler handler = new TextWebSocketHandler() { @Override/*w w w . ja v a2 s. c o m*/ protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { WampMessage wampMessage = WampMessage.fromJson(jsonFactory, message.getPayload()); if (wampMessage instanceof WelcomeMessage) { latch.countDown(); } } }; Long[] start = new Long[1]; ListenableFuture<WebSocketSession> future = webSocketClient.doHandshake(handler, "ws://localhost:8080/wamp"); future.addCallback(wss -> { // Waiting for WELCOME message try { welcomeLatch.await(5, TimeUnit.SECONDS); start[0] = System.currentTimeMillis(); for (int i = 0; i < 1_000_000; i++) { PublishMessage publishMessage = new PublishMessage("/test/myqueue", i); try { wss.sendMessage(new TextMessage(publishMessage.toJson(jsonFactory))); } catch (Exception e) { System.out.println("ERROR SENDING PUBLISH_MESSAGE" + e); } latch.countDown(); } } catch (Exception e1) { System.out.println("SENDING PUBLISH MESSAGES: " + e1); } }, 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"); }
From source file:edu.teilar.jcrop.service.ApplicationTest2.java
public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); // model to return Map<String, Object> model = new HashMap<String, Object>(); // set up json mapper MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); ObjectMapper mapper = new ObjectMapper(); converter.setObjectMapper(mapper);// ww w .j a v a 2 s .c om List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>(); messageConverters.add(converter); restTemplate.setMessageConverters(messageConverters); String uri = "http://localhost:8080/jcrop-service/rest/learningobjects/{kobj}"; KObject kobj = restTemplate.getForObject(uri, KObject.class, "complex1"); System.out.println("Learning Object: " + kobj.getName()); System.out.println("Target Concept: " + kobj.getTargetEducationalObjective().getName()); ArrayList<Node> traverseArrayList = new ArrayList<Node>(); traverseKObject(kobj, traverseArrayList); System.out.println("sss" + traverseArrayList); }
From source file:lab.mage.rate.example.NewsServer.java
public static void main(String[] args) throws Exception { // configure resource final ResourceConfig resourceConfig = new ResourceConfig(); // set news service final NewsService newsService = new NewsService(); resourceConfig.register(newsService); // set Jackson as JSON provider final ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.setDateFormat(new SimpleDateFormat(ISO_8601_DATE_PATTERN)); final JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider(); provider.setMapper(mapper);//from ww w .j av a 2 s.c o m resourceConfig.register(provider); // create Grizzly instance and add handler final HttpHandler handler = ContainerFactory.createContainer(GrizzlyHttpContainer.class, resourceConfig); final URI uri = new URI("http://localhost:4711/"); final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(uri); final ServerConfiguration config = server.getServerConfiguration(); config.addHttpHandler(handler, "/api"); // start server.start(); System.in.read(); }
From source file:HelloSmartsheet.java
public static void main(String[] args) { HttpURLConnection connection = null; StringBuilder response = new StringBuilder(); //We are using Jackson JSON parser to deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome //Feel free to use which ever library you prefer. ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); try {/*w w w . ja v a 2s . c o m*/ System.out.println("STARTING HelloSmartsheet..."); //Create a BufferedReader to read user input. BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter Smartsheet API access token:"); String accessToken = in.readLine(); System.out.println("Fetching list of your sheets..."); //Create a connection and fetch the list of sheets connection = (HttpURLConnection) new URL(GET_SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; //Read the response line by line. while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); //Use Jackson to conver the JSON string to a List of Sheets List<Sheet> sheets = mapper.readValue(response.toString(), new TypeReference<List<Sheet>>() { }); if (sheets.size() == 0) { System.out.println("You don't have any sheets. Goodbye!"); return; } System.out.println("Total sheets: " + sheets.size()); int i = 1; for (Sheet sheet : sheets) { System.out.println(i++ + ": " + sheet.name); } System.out.print("Enter the number of the sheet you want to share: "); //Prompt the user to provide the sheet number, the email address, and the access level Integer sheetNumber = Integer.parseInt(in.readLine().trim()); //NOTE: for simplicity, error handling and input validation is neglected. Sheet chosenSheet = sheets.get(sheetNumber - 1); System.out.print("Enter an email address to share " + chosenSheet.getName() + " to: "); String email = in.readLine(); System.out.print("Choose an access level (VIEWER, EDITOR, EDITOR_SHARE, ADMIN) for " + email + ": "); String accessLevel = in.readLine(); //Create a share object Share share = new Share(); share.setEmail(email); share.setAccessLevel(accessLevel); System.out.println("Sharing " + chosenSheet.name + " to " + email + " as " + accessLevel + "."); //Create a connection. Note the SHARE_SHEET_URL uses /sheet as opposed to /sheets (with an 's') connection = (HttpURLConnection) new URL(SHARE_SHEET_URL.replace(SHEET_ID, "" + chosenSheet.getId())) .openConnection(); connection.setDoOutput(true); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); //Serialize the Share object writer.write(mapper.writeValueAsString(share)); writer.close(); //Read the response and parse the JSON reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } Result result = mapper.readValue(response.toString(), Result.class); System.out.println("Sheet shared successfully, share ID " + result.result.id); System.out.println("Press any key to quit."); in.read(); } catch (IOException e) { BufferedReader reader = new BufferedReader( new InputStreamReader(((HttpURLConnection) connection).getErrorStream())); String line; try { response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); Result result = mapper.readValue(response.toString(), Result.class); System.out.println(result.message); } catch (IOException e1) { e1.printStackTrace(); } } catch (Exception e) { System.out.println("Something broke: " + e.getMessage()); e.printStackTrace(); } }
From source file:AdminExample.java
public static void main(String[] args) { HttpURLConnection connection = null; StringBuilder response = new StringBuilder(); //We are using Jackson JSON parser to serialize and deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome //Feel free to use which ever library you prefer. ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String accessToken = "";//Insert your access token here. Note this must be from an account that is an Admin of an account. String user1Email = ""; //You need access to these two email account. String user2Email = ""; //Note Gmail and Hotmail allow email aliasing. //joe@gmail.com will get email sent to joe+user1@gmail.com try {//ww w . j av a 2 s. c om BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Adding user " + user1Email); //Add the users: User user = new User(); user.setEmail(user1Email); user.setAdmin(false); user.setLicensedSheetCreator(true); connection = (HttpURLConnection) new URL(USERS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), user); Result<User> newUser1Result = mapper.readValue(connection.getInputStream(), new TypeReference<Result<User>>() { }); System.out.println( "User " + newUser1Result.result.email + " added with userId " + newUser1Result.result.getId()); user = new User(); user.setEmail(user2Email); user.setAdmin(true); user.setLicensedSheetCreator(true); connection = (HttpURLConnection) new URL(USERS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), user); Result<User> newUser2Result = mapper.readValue(connection.getInputStream(), new TypeReference<Result<User>>() { }); System.out.println( "User " + newUser2Result.result.email + " added with userId " + newUser2Result.result.getId()); System.out.println("Please visit the email inbox for the users " + user1Email + " and " + user2Email + " and confirm membership to the account."); System.out.print("Press Enter to continue"); in.readLine(); //List all the users of the org connection = (HttpURLConnection) new URL(USERS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); List<User> users = mapper.readValue(connection.getInputStream(), new TypeReference<List<User>>() { }); System.out.println("The following are members of your account: "); for (User orgUser : users) { System.out.println("\t" + orgUser.getEmail()); } //Create a sheet as the admin Sheet newSheet = new Sheet(); newSheet.setName("Admin's Sheet"); newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null), new Column("Column 2", "TEXT_NUMBER", null, null, null), new Column("Column 3", "TEXT_NUMBER", null, null, null))); connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), newSheet); mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() { }); //Create a sheet as user1 newSheet = new Sheet(); newSheet.setName("User 1's Sheet"); newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null), new Column("Column 2", "TEXT_NUMBER", null, null, null), new Column("Column 3", "TEXT_NUMBER", null, null, null))); connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); //Here is where the magic happens - Any action performed in this call will be on behalf of the //user provided. Note that this person must be a confirmed member of your org. //Also note that the email address is url-encoded. connection.addRequestProperty("Assume-User", URLEncoder.encode(user1Email, "UTF-8")); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), newSheet); mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() { }); //Create a sheet as user2 newSheet = new Sheet(); newSheet.setName("User 2's Sheet"); newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null), new Column("Column 2", "TEXT_NUMBER", null, null, null), new Column("Column 3", "TEXT_NUMBER", null, null, null))); connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Assume-User", URLEncoder.encode(user2Email, "UTF-8")); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), newSheet); mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() { }); //List all the sheets in the org: System.out.println("The following sheets are owned by members of your account: "); connection = (HttpURLConnection) new URL(USERS_SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); List<Sheet> allSheets = mapper.readValue(connection.getInputStream(), new TypeReference<List<Sheet>>() { }); for (Sheet orgSheet : allSheets) { System.out.println("\t" + orgSheet.getName() + " - " + orgSheet.getOwner()); } //Now delete user1 and transfer their sheets to user2 connection = (HttpURLConnection) new URL(USER_URL.replace(ID, newUser1Result.getResult().getId() + "") + "?transferTo=" + newUser2Result.getResult().getId()).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Assume-User", URLEncoder.encode(user2Email, "UTF-8")); connection.addRequestProperty("Content-Type", "application/json"); connection.setRequestMethod("DELETE"); Result<Object> resultObject = mapper.readValue(connection.getInputStream(), new TypeReference<Result<Object>>() { }); System.out.println("Sheets transferred : " + resultObject.getSheetsTransferred()); } catch (IOException e) { InputStream is = connection == null ? null : ((HttpURLConnection) connection).getErrorStream(); if (is != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; try { response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); Result<?> result = mapper.readValue(response.toString(), Result.class); System.err.println(result.message); } catch (IOException e1) { e1.printStackTrace(); } } e.printStackTrace(); } catch (Exception e) { System.out.println("Something broke: " + e.getMessage()); e.printStackTrace(); } }