List of usage examples for java.lang System currentTimeMillis
@HotSpotIntrinsicCandidate public static native long currentTimeMillis();
From source file:com.ict.dtube.example.operation.Producer.java
public static void main(String[] args) throws MQClientException, InterruptedException { CommandLine commandLine = buildCommandline(args); if (commandLine != null) { String group = commandLine.getOptionValue('g'); String topic = commandLine.getOptionValue('t'); String tags = commandLine.getOptionValue('a'); String keys = commandLine.getOptionValue('k'); String msgCount = commandLine.getOptionValue('c'); DtubeProducer producer = new DtubeProducer(group); producer.setInstanceName(Long.toString(System.currentTimeMillis())); producer.start();//from w w w.ja va 2 s . c o m for (int i = 0; i < Integer.parseInt(msgCount); i++) { try { Message msg = new Message(// topic, // topic tags, // tag keys, // key ("Hello Dtube " + i).getBytes());// body SendResult sendResult = producer.send(msg); System.out.printf("%-8d %s\n", i, sendResult); } catch (Exception e) { e.printStackTrace(); Thread.sleep(1000); } } producer.shutdown(); } }
From source file:SwingTimerDemo.java
public static void main(String[] args) { // Run a default fixed-delay timer timer = new Timer(DELAY, new SwingTimerDemo()); startTime = prevTime = System.currentTimeMillis(); System.out.println("Fixed Delay Times"); timer.start();//from w w w . j a v a2s .co m // Sleep for long enough that the first timer ends try { Thread.sleep(DURATION * 2); } catch (Exception e) { } // Run a timer with no coalescing to get fixed-rate behavior timer = new Timer(DELAY, new SwingTimerDemo()); startTime = prevTime = System.currentTimeMillis(); timer.setCoalesce(false); System.out.println("\nFixed Rate Times"); timer.start(); }
From source file:com.denimgroup.threadfix.importer.cli.CommandLineMigration.java
public static void main(String[] args) { if (!check(args)) return;/* www.j a va 2 s . c o m*/ try { String inputScript = args[0]; String inputMySqlConfig = args[1]; String outputScript = "import.sql"; String outputMySqlConfigTemp = "jdbc_temp.properties"; String errorLogFile = "error.log"; String fixedSqlFile = "error_sql.sql"; String errorLogAttemp1 = "error1.log"; String infoLogFile = "info.log"; String rollbackScript = "rollback.sql"; deleteFile(outputScript); deleteFile(errorLogFile); deleteFile(errorLogFile); deleteFile(fixedSqlFile); deleteFile(errorLogAttemp1); deleteFile(infoLogFile); deleteFile(rollbackScript); PrintStream infoPrintStream = new PrintStream(new FileOutputStream(new File(infoLogFile))); System.setOut(infoPrintStream); long startTime = System.currentTimeMillis(); copyFile(inputMySqlConfig, outputMySqlConfigTemp); LOGGER.info("Creating threadfix table in mySql database ..."); ScriptRunner scriptRunner = SpringConfiguration.getContext().getBean(ScriptRunner.class); startTime = printTimeConsumed(startTime); convert(inputScript, outputScript); startTime = printTimeConsumed(startTime); PrintStream errPrintStream = new PrintStream(new FileOutputStream(new File(errorLogFile))); System.setErr(errPrintStream); LOGGER.info("Sending sql script to MySQL server ..."); scriptRunner.run(outputScript, outputMySqlConfigTemp); long errorCount = scriptRunner.checkRunningAndFixStatements(errorLogFile, fixedSqlFile); long lastCount = errorCount + 1; int times = 1; int sameFixedSet = 0; // Repeat while (errorCount > 0) { //Flush error log screen to other file errPrintStream = new PrintStream(new FileOutputStream(new File(errorLogAttemp1))); System.setErr(errPrintStream); times += 1; if (errorCount == lastCount) { sameFixedSet++; } else { sameFixedSet = 0; } LOGGER.info("Found " + errorCount + " error statements. Sending fixed sql script to MySQL server " + times + " times ..."); scriptRunner.run(fixedSqlFile, outputMySqlConfigTemp); lastCount = errorCount; errorCount = scriptRunner.checkRunningAndFixStatements(errorLogAttemp1, fixedSqlFile); if (errorCount > lastCount || sameFixedSet > SAME_SET_TRY_LIMIT) break; } if (errorCount > 0) { LOGGER.error("After " + times + " of trying, still found errors in sql script. " + "Please check error_sql.sql and error1.log for more details."); LOGGER.info("Do you want to keep data in MySQL, and then import manually error statements (y/n)? "); try (java.util.Scanner in = new java.util.Scanner(System.in)) { String answer = in.nextLine(); if (!answer.equalsIgnoreCase("y")) { rollbackData(scriptRunner, outputMySqlConfigTemp, rollbackScript); } else { LOGGER.info( "Data imported to MySQL, but still have some errors. Please check error_sql.sql and error1.log to import manually."); } } } else { printTimeConsumed(startTime); LOGGER.info("Migration successfully finished"); } deleteFile(outputMySqlConfigTemp); } catch (Exception e) { LOGGER.error("Error: ", e); } }
From source file:fr.inria.atlanmod.kyanos.benchmarks.XmiTraverser.java
public static void main(String[] args) { Options options = new Options(); Option inputOpt = OptionBuilder.create(IN); inputOpt.setArgName("INPUT"); inputOpt.setDescription("Input model"); inputOpt.setArgs(1);//from w w w . ja v a 2 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); options.addOption(inputOpt); options.addOption(inClassOpt); CommandLineParser parser = new PosixParser(); try { CommandLine commandLine = parser.parse(options, args); URI uri = URI.createFileURI(commandLine.getOptionValue(IN)); Class<?> inClazz = XmiTraverser.class.getClassLoader() .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS)); inClazz.getMethod("init").invoke(null); ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi", new XMIResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi", new XMIResourceFactoryImpl()); Resource resource = resourceSet.createResource(uri); Map<String, Object> loadOpts = new HashMap<String, Object>(); resource.load(loadOpts); LOG.log(Level.INFO, "Start counting"); int count = 0; long begin = System.currentTimeMillis(); for (Iterator<EObject> iterator = resource.getAllContents(); iterator.hasNext(); iterator .next(), count++) ; long end = System.currentTimeMillis(); LOG.log(Level.INFO, "End counting"); LOG.log(Level.INFO, MessageFormat.format("Resource {0} contains {1} elements", uri, count)); LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin))); resource.unload(); } 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:edu.uci.ics.crawler4j.weatherCrawler.BasicCrawlController.java
public static void main(String[] args) { String folder = ConfigUtils.getFolder(); String crawlerCount = ConfigUtils.getCrawlerCount(); args = new String[2]; if (StringUtils.isBlank(folder) || StringUtils.isBlank(crawlerCount)) { args[0] = "weather"; args[1] = "10"; System.out.println("No parameters in config.properties ......."); System.out.println("[weather] will be used as rootFolder (it will contain intermediate crawl data)"); System.out.println("[10] will be used as numberOfCralwers (number of concurrent threads)"); } else {/*from w w w . j a va2 s . c o m*/ args[0] = folder; args[1] = crawlerCount; } /* * crawlStorageFolder is a folder where intermediate crawl data is * stored. */ String crawlStorageFolder = args[0]; /* * numberOfCrawlers shows the number of concurrent threads that should * be initiated for crawling. */ int numberOfCrawlers = Integer.parseInt(args[1]); CrawlConfig config = new CrawlConfig(); if (crawlStorageFolder != null && IO.deleteFolderContents(new File(crawlStorageFolder))) System.out.println(""); config.setCrawlStorageFolder(crawlStorageFolder + "/d" + System.currentTimeMillis()); /* * Be polite: Make sure that we don't send more than 1 request per * second (1000 milliseconds between requests). */ config.setPolitenessDelay(1000); config.setConnectionTimeout(1000 * 60); // config1.setPolitenessDelay(1000); /* * You can set the maximum crawl depth here. The default value is -1 for * unlimited depth */ config.setMaxDepthOfCrawling(StringUtils.isBlank(ConfigUtils.getCrawlerDepth()) ? 40 : Integer.valueOf(ConfigUtils.getCrawlerDepth())); // config1.setMaxDepthOfCrawling(0); /* * You can set the maximum number of pages to crawl. The default value * is -1 for unlimited number of pages */ config.setMaxPagesToFetch(100000); // config1.setMaxPagesToFetch(10000); /* * Do you need to set a proxy? If so, you can use: * config.setProxyHost("proxyserver.example.com"); * config.setProxyPort(8080); * * If your proxy also needs authentication: * config.setProxyUsername(username); config.getProxyPassword(password); */ if (ConfigUtils.getValue("useProxy", "false").equalsIgnoreCase("true")) { System.out.println("?============"); List<ProxySetting> proxys = ConfigUtils.getProxyList(); ProxySetting proxy = proxys.get(RandomUtils.nextInt(proxys.size() - 1)); /* test the proxy is alaviable or not */ while (!TestProxy.testProxyAvailable(proxy)) { proxy = proxys.get(RandomUtils.nextInt(proxys.size() - 1)); } System.out.println("??" + proxy.getIp() + ":" + proxy.getPort()); config.setProxyHost(proxy.getIp()); config.setProxyPort(proxy.getPort()); // config.setProxyHost("127.0.0.1"); // config.setProxyPort(8087); } else { System.out.println("??============"); } /* * This config parameter can be used to set your crawl to be resumable * (meaning that you can resume the crawl from a previously * interrupted/crashed crawl). Note: if you enable resuming feature and * want to start a fresh crawl, you need to delete the contents of * rootFolder manually. */ config.setResumableCrawling(false); // config1.setResumableCrawling(false); /* * Instantiate the controller for this crawl. */ PageFetcher pageFetcher = new PageFetcher(config); // PageFetcher pageFetcher1 = new PageFetcher(config1); RobotstxtConfig robotstxtConfig = new RobotstxtConfig(); RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher); try { /* * For each crawl, you need to add some seed urls. These are the * first URLs that are fetched and then the crawler starts following * links which are found in these pages */ CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer); controller.addSeed(StringUtils.isBlank(ConfigUtils.getSeed()) ? "http://www.tianqi.com/chinacity.html" : ConfigUtils.getSeed()); // controller.addSeed("http://www.ics.uci.edu/~lopes/"); // controller.addSeed("http://www.ics.uci.edu/~welling/"); /* * Start the crawl. This is a blocking operation, meaning that your * code will reach the line after this only when crawling is * finished. */ String isDaily = null; isDaily = ConfigUtils.getValue("isDaily", "true"); System.out .println("?=======" + ConfigUtils.getValue("table", "weather_data") + "======="); if (isDaily.equalsIgnoreCase("true")) { System.out.println("???=============="); controller.start(BasicDailyCrawler.class, numberOfCrawlers); } else { System.out.println("???=============="); controller.start(BasicCrawler.class, numberOfCrawlers); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.alibaba.rocketmq.example.operation.Producer.java
public static void main(String[] args) throws MQClientException, InterruptedException { CommandLine commandLine = buildCommandline(args); if (commandLine != null) { String group = commandLine.getOptionValue('g'); String topic = commandLine.getOptionValue('t'); String tags = commandLine.getOptionValue('a'); String keys = commandLine.getOptionValue('k'); String msgCount = commandLine.getOptionValue('c'); DefaultMQProducer producer = new DefaultMQProducer(group); producer.setInstanceName(Long.toString(System.currentTimeMillis())); producer.start();/*from ww w .j a v a 2 s. c o m*/ for (int i = 0; i < Integer.parseInt(msgCount); i++) { try { Message msg = new Message(// topic, // topic tags, // tag keys, // key ("Hello RocketMQ " + i).getBytes());// body SendResult sendResult = producer.send(msg); System.out.printf("%-8d %s\n", i, sendResult); } catch (Exception e) { e.printStackTrace(); Thread.sleep(1000); } } producer.shutdown(); } }
From source file:com.ict.dtube.example.operation.Consumer.java
public static void main(String[] args) throws InterruptedException, MQClientException { CommandLine commandLine = buildCommandline(args); if (commandLine != null) { String group = commandLine.getOptionValue('g'); String topic = commandLine.getOptionValue('t'); String subscription = commandLine.getOptionValue('s'); final String returnFailedHalf = commandLine.getOptionValue('f'); DtubePushConsumer consumer = new DtubePushConsumer(group); consumer.setInstanceName(Long.toString(System.currentTimeMillis())); consumer.subscribe(topic, subscription); consumer.registerMessageListener(new MessageListenerConcurrently() { AtomicLong consumeTimes = new AtomicLong(0); @Override/*from w ww . j av a2 s .c om*/ public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) { long currentTimes = this.consumeTimes.incrementAndGet(); System.out.printf("%-8d %s\n", currentTimes, msgs); if (Boolean.parseBoolean(returnFailedHalf)) { if ((currentTimes % 2) == 0) { return ConsumeConcurrentlyStatus.RECONSUME_LATER; } } return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } }); consumer.start(); System.out.println("Consumer Started."); } }
From source file:edu.msu.cme.rdp.graph.sandbox.KmerStartsFromKnown.java
public static void main(String[] args) throws Exception { final KmerStartsWriter out; final boolean translQuery; final int wordSize; final int translTable; try {// w w w . j av a2s . co m CommandLine cmdLine = new PosixParser().parse(options, args); args = cmdLine.getArgs(); if (args.length < 2) { throw new Exception("Unexpected number of arguments"); } if (cmdLine.hasOption("out")) { out = new KmerStartsWriter(cmdLine.getOptionValue("out")); } else { out = new KmerStartsWriter(System.out); } if (cmdLine.hasOption("transl-table")) { translTable = Integer.valueOf(cmdLine.getOptionValue("transl-table")); } else { translTable = 11; } translQuery = cmdLine.hasOption("transl-kmer"); wordSize = Integer.valueOf(args[0]); } catch (Exception e) { new HelpFormatter().printHelp("KmerStartsFromKnown <word_size> [name=]<ref_file> ...", options); System.err.println(e.getMessage()); System.exit(1); throw new RuntimeException("Stupid jvm"); //While this will never get thrown it is required to make sure javac doesn't get confused about uninitialized variables } long startTime = System.currentTimeMillis(); /* * if (args.length == 4) { maxThreads = Integer.valueOf(args[3]); } else * { */ //} System.err.println("Starting kmer mapping at " + new Date()); System.err.println("* References: " + Arrays.asList(args)); System.err.println("* Kmer length: " + wordSize); for (int index = 1; index < args.length; index++) { String refName; String refFileName = args[index]; if (refFileName.contains("=")) { String[] lexemes = refFileName.split("="); refName = lexemes[0]; refFileName = lexemes[1]; } else { String tmpName = new File(refFileName).getName(); if (tmpName.contains(".")) { refName = tmpName.substring(0, tmpName.lastIndexOf(".")); } else { refName = tmpName; } } File refFile = new File(refFileName); if (SeqUtils.guessSequenceType(refFile) != SequenceType.Nucleotide) { throw new Exception("Reference file " + refFile + " contains " + SeqUtils.guessFileFormat(refFile) + " sequences but expected nucleotide sequences"); } SequenceReader seqReader = new SequenceReader(refFile); Sequence seq; while ((seq = seqReader.readNextSequence()) != null) { if (seq.getSeqName().startsWith("#")) { continue; } ModelPositionKmerGenerator kmers = new ModelPositionKmerGenerator(seq.getSeqString(), wordSize, SequenceType.Nucleotide); for (char[] charmer : kmers) { int pos = kmers.getModelPosition() - 1; if (translQuery) { if (pos % 3 != 0) { continue; } else { pos /= 3; } } String kmer = new String(charmer); out.write(new KmerStart(refName, seq.getSeqName(), seq.getSeqName(), kmer, 1, pos, translQuery, (translQuery ? ProteinUtils.getInstance().translateToProtein(kmer, true, translTable) : null))); } } seqReader.close(); } out.close(); }
From source file:com.pnf.pdfscan.PDFScanner.java
public static void main(String[] argv) throws Exception { if (jebEnginesCfg == null || licenseKey == null) { System.out// w w w .j a v a2 s .c o m .format("Please set the jeb.engcfg and jeb.lickey properties before executing this program.\n"); System.exit(-1); } if (argv.length <= 0) { System.out.format("PDF scanner using JEB2 Business/Enterprise -- PNF Software (c) 2015\n"); System.out.format("Usage:\n"); System.out.format( " [java] PDFScanner -Djeb.engcfg=<enginesCfgPath> -Djeb.lickey=<licenseKey> <location>\n"); System.exit(-1); } System.out.format("Scanning files...\n"); List<File> files = AutoUtil.retrieveFiles(argv[0]); long t0 = System.currentTimeMillis(); // simple heuristic (see javadoc) PDFScanner scanner = new PDFScanner(2, 70); scanner.scanFiles(files); System.out.format("\nScanned %d files (%d suspicious) in %ds\n", scanner.getScannedCount(), scanner.getSuspiciousCount(), (System.currentTimeMillis() - t0) / 1000); }
From source file:it.tizianofagni.sparkboost.MPBoostLearnerExe.java
public static void main(String[] args) { Options options = new Options(); options.addOption("b", "binaryProblem", false, "Indicate if the input dataset contains a binary problem and not a multilabel one"); options.addOption("z", "labels0based", false, "Indicate if the labels IDs in the dataset to classifyLibSvmWithResults are already assigned in the range [0, numLabels-1] included"); options.addOption("l", "enableSparkLogging", false, "Enable logging messages of Spark"); options.addOption("w", "windowsLocalModeFix", true, "Set the directory containing the winutils.exe command"); options.addOption("dp", "documentPartitions", true, "The number of document partitions"); options.addOption("fp", "featurePartitions", true, "The number of feature partitions"); options.addOption("lp", "labelPartitions", true, "The number of label partitions"); CommandLineParser parser = new BasicParser(); CommandLine cmd = null;/* w ww.j ava2 s . co m*/ String[] remainingArgs = null; try { cmd = parser.parse(options, args); remainingArgs = cmd.getArgs(); if (remainingArgs.length != 3) throw new ParseException("You need to specify all mandatory parameters"); } catch (ParseException e) { System.out.println("Parsing failed. Reason: " + e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( MPBoostLearnerExe.class.getSimpleName() + " [OPTIONS] <inputFile> <outputFile> <numIterations>", options); System.exit(-1); } boolean binaryProblem = false; if (cmd.hasOption("b")) binaryProblem = true; boolean labels0Based = false; if (cmd.hasOption("z")) labels0Based = true; boolean enablingSparkLogging = false; if (cmd.hasOption("l")) enablingSparkLogging = true; if (cmd.hasOption("w")) { System.setProperty("hadoop.home.dir", cmd.getOptionValue("w")); } String inputFile = remainingArgs[0]; String outputFile = remainingArgs[1]; int numIterations = Integer.parseInt(remainingArgs[2]); long startTime = System.currentTimeMillis(); // Disable Spark logging. if (!enablingSparkLogging) { Logger.getLogger("org").setLevel(Level.OFF); Logger.getLogger("akka").setLevel(Level.OFF); } // Create and configure Spark context. SparkConf conf = new SparkConf().setAppName("Spark MPBoost learner"); JavaSparkContext sc = new JavaSparkContext(conf); // Create and configure learner. MpBoostLearner learner = new MpBoostLearner(sc); learner.setNumIterations(numIterations); if (cmd.hasOption("dp")) { learner.setNumDocumentsPartitions(Integer.parseInt(cmd.getOptionValue("dp"))); } if (cmd.hasOption("fp")) { learner.setNumFeaturesPartitions(Integer.parseInt(cmd.getOptionValue("fp"))); } if (cmd.hasOption("lp")) { learner.setNumLabelsPartitions(Integer.parseInt(cmd.getOptionValue("lp"))); } // Build classifier with MPBoost learner. BoostClassifier classifier = learner.buildModel(inputFile, labels0Based, binaryProblem); // Save classifier to disk. DataUtils.saveModel(sc, classifier, outputFile); long endTime = System.currentTimeMillis(); System.out.println("Execution time: " + (endTime - startTime) + " milliseconds."); }