List of usage examples for java.util.concurrent TimeUnit MINUTES
TimeUnit MINUTES
To view the source code for java.util.concurrent TimeUnit MINUTES.
Click Source Link
From source file:no.uis.fsws.proxy.StudinfoProxyImpl.java
@Override public List<Studieprogram> getStudieprogram(final XMLGregorianCalendar arstall, final Terminkode terminkode, final Sprakkode sprak, final boolean medUPinfo, final String studieprogramkode) { final StudInfoImport svc = getServiceForPrincipal(); try {/*ww w . j a va 2 s .c o m*/ Future<List<Studieprogram>> future = executor.submit(new Callable<List<Studieprogram>>() { @Override public List<Studieprogram> call() throws Exception { final FsStudieinfo sinfo = svc.fetchStudyProgram(studieprogramkode, arstall.getYear(), terminkode.toString(), medUPinfo, sprak.toString()); return sinfo.getStudieprogram(); } }); return future.get(timeoutMinutes, TimeUnit.MINUTES); } catch (ExecutionException | InterruptedException | TimeoutException e) { throw new RuntimeException(e); } }
From source file:cz.muni.fi.crocs.EduHoc.SerialMain.java
public void startSerial() { List<SerialPortHandler> handlers = new ArrayList<SerialPortHandler>(); for (String mote : motelist.getMotes().keySet()) { SerialPortHandler handler = null; try {//ww w.java 2 s.c o m //open serial port and connect to it handler = new SerialPortHandler(); handler.connect(motelist.getMotes().get(mote)); if (verbose) { handler.setVerbose(); } if (silent) { handler.setSilent(); } handlers.add(handler); } catch (IOException ex) { System.err.println("port connection to " + mote + " failed"); continue; } if (cmd.hasOption("l")) { //create file for each node File file = new File(cmd.getOptionValue("l"), mote.substring(mote.lastIndexOf("/"))); if (verbose) { System.out.println("File " + file.getAbsolutePath() + " created"); } handler.listen(file); } if (cmd.hasOption("w")) { String prefix = cmd.getOptionValue("w"); if (prefix.charAt(prefix.length() - 1) == '/') { prefix = prefix.substring(0, prefix.length() - 1); } File file = new File(prefix, mote.substring(mote.lastIndexOf("/"))); if (file.exists()) { System.out.println("file " + file.getAbsolutePath() + " found, starting write"); handler.write(file); } } } try { if (cmd.hasOption("T")) { if (verbose) { System.out.println("Going to sleep for " + cmd.getOptionValue("T") + " minutes"); } Thread.sleep(TimeUnit.MINUTES.toMillis(Integer.parseInt(cmd.getOptionValue("T")))); } else { if (verbose) { System.out.println("Going to sleep for " + 15 + " minutes"); } Thread.sleep(TimeUnit.MINUTES.toMillis(15)); } } catch (InterruptedException ex) { } for (SerialPortHandler h : handlers) { h.closePort(); } System.out.println("All closed"); System.exit(0); }
From source file:com.esri.geoevent.test.performance.report.AbstractFileRollOverReportWriter.java
protected String formatTime(final long timeInMillisec) { final long hr = TimeUnit.MILLISECONDS.toHours(timeInMillisec); final long min = TimeUnit.MILLISECONDS.toMinutes(timeInMillisec - TimeUnit.HOURS.toMillis(hr)); final long sec = TimeUnit.MILLISECONDS .toSeconds(timeInMillisec - TimeUnit.HOURS.toMillis(hr) - TimeUnit.MINUTES.toMillis(min)); final long ms = TimeUnit.MILLISECONDS.toMillis(timeInMillisec - TimeUnit.HOURS.toMillis(hr) - TimeUnit.MINUTES.toMillis(min) - TimeUnit.SECONDS.toMillis(sec)); if (hr > 0) { return String.format("%02d:%02d:%02d.%03d", hr, min, sec, ms); } else {/* w ww .j a va 2 s . c o m*/ return String.format("%02d:%02d.%03d", min, sec, ms); } }
From source file:com.bitsofproof.supernode.core.TxHandler.java
public TxHandler(final BitcoinNetwork network) { this.network = network; final BlockStore store = network.getStore(); network.scheduleJobWithFixedDelay(new Runnable() { @Override//from w w w . j a v a 2s .co m public void run() { // give retransmits of previously failed tx a chance synchronized (heard) { heard.clear(); } // re-transmit own until not in a block synchronized (own) { if (!own.isEmpty()) { for (BitcoinPeer peer : network.getConnectPeers()) { InvMessage tm = (InvMessage) peer.createMessage("inv"); for (String t : own) { log.debug("Re-broadcast " + t); tm.getTransactionHashes().add(new Hash(t).toByteArray()); } peer.send(tm); } } } } }, 10, 10, TimeUnit.MINUTES); store.addTrunkListener(this); network.getStore().runInCacheContext(new BlockStore.CacheContextRunnable() { @Override public void run(TxOutCache cache) { availableOutput = new ImplementTxOutCacheDelta(cache); } }); network.addListener("inv", new BitcoinMessageListener<InvMessage>() { @Override public void process(InvMessage im, BitcoinPeer peer) { GetDataMessage get = (GetDataMessage) peer.createMessage("getdata"); for (byte[] h : im.getTransactionHashes()) { String hash = new Hash(h).toString(); synchronized (unconfirmed) { synchronized (heard) { if (!heard.contains(hash)) { heard.add(hash); if (!unconfirmed.containsKey(hash)) { log.trace("heard about new transaction " + hash + " from " + peer.getAddress()); get.getTransactions().add(h); } } } } } if (get.getTransactions().size() > 0) { log.trace("asking for transaction details from " + peer.getAddress()); peer.send(get); } } }); network.addListener("tx", new BitcoinMessageListener<TxMessage>() { @Override public void process(final TxMessage txm, final BitcoinPeer peer) { log.trace( "received transaction details for " + txm.getTx().getHash() + " from " + peer.getAddress()); try { validateCacheAndSend(txm.getTx(), peer); } catch (ValidationException e) { } } }); network.addListener("mempool", new BitcoinMessageListener<MempoolMessage>() { @Override public void process(final MempoolMessage m, final BitcoinPeer peer) { log.trace("received mempool request from " + peer.getAddress()); InvMessage tm = (InvMessage) peer.createMessage("inv"); synchronized (unconfirmed) { for (Tx tx : unconfirmed.values()) { tm.getTransactionHashes().add(new Hash(tx.getHash()).toByteArray()); } } peer.send(tm); log.debug("sent mempool to " + peer.getAddress()); } }); }
From source file:org.fast.maven.plugin.AssemblyMojo.java
/** * @throws MojoExecutionException/*from w w w. j a v a 2 s . co m*/ * thrown if modules are not found */ public void execute() throws MojoExecutionException { Properties prop = new Properties(); prop.put("remoteUrlBase", outputDirectory.getAbsolutePath() + "/modules"); prop.put("uriEncoding", charset); StaticDriver driver = new StaticDriver("modules", prop); try { checkStructure(); init(driver); this.executor = Executors.newFixedThreadPool(this.threads); assemblePages(driver); copyStaticResources(); this.executor.shutdown(); this.executor.awaitTermination(10, TimeUnit.MINUTES); for (Future task : tasks) { task.get(); } } catch (HttpErrorPage e) { throw new MojoExecutionException("Error", e); } catch (IOException e) { throw new MojoExecutionException("Error", e); } catch (InterruptedException e) { throw new MojoExecutionException("Error", e); } catch (ExecutionException e) { throw new MojoExecutionException("Error", e); } }
From source file:com.linkedin.pinot.core.realtime.RealtimeFileBasedReaderTest.java
private void setUp(SegmentVersion segmentVersion) throws Exception { filePath = RealtimeFileBasedReaderTest.class.getClassLoader().getResource(AVRO_DATA).getFile(); fieldTypeMap = new HashMap<>(); fieldTypeMap.put("column1", FieldType.DIMENSION); fieldTypeMap.put("column2", FieldType.DIMENSION); fieldTypeMap.put("column3", FieldType.DIMENSION); fieldTypeMap.put("column4", FieldType.DIMENSION); fieldTypeMap.put("column5", FieldType.DIMENSION); fieldTypeMap.put("column6", FieldType.DIMENSION); fieldTypeMap.put("column7", FieldType.DIMENSION); fieldTypeMap.put("column8", FieldType.DIMENSION); fieldTypeMap.put("column9", FieldType.DIMENSION); fieldTypeMap.put("column10", FieldType.DIMENSION); fieldTypeMap.put("weeksSinceEpochSunday", FieldType.DIMENSION); fieldTypeMap.put("daysSinceEpoch", FieldType.DIMENSION); fieldTypeMap.put("column13", FieldType.TIME); fieldTypeMap.put("count", FieldType.METRIC); schema = SegmentTestUtils.extractSchemaFromAvro(new File(filePath), fieldTypeMap, TimeUnit.MINUTES); StreamProviderConfig config = new FileBasedStreamProviderConfig(FileFormat.AVRO, filePath, schema); StreamProvider provider = new FileBasedStreamProviderImpl(); final String tableName = RealtimeFileBasedReaderTest.class.getSimpleName() + ".noTable"; provider.init(config, tableName, new ServerMetrics(new MetricsRegistry())); realtimeSegment = new RealtimeSegmentImpl(schema, 100000, tableName, segmentName, AVRO_DATA, new ServerMetrics(new MetricsRegistry())); GenericRow row = provider.next();//from w w w. ja v a2 s. co m while (row != null) { realtimeSegment.index(row); row = provider.next(); } provider.shutdown(); if (new File("/tmp/realtime").exists()) { FileUtils.deleteQuietly(new File("/tmp/realtime")); } RealtimeSegmentConverter conveter = new RealtimeSegmentConverter(realtimeSegment, "/tmp/realtime", schema, tableName, segmentName, null); conveter.build(segmentVersion); offlineSegment = Loaders.IndexSegment.load(new File("/tmp/realtime").listFiles()[0], ReadMode.mmap); }
From source file:com.wattzap.view.graphs.SCHRGraph.java
public SCHRGraph(ArrayList<Telemetry> telemetry[]) { super();//from w ww . j a v a 2 s. c o m this.telemetry = telemetry; final NumberAxis domainAxis = new NumberAxis("Time (h:m:s)"); domainAxis.setVerticalTickLabels(true); domainAxis.setTickLabelPaint(Color.black); domainAxis.setAutoRange(true); domainAxis.setNumberFormatOverride(new NumberFormat() { @Override public StringBuffer format(double millis, StringBuffer toAppendTo, FieldPosition pos) { if (millis >= 3600000) { // hours, minutes and seconds return new StringBuffer( String.format("%d:%d:%d", TimeUnit.MILLISECONDS.toHours((long) millis), TimeUnit.MILLISECONDS.toMinutes( (long) millis - TimeUnit.MILLISECONDS.toHours((long) millis) * 3600000), TimeUnit.MILLISECONDS.toSeconds((long) millis) - TimeUnit.MINUTES .toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) millis)))); } else if (millis >= 60000) { // minutes and seconds return new StringBuffer(String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes((long) millis), TimeUnit.MILLISECONDS.toSeconds((long) millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) millis)))); } else { return new StringBuffer(String.format("%d", TimeUnit.MILLISECONDS.toSeconds((long) millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) millis)))); } } @Override public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) { return new StringBuffer(String.format("%s", number)); } @Override public Number parse(String source, ParsePosition parsePosition) { return null; } }); // create plot ... final XYItemRenderer powerRenderer = new StandardXYItemRenderer() { Stroke regularStroke = new BasicStroke(0.7f); Color color; public void setColor(Color color) { this.color = color; } @Override public Stroke getItemStroke(int row, int column) { return regularStroke; } @Override public Paint getItemPaint(int row, int column) { return orange; } }; powerRenderer.setSeriesPaint(0, orange); plot = new XYPlot(); plot.setRenderer(0, powerRenderer); plot.setRangeAxis(0, powerAxis); plot.setDomainAxis(domainAxis); // add a second dataset and renderer... final XYItemRenderer cadenceRenderer = new StandardXYItemRenderer() { Stroke regularStroke = new BasicStroke(0.7f); Color color; public void setColor(Color color) { this.color = color; } @Override public Stroke getItemStroke(int row, int column) { return regularStroke; } @Override public Paint getItemPaint(int row, int column) { return cornflower; } public Shape lookupLegendShape(int series) { return new Rectangle(15, 15); } }; final ValueAxis cadenceAxis = new NumberAxis(userPrefs.messages.getString("cDrpm")); cadenceAxis.setRange(0, 200); // arguments of new XYLineAndShapeRenderer are to activate or deactivate // the display of points or line. Set first argument to true if you want // to draw lines between the points for e.g. plot.setRenderer(1, cadenceRenderer); plot.setRangeAxis(1, cadenceAxis); plot.mapDatasetToRangeAxis(1, 1); cadenceRenderer.setSeriesPaint(0, cornflower); // add a third dataset and renderer... final XYItemRenderer hrRenderer = new StandardXYItemRenderer() { Stroke regularStroke = new BasicStroke(0.7f); Color color; public void setColor(Color color) { this.color = color; } @Override public Stroke getItemStroke(int row, int column) { return regularStroke; } @Override public Paint getItemPaint(int row, int column) { return straw; } }; // arguments of new XYLineAndShapeRenderer are to activate or deactivate // the display of points or line. Set first argument to true if you want // to draw lines between the points for e.g. final ValueAxis heartRateAxis = new NumberAxis(userPrefs.messages.getString("hrBpm")); heartRateAxis.setRange(0, 200); plot.setRenderer(2, hrRenderer); hrRenderer.setSeriesPaint(0, straw); plot.setRangeAxis(2, heartRateAxis); plot.mapDatasetToRangeAxis(2, 2); plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD); plot.setBackgroundPaint(Color.DARK_GRAY); // return a new chart containing the overlaid plot... JFreeChart chart = new JFreeChart("", JFreeChart.DEFAULT_TITLE_FONT, plot, true); chart.getLegend().setBackgroundPaint(Color.gray); chartPanel = new ChartPanel(chart); // TODO: maybe remember sizes set by user? this.setPreferredSize(new Dimension(1200, 500)); chartPanel.setFillZoomRectangle(true); chartPanel.setMouseWheelEnabled(true); chartPanel.setBackground(Color.gray); setLayout(new BorderLayout()); add(chartPanel, BorderLayout.CENTER); SmoothingPanel smoothingPanel = new SmoothingPanel(this); add(smoothingPanel, BorderLayout.SOUTH); //infoPanel = new InfoPanel(); //add(infoPanel, BorderLayout.NORTH); setVisible(true); }
From source file:com.javiermoreno.springboot.rest.App.java
@Bean public EmbeddedServletContainerFactory servletContainer() { TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory(); //factory.setPort(7777); (est definido en el application.properties factory.setSessionTimeout(10, TimeUnit.MINUTES); factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/errores/error404.html"), new ErrorPage(HttpStatus.UNAUTHORIZED, "/errores/error401.html"), new ErrorPage(HttpStatus.FORBIDDEN, "/errores/error403.html")); // Activacin gzip sobre http (*NO* activar sobre ssl, induce ataques.) // http://stackoverflow.com/questions/21410317/using-gzip-compression-with-spring-boot-mvc-javaconfig-with-restful factory.addConnectorCustomizers((TomcatConnectorCustomizer) (Connector connector) -> { AbstractHttp11Protocol httpProtocol = (AbstractHttp11Protocol) connector.getProtocolHandler(); httpProtocol.setCompression("on"); httpProtocol.setCompressionMinSize(256); String mimeTypes = httpProtocol.getCompressableMimeTypes(); String mimeTypesWithJson = mimeTypes + "," + MediaType.APPLICATION_JSON_VALUE; httpProtocol.setCompressableMimeTypes(mimeTypesWithJson); });/* ww w. ja v a2s . com*/ factory.addAdditionalTomcatConnectors(createSslConnector()); /* En el caso de que se desee sustitur http por https: ************************ // keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650 final String keystoreFilePath = "keystore.p12"; final String keystoreType = "PKCS12"; final String keystoreProvider = "SunJSSE"; final String keystoreAlias = "tomcat"; factory.addConnectorCustomizers((TomcatConnectorCustomizer) (Connector con) -> { con.setScheme("https"); con.setSecure(true); Http11NioProtocol proto = (Http11NioProtocol) con.getProtocolHandler(); proto.setSSLEnabled(true); // @todo: Descarga el fichero con el certificado actual File keystoreFile = new File(keystoreFilePath); proto.setKeystoreFile(keystoreFile.getAbsolutePath()); proto.setKeystorePass(remoteProps.getKeystorePass()); proto.setKeystoreType(keystoreType); proto.setProperty("keystoreProvider", keystoreProvider); proto.setKeyAlias(keystoreAlias); }); ***************************************************************************** */ return factory; }
From source file:com.google.cloud.bigtable.hbase.TestCreateTable.java
/** * Requirement 1.8 - Table names must match [_a-zA-Z0-9][-_.a-zA-Z0-9]* */// w w w. j a v a 2 s . com @Test(timeout = 1000l * 60 * 4) public void testTableNames() throws IOException { String shouldTest = System.getProperty("bigtable.test.create.table", "true"); if (!"true".equals(shouldTest)) { return; } String[] goodNames = { "a", "1", "_", // Really? Yuck. "_x", "a-._5x", "_a-._5x", // TODO(sduskis): Join the last 2 strings once the Bigtable backend supports table names // longer than 50 characters. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghi", "jklmnopqrstuvwxyz1234567890_-." }; String[] badNames = { "-x", ".x", "a!", "a@", "a#", "a$", "a%", "a^", "a&", "a*", "a(", "a+", "a=", "a~", "a`", "a{", "a[", "a|", "a\\", "a/", "a<", "a,", "a?", "a" + RandomStringUtils.random(10, false, false) }; final Admin admin = getConnection().getAdmin(); for (String badName : badNames) { boolean failed = false; try { admin.createTable(new HTableDescriptor(TableName.valueOf(badName)) .addFamily(new HColumnDescriptor(COLUMN_FAMILY))); } catch (IllegalArgumentException e) { failed = true; } Assert.assertTrue("Should fail as table name: '" + badName + "'", failed); } final TableName[] tableNames = admin.listTableNames(); List<ListenableFuture<Void>> futures = new ArrayList<>(); ListeningExecutorService es = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool()); for (final String goodName : goodNames) { futures.add(es.submit(new Callable<Void>() { @Override public Void call() throws IOException { createTable(admin, goodName, tableNames); return null; } })); } try { try { Futures.allAsList(futures).get(3, TimeUnit.MINUTES); } catch (Exception e) { throw new RuntimeException(e); } } finally { es.shutdownNow(); } }
From source file:com.opensoc.enrichment.common.AbstractEnrichmentBolt.java
public final void prepare(Map conf, TopologyContext topologyContext, OutputCollector collector) { _collector = collector;/*from www.ja v a 2 s .c o m*/ if (this._OutputFieldName == null) throw new IllegalStateException("OutputFieldName must be specified"); if (this._enrichment_tag == null) throw new IllegalStateException("enrichment_tag must be specified"); if (this._MAX_CACHE_SIZE_OBJECTS_NUM == null) throw new IllegalStateException("MAX_CACHE_SIZE_OBJECTS_NUM must be specified"); if (this._MAX_TIME_RETAIN_MINUTES == null) throw new IllegalStateException("MAX_TIME_RETAIN_MINUTES must be specified"); if (this._adapter == null) throw new IllegalStateException("Adapter must be specified"); if (this._jsonKeys == null) throw new IllegalStateException("JSON Keys to be enriched, must be specified"); loader = new CacheLoader<String, JSONObject>() { public JSONObject load(String key) throws Exception { return _adapter.enrich(key); } }; cache = CacheBuilder.newBuilder().maximumSize(_MAX_CACHE_SIZE_OBJECTS_NUM) .expireAfterWrite(_MAX_TIME_RETAIN_MINUTES, TimeUnit.MINUTES).build(loader); boolean success = _adapter.initializeAdapter(); if (!success) { LOG.error("[OpenSOC] EnrichmentBolt could not initialize adapter"); throw new IllegalStateException("Could not initialize adapter..."); } try { doPrepare(conf, topologyContext, collector); } catch (IOException e) { LOG.error("[OpenSOC] Counld not initialize..."); e.printStackTrace(); } }