List of usage examples for java.io OutputStreamWriter OutputStreamWriter
public OutputStreamWriter(OutputStream out)
From source file:com.athena.peacock.agent.Starter.java
/** * <pre>/* w ww .j av a 2s .co m*/ * * </pre> * @param args */ @SuppressWarnings("resource") public static void main(String[] args) { int rand = (int) (Math.random() * 100) % 50; System.setProperty("random.seconds", Integer.toString(rand)); String configFile = null; try { configFile = PropertyUtil.getProperty(PeacockConstant.CONFIG_FILE_KEY); } catch (Exception e) { // nothing to do. } finally { if (StringUtils.isEmpty(configFile)) { configFile = "/peacock/agent/config/agent.conf"; } } /** * ${peacock.agent.config.file.name} ?? load ? ?? ? ? ? . */ String errorMsg = "\n\"" + configFile + "\" file does not exist or cannot read.\n" + "Please check \"" + configFile + "\" file exists and can read."; Assert.isTrue(AgentConfigUtil.exception == null, errorMsg); Assert.notNull(AgentConfigUtil.getConfig(PeacockConstant.SERVER_IP), "ServerIP cannot be empty."); Assert.notNull(AgentConfigUtil.getConfig(PeacockConstant.SERVER_PORT), "ServerPort cannot be empty."); /** * Agent ID ?? ${peacock.agent.agent.file.name} ? ?, * ?? ? Agent ID ? ?? . */ String agentFile = null; String agentId = null; try { agentFile = PropertyUtil.getProperty(PeacockConstant.AGENT_ID_FILE_KEY); } catch (Exception e) { // nothing to do. } finally { if (StringUtils.isEmpty(agentFile)) { agentFile = "/peacock/agent/.agent"; } } File file = new File(agentFile); boolean isNew = false; if (file.exists()) { try { agentId = IOUtils.toString(file.toURI()); // ? ? agent ID agent ID? ? 36? ? ?. if (StringUtils.isEmpty(agentId) || agentId.length() != 36) { throw new IOException(); } } catch (IOException e) { logger.error(agentFile + " file cannot read or saved invalid agent ID.", e); agentId = PeacockAgentIDGenerator.generateId(); isNew = true; } } else { agentId = PeacockAgentIDGenerator.generateId(); isNew = true; } if (isNew) { logger.info("New Agent-ID({}) be generated.", agentId); try { file.setWritable(true); OutputStreamWriter output = new OutputStreamWriter(new FileOutputStream(file)); output.write(agentId); file.setReadOnly(); IOUtils.closeQuietly(output); } catch (UnsupportedEncodingException e) { logger.error("UnsupportedEncodingException has occurred : ", e); } catch (FileNotFoundException e) { logger.error("FileNotFoundException has occurred : ", e); } catch (IOException e) { logger.error("IOException has occurred : ", e); } } // Spring Application Context Loading logger.debug("Starting application context..."); AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext( "classpath:spring/context-*.xml"); applicationContext.registerShutdownHook(); }
From source file:edu.cmu.lti.oaqa.knn4qa.apps.FilterTranTable.java
public static void main(String[] args) { Options options = new Options(); options.addOption(INPUT_PARAM, null, true, INPUT_DESC); options.addOption(OUTPUT_PARAM, null, true, OUTPUT_DESC); options.addOption(CommonParams.MEM_FWD_INDEX_PARAM, null, true, CommonParams.MEM_FWD_INDEX_DESC); options.addOption(CommonParams.GIZA_ITER_QTY_PARAM, null, true, CommonParams.GIZA_ITER_QTY_PARAM); options.addOption(CommonParams.GIZA_ROOT_DIR_PARAM, null, true, CommonParams.GIZA_ROOT_DIR_PARAM); options.addOption(CommonParams.MIN_PROB_PARAM, null, true, CommonParams.MIN_PROB_DESC); options.addOption(CommonParams.MAX_WORD_QTY_PARAM, null, true, CommonParams.MAX_WORD_QTY_PARAM); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); try {/*from ww w . j a v a 2 s . c om*/ CommandLine cmd = parser.parse(options, args); String outputFile = null; outputFile = cmd.getOptionValue(OUTPUT_PARAM); if (null == outputFile) { Usage("Specify 'A name of the output file'", options); } String gizaRootDir = cmd.getOptionValue(CommonParams.GIZA_ROOT_DIR_PARAM); if (null == gizaRootDir) { Usage("Specify '" + CommonParams.GIZA_ROOT_DIR_DESC + "'", options); } String gizaIterQty = cmd.getOptionValue(CommonParams.GIZA_ITER_QTY_PARAM); if (null == gizaIterQty) { Usage("Specify '" + CommonParams.GIZA_ITER_QTY_DESC + "'", options); } float minProb = 0; String tmpf = cmd.getOptionValue(CommonParams.MIN_PROB_PARAM); if (tmpf != null) { minProb = Float.parseFloat(tmpf); } int maxWordQty = Integer.MAX_VALUE; String tmpi = cmd.getOptionValue(CommonParams.MAX_WORD_QTY_PARAM); if (null != tmpi) { maxWordQty = Integer.parseInt(tmpi); } String memFwdIndxName = cmd.getOptionValue(CommonParams.MEM_FWD_INDEX_PARAM); if (null == memFwdIndxName) { Usage("Specify '" + CommonParams.MEM_FWD_INDEX_DESC + "'", options); } System.out.println("Filtering index: " + memFwdIndxName + " max # of frequent words: " + maxWordQty + " min. probability:" + minProb); VocabularyFilterAndRecoder filter = new FrequentIndexWordFilterAndRecoder(memFwdIndxName, maxWordQty); String srcVocFile = CompressUtils.findFileVariant(gizaRootDir + "/source.vcb"); System.out.println("Source vocabulary file: " + srcVocFile); GizaVocabularyReader srcVoc = new GizaVocabularyReader(srcVocFile, filter); String dstVocFile = CompressUtils.findFileVariant(gizaRootDir + "/target.vcb"); System.out.println("Target vocabulary file: " + dstVocFile); GizaVocabularyReader dstVoc = new GizaVocabularyReader(CompressUtils.findFileVariant(dstVocFile), filter); String inputFile = CompressUtils.findFileVariant(gizaRootDir + "/output.t1." + gizaIterQty); BufferedReader finp = new BufferedReader( new InputStreamReader(CompressUtils.createInputStream(inputFile))); BufferedWriter fout = new BufferedWriter( new OutputStreamWriter(CompressUtils.createOutputStream(outputFile))); try { String line; int prevSrcId = -1; int wordQty = 0; long addedQty = 0; long totalQty = 0; boolean isNotFiltered = false; for (totalQty = 0; (line = finp.readLine()) != null;) { ++totalQty; // Skip empty lines line = line.trim(); if (line.isEmpty()) continue; GizaTranRec rec = new GizaTranRec(line); if (rec.mSrcId != prevSrcId) { ++wordQty; } if (totalQty % REPORT_INTERVAL_QTY == 0) { System.out.println(String.format( "Processed %d lines (%d source word entries) from '%s', added %d lines", totalQty, wordQty, inputFile, addedQty)); } // isNotFiltered should be set after procOneWord if (rec.mSrcId != prevSrcId) { if (rec.mSrcId == 0) isNotFiltered = true; else { String wordSrc = srcVoc.getWord(rec.mSrcId); isNotFiltered = filter == null || (wordSrc != null && filter.checkWord(wordSrc)); } } prevSrcId = rec.mSrcId; if (rec.mProb >= minProb && isNotFiltered) { String wordDst = dstVoc.getWord(rec.mDstId); if (filter == null || (wordDst != null && filter.checkWord(wordDst))) { fout.write(String.format(rec.mSrcId + " " + rec.mDstId + " " + rec.mProb)); fout.newLine(); addedQty++; } } } System.out.println( String.format("Processed %d lines (%d source word entries) from '%s', added %d lines", totalQty, wordQty, inputFile, addedQty)); } finally { finp.close(); fout.close(); } } catch (ParseException e) { Usage("Cannot parse arguments", options); } catch (Exception e) { e.printStackTrace(); System.err.println("Terminating due to an exception: " + e); System.exit(1); } }
From source file:MainClass.java
public static void main(String[] args) throws Exception { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); X509Certificate[] chain = buildChain(); PEMWriter pemWrt = new PEMWriter(new OutputStreamWriter(System.out)); pemWrt.writeObject(chain[0]);// w w w . j av a 2s. c o m pemWrt.writeObject(chain[1]); pemWrt.close(); }
From source file:PopClean.java
public static void main(String args[]) { try {//from w ww .ja va2 s .c o m String hostname = null, username = null, password = null; int port = 110; int sizelimit = -1; String subjectPattern = null; Pattern pattern = null; Matcher matcher = null; boolean delete = false; boolean confirm = true; // Handle command-line arguments for (int i = 0; i < args.length; i++) { if (args[i].equals("-user")) username = args[++i]; else if (args[i].equals("-pass")) password = args[++i]; else if (args[i].equals("-host")) hostname = args[++i]; else if (args[i].equals("-port")) port = Integer.parseInt(args[++i]); else if (args[i].equals("-size")) sizelimit = Integer.parseInt(args[++i]); else if (args[i].equals("-subject")) subjectPattern = args[++i]; else if (args[i].equals("-debug")) debug = true; else if (args[i].equals("-delete")) delete = true; else if (args[i].equals("-force")) // don't confirm confirm = false; } // Verify them if (hostname == null || username == null || password == null || sizelimit == -1) usage(); // Make sure the pattern is a valid regexp if (subjectPattern != null) { pattern = Pattern.compile(subjectPattern); matcher = pattern.matcher(""); } // Say what we are going to do System.out .println("Connecting to " + hostname + " on port " + port + " with username " + username + "."); if (delete) { System.out.println("Will delete all messages longer than " + sizelimit + " bytes"); if (subjectPattern != null) System.out.println("that have a subject matching: [" + subjectPattern + "]"); } else { System.out.println("Will list subject lines for messages " + "longer than " + sizelimit + " bytes"); if (subjectPattern != null) System.out.println("that have a subject matching: [" + subjectPattern + "]"); } // If asked to delete, ask for confirmation unless -force is given if (delete && confirm) { System.out.println(); System.out.print("Do you want to proceed (y/n) [n]: "); System.out.flush(); BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); String response = console.readLine(); if (!response.equals("y")) { System.out.println("No messages deleted."); System.exit(0); } } // Connect to the server, and set up streams s = new Socket(hostname, port); in = new BufferedReader(new InputStreamReader(s.getInputStream())); out = new PrintWriter(new OutputStreamWriter(s.getOutputStream())); // Read the welcome message from the server, confirming it is OK. System.out.println("Connected: " + checkResponse()); // Now log in send("USER " + username); // Send username, wait for response send("PASS " + password); // Send password, wait for response System.out.println("Logged in"); // Check how many messages are waiting, and report it String stat = send("STAT"); StringTokenizer t = new StringTokenizer(stat); System.out.println(t.nextToken() + " messages in mailbox."); System.out.println("Total size: " + t.nextToken()); // Get a list of message numbers and sizes send("LIST"); // Send LIST command, wait for OK response. // Now read lines from the server until we get . by itself List msgs = new ArrayList(); String line; for (;;) { line = in.readLine(); if (line == null) throw new IOException("Unexpected EOF"); if (line.equals(".")) break; msgs.add(line); } // Now loop through the lines we read one at a time. // Each line should specify the message number and its size. int nummsgs = msgs.size(); for (int i = 0; i < nummsgs; i++) { String m = (String) msgs.get(i); StringTokenizer st = new StringTokenizer(m); int msgnum = Integer.parseInt(st.nextToken()); int msgsize = Integer.parseInt(st.nextToken()); // If the message is too small, ignore it. if (msgsize <= sizelimit) continue; // If we're listing messages, or matching subject lines // find the subject line for this message String subject = null; if (!delete || pattern != null) { subject = getSubject(msgnum); // get the subject line // If we couldn't find a subject, skip the message if (subject == null) continue; // If this subject does not match the pattern, then // skip the message if (pattern != null) { matcher.reset(subject); if (!matcher.matches()) continue; } // If we are listing, list this message if (!delete) { System.out.println("Subject " + msgnum + ": " + subject); continue; // so we never delete it } } // If we were asked to delete, then delete the message if (delete) { send("DELE " + msgnum); if (pattern == null) System.out.println("Deleted message " + msgnum); else System.out.println("Deleted message " + msgnum + ": " + subject); } } // When we're done, log out and shutdown the connection shutdown(); } catch (Exception e) { // If anything goes wrong print exception and show usage System.err.println(e); usage(); // Always try to shutdown nicely so the server doesn't hang on us shutdown(); } }
From source file:btrplace.fromEntropy.Converter.java
public static void main(String[] args) { String src, dst = null, output, scriptDC = null, dirScriptsCL = null; if (args.length < 5 || args.length > 6 || !args[args.length - 2].equals("-o")) { usage(1);// w w w .j av a 2s. co m } src = args[0]; output = args[args.length - 1]; if (args.length > 5) { dst = args[1]; } scriptDC = args[args.length - 4]; dirScriptsCL = args[args.length - 3]; OutputStreamWriter out = null; try { // Convert the src file ConfigurationConverter conv = new ConfigurationConverter(src); Instance i = conv.getInstance(); // Read the dst file, deduce and add the states constraints if (dst != null) { i.getSatConstraints().addAll(conv.getNextStates(dst)); } // Read the script files ScriptBuilder scriptBuilder = new ScriptBuilder(i.getModel()); //scriptBuilder.setIncludes(new PathBasedIncludes(scriptBuilder, // new File("src/test/resources"))); // Read the datacenter script file if exists if (scriptDC != null) { String strScriptDC = null; try { strScriptDC = readFile(scriptDC); } catch (IOException e) { e.printStackTrace(); } Script scrDC = null; try { // Build the DC script scrDC = scriptBuilder.build(strScriptDC); } catch (ScriptBuilderException sbe) { System.out.println(sbe); } // Set the DC script as an include BasicIncludes bi = new BasicIncludes(); bi.add(scrDC); scriptBuilder.setIncludes(bi); } // Read all the client script files String scriptCL = null, strScriptCL = null; Script scrCL = null; Iterator it = FileUtils.iterateFiles(new File(dirScriptsCL), null, false); while (it.hasNext()) { scriptCL = dirScriptsCL + "/" + ((File) it.next()).getName(); if (scriptCL != null) { // Read try { strScriptCL = readFile(scriptCL); } catch (IOException e) { e.printStackTrace(); } // Parse try { scrCL = scriptBuilder.build(strScriptCL); } catch (ScriptBuilderException sbe) { System.out.println(sbe); sbe.printStackTrace(); } // Add the resulting constraints if (scrCL.getConstraints() != null) { i.getSatConstraints().addAll(scrCL.getConstraints()); } } } /************** PATCH **************/ // State constraints; for (Node n : i.getModel().getMapping().getOnlineNodes()) { i.getSatConstraints().add(new Online(n)); } for (Node n : i.getModel().getMapping().getOfflineNodes()) { i.getSatConstraints().add(new Offline(n)); } // Remove preserve constraints for (Iterator<SatConstraint> ite = i.getSatConstraints().iterator(); ite.hasNext();) { SatConstraint s = ite.next(); if (s instanceof Preserve && src.contains("nr")) { ite.remove(); } } /************************************/ // Convert to JSON InstanceConverter iConv = new InstanceConverter(); JSONObject o = iConv.toJSON(i); // Check for gzip extension if (output.endsWith(".gz")) { out = new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(output))); } else { out = new FileWriter(output); } // Write the output file o.writeJSONString(out); out.close(); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(1); } finally { if (out != null) { try { out.close(); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(1); } } } }
From source file:com.act.lcms.db.io.ExportPlateCompositionFromDB.java
public static void main(String[] args) throws Exception { Options opts = new Options(); opts.addOption(Option.builder("b").argName("barcode").desc("The barcode of the plate to print").hasArg() .longOpt("barcode").build()); opts.addOption(Option.builder("n").argName("name").desc("The name of the plate to print").hasArg() .longOpt("name").build()); opts.addOption(Option.builder("o").argName("output file").desc( "An output file to which to write this plate's composition table (writes to stdout if omitted") .hasArg().longOpt("output-file").build()); // DB connection options. opts.addOption(Option.builder().argName("database url") .desc("The url to use when connecting to the LCMS db").hasArg().longOpt("db-url").build()); opts.addOption(Option.builder("u").argName("database user").desc("The LCMS DB user").hasArg() .longOpt("db-user").build()); opts.addOption(Option.builder("p").argName("database password").desc("The LCMS DB password").hasArg() .longOpt("db-pass").build()); opts.addOption(Option.builder("H").argName("database host") .desc(String.format("The LCMS DB host (default = %s)", DB.DEFAULT_HOST)).hasArg().longOpt("db-host") .build());//ww w .j a va 2 s . co m opts.addOption(Option.builder("P").argName("database port") .desc(String.format("The LCMS DB port (default = %d)", DB.DEFAULT_PORT)).hasArg().longOpt("db-port") .build()); opts.addOption(Option.builder("N").argName("database name") .desc(String.format("The LCMS DB name (default = %s)", DB.DEFAULT_DB_NAME)).hasArg() .longOpt("db-name").build()); // Everybody needs a little help from their friends. opts.addOption( Option.builder("h").argName("help").desc("Prints this help message").longOpt("help").build()); CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s\n", e.getMessage()); new HelpFormatter().printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), opts, true); System.exit(1); } if (cl.hasOption("help")) { new HelpFormatter().printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), opts, true); return; } if (!cl.hasOption("b") && !cl.hasOption("n")) { System.err.format("Must specify either plate barcode or plate name."); new HelpFormatter().printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), opts, true); System.exit(1); } DB db = null; try { if (cl.hasOption("db-url")) { db = new DB().connectToDB(cl.getOptionValue("db-url")); } else { Integer port = null; if (cl.getOptionValue("P") != null) { port = Integer.parseInt(cl.getOptionValue("P")); } db = new DB().connectToDB(cl.getOptionValue("H"), port, cl.getOptionValue("N"), cl.getOptionValue("u"), cl.getOptionValue("p")); } Writer writer = null; if (cl.hasOption("o")) { writer = new FileWriter(cl.getOptionValue("o")); } else { writer = new OutputStreamWriter(System.out); } PlateCompositionWriter cw = new PlateCompositionWriter(); if (cl.hasOption("b")) { cw.writePlateCompositionByBarcode(db, cl.getOptionValue("b"), writer); } else if (cl.hasOption("n")) { cw.writePlateCompositionByName(db, cl.getOptionValue("n"), writer); } writer.close(); } finally { if (db != null) { db.close(); } } }
From source file:json_cmp.Comparer.java
public static void main(String[] args) { System.out.println("Testing Begin"); try {//w ww. jav a 2s. c o m 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:com.act.lcms.v2.fullindex.Searcher.java
public static void main(String args[]) throws Exception { CLIUtil cliUtil = new CLIUtil(Searcher.class, HELP_MESSAGE, OPTION_BUILDERS); CommandLine cl = cliUtil.parseCommandLine(args); File indexDir = new File(cl.getOptionValue(OPTION_INDEX_PATH)); if (!indexDir.exists() || !indexDir.isDirectory()) { cliUtil.failWithMessage("Unable to read index directory at %s", indexDir.getAbsolutePath()); }// w w w. ja v a 2 s . c o m if (!cl.hasOption(OPTION_MZ_RANGE) && !cl.hasOption(OPTION_TIME_RANGE)) { cliUtil.failWithMessage( "Extracting all readings is not currently supported; specify an m/z or time range"); } Pair<Double, Double> mzRange = extractRange(cl.getOptionValue(OPTION_MZ_RANGE)); Pair<Double, Double> timeRange = extractRange(cl.getOptionValue(OPTION_TIME_RANGE)); Searcher searcher = Factory.makeSearcher(indexDir); List<TMzI> results = searcher.searchIndexInRange(mzRange, timeRange); if (cl.hasOption(OPTION_OUTPUT_FILE)) { try (PrintWriter writer = new PrintWriter(new FileWriter(cl.getOptionValue(OPTION_OUTPUT_FILE)))) { Searcher.writeOutput(writer, results); } } else { // Don't close the print writer if we're writing to stdout. Searcher.writeOutput(new PrintWriter(new OutputStreamWriter(System.out)), results); } LOGGER.info("Done"); }
From source file:edu.vt.middleware.ldap.search.PeopleSearch.java
/** * This provides command line access to a <code>PeopleSearch</code>. * * @param args <code>String[]</code> * * @throws Exception if an error occurs *//*from ww w . jav a 2 s.c om*/ public static void main(final String[] args) throws Exception { final PeopleSearch ps = createFromSpringContext("/peoplesearch-context.xml", "peopleSearch"); final Query query = new Query(); final List<String> attrs = new ArrayList<String>(); try { for (int i = 0; i < args.length; i++) { if ("-query".equals(args[i])) { query.setRawQuery(args[++i]); } else { attrs.add(args[i]); } } if (query.getRawQuery() == null) { throw new ArrayIndexOutOfBoundsException(); } if (!attrs.isEmpty()) { query.setQueryAttributes(attrs.toArray(new String[0])); } ps.search(query, OutputFormat.LDIF, new BufferedWriter(new OutputStreamWriter(System.out))); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Usage: java " + PeopleSearch.class.getName() + " -query <query> <attributes>"); System.exit(1); } }
From source file:com.akana.demo.freemarker.templatetester.App.java
public static void main(String[] args) { final Options options = new Options(); @SuppressWarnings("static-access") Option optionContentType = OptionBuilder.withArgName("content-type").hasArg() .withDescription("content type of model").create("content"); @SuppressWarnings("static-access") Option optionUrlPath = OptionBuilder.withArgName("httpRequestLine").hasArg() .withDescription("url path and parameters in HTTP Request Line format").create("url"); @SuppressWarnings("static-access") Option optionRootMessageName = OptionBuilder.withArgName("messageName").hasArg() .withDescription("root data object name, defaults to 'message'").create("root"); @SuppressWarnings("static-access") Option optionAdditionalMessages = OptionBuilder.withArgName("dataModelPaths") .hasArgs(Option.UNLIMITED_VALUES).withDescription("additional message object data sources") .create("messages"); @SuppressWarnings("static-access") Option optionDebugMessages = OptionBuilder.hasArg(false) .withDescription("Shows debug information about template processing").create("debug"); Option optionHelp = new Option("help", "print this message"); options.addOption(optionHelp);/*from www .jav a2s .c o m*/ options.addOption(optionContentType); options.addOption(optionUrlPath); options.addOption(optionRootMessageName); options.addOption(optionAdditionalMessages); options.addOption(optionDebugMessages); CommandLineParser parser = new DefaultParser(); CommandLine cmd; try { cmd = parser.parse(options, args); // Check for help flag if (cmd.hasOption("help")) { showHelp(options); return; } String[] remainingArguments = cmd.getArgs(); if (remainingArguments.length < 2) { showHelp(options); return; } String ftlPath, dataPath = "none"; ftlPath = remainingArguments[0]; dataPath = remainingArguments[1]; String contentType = "text/xml"; // Discover content type from file extension String ext = FilenameUtils.getExtension(dataPath); if (ext.equals("json")) { contentType = "json"; } else if (ext.equals("txt")) { contentType = "txt"; } // Override discovered content type if (cmd.hasOption("content")) { contentType = cmd.getOptionValue("content"); } // Root data model name String rootMessageName = "message"; if (cmd.hasOption("root")) { rootMessageName = cmd.getOptionValue("root"); } // Additional data models String[] additionalModels = new String[0]; if (cmd.hasOption("messages")) { additionalModels = cmd.getOptionValues("messages"); } // Debug Info if (cmd.hasOption("debug")) { System.out.println(" Processing ftl : " + ftlPath); System.out.println(" with data model: " + dataPath); System.out.println(" with content-type: " + contentType); System.out.println(" data model object: " + rootMessageName); if (cmd.hasOption("messages")) { System.out.println("additional models: " + additionalModels.length); } } Configuration cfg = new Configuration(Configuration.VERSION_2_3_23); cfg.setDirectoryForTemplateLoading(new File(".")); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); /* Create the primary data-model */ Map<String, Object> message = new HashMap<String, Object>(); if (contentType.contains("json") || contentType.contains("txt")) { message.put("contentAsString", FileUtils.readFileToString(new File(dataPath), StandardCharsets.UTF_8)); } else { message.put("contentAsXml", freemarker.ext.dom.NodeModel.parse(new File(dataPath))); } if (cmd.hasOption("url")) { message.put("getProperty", new AkanaGetProperty(cmd.getOptionValue("url"))); } Map<String, Object> root = new HashMap<String, Object>(); root.put(rootMessageName, message); if (additionalModels.length > 0) { for (int i = 0; i < additionalModels.length; i++) { Map<String, Object> m = createMessageFromFile(additionalModels[i], contentType); root.put("message" + i, m); } } /* Get the template (uses cache internally) */ Template temp = cfg.getTemplate(ftlPath); /* Merge data-model with template */ Writer out = new OutputStreamWriter(System.out); temp.process(root, out); } catch (ParseException e) { showHelp(options); System.exit(1); } catch (IOException e) { System.out.println("Unable to parse ftl."); e.printStackTrace(); } catch (SAXException e) { System.out.println("XML parsing issue."); e.printStackTrace(); } catch (ParserConfigurationException e) { System.out.println("Unable to configure parser."); e.printStackTrace(); } catch (TemplateException e) { System.out.println("Unable to parse template."); e.printStackTrace(); } }