List of usage examples for java.util List add
boolean add(E e);
From source file:com.act.analysis.similarity.SimilarityAnalysis.java
public static void main(String[] args) throws Exception { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());//from w ww . j a va 2 s. co m } 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()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } LicenseManager.setLicenseFile(cl.getOptionValue(OPTION_LICENSE_FILE)); if (cl.hasOption(OPTION_TARGET_INCHI) && cl.hasOption(OPTION_TARGET_FILE)) { System.err.format("Specify only one of -%s or -%s\n", OPTION_TARGET_INCHI, OPTION_TARGET_FILE); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } List<SimilarityOperator> querySimilarityOperators = new ArrayList<>(); List<String> header = new ArrayList<>(); header.add("name"); header.add("id"); header.add("inchi"); if (cl.hasOption(OPTION_QUERY_INCHI) && !cl.hasOption(OPTION_QUERY_FILE)) { SimilarityOperator so = makeSimilarityOperators("from inchi", cl.getOptionValue(OPTION_QUERY_INCHI)); so.init(); querySimilarityOperators.add(so); header.addAll(so.getResultFields()); } else if (cl.hasOption(OPTION_QUERY_FILE) && !cl.hasOption(OPTION_QUERY_INCHI)) { TSVParser parser = new TSVParser(); parser.parse(new File(cl.getOptionValue(OPTION_QUERY_FILE))); for (Map<String, String> row : parser.getResults()) { System.out.format("Compiling query for %s, %s\n", row.get("name"), row.get("inchi")); SimilarityOperator so = makeSimilarityOperators(row.get("name"), row.get("inchi")); so.init(); querySimilarityOperators.add(so); header.addAll(so.getResultFields()); } } else { System.err.format("Specify exactly one of -%s or -%s\n", OPTION_QUERY_INCHI, OPTION_QUERY_FILE); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } List<Map<String, String>> targetChemicals = null; if (cl.hasOption(OPTION_TARGET_INCHI) && !cl.hasOption(OPTION_TARGET_FILE)) { String inchi = cl.getOptionValue(OPTION_TARGET_INCHI); targetChemicals = Collections.singletonList(new HashMap<String, String>() { { put("name", "direct-input"); put("id", null); put("inchi", inchi); } }); } else if (cl.hasOption(OPTION_TARGET_FILE) && !cl.hasOption(OPTION_TARGET_INCHI)) { TSVParser parser = new TSVParser(); parser.parse(new File(cl.getOptionValue(OPTION_TARGET_FILE))); targetChemicals = parser.getResults(); } else { System.err.format("Specify exactly one of -%s or -%s\n", OPTION_TARGET_INCHI, OPTION_TARGET_FILE); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } AlignmentMoleculeFactory alignmentMoleculeFactory = new AlignmentMoleculeFactory(); // TODO: add symmetric computations for target as query and each query as target. TSVWriter<String, String> writer = new TSVWriter<>(header); writer.open(new File(cl.getOptionValue(OPTION_OUTPUT_FILE))); try { for (Map<String, String> row : targetChemicals) { Molecule targetMol = MolImporter.importMol(row.get("inchi")); Cleaner.clean(targetMol, 3); // This will assign 3D atom coordinates to the MolAtoms in targetMol. Molecule targetFragment = findLargestFragment(targetMol.convertToFrags()); AlignmentMolecule am = alignmentMoleculeFactory.create(targetFragment, AlignmentProperties.DegreeOfFreedomType.TRANSLATE_ROTATE_FLEXIBLE); Map<String, String> outputRow = new HashMap<>(row); System.out.format("Processing target %s\n", row.get("name")); for (SimilarityOperator so : querySimilarityOperators) { System.out.format(" running query %s\n", so.getName()); Map<String, Double> results = so.calculateSimilarity(am); outputRow.putAll(doubleMapToStringMap(results)); } writer.append(outputRow); writer.flush(); } } finally { if (writer != null) { writer.close(); } } System.out.format("Done\n"); }
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 www. j ava 2 s . co 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:com.stratio.decision.executables.DataFlowFromCsvMain.java
public static void main(String[] args) throws IOException, NumberFormatException, InterruptedException { if (args.length < 4) { log.info(//from ww w . jav a 2 s.com "Usage: \n param 1 - path to file \n param 2 - stream name to send the data \n param 3 - time in ms to wait to send each data \n param 4 - broker list"); } else { Producer<String, String> producer = new Producer<String, String>(createProducerConfig(args[3])); Gson gson = new Gson(); Reader in = new FileReader(args[0]); CSVParser parser = CSVFormat.DEFAULT.parse(in); List<String> columnNames = new ArrayList<>(); for (CSVRecord csvRecord : parser.getRecords()) { if (columnNames.size() == 0) { Iterator<String> iterator = csvRecord.iterator(); while (iterator.hasNext()) { columnNames.add(iterator.next()); } } else { StratioStreamingMessage message = new StratioStreamingMessage(); message.setOperation(STREAM_OPERATIONS.MANIPULATION.INSERT.toLowerCase()); message.setStreamName(args[1]); message.setTimestamp(System.currentTimeMillis()); message.setSession_id(String.valueOf(System.currentTimeMillis())); message.setRequest_id(String.valueOf(System.currentTimeMillis())); message.setRequest("dummy request"); List<ColumnNameTypeValue> sensorData = new ArrayList<>(); for (int i = 0; i < columnNames.size(); i++) { // Workaround Object value = null; try { value = Double.valueOf(csvRecord.get(i)); } catch (NumberFormatException e) { value = csvRecord.get(i); } sensorData.add(new ColumnNameTypeValue(columnNames.get(i), null, value)); } message.setColumns(sensorData); String json = gson.toJson(message); log.info("Sending data: {}", json); producer.send(new KeyedMessage<String, String>(InternalTopic.TOPIC_DATA.getTopicName(), STREAM_OPERATIONS.MANIPULATION.INSERT, json)); log.info("Sleeping {} ms...", args[2]); Thread.sleep(Long.valueOf(args[2])); } } log.info("Program completed."); } }
From source file:de.jackwhite20.japs.server.Main.java
public static void main(String[] args) throws Exception { Config config = null;/*from w w w . j av a2 s . c om*/ if (args.length > 0) { Options options = new Options(); options.addOption("h", true, "Address to bind to"); options.addOption("p", true, "Port to bind to"); options.addOption("b", true, "The backlog"); options.addOption("t", true, "Worker thread count"); options.addOption("d", false, "If debug is enabled or not"); options.addOption("c", true, "Add server as a cluster"); options.addOption("ci", true, "Sets the cache check interval"); options.addOption("si", true, "Sets the snapshot interval"); CommandLineParser commandLineParser = new BasicParser(); CommandLine commandLine = commandLineParser.parse(options, args); if (commandLine.hasOption("h") && commandLine.hasOption("p") && commandLine.hasOption("b") && commandLine.hasOption("t")) { List<ClusterServer> clusterServers = new ArrayList<>(); if (commandLine.hasOption("c")) { for (String c : commandLine.getOptionValues("c")) { String[] splitted = c.split(":"); clusterServers.add(new ClusterServer(splitted[0], Integer.parseInt(splitted[1]))); } } config = new Config(commandLine.getOptionValue("h"), Integer.parseInt(commandLine.getOptionValue("p")), Integer.parseInt(commandLine.getOptionValue("b")), commandLine.hasOption("d"), Integer.parseInt(commandLine.getOptionValue("t")), clusterServers, (commandLine.hasOption("ci")) ? Integer.parseInt(commandLine.getOptionValue("ci")) : 300, (commandLine.hasOption("si")) ? Integer.parseInt(commandLine.getOptionValue("si")) : -1); } else { System.out.println( "Usage: java -jar japs-server.jar -h <Host> -p <Port> -b <Backlog> -t <Threads> [-c IP:Port IP:Port] [-d]"); System.out.println( "Example (with debugging enabled): java -jar japs-server.jar -h localhost -p 1337 -b 100 -t 4 -d"); System.out.println( "Example (with debugging enabled and cluster setup): java -jar japs-server.jar -h localhost -p 1337 -b 100 -t 4 -c localhost:1338 -d"); System.exit(-1); } } else { File configFile = new File("config.json"); if (!configFile.exists()) { try { Files.copy(JaPS.class.getClassLoader().getResourceAsStream("config.json"), configFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { System.err.println("Unable to load default config!"); System.exit(-1); } } try { config = new Gson().fromJson( Files.lines(configFile.toPath()).map(String::toString).collect(Collectors.joining(" ")), Config.class); } catch (IOException e) { System.err.println("Unable to load 'config.json' in current directory!"); System.exit(-1); } } if (config == null) { System.err.println("Failed to create a Config!"); System.err.println("Please check the program parameters or the 'config.json' file!"); } else { System.err.println("Using Config: " + config); JaPS jaPS = new JaPS(config); jaPS.init(); jaPS.start(); jaPS.stop(); } }
From source file:com.hotwire.sid.QuovaIP_GeoServerAdapter.java
public static void main(String[] args) throws HwIP_GeoException, IOException { AppProperties app = new AppProperties(); Properties prop = app.readProperties(); QuovaIP_GeoServerAdapter q = new QuovaIP_GeoServerAdapter(); q.setHwProps(prop);//from w w w. j a va 2s. c om q.configurationChanged(); IP_GeoResponse s = q.lookup("68.184.77.220"); System.out.println(s.to_String()); q.printDetails(s); List<String> ips = new ArrayList<>(); ips.add("172.17.29.112"); ips.add("192.172.150.56"); for (String ip : ips) { IP_GeoResponse r = q.lookup(ip); System.out.println("---------------------------------------------------"); System.out.println(ip); q.printDetails(r); } }
From source file:com.basho.contact.ContactConsole.java
public static void main(String[] args) throws IOException { CommandLine commandLine = processArgs(args); ConsoleReader reader = new ConsoleReader(); reader.setBellEnabled(false);/*from w w w. j a v a 2 s . c o m*/ reader.setExpandEvents(false); // TODO: look into this // TODO: Pasting in text with tabs prints out a ton of completions //reader.addCompleter(new jline.console.completer.StringsCompleter(keywords)); String line; PrintWriter out = new PrintWriter(System.out); DefaultConnectionProvider connections = new DefaultConnectionProvider(); RuntimeContext ctx = new RuntimeContext(connections, System.out, System.err); if (!commandLine.hasOption("nosignals")) { ConsoleSignalHander.install("INT", ctx); } ContactWalker walker = new ContactWalker(ctx); ContactAdminWalker adminWalker = new ContactAdminWalker(ctx); List<ContactBaseListener> walkers = new ArrayList<ContactBaseListener>(); walkers.add(walker); walkers.add(adminWalker); boolean nextLinePrompt = false; ANSIBuffer buf = new ANSIBuffer(); buf.setAnsiEnabled(!commandLine.hasOption("nocolor")); buf.blue("Welcome to Riak Contact\n"); buf.blue("(c) 2013 Dave Parfitt\n"); System.out.println(buf.toString()); if (!commandLine.hasOption("noconfig")) { String config = null; try { config = readConfig(); } catch (Exception e) { e.printStackTrace(); } if (config != null && !config.trim().isEmpty()) { processInput(config, walkers, ctx); processOutput(ctx, out, !commandLine.hasOption("nocolor")); } } if (commandLine.hasOption("infile")) { String filename = commandLine.getOptionValue("infile"); readInputFile(filename, walkers, ctx); ctx.getActionListener().term(); System.exit(0); } StringBuffer lines = new StringBuffer(); ANSIBuffer ansiprompt = new ANSIBuffer(); ansiprompt.setAnsiEnabled(true); ansiprompt.green("> "); String prompt = ansiprompt.toString(!commandLine.hasOption("nocolor")); boolean inHereDoc = false; while ((line = reader.readLine(nextLinePrompt ? "" : prompt)) != null) { out.flush(); String chunks[] = line.split(" "); String consoleCommandCheck = chunks[0].toLowerCase().trim(); if (consoleOnlyCommands.containsKey(consoleCommandCheck)) { consoleOnlyCommands.get(consoleCommandCheck).run(line, reader); continue; } if (line.contains("~%~") && !line.contains("\\~%~")) { inHereDoc = !inHereDoc; } if (!line.trim().endsWith(";")) { nextLinePrompt = true; lines.append(line); lines.append("\n"); } else if (line.trim().endsWith(";") && !inHereDoc) { lines.append(line); String input = lines.toString(); nextLinePrompt = false; processInput(input, walkers, ctx); processOutput(ctx, out, !commandLine.hasOption("nocolor")); lines = new StringBuffer(); } else if (inHereDoc) { lines.append(line); lines.append("\n"); } } ctx.getActionListener().term(); }
From source file:com.act.lcms.MassCalculator2.java
public static void main(String[] args) throws Exception { CommandLine cl = CLI_UTIL.parseCommandLine(args); if (cl.hasOption(OPTION_LICENSE_FILE)) { LOGGER.info("Using license file at %s", cl.getOptionValue(OPTION_LICENSE_FILE)); LicenseManager.setLicenseFile(cl.getOptionValue(OPTION_LICENSE_FILE)); }/* w ww . ja v a 2 s. co m*/ List<String> inchis = new ArrayList<>(); if (cl.hasOption(OPTION_INPUT_FILE)) { try (BufferedReader reader = new BufferedReader(new FileReader(cl.getOptionValue(OPTION_INPUT_FILE)))) { String line; while ((line = reader.readLine()) != null) { inchis.add(line); } } } if (cl.getArgList().size() > 0) { LOGGER.info("Reading %d InChIs from the command line", cl.getArgList().size()); inchis.addAll(cl.getArgList()); } try (PrintWriter writer = new PrintWriter( cl.hasOption(OPTION_OUTPUT_FILE) ? new FileWriter(cl.getOptionValue(OPTION_OUTPUT_FILE)) : new OutputStreamWriter(System.out))) { writer.format("InChI\tMass\tCharge\n"); for (String inchi : inchis) { try { Pair<Double, Integer> massAndCharge = calculateMassAndCharge(inchi); writer.format("%s\t%.6f\t%3d\n", inchi, massAndCharge.getLeft(), massAndCharge.getRight()); } catch (MolFormatException e) { LOGGER.error("Unable to compute mass for %s: %s", inchi, e.getMessage()); } } } }
From source file:com.coul.common.mapper.JsonMapper.java
/** * /*from w ww. jav a 2 s.co m*/ */ public static void main(String[] args) { List<Map<String, Object>> list = Lists.newArrayList(); Map<String, Object> map = Maps.newHashMap(); map.put("id", 1); map.put("pId", -1); map.put("name", ""); list.add(map); map = Maps.newHashMap(); map.put("id", 2); map.put("pId", 1); map.put("name", ""); map.put("open", true); list.add(map); String json = JsonMapper.getInstance().toJson(list); System.out.println(json); }
From source file:com.cjwagner.InfoSecPriv.ExtensionServer.java
public static void main(String[] args) { initializeLogStore();/*w ww. j a v a 2 s.c om*/ get("/data", (request, response) -> { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.MINUTE, -5); Date tMinusDelta = cal.getTime(); Map<String, LoggerMessage> filtered = new HashMap<String, LoggerMessage>(); for (Map.Entry<String, LoggerMessage> entry : logStore.entrySet()) { String ip = entry.getKey(); LoggerMessage logmess = entry.getValue(); LoggerMessage logmessFiltered = new LoggerMessage(); logmessFiltered.setFirstLogTime(logmess.getFirstLogTime()); List<LogData> filteredData = new ArrayList<LogData>(); logmessFiltered.setLogs(filteredData); for (LogData data : logmess.getLogs()) { if (data.getDate().after(tMinusDelta)) { filteredData.add(data); } } filtered.put(ip, logmessFiltered); } ObjectMapper objMapper = new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true); String jsonResponse = objMapper.writeValueAsString(filtered); System.out.println("Responded to query for recent data from IP: " + request.ip()); return jsonResponse; }); post("/LicenseRegistry", (request, response) -> { if (storeSize >= MAXSTORESIZE) { response.status(507);//insufficient storage return "Server storage full!"; } String ip = request.ip().replace(':', '_'); String json = request.body(); try { LoggerMessage logMess = LoggerMessage.fromJSON(json); logMess.setFirstLogTime(new Date()); LoggerMessage rec = logStore.get(ip); if (rec == null) { logStore.put(ip, logMess); rec = logMess; } else { rec.getLogs().addAll(logMess.getLogs()); } updateLogFile(ip, rec); storeSize += logMess.getLogs().size(); response.status(200); System.out.println("Recieved log data from IP: " + ip); return "LicenseKey:<c706cfe7-b748-4d75-98b5-c6b32ab789cb>"; } catch (JsonParseException jpe) { response.status(HTTP_BAD_REQUEST); System.out.println("Failed to parse log data from IP: " + ip); return jpe.getMessage(); } }); }
From source file:au.com.addstar.SpigotUpdater.java
public static void main(String[] args) { Configuration config = new Configuration(); final boolean check = !(args.length >= 1 && args[0].equals("--check")); if (check) {/*from w w w .j a v a 2s .c o m*/ System.out.println(" ONLY CHECKING NO DOWNLOADS WILL BE PERFORMED."); } else { System.out.println(" Preparing Plugins .... "); } downloadDir = config.downloadDir; if (!downloadDir.exists()) { downloadDir.mkdir(); } List<String> search = new ArrayList<>(); if (args.length > 1) { int i = 0; for (String arg : args) { if (i > 0) { search.add(arg); } i++; } } datFile = new File(downloadDir, "plugins.dat"); externalDownloads = config.externalDownloads; loadPlugins(search); spigotDownloader = new SpigotDirectDownloader(config); doOutHeader(plugins); for (final Plugin p : plugins) { SpigetUpdater updater = new SpigetUpdater(p.getVersion(), Logger.getAnonymousLogger(), p.getResourceID(), config); updater.setExternal(externalDownloads); updater.checkForUpdate(getUpdateCallBack(updater, p, check)); } /*try { savePlugins(); }catch (IOException e){ e.printStackTrace(); }*/ System.out.println("Processed: " + plugins.size() + " plugins"); }