List of usage examples for com.fasterxml.jackson.databind ObjectMapper readTree
public JsonNode readTree(URL source) throws IOException, JsonProcessingException
From source file:org.apache.infra.reviewboard.ReviewBoard.java
public static void main(String... args) throws IOException { URL url = new URL(REVIEW_BOARD_URL); HttpHost host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); Executor executor = Executor.newInstance().auth(host, REVIEW_BOARD_USERNAME, REVIEW_BOARD_PASSWORD) .authPreemptive(host);/*from w w w . j a v a 2s . c o m*/ Request request = Request.Get(REVIEW_BOARD_URL + "/api/review-requests/"); Response response = executor.execute(request); request = Request.Get(REVIEW_BOARD_URL + "/api/review-requests/"); response = executor.execute(request); ObjectMapper mapper = new ObjectMapper(); JsonNode json = mapper.readTree(response.returnResponse().getEntity().getContent()); JsonFactory factory = new JsonFactory(); JsonGenerator generator = factory.createGenerator(new PrintWriter(System.out)); generator.setPrettyPrinter(new DefaultPrettyPrinter()); mapper.writeTree(generator, json); }
From source file:com.enitalk.controllers.youtube.CalendarTest.java
public static void main(String[] args) throws IOException { InputStream is = new ClassPathResource("events.json").getInputStream(); ObjectMapper jackson = new ObjectMapper(); JsonNode tree = jackson.readTree(is); IOUtils.closeQuietly(is);/*from w w w . ja va 2 s .c om*/ DateTimeFormatter fmtDateTime = ISODateTimeFormat.dateTimeNoMillis(); DateTimeFormatter fmt = ISODateTimeFormat.date(); TreeMultimap<DateTime, DateTime> set = CalendarTest.getPeriodSet(10, 18); Iterator<JsonNode> nodes = tree.elements(); while (nodes.hasNext()) { JsonNode ev = nodes.next(); boolean isFullDay = ev.path("start").has("date"); DateTime stDate = isFullDay ? fmt.parseDateTime(ev.path("start").path("date").asText()) : fmtDateTime.parseDateTime(ev.path("start").path("dateTime").asText()); DateTime enDate = isFullDay ? fmt.parseDateTime(ev.path("end").path("date").asText()) : fmtDateTime.parseDateTime(ev.path("end").path("dateTime").asText()); System.out.println("St " + stDate + " en " + enDate); int days = Days.daysBetween(stDate, enDate).getDays(); System.out.println("Days between " + days); if (isFullDay) { switch (days) { case 1: set.removeAll(stDate); break; default: while (days-- > 0) { set.removeAll(stDate.plusDays(days)); } } } else { DateTime copySt = stDate.minuteOfHour().setCopy(0).secondOfMinute().setCopy(0); DateTime copyEn = enDate.plusHours(1).minuteOfHour().setCopy(0).secondOfMinute().setCopy(0); // System.out.println("Dates truncated " + copySt + " " + copyEn); // System.out.println("Ll set " + set); // System.out.println("Getting set for key " + stDate.millisOfDay().setCopy(0)); SortedSet<DateTime> ss = set.get(stDate.millisOfDay().setCopy(0)); SortedSet<DateTime> subset = ss.subSet(copySt, copyEn); subset.clear(); set.remove(enDate.millisOfDay().setCopy(0), copyEn); } } }
From source file:org.apache.http.examples.client.ClientWithResponseHandler.java
public final static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); // DefaultHttpParams.getDefaultParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY); // httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); try {//from w w w. ja va 2 s . co m // HttpGet httpget = new HttpGet("http://localhost/"); HttpGet httpget = new HttpGet( "http://api.map.baidu.com/geocoder/v2/?address=&output=json&ak=E4805d16520de693a3fe707cdc962045&callback=showLocation"); // httpget.setHeader("Accept", "180.97.33.90:80"); httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); httpget.setHeader("Accept-Encoding", "gzip, deflate, sdch"); httpget.setHeader("Accept-Language", "zh-CN,zh;q=0.8"); httpget.setHeader("Cache-Control", "no-cache"); httpget.setHeader("Connection", "keep-alive"); httpget.setHeader("Referer", "http://developer.baidu.com/map/index.php?title=webapi/guide/changeposition"); httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36"); System.out.println("Executing request httpget.getRequestLine() " + httpget.getRequestLine()); // Create a custom response handler ResponseHandler<String> responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity, "utf-8") : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; String responseBody = httpclient.execute(httpget, responseHandler); System.out.println("----------------------------------------"); System.out.println(responseBody); //showLocation&&showLocation({"status":0,"result":{"location":{"lng":112.25009284837,"lat":32.229168591538},"precise":0,"confidence":14,"level":"\u533a\u53bf"}}) System.out.println("----------------------------------------"); ObjectMapper mapper = new ObjectMapper(); // mapper.readValue(responseBody, AddressCoord.class); JsonNode root = mapper.readTree( responseBody.substring("showLocation&&showLocation(".length(), responseBody.length() - 1)); // String name = root.get("name").asText(); // int age = root.get("age").asInt(); String status = root.get("status").asText(); String lng = root.with("result").with("location").get("lng").asText(); String lat = root.with("result").with("location").get("lat").asText(); String level = root.with("result").get("level").asText(); System.out.println(String.format("'%1$s': [%2$s, %3$s], status: %4$s", level, lng, lat, status)); } finally { httpclient.close(); } }
From source file:org.glowroot.benchmark.ResultFormatter.java
public static void main(String[] args) throws IOException { File resultFile = new File(args[0]); Scores scores = new Scores(); double baselineStartupTime = -1; double glowrootStartupTime = -1; ObjectMapper mapper = new ObjectMapper(); String content = Files.toString(resultFile, Charsets.UTF_8); content = content.replaceAll("\n", " "); ArrayNode results = (ArrayNode) mapper.readTree(content); for (JsonNode result : results) { String benchmark = result.get("benchmark").asText(); benchmark = benchmark.substring(0, benchmark.lastIndexOf('.')); ObjectNode primaryMetric = (ObjectNode) result.get("primaryMetric"); double score = primaryMetric.get("score").asDouble(); if (benchmark.equals(StartupBenchmark.class.getName())) { baselineStartupTime = score; continue; } else if (benchmark.equals(StartupWithGlowrootBenchmark.class.getName())) { glowrootStartupTime = score; continue; }// w ww . jav a 2 s .c o m ObjectNode scorePercentiles = (ObjectNode) primaryMetric.get("scorePercentiles"); double score50 = scorePercentiles.get("50.0").asDouble(); double score95 = scorePercentiles.get("95.0").asDouble(); double score99 = scorePercentiles.get("99.0").asDouble(); double score999 = scorePercentiles.get("99.9").asDouble(); double score9999 = scorePercentiles.get("99.99").asDouble(); double allocatedBytes = getAllocatedBytes(result); if (benchmark.equals(ServletBenchmark.class.getName())) { scores.baselineResponseTimeAvg = score; scores.baselineResponseTime50 = score50; scores.baselineResponseTime95 = score95; scores.baselineResponseTime99 = score99; scores.baselineResponseTime999 = score999; scores.baselineResponseTime9999 = score9999; scores.baselineAllocatedBytes = allocatedBytes; } else if (benchmark.equals(ServletWithGlowrootBenchmark.class.getName())) { scores.glowrootResponseTimeAvg = score; scores.glowrootResponseTime50 = score50; scores.glowrootResponseTime95 = score95; scores.glowrootResponseTime99 = score99; scores.glowrootResponseTime999 = score999; scores.glowrootResponseTime9999 = score9999; scores.glowrootAllocatedBytes = allocatedBytes; } else { throw new AssertionError(benchmark); } } System.out.println(); printScores(scores); if (baselineStartupTime != -1) { System.out.println("STARTUP"); System.out.format("%25s%14s%14s%n", "", "baseline", "glowroot"); printLine("Startup time (avg)", "ms", baselineStartupTime, glowrootStartupTime); } System.out.println(); }
From source file:software.uncharted.Reindex.java
public static void main(String[] args) throws IOException { // Get all images JsonNode response = HTTPUtil.getJSON("http://localhost:3030/images/all"); final ObjectMapper mapper = new ObjectMapper(); // Create a list of post requests List<JsonNode> indexRequestBodies = JSONUtil.getStringList(response, "files").stream() .map(file -> "http://localhost:3030/image/" + file).map(url -> "{\"url\":\"" + url + "\"}") .map(json -> {/* w w w .j ava2 s . c o m*/ try { return mapper.readTree(json); } catch (IOException e) { } return null; }).filter(Objects::nonNull).collect(Collectors.toList()); // Reindex each for (JsonNode body : indexRequestBodies) { System.out.println("Indexing " + body.get("url").asText()); HTTPUtil.post("http://localhost:8080/index", body); } }
From source file:nab.detectors.htmjava.HTMModel.java
/** * Launch htm.java NAB detector//w ww .j a v a2 s . c o m * * Usage: * As a standalone application (for debug purpose only): * * java -jar htm.java-nab.jar "{\"modelParams\":{....}}" < nab_data.csv > anomalies.out * * For complete list of command line options use: * * java -jar htm.java-nab.jar --help * * As a NAB detector (see 'htmjava_detector.py'): * * python run.py --detect --score --normalize -d htmjava * * Logging options, see "log4j.properties": * * - "LOGLEVEL": Controls log output (default: "OFF") * - "LOGGER": Either "CONSOLE" or "FILE" (default: "CONSOLE") * - "LOGFILE": Log file destination (default: "htmjava.log") * * For example: * * java -DLOGLEVEL=TRACE -DLOGGER=FILE -jar htm.java-nab.jar "{\"modelParams\":{....}}" < nab_data.csv > anomalies.out * */ @SuppressWarnings("resource") public static void main(String[] args) { try { LOGGER.trace("main({})", Arrays.asList(args)); // Parse command line args OptionParser parser = new OptionParser(); parser.nonOptions("OPF parameters object (JSON)"); parser.acceptsAll(Arrays.asList("p", "params"), "OPF parameters file (JSON).\n(default: first non-option argument)").withOptionalArg() .ofType(File.class); parser.acceptsAll(Arrays.asList("i", "input"), "Input data file (csv).\n(default: stdin)") .withOptionalArg().ofType(File.class); parser.acceptsAll(Arrays.asList("o", "output"), "Output results file (csv).\n(default: stdout)") .withOptionalArg().ofType(File.class); parser.acceptsAll(Arrays.asList("s", "skip"), "Header lines to skip").withOptionalArg() .ofType(Integer.class).defaultsTo(0); parser.acceptsAll(Arrays.asList("h", "?", "help"), "Help"); OptionSet options = parser.parse(args); if (args.length == 0 || options.has("h")) { parser.printHelpOn(System.out); return; } // Get in/out files final PrintStream output; final InputStream input; if (options.has("i")) { input = new FileInputStream((File) options.valueOf("i")); } else { input = System.in; } if (options.has("o")) { output = new PrintStream((File) options.valueOf("o")); } else { output = System.out; } // Parse OPF Model Parameters JsonNode params; ObjectMapper mapper = new ObjectMapper(); if (options.has("p")) { params = mapper.readTree((File) options.valueOf("p")); } else if (options.nonOptionArguments().isEmpty()) { try { input.close(); } catch (Exception ignore) { } if (options.has("o")) { try { output.flush(); output.close(); } catch (Exception ignore) { } } throw new IllegalArgumentException("Expecting OPF parameters. See 'help' for more information"); } else { params = mapper.readTree((String) options.nonOptionArguments().get(0)); } // Number of header lines to skip int skip = (int) options.valueOf("s"); // Force timezone to UTC DateTimeZone.setDefault(DateTimeZone.UTC); // Create NAB Network Model HTMModel model = new HTMModel(params); Network network = model.getNetwork(); network.observe().subscribe((inference) -> { double score = inference.getAnomalyScore(); int record = inference.getRecordNum(); LOGGER.trace("record = {}, score = {}", record, score); // Output raw anomaly score output.println(score); }, (error) -> { LOGGER.error("Error processing data", error); }, () -> { LOGGER.trace("Done processing data"); if (LOGGER.isDebugEnabled()) { model.showDebugInfo(); } }); network.start(); // Pipe data to network Publisher publisher = model.getPublisher(); BufferedReader in = new BufferedReader(new InputStreamReader(input)); String line; while ((line = in.readLine()) != null && line.trim().length() > 0) { // Skip header lines if (skip > 0) { skip--; continue; } publisher.onNext(line); } publisher.onComplete(); in.close(); LOGGER.trace("Done publishing data"); } catch (IOException e) { e.printStackTrace(); } }
From source file:json_cmp.Comparer.java
public static void main(String[] args) { System.out.println("Testing Begin"); try {/*from w w w . ja v a2s. c om*/ String accessLogFolder = "/Users/herizhao/workspace/accessLog/"; // String yqlFileName = "json_cmp/test1.log"; // String yqlpFileName = "json_cmp/test2.log"; String yqlFileName = "tempLog/0812_yql.res"; String yqlpFileName = "tempLog/0812_yqlp.res"; ReadResults input1 = new ReadResults(accessLogFolder + yqlFileName); ReadResults input2 = new ReadResults(accessLogFolder + yqlpFileName); Integer diffNum = 0; Integer errorCount = 0; Integer totalIDNum1 = 0; Integer totalIDNum2 = 0; Integer equalIDwithDuplicate = 0; Integer beacons = 0; Integer lineNum = 0; Integer tempCount = 0; HashMap<String, IDclass> IDarray = new HashMap<String, IDclass>(); FileOutputStream fos = new FileOutputStream( "/Users/herizhao/workspace/accessLog/json_cmp/cmp_result.txt"); OutputStreamWriter osw = new OutputStreamWriter(fos); BufferedWriter bw = new BufferedWriter(osw); FileOutputStream consoleStream = new FileOutputStream( "/Users/herizhao/workspace/accessLog/json_cmp/console"); OutputStreamWriter consoleOSW = new OutputStreamWriter(consoleStream); BufferedWriter console = new BufferedWriter(consoleOSW); while (true) { input1.ReadNextLine(); if (input1.line == null) break; input2.ReadNextLine(); if (input2.line == null) break; while (input1.line.equals("")) { lineNum++; input1.ReadNextLine(); input2.ReadNextLine(); } if (input2.line == null) break; if (input1.line == null) break; lineNum++; System.out.println("lineNum = " + lineNum); String str1 = input1.line; String str2 = input2.line; ObjectMapper mapper1 = new ObjectMapper(); ObjectMapper mapper2 = new ObjectMapper(); JsonNode root1 = mapper1.readTree(str1); JsonNode root2 = mapper2.readTree(str2); JsonNode mediaNode1 = root1.path("query").path("results").path("mediaObj"); JsonNode mediaNode2 = root2.path("query").path("results").path("mediaObj"); if (mediaNode2.isMissingNode() && !mediaNode1.isMissingNode()) tempCount += mediaNode1.size(); //For yqlp if (mediaNode2.isArray()) { totalIDNum2 += mediaNode2.size(); for (int i = 0; i < mediaNode2.size(); i++) { ObjectNode mediaObj = (ObjectNode) mediaNode2.get(i); mediaObj.put("yvap", ""); JsonNode streamsNode = mediaObj.path("streams"); //streams if (streamsNode.isArray()) { for (int j = 0; j < streamsNode.size(); j++) { ObjectNode streamsObj = (ObjectNode) streamsNode.get(j); changeStreamsPath(streamsObj); ChangedHost(streamsObj); //if(streamsObj.path("h264_profile").isMissingNode()) streamsObj.put("h264_profile", ""); if (streamsObj.path("is_primary").isMissingNode()) streamsObj.put("is_primary", false); } } //meta if (!mediaObj.path("meta").isMissingNode()) { ObjectNode metaObj = (ObjectNode) mediaObj.path("meta"); changeMetaThumbnail(metaObj); if (metaObj.path("show_name").isMissingNode()) metaObj.put("show_name", ""); if (metaObj.path("event_start").isMissingNode()) metaObj.put("event_start", ""); if (metaObj.path("event_stop").isMissingNode()) metaObj.put("event_stop", ""); //if(metaObj.path("credits").path("label").isMissingNode()) ((ObjectNode) metaObj.path("credits")).put("label", ""); } //Metrics -> plidl & isrc changeMetrics(mediaObj); } } //For yql if (mediaNode1.isArray()) { totalIDNum1 += mediaNode1.size(); for (int i = 0; i < mediaNode1.size(); i++) { JsonNode mediaObj = mediaNode1.get(i); ((ObjectNode) mediaObj).put("yvap", ""); //Meta //System.out.println("meta: "); if (!mediaObj.path("meta").isMissingNode()) { ObjectNode metaObj = (ObjectNode) mediaObj.path("meta"); changeMetaThumbnail(metaObj); metaObj.put("event_start", ""); metaObj.put("event_stop", ""); FloatingtoInt(metaObj, "duration"); if (metaObj.path("show_name").isMissingNode()) metaObj.put("show_name", ""); //System.out.println("thub_dem: "); if (!metaObj.path("thumbnail_dimensions").isMissingNode()) { ObjectNode thub_demObj = (ObjectNode) metaObj.path("thumbnail_dimensions"); FloatingtoInt(thub_demObj, "height"); FloatingtoInt(thub_demObj, "width"); } ((ObjectNode) metaObj.path("credits")).put("label", ""); } //Visualseek //System.out.println("visualseek: "); if (!mediaObj.path("visualseek").isMissingNode()) { ObjectNode visualseekObj = (ObjectNode) mediaObj.path("visualseek"); FloatingtoInt(visualseekObj, "frequency"); FloatingtoInt(visualseekObj, "width"); FloatingtoInt(visualseekObj, "height"); //visualseek -> images, float to int JsonNode imagesNode = visualseekObj.path("images"); if (imagesNode.isArray()) { for (int j = 0; j < imagesNode.size(); j++) { ObjectNode imageObj = (ObjectNode) imagesNode.get(j); FloatingtoInt(imageObj, "start_index"); FloatingtoInt(imageObj, "count"); } } } //Streams //System.out.println("streams: "); JsonNode streamsNode = mediaObj.path("streams"); if (streamsNode.isArray()) { for (int j = 0; j < streamsNode.size(); j++) { ObjectNode streamsObj = (ObjectNode) streamsNode.get(j); FloatingtoInt(streamsObj, "height"); FloatingtoInt(streamsObj, "bitrate"); FloatingtoInt(streamsObj, "duration"); FloatingtoInt(streamsObj, "width"); changeStreamsPath(streamsObj); ChangedHost(streamsObj); // if(streamsObj.path("h264_profile").isMissingNode()) streamsObj.put("h264_profile", ""); if (streamsObj.path("is_primary").isMissingNode()) streamsObj.put("is_primary", false); } } //Metrics -> plidl & isrc changeMetrics(mediaObj); } } //Compare if (mediaNode2.isArray() && mediaNode1.isArray()) { for (int i = 0; i < mediaNode2.size() && i < mediaNode1.size(); i++) { JsonNode mediaObj1 = mediaNode1.get(i); JsonNode mediaObj2 = mediaNode2.get(i); if (!mediaObj1.equals(mediaObj2)) { if (!mediaObj1.path("id").toString().equals(mediaObj2.path("id").toString())) { errorCount++; } else { Integer IFdiffStreams = 0; Integer IFdiffMeta = 0; Integer IFdiffvisualseek = 0; Integer IFdiffMetrics = 0; Integer IFdifflicense = 0; Integer IFdiffclosedcaptions = 0; String statusCode = ""; MetaClass tempMeta = new MetaClass(); if (!mediaObj1.path("status").equals(mediaObj2.path("status"))) { JsonNode statusNode1 = mediaObj1.path("status"); JsonNode statusNode2 = mediaObj2.path("status"); if (statusNode2.path("code").toString().equals("\"100\"") || (statusNode1.path("code").toString().equals("\"400\"") && statusNode1.path("code").toString().equals("\"404\"")) || (statusNode1.path("code").toString().equals("\"200\"") && statusNode1.path("code").toString().equals("\"200\"")) || (statusNode1.path("code").toString().equals("\"200\"") && statusNode1.path("code").toString().equals("\"403\""))) statusCode = ""; else statusCode = "yql code: " + mediaObj1.path("status").toString() + " yqlp code:" + mediaObj2.path("status").toString(); } else {//Status code is 100 if (!mediaObj1.path("streams").equals(mediaObj2.path("streams"))) IFdiffStreams = 1; if (!tempMeta.CompareMeta(mediaObj1.path("meta"), mediaObj2.path("meta"), lineNum)) IFdiffMeta = 1; if (!mediaObj1.path("visualseek").equals(mediaObj2.path("visualseek"))) IFdiffvisualseek = 1; if (!mediaObj1.path("metrics").equals(mediaObj2.path("metrics"))) { IFdiffMetrics = 1; JsonNode metrics1 = mediaObj1.path("metrics"); JsonNode metrics2 = mediaObj2.path("metrics"); if (!metrics1.path("beacons").equals(metrics2.path("beacons"))) beacons++; } if (!mediaObj1.path("license").equals(mediaObj2.path("license"))) IFdifflicense = 1; if (!mediaObj1.path("closedcaptions").equals(mediaObj2.path("closedcaptions"))) IFdiffclosedcaptions = 1; } if (IFdiffStreams + IFdiffMeta + IFdiffvisualseek + IFdiffMetrics + IFdifflicense + IFdiffclosedcaptions != 0 || !statusCode.equals("")) { String ID_str = mediaObj1.path("id").toString(); if (!IDarray.containsKey(ID_str)) { IDclass temp_IDclass = new IDclass(ID_str); temp_IDclass.addNum(IFdiffStreams, IFdiffMeta, IFdiffvisualseek, IFdiffMetrics, IFdifflicense, IFdiffclosedcaptions, lineNum); if (!statusCode.equals("")) temp_IDclass.statusCode = statusCode; IDarray.put(ID_str, temp_IDclass); } else { IDarray.get(ID_str).addNum(IFdiffStreams, IFdiffMeta, IFdiffvisualseek, IFdiffMetrics, IFdifflicense, IFdiffclosedcaptions, lineNum); if (!statusCode.equals("")) IDarray.get(ID_str).statusCode = statusCode; } IDarray.get(ID_str).stream.CompareStream(IFdiffStreams, mediaObj1.path("streams"), mediaObj2.path("streams"), lineNum); if (!IDarray.get(ID_str).metaDone) { IDarray.get(ID_str).meta = tempMeta; IDarray.get(ID_str).metaDone = true; } } else equalIDwithDuplicate++; } } else equalIDwithDuplicate++; } } bw.flush(); console.flush(); } //while System.out.println("done"); bw.write("Different ID" + " " + "num "); bw.write(PrintStreamsTitle()); bw.write(PrintMetaTitle()); bw.write(PrintTitle()); bw.newLine(); Iterator<String> iter = IDarray.keySet().iterator(); while (iter.hasNext()) { String key = iter.next(); bw.write(key + " "); bw.write(IDarray.get(key).num.toString() + " "); bw.write(IDarray.get(key).stream.print()); bw.write(IDarray.get(key).meta.print()); bw.write(IDarray.get(key).print()); bw.newLine(); //System.out.println(key); } //System.out.println("different log num = " + diffNum); //System.out.println("same log num = " + sameLogNum); System.out.println("Different ID size = " + IDarray.size()); // System.out.println("streamEqual = " + streamEqual); // System.out.println("metaEqual = " + metaEqual); // System.out.println("metricsEqual = " + metricsEqual); // System.out.println("visualseekEqual = " + visualseekEqual); // System.out.println("licenseEqual = " + licenseEqual); // System.out.println("closedcaptionsEqualEqual = " + closedcaptionsEqual); System.out.println(tempCount); System.out.println("beacons = " + beacons); System.out.println("equalIDwithDuplicate = " + equalIDwithDuplicate); System.out.println("Total ID num yql (including duplicates) = " + totalIDNum1); System.out.println("Total ID num yqpl (including duplicates) = " + totalIDNum2); System.out.println("Error " + errorCount); bw.close(); console.close(); } catch (IOException e) { } }
From source file:org.nuxeo.connect.tools.report.viewer.Viewer.java
public static void main(String[] varargs) throws IOException, ParseException { class Arguments { Options options = new Options() .addOption(Option.builder("i").longOpt("input").hasArg().argName("file") .desc("report input file").build()) .addOption(Option.builder("o").longOpt("output").hasArg().argName("file") .desc("thread dump output file").build()); final CommandLine commandline = new DefaultParser().parse(options, varargs); Arguments() throws ParseException { }//from ww w .ja v a 2 s .c om InputStream input() throws IOException { if (!commandline.hasOption('i')) { return System.in; } return Files.newInputStream(Paths.get(commandline.getOptionValue('i'))); } PrintStream output() throws IOException { if (!commandline.hasOption('o')) { return System.out; } return new PrintStream(commandline.getOptionValue('o')); } } Arguments arguments = new Arguments(); final JsonFactory jsonFactory = new JsonFactory(); PrintStream output = arguments.output(); JsonParser parser = jsonFactory.createParser(arguments.input()); ObjectMapper mapper = new ObjectMapper(); while (!parser.isClosed() && parser.nextToken() != JsonToken.NOT_AVAILABLE) { String hostid = parser.nextFieldName(); output.println(hostid); { parser.nextToken(); while (parser.nextToken() == JsonToken.FIELD_NAME) { if ("mx-thread-dump".equals(parser.getCurrentName())) { parser.nextToken(); // start mx-thread-dump report while (parser.nextToken() == JsonToken.FIELD_NAME) { if ("value".equals(parser.getCurrentName())) { parser.nextToken(); printThreadDump(mapper.readTree(parser), output); } else { parser.nextToken(); parser.skipChildren(); } } } else if ("mx-thread-deadlocked".equals(parser.getCurrentName())) { parser.nextToken(); while (parser.nextToken() == JsonToken.FIELD_NAME) { if ("value".equals(parser.getCurrentName())) { if (parser.nextToken() == JsonToken.START_ARRAY) { printThreadDeadlocked(mapper.readerFor(Long.class).readValue(parser), output); } } else { parser.nextToken(); parser.skipChildren(); } } } else if ("mx-thread-monitor-deadlocked".equals(parser.getCurrentName())) { parser.nextToken(); while (parser.nextToken() == JsonToken.FIELD_NAME) { if ("value".equals(parser.getCurrentName())) { if (parser.nextToken() == JsonToken.START_ARRAY) { printThreadMonitorDeadlocked(mapper.readerFor(Long.class).readValues(parser), output); } } else { parser.nextToken(); parser.skipChildren(); } } } else { parser.nextToken(); parser.skipChildren(); } } } } }
From source file:org.trustedanalytics.h2oscoringengine.publisher.http.JsonDataFetcher.java
private static JsonNode getJsonRootNode(String json) throws IOException { ObjectMapper mapper = new ObjectMapper(); return mapper.readTree(json); }
From source file:com.dougtest.restTest.getJsonInfo.java
public static JsonNode retrieveResourceFromResponse(final HttpResponse response) throws IOException { final String jsonFromResponse = EntityUtils.toString(response.getEntity()); final ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(jsonFromResponse); return root;/*from w w w . ja v a 2s. c o m*/ }