List of usage examples for java.lang System in
InputStream in
To view the source code for java.lang System in.
Click Source Link
From source file:fr.ippon.tatami.test.support.LdapTestServer.java
/** * Main class. We just do a lookup on the server to check that it's available. * /*from w w w . j av a 2 s . c o m*/ * @param args * Not used. * @throws Exception */ public static void main(String[] args) throws Exception // throws Exception { FileUtils.deleteDirectory(workingDir); LdapTestServer ads = null; try { // Create the server ads = new LdapTestServer(); ads.start(); // Read an entry Entry result = ads.service.getAdminSession().lookup(new LdapDN("dc=ippon,dc=fr")); // And print it if available System.out.println("Found entry : " + result); } catch (Exception e) { // Ok, we have something wrong going on ... e.printStackTrace(); } System.out.println("Press enter"); new BufferedReader(new InputStreamReader(System.in)).readLine(); ads.stop(); }
From source file:org.eclipse.oomph.internal.util.HTTPServer.java
public static void main(String[] args) throws Exception { HTTPServer server = new HTTPServer(80, 100); server.addContext(new FileContext("/file/c", true, new File("C:"))); server.addContext(new FileContext("/file/e", true, new File("E:"))); System.out.println("http://localhost:" + server.getPort()); System.out.println();/*from www.j ava 2 s . c o m*/ while (System.in.available() == 0) { Thread.sleep(50); } server.stop(); }
From source file:com.github.ruananswer.stl.StlPlotter.java
public static void main(String[] args) throws Exception { List<Double> times = new ArrayList<Double>(); List<Double> series = new ArrayList<Double>(); List<Double> trend = new ArrayList<Double>(); List<Double> seasonal = new ArrayList<Double>(); List<Double> remainder = new ArrayList<Double>(); // Read from STDIN String line;/* ww w. ja va 2 s. com*/ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while ((line = reader.readLine()) != null) { String[] tokens = line.split(","); times.add(Double.valueOf(tokens[0])); series.add(Double.valueOf(tokens[1])); trend.add(Double.valueOf(tokens[2])); seasonal.add(Double.valueOf(tokens[3])); remainder.add(Double.valueOf(tokens[4])); } STLResult res = new STLResult(convert(trend), convert(seasonal), convert(remainder)); double[] tmpSeries = convert(series); double[] tmpTimes = convert(times); if (args.length == 1) { plot(res, tmpSeries, tmpTimes, new File(args[0])); } else { plotOnScreen(res, tmpSeries, tmpTimes, "Seasonal Decomposition"); } }
From source file:PeerDiscovery.java
/** * @param args//from w ww. j a v a2s . c om */ public static void main(String[] args) { try { int group = 6969; PeerDiscovery mp = new PeerDiscovery(group, 6969); boolean stop = false; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (!stop) { System.out.println("enter \"q\" to quit, or anything else to query peers"); String s = br.readLine(); if (s.equals("q")) { System.out.print("Closing down..."); mp.disconnect(); System.out.println(" done"); stop = true; } else { System.out.println("Querying"); Peer[] peers = mp.getPeers(100, (byte) 0); System.out.println(peers.length + " peers found"); for (Peer p : peers) { System.out.println("\t" + p); } } } } catch (Exception e) { e.printStackTrace(); } }
From source file:ca.uqac.info.monitor.BeepBeepMonitor.java
public static void main(String[] args) { int verbosity = 1, slowdown = 0, tcp_port = 0; boolean show_stats = false, to_stdout = false; String trace_filename = "", pipe_filename = "", event_name = "message"; final MonitorFactory mf = new MonitorFactory(); // In case we open a socket ServerSocket m_serverSocket = null; Socket m_connection = null;//from w w w .ja va2 s .co m // Parse command line arguments Options options = setupOptions(); CommandLine c_line = setupCommandLine(args, options); assert c_line != null; if (c_line.hasOption("verbosity")) { verbosity = Integer.parseInt(c_line.getOptionValue("verbosity")); } if (verbosity > 0) { showHeader(); } if (c_line.hasOption("version")) { System.err.println("(C) 2008-2013 Sylvain Hall et al., Universit du Qubec Chicoutimi"); System.err.println("This program comes with ABSOLUTELY NO WARRANTY."); System.err.println("This is a free software, and you are welcome to redistribute it"); System.err.println("under certain conditions. See the file COPYING for details.\n"); System.exit(ERR_OK); } if (c_line.hasOption("h")) { showUsage(options); System.exit(ERR_OK); } if (c_line.hasOption("version")) { System.exit(ERR_OK); } if (c_line.hasOption("slowdown")) { slowdown = Integer.parseInt(c_line.getOptionValue("slowdown")); if (verbosity > 0) System.err.println("Slowdown factor: " + slowdown + " ms"); } if (c_line.hasOption("stats")) { show_stats = true; } if (c_line.hasOption("csv")) { // Will output data in CSV format to stdout to_stdout = true; } if (c_line.hasOption("eventname")) { // Set event name event_name = c_line.getOptionValue("eventname"); } if (c_line.hasOption("t")) { // Read events from a trace trace_filename = c_line.getOptionValue("t"); } if (c_line.hasOption("p")) { // Read events from a pipe pipe_filename = c_line.getOptionValue("p"); } if (c_line.hasOption("k")) { // Read events from a TCP port tcp_port = Integer.parseInt(c_line.getOptionValue("k")); } if (!trace_filename.isEmpty() && !pipe_filename.isEmpty()) { System.err.println("ERROR: you must specify at most one of trace file or named pipe"); showUsage(options); System.exit(ERR_ARGUMENTS); } @SuppressWarnings("unchecked") List<String> remaining_args = c_line.getArgList(); if (remaining_args.isEmpty()) { System.err.println("ERROR: no input formula specified"); showUsage(options); System.exit(ERR_ARGUMENTS); } // Instantiate the event notifier boolean notify = (verbosity > 0); EventNotifier en = new EventNotifier(notify); en.m_slowdown = slowdown; en.m_csvToStdout = to_stdout; // Create one monitor for each input file and add it to the notifier for (String formula_filename : remaining_args) { try { String formula_contents = FileReadWrite.readFile(formula_filename); Operator op = Operator.parseFromString(formula_contents); op.accept(mf); Monitor mon = mf.getMonitor(); Map<String, String> metadata = getMetadata(formula_contents); metadata.put("Filename", formula_filename); en.addMonitor(mon, metadata); } catch (IOException e) { e.printStackTrace(); System.exit(ERR_IO); } catch (Operator.ParseException e) { System.err.println("Error parsing input formula"); System.exit(ERR_PARSE); } } // Read trace and iterate // Opens file PipeReader pr = null; try { if (!pipe_filename.isEmpty()) { // We tell the pipe reader we read a pipe File f = new File(pipe_filename); if (verbosity > 0) System.err.println("Reading from pipe named " + f.getName()); pr = new PipeReader(new FileInputStream(f), en, false); } else if (!trace_filename.isEmpty()) { // We tell the pipe reader we read a regular file File f = new File(trace_filename); if (verbosity > 0) System.err.println("Reading from file " + f.getName()); pr = new PipeReader(new FileInputStream(f), en, true); } else if (tcp_port > 0) { // We tell the pipe reader we read from a socket if (verbosity > 0) System.err.println("Reading from TCP port " + tcp_port); m_serverSocket = new ServerSocket(tcp_port); m_connection = m_serverSocket.accept(); pr = new PipeReader(m_connection.getInputStream(), en, false); } else { // We tell the pipe reader we read from standard input if (verbosity > 0) System.err.println("Reading from standard input"); pr = new PipeReader(System.in, en, false); } } catch (FileNotFoundException ex) { // We print both trace and pipe since one of them must be empty System.err.println("ERROR: file not found " + trace_filename + pipe_filename); System.exit(ERR_IO); } catch (IOException e) { // Caused by socket error e.printStackTrace(); System.exit(ERR_IO); } pr.setSeparator("<" + event_name + ">", "</" + event_name + ">"); // Check parameters for the event notifier if (c_line.hasOption("no-trigger")) { en.m_notifyOnVerdict = false; } else { en.m_notifyOnVerdict = true; } if (c_line.hasOption("mirror")) { en.m_mirrorEventsOnStdout = true; } // Start event notifier en.reset(); Thread th = new Thread(pr); long clock_start = System.nanoTime(); th.start(); try { th.join(); // Wait for thread to finish } catch (InterruptedException e1) { // Thread is finished } if (tcp_port > 0 && m_serverSocket != null) { // We opened a socket; now we close it try { m_serverSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } long clock_end = System.nanoTime(); int ret_code = pr.getReturnCode(); switch (ret_code) { case PipeReader.ERR_EOF: if (verbosity > 0) System.err.println("\nEnd of file reached"); break; case PipeReader.ERR_EOT: if (verbosity > 0) System.err.println("\nEOT received on pipe: closing"); break; case PipeReader.ERR_OK: // Do nothing break; default: // An error System.err.println("Runtime error"); System.exit(ERR_RUNTIME); break; } if (show_stats) { if (verbosity > 0) { System.out.println("Messages: " + en.m_numEvents); System.out.println("Time: " + (int) (en.m_totalTime / 1000000f) + " ms"); System.out.println("Clock time: " + (int) ((clock_end - clock_start) / 1000000f) + " ms"); System.out.println("Max heap: " + (int) (en.heapSize / 1048576f) + " MB"); } else { // If stats are asked but verbosity = 0, only show time value // (both monitor and wall clock) System.out.print((int) (en.m_totalTime / 1000000f)); System.out.print(","); System.out.print((int) ((clock_end - clock_start) / 1000000f)); } } System.exit(ERR_OK); }
From source file:com.netflix.aegisthus.tools.SSTableExport.java
@SuppressWarnings("rawtypes") public static void main(String[] args) throws IOException { String usage = String.format("Usage: %s <sstable>", SSTableExport.class.getName()); CommandLineParser parser = new PosixParser(); try {/*w w w .ja va 2 s . c o m*/ cmd = parser.parse(options, args); } catch (ParseException e1) { System.err.println(e1.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(usage, options); System.exit(1); } if (cmd.getArgs().length != 1) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(usage, options); System.exit(1); } Map<String, AbstractType> convertors = null; if (cmd.hasOption(COLUMN_NAME_TYPE)) { try { convertors = new HashMap<String, AbstractType>(); convertors.put(SSTableScanner.COLUMN_NAME_KEY, TypeParser.parse(cmd.getOptionValue(COLUMN_NAME_TYPE))); } catch (ConfigurationException e) { System.err.println(e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(usage, options); System.exit(1); } catch (SyntaxException e) { System.err.println(e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(usage, options); System.exit(1); } } Descriptor.Version version = null; if (cmd.hasOption(OPT_VERSION)) { version = new Descriptor.Version(cmd.getOptionValue(OPT_VERSION)); } if (cmd.hasOption(INDEX_SPLIT)) { String ssTableFileName; DataInput input = null; if ("-".equals(cmd.getArgs()[0])) { ssTableFileName = System.getProperty("aegisthus.file.name"); input = new DataInputStream(new BufferedInputStream(System.in, 65536 * 10)); } else { ssTableFileName = new File(cmd.getArgs()[0]).getAbsolutePath(); input = new DataInputStream( new BufferedInputStream(new FileInputStream(ssTableFileName), 65536 * 10)); } exportIndexSplit(ssTableFileName, input); } else if (cmd.hasOption(INDEX)) { String ssTableFileName = new File(cmd.getArgs()[0]).getAbsolutePath(); exportIndex(ssTableFileName); } else if (cmd.hasOption(ROWSIZE)) { String ssTableFileName = new File(cmd.getArgs()[0]).getAbsolutePath(); exportRowSize(ssTableFileName); } else if ("-".equals(cmd.getArgs()[0])) { if (version == null) { System.err.println("when streaming must supply file version"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(usage, options); System.exit(1); } exportStream(version); } else { String ssTableFileName = new File(cmd.getArgs()[0]).getAbsolutePath(); FileInputStream fis = new FileInputStream(ssTableFileName); InputStream inputStream = new DataInputStream(new BufferedInputStream(fis, 65536 * 10)); long end = -1; if (cmd.hasOption(END)) { end = Long.valueOf(cmd.getOptionValue(END)); } if (cmd.hasOption(OPT_COMP)) { CompressionMetadata cm = new CompressionMetadata( new BufferedInputStream(new FileInputStream(cmd.getOptionValue(OPT_COMP)), 65536), fis.getChannel().size()); inputStream = new CompressionInputStream(inputStream, cm); end = cm.getDataLength(); } DataInputStream input = new DataInputStream(inputStream); if (version == null) { version = Descriptor.fromFilename(ssTableFileName).version; } SSTableScanner scanner = new SSTableScanner(input, convertors, end, version); if (cmd.hasOption(OPT_MAX_COLUMN_SIZE)) { scanner.setMaxColSize(Long.parseLong(cmd.getOptionValue(OPT_MAX_COLUMN_SIZE))); } export(scanner); if (cmd.hasOption(OPT_MAX_COLUMN_SIZE)) { if (scanner.getErrorRowCount() > 0) { System.err.println(String.format("%d rows were too large", scanner.getErrorRowCount())); } } } }
From source file:com.genentech.chemistry.openEye.apps.enumerate.SDFEnumerator.java
public static void main(String... args) throws IOException { Options options = new Options(); Option opt = new Option("out", true, "output file oe-supported"); opt.setRequired(true);/* w w w.j a v a 2s . c o m*/ options.addOption(opt); opt = new Option("hydrogenExplicit", false, "Use explicit hydrogens"); options.addOption(opt); opt = new Option("correctValences", false, "Correct valences after the enumeration"); options.addOption(opt); opt = new Option("regenerate2D", false, "Regenerate 2D coordinates for the products"); options.addOption(opt); opt = new Option("reactAllSites", false, "Generate a product for each match in a reagent."); options.addOption(opt); opt = new Option("randomFraction", true, "Only output a fraction of the products."); options.addOption(opt); opt = new Option("maxAtoms", true, "Only output products with <= maxAtoms."); options.addOption(opt); opt = new Option("notReacted", true, "Output file for reagents that didn't produce at leaste one output molecule, useful for debugging SMIRKS."); options.addOption(opt); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (Exception e) { System.err.println(e.getMessage()); exitWithHelp("", options); } args = cmd.getArgs(); if (args.length < 2) { exitWithHelp("Transformation and/or reagentFiles missing", options); } String smirks = args[0]; if (new File(smirks).canRead()) smirks = IOUtil.fileToString(smirks).trim(); if (!smirks.contains(">>")) smirks = scaffoldToSmirks(smirks); String[] reagentSmiOrFiles = Arrays.copyOfRange(args, 1, args.length); if (cmd.hasOption("d")) { System.err.println("Start debugger and press return:"); new BufferedReader(new InputStreamReader(System.in)).readLine(); } String outFile = cmd.getOptionValue("out"); OELibraryGen lg = new OELibraryGen(); lg.Init(smirks); if (!lg.IsValid()) exitWithHelp("Invalid Transform: " + smirks, options); lg.SetExplicitHydrogens(cmd.hasOption("hydrogenExplicit")); lg.SetValenceCorrection(cmd.hasOption("correctValences")); lg.SetRemoveUnmappedFragments(true); boolean regenerate2D = cmd.hasOption("regenerate2D"); boolean reactAllSites = cmd.hasOption("reactAllSites"); String unreactedFile = null; if (cmd.hasOption("notReacted")) { unreactedFile = cmd.getOptionValue("notReacted"); } double randomFract = 2; if (cmd.hasOption("randomFraction")) randomFract = Double.parseDouble(cmd.getOptionValue("randomFraction")); int maxAtoms = 0; if (cmd.hasOption("maxAtoms")) maxAtoms = Integer.parseInt(cmd.getOptionValue("maxAtoms")); SDFEnumerator en = new SDFEnumerator(lg, reactAllSites, reagentSmiOrFiles); en.generateLibrary(outFile, maxAtoms, randomFract, regenerate2D, unreactedFile); en.delete(); }
From source file:org.tommy.stationery.moracle.core.client.load.StompWebSocketLoadTestClient.java
public static void main(String[] args) throws Exception { // Modify host and port below to match wherever StompWebSocketServer.java is running!! // When StompWebSocketServer starts it prints the selected available String host = "localhost"; if (args.length > 0) { host = args[0];/*from w w w .j av a2 s. c o m*/ } int port = 59984; if (args.length > 1) { port = Integer.valueOf(args[1]); } String url = "http://" + host + ":" + port + "/home"; logger.debug("Sending warm-up HTTP request to " + url); HttpStatus status = new RestTemplate().getForEntity(url, Void.class).getStatusCode(); Assert.state(status == HttpStatus.OK); final CountDownLatch connectLatch = new CountDownLatch(NUMBER_OF_USERS); final CountDownLatch subscribeLatch = new CountDownLatch(NUMBER_OF_USERS); final CountDownLatch messageLatch = new CountDownLatch(NUMBER_OF_USERS); final CountDownLatch disconnectLatch = new CountDownLatch(NUMBER_OF_USERS); final AtomicReference<Throwable> failure = new AtomicReference<Throwable>(); Executor executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE); org.eclipse.jetty.websocket.client.WebSocketClient jettyClient = new WebSocketClient(executor); JettyWebSocketClient webSocketClient = new JettyWebSocketClient(jettyClient); webSocketClient.start(); HttpClient jettyHttpClient = new HttpClient(); jettyHttpClient.setMaxConnectionsPerDestination(1000); jettyHttpClient.setExecutor(new QueuedThreadPool(1000)); jettyHttpClient.start(); List<Transport> transports = new ArrayList<>(); transports.add(new WebSocketTransport(webSocketClient)); transports.add(new JettyXhrTransport(jettyHttpClient)); SockJsClient sockJsClient = new SockJsClient(transports); try { URI uri = new URI("ws://" + host + ":" + port + "/stomp"); WebSocketStompClient stompClient = new WebSocketStompClient(uri, null, sockJsClient); stompClient.setMessageConverter(new StringMessageConverter()); logger.debug("Connecting and subscribing " + NUMBER_OF_USERS + " users "); StopWatch stopWatch = new StopWatch("STOMP Broker Relay WebSocket Load Tests"); stopWatch.start(); List<ConsumerStompMessageHandler> consumers = new ArrayList<>(); for (int i = 0; i < NUMBER_OF_USERS; i++) { consumers.add(new ConsumerStompMessageHandler(BROADCAST_MESSAGE_COUNT, connectLatch, subscribeLatch, messageLatch, disconnectLatch, failure)); stompClient.connect(consumers.get(i)); } if (failure.get() != null) { throw new AssertionError("Test failed", failure.get()); } if (!connectLatch.await(5000, TimeUnit.MILLISECONDS)) { logger.info("Not all users connected, remaining: " + connectLatch.getCount()); } if (!subscribeLatch.await(5000, TimeUnit.MILLISECONDS)) { logger.info("Not all users subscribed, remaining: " + subscribeLatch.getCount()); } stopWatch.stop(); logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis"); logger.debug("Broadcasting " + BROADCAST_MESSAGE_COUNT + " messages to " + NUMBER_OF_USERS + " users "); stopWatch.start(); ProducerStompMessageHandler producer = new ProducerStompMessageHandler(BROADCAST_MESSAGE_COUNT, failure); stompClient.connect(producer); if (failure.get() != null) { throw new AssertionError("Test failed", failure.get()); } if (!messageLatch.await(1 * 60 * 1000, TimeUnit.MILLISECONDS)) { for (ConsumerStompMessageHandler consumer : consumers) { if (consumer.messageCount.get() < consumer.expectedMessageCount) { logger.debug(consumer); } } } if (!messageLatch.await(1 * 60 * 1000, TimeUnit.MILLISECONDS)) { logger.info("Not all handlers received every message, remaining: " + messageLatch.getCount()); } producer.session.disconnect(); if (!disconnectLatch.await(5000, TimeUnit.MILLISECONDS)) { logger.info("Not all disconnects completed, remaining: " + disconnectLatch.getCount()); } stopWatch.stop(); logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis"); System.out.println("\nPress any key to exit..."); System.in.read(); } catch (Throwable t) { t.printStackTrace(); } finally { webSocketClient.stop(); jettyHttpClient.stop(); } logger.debug("Exiting"); System.exit(0); }
From source file:edu.oregonstate.eecs.mcplan.domains.inventory.InventorySimulator.java
public static void main(final String[] argv) throws IOException { final RandomGenerator rng = new MersenneTwister(42); final int Nproducts = 2; final int max_inventory = 10; final double warehouse_cost = 1; final int min_order = 1; final int max_order = 2; final double delivery_probability = 0.5; final int max_demand = 5; final int[] price = new int[] { 1, 2 }; final InventoryProblem problem = InventoryProblem.TwoProducts(); // Nproducts, price, max_inventory, warehouse_cost, min_order, max_order, delivery_probability, max_demand ); while (true) { final InventoryState s = new InventoryState(rng, problem); final InventorySimulator sim = new InventorySimulator(s); final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (!s.isTerminal()) { System.out.println(sim.state()); final String cmd = reader.readLine(); final String[] tokens = cmd.split(","); final InventoryAction a; if ("n".equals(tokens[0])) { a = new InventoryNothingAction(); } else { final int product = Integer.parseInt(tokens[0]); final int quantity = Integer.parseInt(tokens[1]); a = new InventoryOrderAction(product, quantity, s.problem.cost[product]); }/*www. j ava 2 s. c o m*/ sim.takeAction(new JointAction<InventoryAction>(a)); System.out.println("r = " + Arrays.toString(sim.reward())); } // System.out.print( "Hand: " ); // System.out.print( sim.state().player_hand ); // System.out.print( " (" ); // final ArrayList<int[]> values = sim.state().player_hand.values(); // for( int i = 0; i < values.size(); ++i ) { // if( i > 0 ) { // System.out.print( ", " ); // } // System.out.print( Arrays.toString( values.get( i ) ) ); // } // System.out.println( ")" ); // // System.out.print( "Reward: " ); // System.out.println( Arrays.toString( sim.reward() ) ); // System.out.print( "Dealer hand: " ); // System.out.print( sim.state().dealerHand().toString() ); // System.out.print( " (" ); // System.out.print( SpBjHand.handValue( sim.state().dealerHand() )[0] ); // System.out.println( ")" ); // System.out.println( "----------------------------------------" ); } }
From source file:org.alfresco.filesys.NFSServerBean.java
/** * Runs the NFS server directly/*from w ww. j av a 2 s .co m*/ * * @param args String[] */ public static void main(String[] args) { PrintStream out = System.out; out.println("NFS Server Test"); out.println("----------------"); try { // Create the configuration service in the same way that Spring creates it ApplicationContext ctx = new ClassPathXmlApplicationContext("alfresco/application-context.xml"); // Get the NFS server bean NFSServerBean server = (NFSServerBean) ctx.getBean("nfsServer"); if (server == null) { throw new AlfrescoRuntimeException("Server bean 'nfsServer' not defined"); } // Stop the FTP server, if running NetworkServer srv = server.getConfiguration().findServer("FTP"); if (srv != null) srv.shutdownServer(true); // Stop the CIFS server, if running srv = server.getConfiguration().findServer("SMB"); if (srv != null) srv.shutdownServer(true); // Only wait for shutdown if the NFS server is enabled if (server.getConfiguration().hasConfigSection(NFSConfigSection.SectionName)) { // NFS server should have automatically started // Wait for shutdown via the console out.println("Enter 'x' to shutdown ..."); boolean shutdown = false; // Wait while the server runs, user may stop the server by typing a key while (shutdown == false) { // Wait for the user to enter the shutdown key int ch = System.in.read(); if (ch == 'x' || ch == 'X') shutdown = true; synchronized (server) { server.wait(20); } } // Stop the server server.stopServer(); } } catch (Exception ex) { ex.printStackTrace(); } System.exit(1); }