List of usage examples for java.io PrintWriter PrintWriter
public PrintWriter(File file, Charset charset) throws IOException
From source file:gr.demokritos.iit.demos.Demo.java
public static void main(String[] args) { try {/*w w w . ja va 2 s.com*/ Options options = new Options(); options.addOption("h", HELP, false, "show help."); options.addOption("i", INPUT, true, "The file containing JSON " + " representations of tweets or SAG posts - 1 per line" + " default file looked for is " + DEFAULT_INFILE); options.addOption("o", OUTPUT, true, "Where to write the output " + " default file looked for is " + DEFAULT_OUTFILE); options.addOption("p", PROCESS, true, "Type of processing to do " + " ner for Named Entity Recognition re for Relation Extraction" + " default is NER"); options.addOption("s", SAG, false, "Whether to process as SAG posts" + " default is off - if passed means process as SAG posts"); CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); // DEFAULTS String filename = DEFAULT_INFILE; String outfilename = DEFAULT_OUTFILE; String process = NER; boolean isSAG = false; if (cmd.hasOption(HELP)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("NER + RE extraction module", options); System.exit(0); } if (cmd.hasOption(INPUT)) { filename = cmd.getOptionValue(INPUT); } if (cmd.hasOption(OUTPUT)) { outfilename = cmd.getOptionValue(OUTPUT); } if (cmd.hasOption(SAG)) { isSAG = true; } if (cmd.hasOption(PROCESS)) { process = cmd.getOptionValue(PROCESS); } System.out.println(); System.out.println("Reading from file: " + filename); System.out.println("Process type: " + process); System.out.println("Processing SAG: " + isSAG); System.out.println("Writing to file: " + outfilename); System.out.println(); List<String> jsoni = new ArrayList(); Scanner in = new Scanner(new FileReader(filename)); while (in.hasNextLine()) { String json = in.nextLine(); jsoni.add(json); } PrintWriter writer = new PrintWriter(outfilename, "UTF-8"); System.out.println("Read " + jsoni.size() + " lines from " + filename); if (process.equalsIgnoreCase(RE)) { System.out.println("Running Relation Extraction"); System.out.println(); String json = API.RE(jsoni, isSAG); System.out.println(json); writer.print(json); } else { System.out.println("Running Named Entity Recognition"); System.out.println(); jsoni = API.NER(jsoni, isSAG); /* for(String json: jsoni){ NamedEntityList nel = NamedEntityList.fromJSON(json); nel.prettyPrint(); } */ for (String json : jsoni) { System.out.println(json); writer.print(json); } } writer.close(); } catch (ParseException | UnsupportedEncodingException | FileNotFoundException ex) { Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:de.uni_koblenz.west.splendid.tools.NQuadSourceAggregator.java
public static void main(String[] args) { try {/*from w w w . j av a2 s . c om*/ // parse the command line arguments CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(OPTIONS, args); // print help message if (cmd.hasOption("h") || cmd.hasOption("help")) { new HelpFormatter().printHelp(USAGE, OPTIONS); System.exit(0); } // get input files (from option -i or all remaining parameters) String[] inputFiles = cmd.getOptionValues("i"); if (inputFiles == null) inputFiles = cmd.getArgs(); if (inputFiles.length == 0) { System.out.println("need at least one input file."); new HelpFormatter().printUsage(new PrintWriter(System.out, true), 80, USAGE); System.exit(1); } String outputFile = cmd.getOptionValue("o"); // process all input files new NQuadSourceAggregator().process(outputFile, inputFiles); } catch (ParseException exp) { // print parse error and display usage message System.out.println(exp.getMessage()); new HelpFormatter().printUsage(new PrintWriter(System.out, true), 80, USAGE, OPTIONS); } }
From source file:com.thoughtworks.xstream.benchmark.cache.CacheBenchmark.java
public static void main(String[] args) { int counter = 10000; Product product = null;// ww w.j a v a 2 s .com Options options = new Options(); options.addOption("p", "product", true, "Class name of the product to use for benchmark"); options.addOption("n", true, "Number of repetitions"); Parser parser = new PosixParser(); try { CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption('p')) { product = (Product) Class.forName(commandLine.getOptionValue('p')).newInstance(); } if (commandLine.hasOption('n')) { counter = Integer.parseInt(commandLine.getOptionValue('n')); } } catch (ParseException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } Harness harness = new Harness(); // harness.addMetric(new SerializationSpeedMetric(1) { // public String toString() { // return "Initial run serialization"; // } // }); // harness.addMetric(new DeserializationSpeedMetric(1, false) { // public String toString() { // return "Initial run deserialization"; // } // }); harness.addMetric(new SerializationSpeedMetric(counter)); harness.addMetric(new DeserializationSpeedMetric(counter, false)); if (product == null) { harness.addProduct(new NoCache()); harness.addProduct(new Cache122()); harness.addProduct(new RealClassCache()); harness.addProduct(new SerializedClassCache()); harness.addProduct(new AliasedAttributeCache()); harness.addProduct(new DefaultImplementationCache()); harness.addProduct(new NoCache()); } else { harness.addProduct(product); } harness.addTarget(new BasicTarget()); harness.addTarget(new ExtendedTarget()); harness.addTarget(new ReflectionTarget()); harness.addTarget(new SerializableTarget()); harness.run(new TextReporter(new PrintWriter(System.out, true))); System.out.println("Done."); }
From source file:de.uni_koblenz.west.splendid.tools.NXVoidGenerator.java
public static void main(String[] args) { try {// ww w. j a v a 2 s.c o m // parse the command line arguments CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(OPTIONS, args); // print help message if (cmd.hasOption("h") || cmd.hasOption("help")) { new HelpFormatter().printHelp(USAGE, OPTIONS); System.exit(0); } // get input files (from option -i or all remaining parameters) String[] inputFiles = cmd.getOptionValues("i"); if (inputFiles == null) inputFiles = cmd.getArgs(); if (inputFiles.length == 0) { System.out.println("need at least one input file."); new HelpFormatter().printUsage(new PrintWriter(System.out, true), 80, USAGE); System.exit(1); } String outputFile = cmd.getOptionValue("o"); // process all input files new NXVoidGenerator().process(outputFile, inputFiles); } catch (ParseException exp) { // print parse error and display usage message System.out.println(exp.getMessage()); new HelpFormatter().printUsage(new PrintWriter(System.out, true), 80, USAGE, OPTIONS); } }
From source file:EchoClient.java
public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try {//from w w w .java2 s. c o m serverSocket = new ServerSocket(4444); } catch (IOException e) { System.err.println("Could not listen on port: 4444."); System.exit(1); } Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader( clientSocket.getInputStream())); String inputLine, outputLine; KnockKnockProtocol kkp = new KnockKnockProtocol(); outputLine = kkp.processInput(null); out.println(outputLine); while ((inputLine = in.readLine()) != null) { outputLine = kkp.processInput(inputLine); out.println(outputLine); if (outputLine.equals("Bye.")) break; } out.close(); in.close(); clientSocket.close(); serverSocket.close(); }
From source file:com.adobe.aem.demomachine.Json2Csv.java
public static void main(String[] args) throws IOException { String inputFile1 = null;//from www. java2 s.co m String inputFile2 = null; String outputFile = null; HashMap<String, String> hmReportSuites = new HashMap<String, String>(); // Command line options for this tool Options options = new Options(); options.addOption("c", true, "Filename 1"); options.addOption("r", true, "Filename 2"); options.addOption("o", true, "Filename 3"); CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("c")) { inputFile1 = cmd.getOptionValue("c"); } if (cmd.hasOption("r")) { inputFile2 = cmd.getOptionValue("r"); } if (cmd.hasOption("o")) { outputFile = cmd.getOptionValue("o"); } if (inputFile1 == null || inputFile1 == null || outputFile == null) { System.exit(-1); } } catch (ParseException ex) { logger.error(ex.getMessage()); } // List of customers and report suites for these customers String sInputFile1 = readFile(inputFile1, Charset.defaultCharset()); sInputFile1 = sInputFile1.replaceAll("ObjectId\\(\"([0-9a-z]*)\"\\)", "\"$1\""); // Processing the list of report suites for each customer try { JSONArray jCustomers = new JSONArray(sInputFile1.trim()); for (int i = 0, size = jCustomers.length(); i < size; i++) { JSONObject jCustomer = jCustomers.getJSONObject(i); Iterator<?> keys = jCustomer.keys(); String companyName = null; while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("company")) { companyName = jCustomer.getString(key); } } keys = jCustomer.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("report_suites")) { JSONArray jReportSuites = jCustomer.getJSONArray(key); for (int j = 0, rSize = jReportSuites.length(); j < rSize; j++) { hmReportSuites.put(jReportSuites.getString(j), companyName); System.out.println(jReportSuites.get(j) + " for company " + companyName); } } } } // Creating the out put file PrintWriter writer = new PrintWriter(outputFile, "UTF-8"); writer.println("\"" + "Customer" + "\",\"" + "ReportSuite ID" + "\",\"" + "Number of Documents" + "\",\"" + "Last Updated" + "\""); // Processing the list of SOLR collections String sInputFile2 = readFile(inputFile2, Charset.defaultCharset()); sInputFile2 = sInputFile2.replaceAll("NumberLong\\(\"([0-9a-z]*)\"\\)", "\"$1\""); JSONObject jResults = new JSONObject(sInputFile2.trim()); JSONArray jCollections = jResults.getJSONArray("result"); for (int i = 0, size = jCollections.length(); i < size; i++) { JSONObject jCollection = jCollections.getJSONObject(i); String id = null; String number = null; String lastupdate = null; Iterator<?> keys = jCollection.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("_id")) { id = jCollection.getString(key); } } keys = jCollection.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("noOfDocs")) { number = jCollection.getString(key); } } keys = jCollection.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("latestUpdateDate")) { lastupdate = jCollection.getString(key); } } Date d = new Date(Long.parseLong(lastupdate)); System.out.println(hmReportSuites.get(id) + "," + id + "," + number + "," + lastupdate + "," + new SimpleDateFormat("MM-dd-yyyy").format(d)); writer.println("\"" + hmReportSuites.get(id) + "\",\"" + id + "\",\"" + number + "\",\"" + new SimpleDateFormat("MM-dd-yyyy").format(d) + "\""); } writer.close(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.bluemarsh.jswat.console.Main.java
/** * Kicks off the application./* w w w .j a v a2 s.c om*/ * * @param args the command line arguments. */ public static void main(String[] args) { // // An attempt was made early on to use the Console class in java.io, // but that is not designed to handle asynchronous output from // multiple threads, so we just use the usual System.out for output // and System.in for input. Note that automatic flushing is used to // ensure output is shown in a timely fashion. // // // Where console mode seems to work: // - bash // - emacs // // Where console mode does not seem to work: // - NetBeans: output from event listeners is never shown and the // cursor sometimes lags behind the output // // Turn on flushing so printing the prompt will flush // all buffered output generated from other threads. PrintWriter output = new PrintWriter(System.out, true); // Make sure we have the JPDA classes. try { Bootstrap.virtualMachineManager(); } catch (NoClassDefFoundError ncdfe) { output.println(NbBundle.getMessage(Main.class, "MSG_Main_NoJPDA")); System.exit(1); } // Ensure we can create the user directory by requesting the // platform service. Simply asking for it has the desired effect. PlatformProvider.getPlatformService(); // Define the logging configuration. LogManager manager = LogManager.getLogManager(); InputStream is = Main.class.getResourceAsStream("logging.properties"); try { manager.readConfiguration(is); } catch (IOException ioe) { ioe.printStackTrace(); System.exit(1); } // Print out some useful debugging information. logSystemDetails(); // Add a shutdown hook to make sure we exit cleanly. Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { // Save the command aliases. CommandParser parser = CommandProvider.getCommandParser(); parser.saveSettings(); // Save the runtimes to persistent storage. RuntimeManager rm = RuntimeProvider.getRuntimeManager(); rm.saveRuntimes(); // Save the sessions to persistent storage and have them // close down in preparation to exit. SessionManager sm = SessionProvider.getSessionManager(); sm.saveSessions(true); } })); // Initialize the command parser and load the aliases. CommandParser parser = CommandProvider.getCommandParser(); parser.loadSettings(); parser.setOutput(output); // Create an OutputAdapter to display debuggee output. OutputAdapter adapter = new OutputAdapter(output); SessionManager sessionMgr = SessionProvider.getSessionManager(); sessionMgr.addSessionManagerListener(adapter); // Create a SessionWatcher to monitor the session status. SessionWatcher swatcher = new SessionWatcher(); sessionMgr.addSessionManagerListener(swatcher); // Create a BreakpointWatcher to monitor the breakpoints. BreakpointWatcher bwatcher = new BreakpointWatcher(); sessionMgr.addSessionManagerListener(bwatcher); // Add the watchers and adapters to the open sessions. Iterator<Session> iter = sessionMgr.iterateSessions(); while (iter.hasNext()) { Session s = iter.next(); s.addSessionListener(adapter); s.addSessionListener(swatcher); } // Find and run the RC file. try { runStartupFile(parser, output); } catch (IOException ioe) { logger.log(Level.SEVERE, null, ioe); } // Process command line arguments. try { processArguments(args); } catch (ParseException pe) { // Report the problem and keep going. System.err.println("Option parsing failed: " + pe.getMessage()); logger.log(Level.SEVERE, null, pe); } // Display a helpful greeting. output.println(NbBundle.getMessage(Main.class, "MSG_Main_Welcome")); if (jdbEmulationMode) { output.println(NbBundle.getMessage(Main.class, "MSG_Main_Jdb_Emulation")); } // Enter the main loop of processing user input. BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); while (true) { // Keep the prompt format identical to jdb for compatibility // with emacs and other possible wrappers. output.print("> "); output.flush(); try { String command = input.readLine(); // A null value indicates end of stream. if (command != null) { performCommand(output, parser, command); } // Sleep briefly to give the event processing threads, // and the automatic output flushing, a chance to catch // up before printing the input prompt again. Thread.sleep(250); } catch (InterruptedException ie) { logger.log(Level.WARNING, null, ie); } catch (IOException ioe) { logger.log(Level.SEVERE, null, ioe); output.println(NbBundle.getMessage(Main.class, "ERR_Main_IOError", ioe)); } catch (Exception x) { // Don't ever let an internal bug (e.g. in the command parser) // hork the console, as it really irritates people. logger.log(Level.SEVERE, null, x); output.println(NbBundle.getMessage(Main.class, "ERR_Main_Exception", x)); } } }
From source file:fr.tpt.s3.mcdag.bench.MainBench.java
public static void main(String[] args) throws IOException, InterruptedException { // Command line options Options options = new Options(); Option input = new Option("i", "input", true, "MC-DAG XML models"); input.setRequired(true);/* ww w. j av a 2 s. c om*/ input.setArgs(Option.UNLIMITED_VALUES); options.addOption(input); Option output = new Option("o", "output", true, "Folder where results have to be written."); output.setRequired(true); options.addOption(output); Option uUti = new Option("u", "utilization", true, "Utilization."); uUti.setRequired(true); options.addOption(uUti); Option output2 = new Option("ot", "output-total", true, "File where total results are being written"); output2.setRequired(true); options.addOption(output2); Option oCores = new Option("c", "cores", true, "Cores given to the test"); oCores.setRequired(true); options.addOption(oCores); Option oLvls = new Option("l", "levels", true, "Levels tested for the system"); oLvls.setRequired(true); options.addOption(oLvls); Option jobs = new Option("j", "jobs", true, "Number of threads to be launched."); jobs.setRequired(false); options.addOption(jobs); Option debug = new Option("d", "debug", false, "Debug logs."); debug.setRequired(false); options.addOption(debug); /* * Parsing of the command line */ CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println(e.getMessage()); formatter.printHelp("Benchmarks MultiDAG", options); System.exit(1); return; } String inputFilePath[] = cmd.getOptionValues("input"); String outputFilePath = cmd.getOptionValue("output"); String outputFilePathTotal = cmd.getOptionValue("output-total"); double utilization = Double.parseDouble(cmd.getOptionValue("utilization")); boolean boolDebug = cmd.hasOption("debug"); int nbLvls = Integer.parseInt(cmd.getOptionValue("levels")); int nbJobs = 1; int nbFiles = inputFilePath.length; if (cmd.hasOption("jobs")) nbJobs = Integer.parseInt(cmd.getOptionValue("jobs")); int nbCores = Integer.parseInt(cmd.getOptionValue("cores")); /* * While files need to be allocated * run the tests in the pool of threads */ // For dual-criticality systems we call a specific thread if (nbLvls == 2) { System.out.println(">>>>>>>>>>>>>>>>>>>>> NB levels " + nbLvls); int i_files2 = 0; String outFile = outputFilePath.substring(0, outputFilePath.lastIndexOf('.')) .concat("-schedulability.csv"); PrintWriter writer = new PrintWriter(outFile, "UTF-8"); writer.println( "Thread; File; FSched (%); FPreempts; FAct; LSched (%); LPreempts; LAct; ESched (%); EPreempts; EAct; HSched(%); HPreempts; HAct; Utilization"); writer.close(); ExecutorService executor2 = Executors.newFixedThreadPool(nbJobs); while (i_files2 != nbFiles) { BenchThreadDualCriticality bt2 = new BenchThreadDualCriticality(inputFilePath[i_files2], outFile, nbCores, boolDebug); executor2.execute(bt2); i_files2++; } executor2.shutdown(); executor2.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); int fedTotal = 0; int laxTotal = 0; int edfTotal = 0; int hybridTotal = 0; int fedPreempts = 0; int laxPreempts = 0; int edfPreempts = 0; int hybridPreempts = 0; int fedActiv = 0; int laxActiv = 0; int edfActiv = 0; int hybridActiv = 0; // Read lines in file and do average int i = 0; File f = new File(outFile); @SuppressWarnings("resource") Scanner line = new Scanner(f); while (line.hasNextLine()) { String s = line.nextLine(); if (i > 0) { // To skip the first line try (Scanner inLine = new Scanner(s).useDelimiter("; ")) { int j = 0; while (inLine.hasNext()) { String val = inLine.next(); if (j == 2) { fedTotal += Integer.parseInt(val); } else if (j == 3) { fedPreempts += Integer.parseInt(val); } else if (j == 4) { fedActiv += Integer.parseInt(val); } else if (j == 5) { laxTotal += Integer.parseInt(val); } else if (j == 6) { laxPreempts += Integer.parseInt(val); } else if (j == 7) { laxActiv += Integer.parseInt(val); } else if (j == 8) { edfTotal += Integer.parseInt(val); } else if (j == 9) { edfPreempts += Integer.parseInt(val); } else if (j == 10) { edfActiv += Integer.parseInt(val); } else if (j == 11) { hybridTotal += Integer.parseInt(val); } else if (j == 12) { hybridPreempts += Integer.parseInt(val); } else if (j == 13) { hybridActiv += Integer.parseInt(val); } j++; } } } i++; } // Write percentage double fedPerc = (double) fedTotal / nbFiles; double laxPerc = (double) laxTotal / nbFiles; double edfPerc = (double) edfTotal / nbFiles; double hybridPerc = (double) hybridTotal / nbFiles; double fedPercPreempts = (double) fedPreempts / fedActiv; double laxPercPreempts = (double) laxPreempts / laxActiv; double edfPercPreempts = (double) edfPreempts / edfActiv; double hybridPercPreempts = (double) hybridPreempts / hybridActiv; Writer wOutput = new BufferedWriter(new FileWriter(outputFilePathTotal, true)); wOutput.write(Thread.currentThread().getName() + "; " + utilization + "; " + fedPerc + "; " + fedPreempts + "; " + fedActiv + "; " + fedPercPreempts + "; " + laxPerc + "; " + laxPreempts + "; " + laxActiv + "; " + laxPercPreempts + "; " + edfPerc + "; " + edfPreempts + "; " + edfActiv + "; " + edfPercPreempts + "; " + hybridPerc + "; " + hybridPreempts + "; " + hybridActiv + "; " + hybridPercPreempts + "\n"); wOutput.close(); } else if (nbLvls > 2) { int i_files2 = 0; String outFile = outputFilePath.substring(0, outputFilePath.lastIndexOf('.')) .concat("-schedulability.csv"); PrintWriter writer = new PrintWriter(outFile, "UTF-8"); writer.println( "Thread; File; LSched (%); LPreempts; LAct; ESched (%); EPreempts; EAct; HSched(%); HPreempts; HAct; Utilization"); writer.close(); ExecutorService executor2 = Executors.newFixedThreadPool(nbJobs); while (i_files2 != nbFiles) { BenchThreadNLevels bt2 = new BenchThreadNLevels(inputFilePath[i_files2], outFile, nbCores, boolDebug); executor2.execute(bt2); i_files2++; } executor2.shutdown(); executor2.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); int laxTotal = 0; int edfTotal = 0; int hybridTotal = 0; int laxPreempts = 0; int edfPreempts = 0; int hybridPreempts = 0; int laxActiv = 0; int edfActiv = 0; int hybridActiv = 0; // Read lines in file and do average int i = 0; File f = new File(outFile); @SuppressWarnings("resource") Scanner line = new Scanner(f); while (line.hasNextLine()) { String s = line.nextLine(); if (i > 0) { // To skip the first line try (Scanner inLine = new Scanner(s).useDelimiter("; ")) { int j = 0; while (inLine.hasNext()) { String val = inLine.next(); if (j == 2) { laxTotal += Integer.parseInt(val); } else if (j == 3) { laxPreempts += Integer.parseInt(val); } else if (j == 4) { laxActiv += Integer.parseInt(val); } else if (j == 5) { edfTotal += Integer.parseInt(val); } else if (j == 6) { edfPreempts += Integer.parseInt(val); } else if (j == 7) { edfActiv += Integer.parseInt(val); } else if (j == 8) { hybridTotal += Integer.parseInt(val); } else if (j == 9) { hybridPreempts += Integer.parseInt(val); } else if (j == 10) { hybridActiv += Integer.parseInt(val); } j++; } } } i++; } // Write percentage double laxPerc = (double) laxTotal / nbFiles; double edfPerc = (double) edfTotal / nbFiles; double hybridPerc = (double) hybridTotal / nbFiles; double laxPercPreempts = (double) laxPreempts / laxActiv; double edfPercPreempts = (double) edfPreempts / edfActiv; double hybridPercPreempts = (double) hybridPreempts / hybridActiv; Writer wOutput = new BufferedWriter(new FileWriter(outputFilePathTotal, true)); wOutput.write(Thread.currentThread().getName() + "; " + utilization + "; " + laxPerc + "; " + laxPreempts + "; " + laxActiv + "; " + laxPercPreempts + "; " + edfPerc + "; " + edfPreempts + "; " + edfActiv + "; " + edfPercPreempts + "; " + hybridPerc + "; " + hybridPreempts + "; " + hybridActiv + "; " + hybridPercPreempts + "\n"); wOutput.close(); } else { System.err.println("Wrong number of levels"); System.exit(-1); } System.out.println("[BENCH Main] Done benchmarking U = " + utilization + " Levels " + nbLvls); }
From source file:com.thoughtworks.xstream.tools.benchmark.parsers.ParserBenchmark.java
public static void main(String[] args) { int counter = 1000; Options options = new Options(); options.addOption("p", "product", true, "Class name of the product to use for benchmark"); options.addOption("n", true, "Number of repetitions"); Harness harness = new Harness(); harness.addMetric(new DeserializationSpeedMetric(0, false) { public String toString() { return "Initial run deserialization"; }/* w ww . jav a 2 s . c o m*/ }); Parser parser = new PosixParser(); try { CommandLine commandLine = parser.parse(options, args); String name = null; if (commandLine.hasOption('p')) { name = commandLine.getOptionValue('p'); } if (name == null || name.equals("DOM")) { harness.addProduct(new XStreamDom()); } if (name == null || name.equals("JDOM")) { harness.addProduct(new XStreamJDom()); } if (name == null || name.equals("DOM4J")) { harness.addProduct(new XStreamDom4J()); } if (name == null || name.equals("XOM")) { harness.addProduct(new XStreamXom()); } if (name == null || name.equals("BEAStAX")) { harness.addProduct(new XStreamBEAStax()); } if (name == null || name.equals("Woodstox")) { harness.addProduct(new XStreamWoodstox()); } if (JVM.is16() && (name == null || name.equals("SJSXP"))) { harness.addProduct(new XStreamSjsxp()); } if (name == null || name.equals("Xpp3")) { harness.addProduct(new XStreamXpp3()); } if (name == null || name.equals("kXML2")) { harness.addProduct(new XStreamKXml2()); } if (name == null || name.equals("Xpp3DOM")) { harness.addProduct(new XStreamXpp3DOM()); } if (name == null || name.equals("kXML2DOM")) { harness.addProduct(new XStreamKXml2DOM()); } if (commandLine.hasOption('n')) { counter = Integer.parseInt(commandLine.getOptionValue('n')); } } catch (ParseException e) { e.printStackTrace(); } harness.addMetric(new DeserializationSpeedMetric(counter, false)); harness.addTarget(new BasicTarget()); harness.addTarget(new ExtendedTarget()); harness.addTarget(new ReflectionTarget()); harness.addTarget(new SerializableTarget()); harness.addTarget(new JavaBeanTarget()); if (false) { harness.addTarget(new FieldReflection()); harness.addTarget(new HierarchyLevelReflection()); harness.addTarget(new InnerClassesReflection()); harness.addTarget(new StaticInnerClassesReflection()); } harness.run(new TextReporter(new PrintWriter(System.out, true))); System.out.println("Done."); }
From source file:friendsandfollowers.DBFollowersIDs.java
public static void main(String[] args) throws ClassNotFoundException, SQLException, JSONException, FileNotFoundException, UnsupportedEncodingException { // Check arguments that passed in if ((args == null) || (args.length == 0)) { System.err.println("2 Parameters are required plus one optional " + "parameter to launch a Job."); System.err.println("First: String 'OUTPUT: /output/path/'"); System.err.println("Second: (int) Number of ids to fetch. " + "Provide number which increment by 5000 " + "(5000, 10000, 15000 etc) " + "or -1 to fetch all ids."); System.err.println("Third (optional): 'screen_name / user_id_str'"); System.err.println("If 3rd argument not provided then provide" + " Twitter users through database."); System.exit(-1);//from ww w. ja va 2 s . c om } MysqlDB DB = new MysqlDB(); AppOAuth AppOAuths = new AppOAuth(); Misc helpers = new Misc(); String endpoint = "/followers/ids"; String OutputDirPath = null; try { OutputDirPath = StringEscapeUtils.escapeJava(args[0]); } catch (Exception e) { System.err.println("Argument" + args[0] + " must be an String."); System.exit(-1); } int IDS_TO_FETCH_INT = -1; try { IDS_TO_FETCH_INT = Integer.parseInt(args[1]); } catch (NumberFormatException e) { System.err.println("Argument" + args[1] + " must be an integer."); System.exit(-1); } int IDS_TO_FETCH = 0; if (IDS_TO_FETCH_INT > 5000) { float IDS_TO_FETCH_F = (float) IDS_TO_FETCH_INT / 5000; IDS_TO_FETCH = (int) Math.ceil(IDS_TO_FETCH_F); } else if ((IDS_TO_FETCH_INT <= 5000) && (IDS_TO_FETCH_INT > 0)) { IDS_TO_FETCH = 1; } String targetedUser = ""; if (args.length == 3) { try { targetedUser = StringEscapeUtils.escapeJava(args[2]); } catch (Exception e) { System.err.println("Argument" + args[2] + " must be an String."); System.exit(-1); } } try { TwitterFactory tf = AppOAuths.loadOAuthUser(endpoint); Twitter twitter = tf.getInstance(); int RemainingCalls = AppOAuths.RemainingCalls; int RemainingCallsCounter = 0; System.out.println("First Time Remianing Calls: " + RemainingCalls); String Screen_name = AppOAuths.screen_name; System.out.println("First Time Loaded OAuth Screen_name: " + Screen_name); IDs ids; System.out.println("Listing followers ids."); // if targetedUser not provided by argument, then look into database. if (StringUtils.isEmpty(targetedUser)) { String selectQuery = "SELECT * FROM `followers_parent` WHERE " + "`targeteduser` != '' AND " + "`nextcursor` != '0' AND " + "`nextcursor` != '2'"; ResultSet results = DB.selectQ(selectQuery); int numRows = DB.numRows(results); if (numRows < 1) { System.err.println("No User in database to get followersIDS"); System.exit(-1); } OUTERMOST: while (results.next()) { int followers_parent_id = results.getInt("id"); targetedUser = results.getString("targeteduser"); long cursor = results.getLong("nextcursor"); System.out.println("Targeted User: " + targetedUser); int idsLoopCounter = 0; int totalIDs = 0; // put idsJSON in a file PrintWriter writer = new PrintWriter(OutputDirPath + "/" + targetedUser, "UTF-8"); // call different functions for screen_name and id_str Boolean chckedNumaric = helpers.isNumeric(targetedUser); do { ids = null; try { if (chckedNumaric) { long LongValueTargetedUser = Long.valueOf(targetedUser).longValue(); ids = twitter.getFollowersIDs(LongValueTargetedUser, cursor); } else { ids = twitter.getFollowersIDs(targetedUser, cursor); } } catch (TwitterException te) { // do not throw if user has protected tweets, // or if they deleted their account if (te.getStatusCode() == HttpResponseCode.UNAUTHORIZED || te.getStatusCode() == HttpResponseCode.NOT_FOUND) { System.out.println(targetedUser + " is protected or account is deleted"); } else { System.out.println("Followers Get Exception: " + te.getMessage()); } // If rate limit reached then switch Auth user RemainingCallsCounter++; if (RemainingCallsCounter >= RemainingCalls) { // load auth user tf = AppOAuths.loadOAuthUser(endpoint); twitter = tf.getInstance(); System.out.println( "New User Loaded OAuth" + " Screen_name: " + AppOAuths.screen_name); RemainingCalls = AppOAuths.RemainingCalls; RemainingCallsCounter = 0; System.out.println("New Remianing Calls: " + RemainingCalls); } // update cursor in "followers_parent" String fieldValues = "`nextcursor` = 2"; String where = "id = " + followers_parent_id; DB.Update("`followers_parent`", fieldValues, where); // If error then switch to next user continue OUTERMOST; } if (ids.getIDs().length > 0) { idsLoopCounter++; totalIDs += ids.getIDs().length; System.out.println(idsLoopCounter + ": IDS length: " + ids.getIDs().length); JSONObject responseDetailsJson = new JSONObject(); JSONArray jsonArray = new JSONArray(); for (long id : ids.getIDs()) { jsonArray.put(id); } Object idsJSON = responseDetailsJson.put("ids", jsonArray); writer.println(idsJSON); } // If rate limit reached then switch Auth user RemainingCallsCounter++; if (RemainingCallsCounter >= RemainingCalls) { // load auth user tf = AppOAuths.loadOAuthUser(endpoint); twitter = tf.getInstance(); System.out.println("New User Loaded OAuth " + "Screen_name: " + AppOAuths.screen_name); RemainingCalls = AppOAuths.RemainingCalls; RemainingCallsCounter = 0; System.out.println("New Remianing Calls: " + RemainingCalls); } if (IDS_TO_FETCH_INT != -1) { if (idsLoopCounter == IDS_TO_FETCH) { break; } } } while ((cursor = ids.getNextCursor()) != 0); writer.close(); System.out.println("Total ids dumped of " + targetedUser + " are: " + totalIDs); System.out.println(); // update cursor in "followers_parent" String fieldValues = "`nextcursor` = " + cursor; String where = "id = " + followers_parent_id; DB.Update("`followers_parent`", fieldValues, where); } // loop through every result found in db } else { // Second Argument Set, so we are here. System.out.println("screen_name / user_id_str passed by argument"); int idsLoopCounter = 0; int totalIDs = 0; // put idsJSON in a file PrintWriter writer = new PrintWriter( OutputDirPath + "/" + targetedUser + "_ids_" + helpers.getUnixTimeStamp(), "UTF-8"); // call different functions for screen_name and id_str Boolean chckedNumaric = helpers.isNumeric(targetedUser); long cursor = -1; do { ids = null; try { if (chckedNumaric) { long LongValueTargetedUser = Long.valueOf(targetedUser).longValue(); ids = twitter.getFollowersIDs(LongValueTargetedUser, cursor); } else { ids = twitter.getFollowersIDs(targetedUser, cursor); } } catch (TwitterException te) { // do not throw if user has protected tweets, or if they deleted their account if (te.getStatusCode() == HttpResponseCode.UNAUTHORIZED || te.getStatusCode() == HttpResponseCode.NOT_FOUND) { System.out.println(targetedUser + " is protected or account is deleted"); } else { System.out.println("Followers Get Exception: " + te.getMessage()); } System.exit(-1); } if (ids.getIDs().length > 0) { idsLoopCounter++; totalIDs += ids.getIDs().length; System.out.println(idsLoopCounter + ": IDS length: " + ids.getIDs().length); JSONObject responseDetailsJson = new JSONObject(); JSONArray jsonArray = new JSONArray(); for (long id : ids.getIDs()) { jsonArray.put(id); } Object idsJSON = responseDetailsJson.put("ids", jsonArray); writer.println(idsJSON); } // If rate limit reach then switch Auth user RemainingCallsCounter++; if (RemainingCallsCounter >= RemainingCalls) { // load auth user tf = AppOAuths.loadOAuthUser(endpoint); twitter = tf.getInstance(); System.out.println("New User Loaded OAuth Screen_name: " + AppOAuths.screen_name); RemainingCalls = AppOAuths.RemainingCalls; RemainingCallsCounter = 0; System.out.println("New Remianing Calls: " + RemainingCalls); } if (IDS_TO_FETCH_INT != -1) { if (idsLoopCounter == IDS_TO_FETCH) { break; } } } while ((cursor = ids.getNextCursor()) != 0); writer.close(); System.out.println("Total ids dumped of " + targetedUser + " are: " + totalIDs); System.out.println(); } } catch (TwitterException te) { // te.printStackTrace(); System.err.println("Failed to get followers' ids: " + te.getMessage()); System.exit(-1); } System.out.println("!!!! DONE !!!!"); }