List of usage examples for java.lang System currentTimeMillis
@HotSpotIntrinsicCandidate public static native long currentTimeMillis();
From source file:FastDateFormat.java
public static void main(String[] args) { String format = "yyyy-MM-dd HH:mm:ss.SSS"; if (args.length > 0) format = args[0];/*from ww w.ja v a 2 s .c om*/ SimpleDateFormat sdf = new SimpleDateFormat(format); FastDateFormat fdf = new FastDateFormat(sdf); Date d = new Date(); d.setTime(1); System.out.println(fdf.format(d) + "\t" + sdf.format(d)); d.setTime(20); System.out.println(fdf.format(d) + "\t" + sdf.format(d)); d.setTime(500); System.out.println(fdf.format(d) + "\t" + sdf.format(d)); d.setTime(543); System.out.println(fdf.format(d) + "\t" + sdf.format(d)); d.setTime(999); System.out.println(fdf.format(d) + "\t" + sdf.format(d)); d.setTime(1050); System.out.println(fdf.format(d) + "\t" + sdf.format(d)); d.setTime(2543); System.out.println(fdf.format(d) + "\t" + sdf.format(d)); d.setTime(12345); System.out.println(fdf.format(d) + "\t" + sdf.format(d)); d.setTime(12340); System.out.println(fdf.format(d) + "\t" + sdf.format(d)); final int reps = 100000; { long start = System.currentTimeMillis(); for (int i = 0; i < reps; i++) { d.setTime(System.currentTimeMillis()); fdf.format(d); } long elap = System.currentTimeMillis() - start; System.out.println("fast: " + elap + " elapsed"); System.out.println(fdf.format(d)); } { long start = System.currentTimeMillis(); for (int i = 0; i < reps; i++) { d.setTime(System.currentTimeMillis()); sdf.format(d); } long elap = System.currentTimeMillis() - start; System.out.println("slow: " + elap + " elapsed"); System.out.println(sdf.format(d)); } }
From source file:com.clearspring.analytics.stream.cardinality.TestHyperLogLogPlus.java
public static void main(final String[] args) throws Throwable { long startTime = System.currentTimeMillis(); int numSets = 10; int setSize = 1 * 1000 * 1000; int repeats = 5; HyperLogLogPlus[] counters = new HyperLogLogPlus[numSets]; for (int i = 0; i < numSets; i++) { counters[i] = new HyperLogLogPlus(15, 15); }/* w w w . j a va2 s . c o m*/ for (int i = 0; i < numSets; i++) { for (int j = 0; j < setSize; j++) { String val = UUID.randomUUID().toString(); for (int z = 0; z < repeats; z++) { counters[i].offer(val); } } } ICardinality merged = counters[0]; long sum = merged.cardinality(); for (int i = 1; i < numSets; i++) { sum += counters[i].cardinality(); merged = merged.merge(counters[i]); } long trueSize = numSets * setSize; System.out.println("True Cardinality: " + trueSize); System.out.println("Summed Cardinality: " + sum); System.out.println("Merged Cardinality: " + merged.cardinality()); System.out.println("Merged Error: " + (merged.cardinality() - trueSize) / (float) trueSize); System.out.println("Duration: " + ((System.currentTimeMillis() - startTime) / 1000) + "s"); }
From source file:com.hadoopvietnam.commons.crypt.J2MECrypto.java
public static void main(String[] args) { J2MECrypto crypto = new J2MECrypto("LetfyActionCrypto".getBytes()); String code = System.currentTimeMillis() + " " + "tk1cntt@gmail.com" + " " + System.currentTimeMillis(); String encode = new String(Base64.encodeBase64(crypto.encrypt((code).getBytes()))); System.out.println(encode);/*from ww w. ja v a2 s . c om*/ String decode = new String(crypto.decrypt(Base64.decodeBase64(encode.getBytes()))); System.out.println(decode); System.out.println(DigestUtils.md5Hex(code)); }
From source file:fr.inria.atlanmod.kyanos.benchmarks.ase2015.CdoQuerySpecificInvisibleMethodDeclarations.java
public static void main(String[] args) { Options options = new Options(); Option inputOpt = OptionBuilder.create(IN); inputOpt.setArgName("INPUT"); inputOpt.setDescription("Input CDO resource directory"); inputOpt.setArgs(1);//from w w w . jav a2 s .c om inputOpt.setRequired(true); Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS); inClassOpt.setArgName("CLASS"); inClassOpt.setDescription("FQN of EPackage implementation class"); inClassOpt.setArgs(1); inClassOpt.setRequired(true); Option repoOpt = OptionBuilder.create(REPO_NAME); repoOpt.setArgName("REPO_NAME"); repoOpt.setDescription("CDO Repository name"); repoOpt.setArgs(1); repoOpt.setRequired(true); options.addOption(inputOpt); options.addOption(inClassOpt); options.addOption(repoOpt); CommandLineParser parser = new PosixParser(); try { CommandLine commandLine = parser.parse(options, args); String repositoryDir = commandLine.getOptionValue(IN); String repositoryName = commandLine.getOptionValue(REPO_NAME); Class<?> inClazz = CdoQuerySpecificInvisibleMethodDeclarations.class.getClassLoader() .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS)); inClazz.getMethod("init").invoke(null); EmbeddedCDOServer server = new EmbeddedCDOServer(repositoryDir, repositoryName); try { server.run(); CDOSession session = server.openSession(); CDOTransaction transaction = session.openTransaction(); Resource resource = transaction.getRootResource(); { Runtime.getRuntime().gc(); long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.log(Level.INFO, MessageFormat.format("Used memory before query: {0}", MessageUtil.byteCountToDisplaySize(initialUsedMemory))); LOG.log(Level.INFO, "Start query"); long begin = System.currentTimeMillis(); EList<MethodDeclaration> list = ASE2015JavaQueries .getSpecificInvisibleMethodDeclarations(resource); long end = System.currentTimeMillis(); LOG.log(Level.INFO, "End query"); LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size())); LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin))); Runtime.getRuntime().gc(); long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.log(Level.INFO, MessageFormat.format("Used memory after query: {0}", MessageUtil.byteCountToDisplaySize(finalUsedMemory))); LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}", MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory))); } transaction.close(); session.close(); } finally { server.stop(); } } catch (ParseException e) { MessageUtil.showError(e.toString()); MessageUtil.showError("Current arguments: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar <this-file.jar>", options, true); } catch (Throwable e) { MessageUtil.showError(e.toString()); } }
From source file:flink.iso8583.example.Client.java
public static void main(String[] args) throws Exception { Random rng = new Random(System.currentTimeMillis()); log.debug("Reading config"); mfact = ConfigParser.createFromClasspathConfig("flink/iso8583/example/config.xml"); mfact.setAssignDate(true);//www . j a v a 2 s . co m mfact.setTraceNumberGenerator(new SimpleTraceGenerator((int) (System.currentTimeMillis() % 10000))); log.debug("Connecting to server"); Socket sock = new Socket("localhost", 9999); //Send 10 messages, then wait for the responses Client reader = new Client(sock); reader.start(); for (int i = 0; i < 10; i++) { IsoMessage req = mfact.newMessage(0x200); req.setValue(4, amounts[rng.nextInt(amounts.length)], IsoType.AMOUNT, 0); req.setValue(12, req.getObjectValue(7), IsoType.TIME, 0); req.setValue(13, req.getObjectValue(7), IsoType.DATE4, 0); req.setValue(15, req.getObjectValue(7), IsoType.DATE4, 0); req.setValue(17, req.getObjectValue(7), IsoType.DATE4, 0); req.setValue(37, new Long(System.currentTimeMillis() % 1000000), IsoType.NUMERIC, 12); req.setValue(41, data[rng.nextInt(data.length)], IsoType.ALPHA, 16); req.setValue(48, data[rng.nextInt(data.length)], IsoType.LLLVAR, 0); pending.put(req.getField(11).toString(), req); log.debug("Sending request " + req.getField(11)); req.write(sock.getOutputStream(), 2); } log.debug("Waiting for responses"); while (pending.size() > 0 && sock.isConnected()) { sleep(500); } reader.interrupt(); sock.close(); log.debug("DONE."); }
From source file:fr.inria.atlanmod.kyanos.benchmarks.ase2015.CdoQueryInvisibleMethodDeclarations.java
public static void main(String[] args) { Options options = new Options(); Option inputOpt = OptionBuilder.create(IN); inputOpt.setArgName("INPUT"); inputOpt.setDescription("Input CDO resource directory"); inputOpt.setArgs(1);/*from w w w . j ava2 s . c o m*/ inputOpt.setRequired(true); Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS); inClassOpt.setArgName("CLASS"); inClassOpt.setDescription("FQN of EPackage implementation class"); inClassOpt.setArgs(1); inClassOpt.setRequired(true); Option repoOpt = OptionBuilder.create(REPO_NAME); repoOpt.setArgName("REPO_NAME"); repoOpt.setDescription("CDO Repository name"); repoOpt.setArgs(1); repoOpt.setRequired(true); options.addOption(inputOpt); options.addOption(inClassOpt); options.addOption(repoOpt); CommandLineParser parser = new PosixParser(); try { CommandLine commandLine = parser.parse(options, args); String repositoryDir = commandLine.getOptionValue(IN); String repositoryName = commandLine.getOptionValue(REPO_NAME); Class<?> inClazz = CdoQueryInvisibleMethodDeclarations.class.getClassLoader() .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS)); inClazz.getMethod("init").invoke(null); EmbeddedCDOServer server = new EmbeddedCDOServer(repositoryDir, repositoryName); try { server.run(); CDOSession session = server.openSession(); CDOTransaction transaction = session.openTransaction(); Resource resource = transaction.getRootResource(); { Runtime.getRuntime().gc(); long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.log(Level.INFO, MessageFormat.format("Used memory before query: {0}", MessageUtil.byteCountToDisplaySize(initialUsedMemory))); LOG.log(Level.INFO, "Start query"); long begin = System.currentTimeMillis(); EList<MethodDeclaration> list = ASE2015JavaQueries.getInvisibleMethodDeclarations(resource); long end = System.currentTimeMillis(); LOG.log(Level.INFO, "End query"); LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size())); LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin))); Runtime.getRuntime().gc(); long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.log(Level.INFO, MessageFormat.format("Used memory after query: {0}", MessageUtil.byteCountToDisplaySize(finalUsedMemory))); LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}", MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory))); } transaction.close(); session.close(); } finally { server.stop(); } } catch (ParseException e) { MessageUtil.showError(e.toString()); MessageUtil.showError("Current arguments: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar <this-file.jar>", options, true); } catch (Throwable e) { MessageUtil.showError(e.toString()); } }
From source file:fr.inria.atlanmod.kyanos.benchmarks.ase2015.CdoQueryGrabats09.java
public static void main(String[] args) { Options options = new Options(); Option inputOpt = OptionBuilder.create(IN); inputOpt.setArgName("INPUT"); inputOpt.setDescription("Input CDO resource directory"); inputOpt.setArgs(1);//from w ww . j a v a 2s . c o m inputOpt.setRequired(true); Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS); inClassOpt.setArgName("CLASS"); inClassOpt.setDescription("FQN of EPackage implementation class"); inClassOpt.setArgs(1); inClassOpt.setRequired(true); Option repoOpt = OptionBuilder.create(REPO_NAME); repoOpt.setArgName("REPO_NAME"); repoOpt.setDescription("CDO Repository name"); repoOpt.setArgs(1); repoOpt.setRequired(true); options.addOption(inputOpt); options.addOption(inClassOpt); options.addOption(repoOpt); CommandLineParser parser = new PosixParser(); try { CommandLine commandLine = parser.parse(options, args); String repositoryDir = commandLine.getOptionValue(IN); String repositoryName = commandLine.getOptionValue(REPO_NAME); Class<?> inClazz = CdoQueryGrabats09.class.getClassLoader() .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS)); inClazz.getMethod("init").invoke(null); EmbeddedCDOServer server = new EmbeddedCDOServer(repositoryDir, repositoryName); try { server.run(); CDOSession session = server.openSession(); CDOTransaction transaction = session.openTransaction(); Resource resource = transaction.getRootResource(); { Runtime.getRuntime().gc(); long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.log(Level.INFO, MessageFormat.format("Used memory before query: {0}", MessageUtil.byteCountToDisplaySize(initialUsedMemory))); LOG.log(Level.INFO, "Start query"); long begin = System.currentTimeMillis(); EList<ClassDeclaration> list = ASE2015JavaQueries.grabats09(resource); long end = System.currentTimeMillis(); LOG.log(Level.INFO, "End query"); LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size())); LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin))); Runtime.getRuntime().gc(); long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.log(Level.INFO, MessageFormat.format("Used memory after query: {0}", MessageUtil.byteCountToDisplaySize(finalUsedMemory))); LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}", MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory))); } transaction.close(); session.close(); } finally { server.stop(); } } catch (ParseException e) { MessageUtil.showError(e.toString()); MessageUtil.showError("Current arguments: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar <this-file.jar>", options, true); } catch (Throwable e) { MessageUtil.showError(e.toString()); } }
From source file:com.bitsofproof.example.Simple.java
public static void main(String[] args) { Security.addProvider(new BouncyCastleProvider()); final CommandLineParser parser = new GnuParser(); final Options gnuOptions = new Options(); gnuOptions.addOption("h", "help", false, "I can't help you yet"); gnuOptions.addOption("s", "server", true, "Server URL"); gnuOptions.addOption("u", "user", true, "User"); gnuOptions.addOption("p", "password", true, "Password"); System.out.println("BOP Bitcoin Server Simple Client 3.5.0 (c) 2013-2014 bits of proof zrt."); CommandLine cl = null;/*from www.ja v a2 s . c o m*/ String url = null; String user = null; String password = null; try { cl = parser.parse(gnuOptions, args); url = cl.getOptionValue('s'); user = cl.getOptionValue('u'); password = cl.getOptionValue('p'); } catch (org.apache.commons.cli.ParseException e) { e.printStackTrace(); System.exit(1); } if (url == null || user == null || password == null) { System.err.println("Need -s server -u user -p password"); System.exit(1); } BCSAPI api = getServer(url, user, password); try { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); long start = System.currentTimeMillis(); api.ping(start); System.out.println("Server round trip " + (System.currentTimeMillis() - start) + "ms"); api.addAlertListener(new AlertListener() { @Override public void alert(String s, int severity) { System.err.println("ALERT: " + s); } }); System.out.println("Talking to " + (api.isProduction() ? "PRODUCTION" : "test") + " server"); ConfirmationManager confirmationManager = new ConfirmationManager(); confirmationManager.init(api, 144); System.out.printf("Please enter wallet name: "); String wallet = input.readLine(); SimpleFileWallet w = new SimpleFileWallet(wallet + ".wallet"); TransactionFactory am = null; if (!w.exists()) { System.out.printf("Enter passphrase: "); String passphrase = input.readLine(); System.out.printf("Enter master (empty for new): "); String master = input.readLine(); if (master.equals("")) { w.init(passphrase); w.unlock(passphrase); System.out.printf("First account: "); String account = input.readLine(); am = w.createAccountManager(account); w.lock(); w.persist(); } else { StringTokenizer tokenizer = new StringTokenizer(master, "@"); String key = tokenizer.nextToken(); long since = 0; if (tokenizer.hasMoreElements()) { since = Long.parseLong(tokenizer.nextToken()) * 1000; } w.init(passphrase, ExtendedKey.parse(key), true, since); w.unlock(passphrase); System.out.printf("First account: "); String account = input.readLine(); am = w.createAccountManager(account); w.lock(); w.persist(); w.sync(api); } } else { w = SimpleFileWallet.read(wallet + ".wallet"); w.sync(api); List<String> names = w.getAccountNames(); System.out.println("Accounts:"); System.out.println("---------"); String first = null; for (String name : names) { System.out.println(name); if (first == null) { first = name; } } System.out.println("---------"); am = w.getAccountManager(first); System.out.println("Using account " + first); } confirmationManager.addAccount(am); api.registerTransactionListener(am); while (true) { printMenu(); String answer = input.readLine(); System.out.printf("\n"); if (answer.equals("1")) { System.out.printf("The balance is: " + printBit(am.getBalance()) + "\n"); System.out.printf(" confirmed: " + printBit(am.getConfirmed()) + "\n"); System.out.printf(" receiveing: " + printBit(am.getReceiving()) + "\n"); System.out.printf(" change: " + printBit(am.getChange()) + "\n"); System.out.printf("( sending: " + printBit(am.getSending()) + ")\n"); } else if (answer.equals("2")) { for (Address a : am.getAddresses()) { System.out.printf(a + "\n"); } } else if (answer.equals("3")) { ExtendedKeyAccountManager im = (ExtendedKeyAccountManager) am; System.out.printf( im.getMaster().serialize(api.isProduction()) + "@" + im.getCreated() / 1000 + "\n"); } else if (answer.equals("4")) { System.out.printf("Enter passphrase: "); String passphrase = input.readLine(); w.unlock(passphrase); ExtendedKeyAccountManager im = (ExtendedKeyAccountManager) am; System.out.printf( im.getMaster().serialize(api.isProduction()) + "@" + im.getCreated() / 1000 + "\n"); w.lock(); } else if (answer.equals("5")) { System.out.printf("Enter passphrase: "); String passphrase = input.readLine(); w.unlock(passphrase); System.out.printf("Number of recipients"); Integer nr = Integer.valueOf(input.readLine()); Transaction spend; if (nr.intValue() == 1) { System.out.printf("Receiver address: "); String address = input.readLine(); System.out.printf("amount (Bit): "); long amount = parseBit(input.readLine()); spend = am.pay(Address.fromSatoshiStyle(address), amount); System.out.println("About to send " + printBit(amount) + " to " + address); } else { List<Address> addresses = new ArrayList<>(); List<Long> amounts = new ArrayList<>(); long total = 0; for (int i = 0; i < nr; ++i) { System.out.printf("Receiver address: "); String address = input.readLine(); addresses.add(Address.fromSatoshiStyle(address)); System.out.printf("amount (Bit): "); long amount = parseBit(input.readLine()); amounts.add(amount); total += amount; } spend = am.pay(addresses, amounts); System.out.println("About to send " + printBit(total)); } System.out.println("inputs"); for (TransactionInput in : spend.getInputs()) { System.out.println(in.getSourceHash() + " " + in.getIx()); } System.out.println("outputs"); for (TransactionOutput out : spend.getOutputs()) { System.out.println(out.getOutputAddress() + " " + printBit(out.getValue())); } w.lock(); System.out.printf("Type yes to go: "); if (input.readLine().equals("yes")) { api.sendTransaction(spend); System.out.printf("Sent transaction: " + spend.getHash()); } else { System.out.printf("Nothing happened."); } } else if (answer.equals("6")) { System.out.printf("Address: "); Set<Address> match = new HashSet<Address>(); match.add(Address.fromSatoshiStyle(input.readLine())); api.scanTransactionsForAddresses(match, 0, new TransactionListener() { @Override public boolean process(Transaction t) { System.out.printf("Found transaction: " + t.getHash() + "\n"); return true; } }); } else if (answer.equals("7")) { System.out.printf("Public key: "); ExtendedKey ek = ExtendedKey.parse(input.readLine()); api.scanTransactions(ek, 0, 10, 0, new TransactionListener() { @Override public boolean process(Transaction t) { System.out.printf("Found transaction: " + t.getHash() + "\n"); return true; } }); } else if (answer.equals("a")) { System.out.printf("Enter account name: "); String account = input.readLine(); am = w.getAccountManager(account); api.registerTransactionListener(am); confirmationManager.addAccount(am); } else if (answer.equals("c")) { System.out.printf("Enter account name: "); String account = input.readLine(); System.out.printf("Enter passphrase: "); String passphrase = input.readLine(); w.unlock(passphrase); am = w.createAccountManager(account); System.out.println("using account: " + account); w.lock(); w.persist(); api.registerTransactionListener(am); confirmationManager.addAccount(am); } else if (answer.equals("m")) { System.out.printf("Enter passphrase: "); String passphrase = input.readLine(); w.unlock(passphrase); System.out.println(w.getMaster().serialize(api.isProduction())); System.out.println(w.getMaster().getReadOnly().serialize(true)); w.lock(); } else if (answer.equals("s")) { System.out.printf("Enter private key: "); String key = input.readLine(); ECKeyPair k = ECKeyPair.parseWIF(key); KeyListAccountManager alm = new KeyListAccountManager(); alm.addKey(k); alm.syncHistory(api); Address a = am.getNextReceiverAddress(); Transaction t = alm.pay(a, alm.getBalance(), PaymentOptions.receiverPaysFee); System.out.println("About to sweep " + printBit(alm.getBalance()) + " to " + a); System.out.println("inputs"); for (TransactionInput in : t.getInputs()) { System.out.println(in.getSourceHash() + " " + in.getIx()); } System.out.println("outputs"); for (TransactionOutput out : t.getOutputs()) { System.out.println(out.getOutputAddress() + " " + printBit(out.getValue())); } System.out.printf("Type yes to go: "); if (input.readLine().equals("yes")) { api.sendTransaction(t); System.out.printf("Sent transaction: " + t.getHash()); } else { System.out.printf("Nothing happened."); } } else { System.exit(0); } } } catch (Exception e) { System.err.println("Something went wrong"); e.printStackTrace(); System.exit(1); } }
From source file:SDRecord.java
public static void main(String[] args) { boolean recordToInf = false; long recordTo = 0, txsize = 0, wr = 0, max = 0; int sourcePort = 0, destPort = 0; String val; OutputStream writer = null;//from w w w.j a va2 s .co m InetAddress rhost = null, lhost = null; DatagramSocket socket = null; //Default values int buffSize = 1500; try { lhost = InetAddress.getByName("0.0.0.0"); } catch (UnknownHostException e1) { System.err.println("ERROR!: Host not reconized"); System.exit(3); } recordToInf = true; sourcePort = 7355; Options options = new Options(); options.addOption("m", true, "Minutes to record, default is no limit"); options.addOption("l", true, "Bind to a specific local address, default is 0.0.0.0"); options.addOption("p", true, "Local port to use, default is 7355"); options.addOption("r", true, "Remote address where to send data"); options.addOption("d", true, "Remote port, to use with -r option"); options.addOption("f", true, "Output file where to save the recording"); options.addOption("s", true, "Stop recording when reaching specified MBs"); options.addOption("h", false, "Help"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e1) { System.err.println("ERROR!: Error while parsing the command line"); System.exit(1); } if (cmd.hasOption("m")) { val = cmd.getOptionValue("m"); try { if (Long.parseLong(val) < 0) { System.err.println("ERROR!: -m argument value cannot be negative"); System.exit(3); } recordTo = System.currentTimeMillis() + (Long.parseLong(val) * 60000); recordToInf = false; } catch (NumberFormatException e) { System.err.println("ERROR!: -m argument not an integer"); System.exit(3); } } if (cmd.hasOption("l")) { val = cmd.getOptionValue("l"); try { lhost = InetAddress.getByName(val); } catch (UnknownHostException e) { System.err.println("ERROR!: Host not reconized"); System.exit(3); } } if (cmd.hasOption("p")) { val = cmd.getOptionValue("p"); try { sourcePort = Integer.parseInt(val); } catch (NumberFormatException e) { System.err.println("ERROR!: -p argument not an integer"); System.exit(3); } } if (cmd.hasOption("r")) { val = cmd.getOptionValue("r"); try { rhost = InetAddress.getByName(val); } catch (UnknownHostException e) { System.err.println("ERROR!: Host not reconized"); System.exit(3); } } if (cmd.hasOption("d")) { val = cmd.getOptionValue("d"); try { destPort = Integer.parseInt(val); } catch (NumberFormatException e) { System.err.println("-ERROR!: -d argument not an integer"); System.exit(3); } } if (cmd.hasOption("f")) { val = cmd.getOptionValue("f"); try { writer = new FileOutputStream(val); } catch (FileNotFoundException e) { System.err.println("ERROR!: File not found"); System.exit(3); } } if (cmd.hasOption("s")) { val = cmd.getOptionValue("s"); try { max = (long) (Double.parseDouble(val) * 1000000); } catch (NumberFormatException e) { System.err.println("ERROR!: -s argument not valid"); System.exit(3); } if (Double.parseDouble(val) < 0) { System.err.println("ERROR!: -s argument value cannot be negative"); System.exit(3); } } if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("SDRecord", options); System.exit(0); } try { socket = new DatagramSocket(sourcePort, lhost); //socket options socket.setReuseAddress(true); } catch (SocketException e) { e.printStackTrace(); System.exit(3); } byte[] buffer = new byte[buffSize]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); System.err.println("Listening " + lhost.toString() + " on port " + sourcePort); while (recordToInf == true || System.currentTimeMillis() <= recordTo) { //Stop recording when reaching max bytes if (max != 0 && txsize >= max) break; packet.setData(buffer); try { socket.receive(packet); } catch (IOException e) { e.printStackTrace(); System.exit(4); } //Ignoring packets with no data if (basicFilter(packet) == null) continue; if (writer == null && rhost == null) wr = recordToStdout(packet); if (writer != null) wr = recordToFile(packet, writer); if (rhost != null) wr = recordToSocket(packet, socket, rhost, destPort); txsize += wr; System.err .print("\r" + formatSize(txsize) + " transferred" + "\033[K" + "\t Press Ctrl+c to terminate"); } //closing socket and exit System.err.print("\r" + formatSize(txsize) + " transferred" + "\033[K"); socket.close(); System.out.println(); System.exit(0); }
From source file:edu.cmu.lti.oaqa.annographix.apps.SolrQueryApp.java
public static void main(String[] args) { Options options = new Options(); options.addOption("u", null, true, "Solr URI"); options.addOption("q", null, true, "Query"); options.addOption("n", null, true, "Max # of results"); options.addOption("o", null, true, "An optional TREC-style output file"); options.addOption("w", null, false, "Do a warm-up query call, before each query"); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); BufferedWriter trecOutFile = null; try {/*from www . j a va 2 s. c o m*/ CommandLine cmd = parser.parse(options, args); String queryFile = null, solrURI = null; if (cmd.hasOption("u")) { solrURI = cmd.getOptionValue("u"); } else { Usage("Specify Solr URI"); } SolrServerWrapper solr = new SolrServerWrapper(solrURI); if (cmd.hasOption("q")) { queryFile = cmd.getOptionValue("q"); } else { Usage("Specify Query file"); } int numRet = 100; if (cmd.hasOption("n")) { numRet = Integer.parseInt(cmd.getOptionValue("n")); } if (cmd.hasOption("o")) { trecOutFile = new BufferedWriter(new FileWriter(new File(cmd.getOptionValue("o")))); } List<String> fieldList = new ArrayList<String>(); fieldList.add(UtilConst.ID_FIELD); fieldList.add(UtilConst.SCORE_FIELD); double totalTime = 0; double retQty = 0; ArrayList<Double> queryTimes = new ArrayList<Double>(); boolean bDoWarmUp = cmd.hasOption("w"); if (bDoWarmUp) { System.out.println("Using a warmup step!"); } int queryQty = 0; for (String t : FileUtils.readLines(new File(queryFile))) { t = t.trim(); if (t.isEmpty()) continue; int ind = t.indexOf('|'); if (ind < 0) throw new Exception("Wrong format, line: '" + t + "'"); String qID = t.substring(0, ind); String q = t.substring(ind + 1); SolrDocumentList res = null; if (bDoWarmUp) { res = solr.runQuery(q, fieldList, numRet); } Long tm1 = System.currentTimeMillis(); res = solr.runQuery(q, fieldList, numRet); Long tm2 = System.currentTimeMillis(); retQty += res.getNumFound(); System.out.println(qID + " Obtained: " + res.getNumFound() + " entries in " + (tm2 - tm1) + " ms"); double delta = (tm2 - tm1); totalTime += delta; queryTimes.add(delta); ++queryQty; if (trecOutFile != null) { ArrayList<SolrRes> resArr = new ArrayList<SolrRes>(); for (SolrDocument doc : res) { String id = (String) doc.getFieldValue(UtilConst.ID_FIELD); float score = (Float) doc.getFieldValue(UtilConst.SCORE_FIELD); resArr.add(new SolrRes(id, "", score)); } SolrRes[] results = resArr.toArray(new SolrRes[resArr.size()]); Arrays.sort(results); SolrEvalUtils.saveTrecResults(qID, results, trecOutFile, TREC_RUN, results.length); } } double devTime = 0, meanTime = totalTime / queryQty; for (int i = 0; i < queryQty; ++i) { double d = queryTimes.get(i) - meanTime; devTime += d * d; } devTime = Math.sqrt(devTime / (queryQty - 1)); System.out.println(String.format("Query time, mean/standard dev: %.2f/%.2f (ms)", meanTime, devTime)); System.out.println(String.format("Avg # of docs returned: %.2f", retQty / queryQty)); solr.close(); trecOutFile.close(); } catch (ParseException e) { Usage("Cannot parse arguments"); } catch (Exception e) { System.err.println("Terminating due to an exception: " + e); System.exit(1); } }