List of usage examples for java.util.concurrent TimeUnit MILLISECONDS
TimeUnit MILLISECONDS
To view the source code for java.util.concurrent TimeUnit MILLISECONDS.
Click Source Link
From source file:com.quancheng.saluki.registry.consul.internal.ConsulClient.java
public ConsulClient(String host, int port) { client = new com.ecwid.consul.v1.ConsulClient(host, port); ttlScheduler = new TtlScheduler(client); scheduleRegistry = Executors.newScheduledThreadPool(1, new NamedThreadFactory("retryFailedTtl", true)); scheduleRegistry.scheduleAtFixedRate(new Runnable() { @Override//w ww . j ava2 s .c o m public void run() { try { retryFailedTtl(); } catch (Throwable e) { log.info("retry registry znode failed", e); } } }, ConsulConstants.HEARTBEAT_CIRCLE, ConsulConstants.HEARTBEAT_CIRCLE, TimeUnit.MILLISECONDS); log.info("ConsulEcwidClient init finish. client host:" + host + ", port:" + port); }
From source file:com.peach.masktime.module.net.OkHttpStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { OkHttpClient client = mClient.clone(); int timeoutMs = request.getTimeoutMs(); LogUtils.i(TAG, "timeoutMs = " + timeoutMs); client.setProxy(Proxy.NO_PROXY); client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS); com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder(); okHttpRequestBuilder.url(request.getUrl()); Map<String, String> headers = request.getHeaders(); for (final String name : headers.keySet()) { okHttpRequestBuilder.addHeader(name, headers.get(name)); }// w ww.j a v a2 s.co m for (final String name : additionalHeaders.keySet()) { okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name)); } setConnectionParametersForRequest(okHttpRequestBuilder, request); com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build(); Call okHttpCall = client.newCall(okHttpRequest); Response okHttpResponse = okHttpCall.execute(); StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromOkHttpResponse(okHttpResponse)); Headers responseHeaders = okHttpResponse.headers(); for (int i = 0, len = responseHeaders.size(); i < len; i++) { final String name = responseHeaders.name(i), value = responseHeaders.value(i); if (name != null) { response.addHeader(new BasicHeader(name, value)); } } return response; }
From source file:io.stallion.utils.ProcessHelper.java
public CommandResult run() { String cmdString = String.join(" ", args); System.out.printf("----- Execute command: %s ----\n", cmdString); ProcessBuilder pb = new ProcessBuilder(args); if (!empty(directory)) { pb.directory(new File(directory)); }/*ww w . j av a 2s . com*/ Map<String, String> env = pb.environment(); CommandResult commandResult = new CommandResult(); Process p = null; try { if (showDotsWhileWaiting == null) { showDotsWhileWaiting = !inheritIO; } if (inheritIO) { p = pb.inheritIO().start(); } else { p = pb.start(); } BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream())); BufferedReader out = new BufferedReader(new InputStreamReader(p.getInputStream())); if (!empty(input)) { Log.info("Writing input to pipe {0}", input); IOUtils.write(input, p.getOutputStream(), UTF8); p.getOutputStream().flush(); } while (p.isAlive()) { p.waitFor(1000, TimeUnit.MILLISECONDS); if (showDotsWhileWaiting == true) { System.out.printf("."); } } commandResult.setErr(IOUtils.toString(err)); commandResult.setOut(IOUtils.toString(out)); commandResult.setCode(p.exitValue()); if (commandResult.succeeded()) { info("\n---- Command execution completed ----\n"); } else { Log.warn("Command failed with error code: " + commandResult.getCode()); } } catch (IOException e) { Log.exception(e, "Error running command: " + cmdString); commandResult.setCode(999); commandResult.setEx(e); } catch (InterruptedException e) { Log.exception(e, "Error running command: " + cmdString); commandResult.setCode(998); commandResult.setEx(e); } Log.fine( "\n\n----Start shell command result----:\nCommand: {0}\nexitCode: {1}\n----------STDOUT---------\n{2}\n\n----------STDERR--------\n{3}\n\n----end shell command result----\n", cmdString, commandResult.getCode(), commandResult.getOut(), commandResult.getErr()); return commandResult; }
From source file:com.hurence.logisland.connect.opc.da.OpcDaSourceConnectorTest.java
@Test @Ignore/*ww w. j a va2 s .c om*/ public void e2eTest() throws Exception { OpcDaSourceConnector connector = new OpcDaSourceConnector(); Map<String, String> properties = new HashMap<>(); properties.put(OpcDaSourceConnector.PROPERTY_AUTH_NTLM_DOMAIN, "OPC-9167C0D9342"); properties.put(CommonDefinitions.PROPERTY_CONNECTION_SOCKET_TIMEOUT, "2000"); properties.put(OpcDaSourceConnector.PROPERTY_AUTH_NTLM_PASSWORD, "opc"); properties.put(OpcDaSourceConnector.PROPERTY_AUTH_NTLM_USER, "OPC"); properties.put(CommonDefinitions.PROPERTY_SERVER_URI, "opc.da://192.168.99.100"); properties.put(OpcDaSourceConnector.PROPERTY_SERVER_CLSID, "F8582CF2-88FB-11D0-B850-00C0F0104305"); properties.put(CommonDefinitions.PROPERTY_TAGS_ID, "Random.Real8,Triangle Waves.Int4"); properties.put(CommonDefinitions.PROPERTY_TAGS_STREAM_MODE, "SUBSCRIBE,POLL"); properties.put(CommonDefinitions.PROPERTY_TAGS_SAMPLING_RATE, "PT3S,PT1S"); properties.put(OpcDaSourceConnector.PROPERTY_SESSION_REFRESH_PERIOD, "1000"); properties.put(OpcDaSourceConnector.PROPERTY_TAGS_DATA_TYPE_OVERRIDE, "0,8"); connector.start(properties); OpcDaSourceTask task = new OpcDaSourceTask(); task.start(connector.taskConfigs(1).get(0)); ScheduledExecutorService es = Executors.newSingleThreadScheduledExecutor(); Gson json = new Gson(); es.scheduleAtFixedRate(() -> { try { task.poll().stream() .map(a -> org.apache.commons.lang3.tuple.Pair.of( new Date((Long) a.sourceOffset().get(OpcRecordFields.SAMPLED_TIMESTAMP)), json.toJson(a))) .forEach(System.out::println); } catch (InterruptedException e) { //do nothing } }, 0, 10, TimeUnit.MILLISECONDS); Thread.sleep(600000); task.stop(); es.shutdown(); connector.stop(); }
From source file:com.wattzap.view.graphs.MMPGraph.java
public MMPGraph(XYSeries series) { super();/* w ww.ja v a2 s.co m*/ NumberAxis yAxis = new NumberAxis(userPrefs.messages.getString("poWtt")); yAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); double maxY = series.getMaxY(); yAxis.setRange(0, maxY + 20); yAxis.setTickLabelPaint(Color.white); yAxis.setLabelPaint(Color.white); LogAxis xAxis = new LogAxis(userPrefs.messages.getString("time")); xAxis.setTickLabelPaint(Color.white); xAxis.setBase(4); xAxis.setAutoRange(false); xAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); xAxis.setRange(1, series.getMaxX() + 500); xAxis.setNumberFormatOverride(new NumberFormat() { @Override public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) { long millis = (long) number * 1000; if (millis >= 60000) { return new StringBuffer(String.format("%d m %d s", 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 s", 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; } }); XYPlot plot = new XYPlot(new XYSeriesCollection(series), xAxis, yAxis, new XYLineAndShapeRenderer(true, false)); JFreeChart chart = new JFreeChart("", JFreeChart.DEFAULT_TITLE_FONT, plot, false); chart.setBackgroundPaint(Color.gray); plot = chart.getXYPlot(); plot.setBackgroundPaint(Color.darkGray); /*plot.setDomainGridlinePaint(Color.lightGray); plot.setRangeGridlinePaint(Color.lightGray);*/ ValueAxis domainAxis = plot.getDomainAxis(); domainAxis.setTickLabelPaint(Color.white); domainAxis.setLabelPaint(Color.white); chartPanel = new ChartPanel(chart); chartPanel.setSize(100, 800); chartPanel.setFillZoomRectangle(true); chartPanel.setMouseWheelEnabled(true); chartPanel.setBackground(Color.gray); setLayout(new BorderLayout()); add(chartPanel, BorderLayout.CENTER); setBackground(Color.black); chartPanel.revalidate(); setVisible(true); }
From source file:com.netflix.suro.input.thrift.ThriftServer.java
@Override public void start() throws TTransportException { msgProcessor.start();/*from www . ja v a 2 s . c om*/ logger.info("Starting ThriftServer with config " + config); CustomServerSocket transport = new CustomServerSocket(config); port = transport.getPort(); SuroServer.Processor processor = new SuroServer.Processor<MessageSetProcessor>(msgProcessor); THsHaServer.Args serverArgs = new THsHaServer.Args(transport); serverArgs.workerThreads(config.getThriftWorkerThreadNum()); serverArgs.processor(processor); serverArgs.maxReadBufferBytes = config.getThriftMaxReadBufferBytes(); executor = Executors.newSingleThreadExecutor(); server = new THsHaServer(serverArgs); Future<?> serverStarted = executor.submit(new Runnable() { @Override public void run() { server.serve(); } }); try { serverStarted.get(config.getStartupTimeout(), TimeUnit.MILLISECONDS); if (server.isServing()) { logger.info("Server started on port:" + config.getPort()); } else { throw new RuntimeException("ThriftServer didn't start up within: " + config.getStartupTimeout()); } } catch (InterruptedException e) { // ignore this type of exception } catch (TimeoutException e) { if (server.isServing()) { logger.info("Server started on port:" + config.getPort()); } else { logger.error("ThriftServer didn't start up within: " + config.getStartupTimeout()); Throwables.propagate(e); } } catch (ExecutionException e) { logger.error("Exception on starting ThriftServer: " + e.getMessage(), e); Throwables.propagate(e); } }
From source file:com.navercorp.pinpoint.collector.dao.AutoFlusher.java
private void shutdownExecutor() { executor.shutdown();//from w w w . j av a 2 s .c o m try { executor.awaitTermination(3000 + flushPeriod, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
From source file:org.apache.axis2.transport.http.server.SimpleHttpServer.java
public void destroy() throws IOException, InterruptedException { // Attempt to terminate the listener nicely LOG.info("Shut down connection listener"); this.listenerExecutor.shutdownNow(); this.listener.destroy(); this.listenerExecutor.awaitTermination(SHUTDOWN_GRACE_PERIOD, TimeUnit.MILLISECONDS); if (!this.listenerExecutor.isTerminated()) { // Terminate the listener forcibly LOG.info("Force shut down connection listener"); this.listener.destroy(); // Leave it up to the garbage collector to clean up the mess this.listener = null; }/*www .j av a 2 s . c o m*/ // Attempt to terminate the active processors nicely LOG.info("Shut down HTTP processors"); this.requestExecutor.shutdownNow(); this.requestExecutor.awaitTermination(SHUTDOWN_GRACE_PERIOD, TimeUnit.MILLISECONDS); if (!this.requestExecutor.isTerminated()) { // Terminate the active processors forcibly LOG.info("Force shut down HTTP processors"); this.connmanager.shutdown(); // Leave it up to the garbage collector to clean up the mess this.connmanager = null; } LOG.info("HTTP protocol handler shut down"); }
From source file:com.mule.transport.hz.transformer.HzMapResponseMessageTransformer.java
private IMessage requiredResponse(IMap map, String key) { long elapsed = 0; IMessage processedMsg = null; // try cheap first while (!map.containsKey(key) && elapsed < timeout) { try {//from ww w .j av a 2s.co m Thread.sleep(frequency * MILLIS_FACTOR); elapsed = elapsed + frequency; if (logger.isDebugEnabled()) { logger.debug("Time Elapsed = " + elapsed); } } catch (InterruptedException e) { logger.warn("Interrupted while waiting for poll() to complete as part of message receiver stop.", e); break; } } if (isRemoveKey) { try { processedMsg = (IMessage) map.tryRemove(key, 10, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { logger.error("Ouch Cannot acquire the Lock " + e); } } else { processedMsg = (IMessage) map.get(key); } return processedMsg; }
From source file:com.optimizely.ab.event.AsyncEventHandler.java
public AsyncEventHandler(int queueCapacity, int numWorkers, int maxConnections, int connectionsPerRoute, int validateAfter, long closeTimeout, TimeUnit closeTimeoutUnit) { if (queueCapacity <= 0) { throw new IllegalArgumentException("queue capacity must be > 0"); }/*www.j a v a 2s. c om*/ this.httpClient = OptimizelyHttpClient.builder().withMaxTotalConnections(maxConnections) .withMaxPerRoute(connectionsPerRoute).withValidateAfterInactivity(validateAfter).build(); this.workerExecutor = new ThreadPoolExecutor(numWorkers, numWorkers, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(queueCapacity), new NamedThreadFactory("optimizely-event-dispatcher-thread-%s", true)); this.closeTimeout = closeTimeout; this.closeTimeoutUnit = closeTimeoutUnit; }