List of usage examples for java.lang Thread sleep
public static native void sleep(long millis) throws InterruptedException;
From source file:io.anserini.index.IndexGov2.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(//from w ww .j a v a 2 s. c om OptionBuilder.withArgName("path").hasArg().withDescription("input data path").create(INPUT_OPTION)); options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("output index path") .create(INDEX_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of indexer threads") .create(THREADS_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg() .withDescription("max number of documents to index (-1 to index everything)") .create(DOCLIMIT_OPTION)); options.addOption(POSITIONS_OPTION, false, "index positions"); options.addOption(OPTIMIZE_OPTION, false, "merge all index segments"); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(INPUT_OPTION) || !cmdline.hasOption(INDEX_OPTION) || !cmdline.hasOption(THREADS_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(100); formatter.printHelp(IndexGov2.class.getCanonicalName(), options); System.exit(-1); } final String dirPath = cmdline.getOptionValue(INDEX_OPTION); final String dataDir = cmdline.getOptionValue(INPUT_OPTION); final int docCountLimit = cmdline.hasOption(DOCLIMIT_OPTION) ? Integer.parseInt(cmdline.getOptionValue(DOCLIMIT_OPTION)) : -1; final int numThreads = Integer.parseInt(cmdline.getOptionValue(THREADS_OPTION)); final boolean doUpdate = cmdline.hasOption(UPDATE_OPTION); final boolean positions = cmdline.hasOption(POSITIONS_OPTION); final boolean optimize = cmdline.hasOption(OPTIMIZE_OPTION); final Analyzer a = new EnglishAnalyzer(); final TrecContentSource trecSource = createGov2Source(dataDir); final Directory dir = FSDirectory.open(Paths.get(dirPath)); LOG.info("Index path: " + dirPath); LOG.info("Doc limit: " + (docCountLimit == -1 ? "all docs" : "" + docCountLimit)); LOG.info("Threads: " + numThreads); LOG.info("Positions: " + positions); LOG.info("Optimize (merge segments): " + optimize); final IndexWriterConfig config = new IndexWriterConfig(a); if (doUpdate) { config.setOpenMode(IndexWriterConfig.OpenMode.APPEND); } else { config.setOpenMode(IndexWriterConfig.OpenMode.CREATE); } final IndexWriter writer = new IndexWriter(dir, config); Gov2IndexThreads threads = new Gov2IndexThreads(writer, positions, trecSource, numThreads, docCountLimit); LOG.info("Indexer: start"); final long t0 = System.currentTimeMillis(); threads.start(); while (!threads.done()) { Thread.sleep(100); } threads.stop(); final long t1 = System.currentTimeMillis(); LOG.info("Indexer: indexing done (" + (t1 - t0) / 1000.0 + " sec); total " + writer.maxDoc() + " docs"); if (!doUpdate && docCountLimit != -1 && writer.maxDoc() != docCountLimit) { throw new RuntimeException("w.maxDoc()=" + writer.maxDoc() + " but expected " + docCountLimit); } if (threads.failed.get()) { throw new RuntimeException("exceptions during indexing"); } final long t2; t2 = System.currentTimeMillis(); final Map<String, String> commitData = new HashMap<String, String>(); commitData.put("userData", "multi"); writer.setCommitData(commitData); writer.commit(); final long t3 = System.currentTimeMillis(); LOG.info("Indexer: commit multi (took " + (t3 - t2) / 1000.0 + " sec)"); if (optimize) { LOG.info("Indexer: merging all segments"); writer.forceMerge(1); final long t4 = System.currentTimeMillis(); LOG.info("Indexer: segments merged (took " + (t4 - t3) / 1000.0 + " sec)"); } LOG.info("Indexer: at close: " + writer.segString()); final long tCloseStart = System.currentTimeMillis(); writer.close(); LOG.info("Indexer: close took " + (System.currentTimeMillis() - tCloseStart) / 1000.0 + " sec"); dir.close(); final long tFinal = System.currentTimeMillis(); LOG.info("Indexer: finished (" + (tFinal - t0) / 1000.0 + " sec)"); LOG.info("Indexer: net bytes indexed " + threads.getBytesIndexed()); LOG.info("Indexer: " + (threads.getBytesIndexed() / 1024. / 1024. / 1024. / ((tFinal - t0) / 3600000.)) + " GB/hour plain text"); }
From source file:com.ikanow.aleph2.example.external_harvester.services.ExternalProcessLaunchService.java
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, JsonProcessingException, IOException, InterruptedException, ExecutionException { final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty()); // Get the context (unused here) final IHarvestContext context = ContextUtils.getHarvestContext(args[0]); final DataBucketBean bucket = context.getBucket().get(); _logger.info("Launched context, eg bucket status = : " + BeanTemplateUtils.toJson(context.getBucketStatus(Optional.empty()).get())); _logger.info("Retrieved bucket from CON: " + BeanTemplateUtils.toJson(bucket)); // Get the bucket (unused here) _logger.info("Retrieved arg from CLI: " + args[1]); // Check that joins the cluster if I request the data bucket store //context.getService(IManagementDbService.class, Optional.of("core_management_db")).get().getDataBucketStore(); //(But not if it's in read only mode) final IManagementCrudService<DataBucketBean> bucket_service = context.getServiceContext() .getCoreManagementDbService().readOnlyVersion().getDataBucketStore(); _logger.info("Getting Management DB and reading number of buckets = " + bucket_service.countObjects().get().intValue()); // Demonstration of accessing (read only) library state information: final Tuple2<SharedLibraryBean, Optional<GlobalConfigBean>> lib_config = ExternalProcessHarvestTechnology .getConfig(context);// ww w.j a v a 2 s . com _logger.info("Retrieved library configuration: " + lib_config._2().map(g -> BeanTemplateUtils.toJson(g).toString()).orElse("(no config)")); // 1) Preferred method of getting per library state: final ICrudService<ProcessInfoBean> pid_crud = context .getGlobalHarvestTechnologyObjectStore(ProcessInfoBean.class, ProcessInfoBean.PID_COLLECTION_NAME); // 2) Lower level way: //final IManagementDbService core_db = context.getServiceContext().getCoreManagementDbService(); //final ICrudService<ProcessInfoBean> pid_crud = core_db.getPerLibraryState(ProcessInfoBean.class, lib_config._1(), ProcessInfoBean.PID_COLLECTION_NAME); // 3) Alternatively (this construct is how you get per bucket state also): //final ICrudService<ProcessInfoBean> pid_crud = context.getBucketObjectStore(ProcessInfoBean.class, Optional.empty(), ProcessInfoBean.PID_COLLECTION_NAME, Optional.of(AssetStateDirectoryBean.StateDirectoryType.library)); lib_config._2().ifPresent(gc -> { if (gc.store_pids_in_db()) pid_crud.getObjectsBySpec(CrudUtils.allOf(ProcessInfoBean.class).when(ProcessInfoBean::bucket_name, bucket.full_name())).thenAccept(cursor -> { String pids = StreamSupport.stream(cursor.spliterator(), false).map(c -> c._id()) .collect(Collectors.joining(",")); _logger.info("Pids/hostnames for this bucket: " + pids); }).exceptionally(err -> { _logger.error("Failed to get bucket pids", err); return null; }); }); // Just run for 10 minutes as an experiment for (int i = 0; i < 60; ++i) { // Example of promoting data to next stage if ((MasterEnrichmentType.streaming == bucket.master_enrichment_type()) || (MasterEnrichmentType.streaming_and_batch == bucket.master_enrichment_type())) { // Send an object to kafka final JsonNode json = mapper.createObjectNode().put("@timestamp", new Date().getTime()) .put("test_str", "test" + i).put("test_int", i); _logger.info("Sending object to kafka: " + json); context.sendObjectToStreamingPipeline(Optional.empty(), Either.left(json)); } _logger.info("(sleeping: " + i + ")"); try { Thread.sleep(10L * 1000L); } catch (Exception e) { } } }
From source file:amazonechoapi.AmazonEchoApi.java
public static void main(String[] args) throws InterruptedException, IOException { AmazonEchoApi amazonEchoApi = new AmazonEchoApi("https://pitangui.amazon.com", "username", "password"); if (amazonEchoApi.httpLogin()) { while (true) { String output = amazonEchoApi.httpGet("/api/todos?type=TASK&size=1"); // Parse JSON Object obj = JSONValue.parse(output); JSONObject jsonObject = (JSONObject) obj; JSONArray values = (JSONArray) jsonObject.get("values"); JSONObject item = (JSONObject) values.get(0); // Get text and itemId String text = item.get("text").toString(); String itemId = item.get("itemId").toString(); if (!checkItemId(itemId)) { addItemId(itemId);/* w w w .ja v a 2s . c om*/ System.out.println(text); // Do something. ie Hue Lights, etc } else { System.out.println("No new commands"); } // Sleep for 15 seconds Thread.sleep(15000); } } }
From source file:com.johnson.grab.browser.HttpClientUtil.java
public static void main(String[] args) throws IOException, CrawlException { // final String url = "http://192.168.24.248:8080/HbaseDb/youku/"; // String url = "http://business.sohu.com/20131021/n388557348.shtml?pvid=tc_business&a=&b=%E6%A5%BC%E5%B8%82%E6%B3%A1%E6%B2%AB%E7%A0%B4%E7%81%AD%E5%B0%86%E5%9C%A82015%E5%B9%B4%E5%BA%95%E4%B9%8B%E5%89%8D"; final String url = "http://www.sohu.com"; final int threadNum = 20; final int loop = 100; Thread[] threads = new Thread[threadNum]; final List<Integer> times = new ArrayList<Integer>(); final long s = System.currentTimeMillis(); for (int i = 0; i < threads.length; i++) { threads[i] = new Thread() { public void run() { for (int i = 0; i < loop; i++) { try { getContent(url); } catch (CrawlException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Throwable t) { t.printStackTrace(); }/*from w w w.ja va2 s .c o m*/ long e = System.currentTimeMillis(); times.add((int) (e - s)); } } }; threads[i].start(); } while (times.size() < threadNum * loop) { int current = times.size(); System.out.println("total: " + threadNum * loop + ", current: " + current + ", left: " + (threadNum * loop - current)); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } long e = System.currentTimeMillis(); int totalTime = 0; for (Integer time : times) { totalTime += time; } System.out.println("------------------------------------------------------"); System.out.println("thread num: " + threadNum + ", loop: " + loop); System.out.println("totalTime: " + totalTime + ", averTime: " + totalTime / (threadNum * loop)); System.out.println("finalTime: " + (e - s) + ", throughput: " + (e - s) / (threadNum * loop)); }
From source file:j8583.example.Client.java
public static void main(String[] args) throws Exception { Random rng = new Random(System.currentTimeMillis()); log.debug("Reading config"); mfact = ConfigParser.createFromClasspathConfig("j8583/example/config.xml"); mfact.setAssignDate(true);// w w w . ja v a2 s. c om mfact.setTraceNumberGenerator(new SimpleTraceGenerator((int) (System.currentTimeMillis() % 10000))); System.err.println("Connecting to server"); Socket sock = new Socket("localhost", 9999); // Send 10 messages, then wait for the responses Client client = new Client(sock); Thread reader = new Thread(client, "j8583-client"); 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, 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); System.err.println(String.format("Sending request %s", req.getField(11))); req.write(sock.getOutputStream(), 2); } log.debug("Waiting for responses"); while (pending.size() > 0 && sock.isConnected()) { Thread.sleep(500); } client.stop(); reader.interrupt(); log.debug("DONE."); }
From source file:org.eclipse.swt.snippets.Snippet141.java
public static void main(String[] args) { display = new Display(); shell = new Shell(display); shell.setText("Snippet 141"); shell.setSize(300, 300);//from w w w . j a v a 2s . co m shell.open(); shellGC = new GC(shell); shellBackground = shell.getBackground(); FileDialog dialog = new FileDialog(shell); dialog.setFilterExtensions(new String[] { "*.gif" }); String fileName = dialog.open(); final AtomicBoolean stopAnimation = new AtomicBoolean(false); if (fileName != null) { loader = new ImageLoader(); try { imageDataArray = loader.load(fileName); if (imageDataArray.length > 1) { animateThread = new Thread("Animation") { @Override public void run() { /* Create an off-screen image to draw on, and fill it with the shell background. */ Image offScreenImage = new Image(display, loader.logicalScreenWidth, loader.logicalScreenHeight); GC offScreenImageGC = new GC(offScreenImage); offScreenImageGC.setBackground(shellBackground); offScreenImageGC.fillRectangle(0, 0, loader.logicalScreenWidth, loader.logicalScreenHeight); try { /* Create the first image and draw it on the off-screen image. */ int imageDataIndex = 0; ImageData imageData = imageDataArray[imageDataIndex]; if (image != null && !image.isDisposed()) image.dispose(); image = new Image(display, imageData); offScreenImageGC.drawImage(image, 0, 0, imageData.width, imageData.height, imageData.x, imageData.y, imageData.width, imageData.height); /* Now loop through the images, creating and drawing each one * on the off-screen image before drawing it on the shell. */ int repeatCount = loader.repeatCount; while ((loader.repeatCount == 0 || repeatCount > 0) && !stopAnimation.get()) { switch (imageData.disposalMethod) { case SWT.DM_FILL_BACKGROUND: /* Fill with the background color before drawing. */ Color bgColor = null; if (useGIFBackground && loader.backgroundPixel != -1) { bgColor = new Color(display, imageData.palette.getRGB(loader.backgroundPixel)); } offScreenImageGC.setBackground(bgColor != null ? bgColor : shellBackground); offScreenImageGC.fillRectangle(imageData.x, imageData.y, imageData.width, imageData.height); if (bgColor != null) bgColor.dispose(); break; case SWT.DM_FILL_PREVIOUS: /* Restore the previous image before drawing. */ offScreenImageGC.drawImage(image, 0, 0, imageData.width, imageData.height, imageData.x, imageData.y, imageData.width, imageData.height); break; } imageDataIndex = (imageDataIndex + 1) % imageDataArray.length; imageData = imageDataArray[imageDataIndex]; image.dispose(); image = new Image(display, imageData); offScreenImageGC.drawImage(image, 0, 0, imageData.width, imageData.height, imageData.x, imageData.y, imageData.width, imageData.height); /* Draw the off-screen image to the shell. */ shellGC.drawImage(offScreenImage, 0, 0); /* Sleep for the specified delay time (adding commonly-used slow-down fudge factors). */ try { int ms = imageData.delayTime * 10; if (ms < 20) ms += 30; if (ms < 30) ms += 10; Thread.sleep(ms); } catch (InterruptedException e) { } /* If we have just drawn the last image, decrement the repeat count and start again. */ if (imageDataIndex == imageDataArray.length - 1) repeatCount--; } } catch (SWTException ex) { System.out.println("There was an error animating the GIF"); } finally { if (offScreenImage != null && !offScreenImage.isDisposed()) offScreenImage.dispose(); if (offScreenImageGC != null && !offScreenImageGC.isDisposed()) offScreenImageGC.dispose(); if (image != null && !image.isDisposed()) image.dispose(); } } }; animateThread.setDaemon(true); animateThread.start(); } } catch (SWTException ex) { System.out.println("There was an error loading the GIF"); } } while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } stopAnimation.set(true); display.dispose(); }
From source file:edu.kit.dama.transfer.client.impl.CLDownloadClient.java
/** * Main entry point./* w w w. j a va 2 s . c o m*/ * * @param args Command line arguments. */ public static void main(String[] args) { int result = 0; CLDownloadClient client; try { client = new CLDownloadClient(args); Thread.currentThread().setUncaughtExceptionHandler(client); client.performDownload(); while (client.getTransferClient().isTransferRunning()) { try { Thread.sleep(DateUtils.MILLIS_PER_SECOND); } catch (InterruptedException ie) { } } } catch (TransferClientInstatiationException ie) { LOGGER.error("Failed to create instance of command line client", ie); result = 1; } catch (CommandLineHelpOnlyException choe) { result = 0; } System.exit(result); }
From source file:com.oz.digital.sign.window.MainView.java
/** * @param args the command line arguments *//*from w w w . j ava 2 s. c o m*/ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("GTK+".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { LOG.log(Level.SEVERE, null, ex); } //</editor-fold> MainView mainView = new MainView(); mainView.setVisible(true); while (true) { final String entry = mainView.getTxtfEntry().getText(); if (StringUtils.isNotBlank(entry)) { LOG.log(Level.INFO, "== Agregando la entrada : {0}", entry); String entryFormatted = String.format("%s -> %s\n", DateFormatUtils.format(new Date(), "dd/MM/yyyy hh:mm:ss"), entry); mainView.getTxtAreaEntryHistory().append(entryFormatted); } try { Thread.sleep(5000); } catch (InterruptedException ex) { LOG.log(Level.SEVERE, ex.getMessage()); } } }
From source file:generators.ElementMetaValidator.java
public static void main(String[] args) { ClassicEngineBoot.getInstance().start(); int invalidExpressionsCounter = 0; int deprecatedExpressionsCounter = 0; final HashNMap expressionsByGroup = new HashNMap(); ElementTypeRegistry registry = ElementTypeRegistry.getInstance(); final ElementMetaData[] elementMetaDatas = registry.getAllElementTypes(); for (int i = 0; i < elementMetaDatas.length; i++) { final ElementMetaData metaData = elementMetaDatas[i]; if (metaData == null) { logger.warn("Null Expression encountered"); continue; }/*from ww w.j a va 2 s . c o m*/ missingProperties.clear(); try { final Object type = metaData.create(); } catch (InstantiationException e) { logger.warn("Expression class is null"); } final String typeName = metaData.getName(); logger.debug("Processing " + typeName); final Locale locale = Locale.getDefault(); final String displayName = metaData.getDisplayName(locale); if (isValid(displayName, metaData.getName()) == false) { logger.warn("ElementType '" + typeName + ": No valid display name"); } if (metaData.isDeprecated()) { deprecatedExpressionsCounter += 1; final String deprecateMessage = metaData.getDeprecationMessage(locale); if (isValid(deprecateMessage, "Use a Formula instead") == false) { logger.warn("ElementType '" + typeName + ": No valid deprecate message"); } } final String grouping = metaData.getGrouping(locale); if (isValid(grouping, "Group") == false) { logger.warn("ElementType '" + typeName + ": No valid grouping message"); } expressionsByGroup.add(grouping, metaData); final StyleMetaData[] styleMetaDatas = metaData.getStyleDescriptions(); for (int j = 0; j < styleMetaDatas.length; j++) { final StyleMetaData propertyMetaData = styleMetaDatas[j]; final String propertyDisplayName = propertyMetaData.getDisplayName(locale); if (isValid(propertyDisplayName, propertyMetaData.getName()) == false) { logger.warn("ElementType '" + typeName + ": Style " + propertyMetaData.getName() + ": No DisplayName"); } final String propertyGrouping = propertyMetaData.getGrouping(locale); if (isValid(propertyGrouping, "Group") == false) { logger.warn("ElementType '" + typeName + ": Style " + propertyMetaData.getName() + ": Grouping is not valid"); } if (propertyMetaData.isDeprecated()) { final String deprecateMessage = propertyMetaData.getDeprecationMessage(locale); if (isValid(deprecateMessage, "Deprecated") == false) { logger.warn("ElementType '" + typeName + ": Style " + propertyMetaData.getName() + ": No valid deprecate message"); } } } final AttributeMetaData[] attributeMetaDatas = metaData.getAttributeDescriptions(); for (int j = 0; j < attributeMetaDatas.length; j++) { final AttributeMetaData propertyMetaData = attributeMetaDatas[j]; final String propertyDisplayName = propertyMetaData.getDisplayName(locale); if (isValid(propertyDisplayName, propertyMetaData.getName()) == false) { logger.warn("ElementType '" + typeName + ": Attr " + propertyMetaData.getName() + ": No DisplayName"); } final String propertyGrouping = propertyMetaData.getGrouping(locale); if (isValid(propertyGrouping, "Group") == false) { logger.warn("ElementType '" + typeName + ": Attr " + propertyMetaData.getName() + ": Grouping is not valid"); } if (propertyMetaData.isDeprecated()) { final String deprecateMessage = propertyMetaData.getDeprecationMessage(locale); if (isValid(deprecateMessage, "Deprecated") == false) { logger.warn("ElementType '" + typeName + ": Attr " + propertyMetaData.getName() + ": No valid deprecate message"); } } } System.err.flush(); try { Thread.sleep(25); } catch (InterruptedException e) { } for (int x = 0; x < missingProperties.size(); x++) { final String property = (String) missingProperties.get(x); System.out.println(property); } if (missingProperties.isEmpty() == false) { invalidExpressionsCounter += 1; missingProperties.clear(); } System.out.flush(); try { Thread.sleep(25); } catch (InterruptedException e) { } } logger.info("Validated " + elementMetaDatas.length + " expressions. Invalid: " + invalidExpressionsCounter + " Deprecated: " + deprecatedExpressionsCounter); final Object[] keys = expressionsByGroup.keySet().toArray(); Arrays.sort(keys); for (int i = 0; i < keys.length; i++) { final Object key = keys[i]; logger.info("Group: '" + key + "' Size: " + expressionsByGroup.getValueCount(key)); final Object[] objects = expressionsByGroup.toArray(key); for (int j = 0; j < objects.length; j++) { ElementMetaData metaData = (ElementMetaData) objects[j]; logger.info(" " + metaData.getName()); } } }