List of usage examples for java.util.concurrent TimeUnit DAYS
TimeUnit DAYS
To view the source code for java.util.concurrent TimeUnit DAYS.
Click Source Link
From source file:mamo.vanillaVotifier.VotifierServer.java
public synchronized void start() throws IOException { if (isRunning()) { throw new IllegalStateException("Server is already running!"); }/*from w ww . ja va 2s . com*/ notifyListeners(new ServerStartingEvent()); serverSocket = new ServerSocket(); serverSocket.bind(votifier.getConfig().getInetSocketAddress()); running = true; notifyListeners(new ServerStartedEvent()); new Thread(new Runnable() { @Override public void run() { ExecutorService executorService = Executors.newSingleThreadExecutor(); while (isRunning()) { try { final Socket socket = serverSocket.accept(); executorService.execute(new Runnable() { @Override public void run() { try { notifyListeners(new ConnectionEstablishedEvent(socket)); socket.setSoTimeout(SocketOptions.SO_TIMEOUT); // SocketException: handled by try/catch. BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())); writer.write("VOTIFIER 2.9\n"); writer.flush(); BufferedInputStream in = new BufferedInputStream(socket.getInputStream()); // IOException: handled by try/catch. byte[] request = new byte[((RSAPublicKey) votifier.getConfig().getKeyPair() .getPublic()).getModulus().bitLength() / Byte.SIZE]; in.read(request); // IOException: handled by try/catch. notifyListeners(new EncryptedInputReceivedEvent(socket, new String(request))); request = RsaUtils .getDecryptCipher(votifier.getConfig().getKeyPair().getPrivate()) .doFinal(request); // IllegalBlockSizeException: can't happen. String requestString = new String(request); notifyListeners(new DecryptedInputReceivedEvent(socket, requestString)); String[] requestArray = requestString.split("\n"); if ((requestArray.length == 5 || requestArray.length == 6) && requestArray[0].equals("VOTE")) { notifyListeners(new VoteEventVotifier(socket, new Vote(requestArray[1], requestArray[2], requestArray[3], requestArray[4]))); for (VoteAction voteAction : votifier.getConfig().getVoteActions()) { String[] params = new String[4]; try { for (int i = 0; i < params.length; i++) { params[i] = SubstitutionUtils.applyRegexReplacements( requestArray[i + 1], voteAction.getRegexReplacements()); } } catch (PatternSyntaxException e) { notifyListeners(new RegularExpressionPatternErrorException(e)); params = new String[] { requestArray[1], requestArray[2], requestArray[3], requestArray[4] }; } if (voteAction.getCommandSender() instanceof RconCommandSender) { RconCommandSender commandSender = (RconCommandSender) voteAction .getCommandSender(); StrSubstitutor substitutor = SubstitutionUtils.buildStrSubstitutor( new SimpleEntry<String, Object>("service-name", params[0]), new SimpleEntry<String, Object>("user-name", params[1]), new SimpleEntry<String, Object>("address", params[2]), new SimpleEntry<String, Object>("timestamp", params[3])); for (String command : voteAction.getCommands()) { String theCommand = substitutor.replace(command); notifyListeners(new SendingRconCommandEvent( commandSender.getRconConnection(), theCommand)); try { notifyListeners(new RconCommandResponseEvent( commandSender.getRconConnection(), commandSender .sendCommand(theCommand).getPayload())); } catch (Exception e) { notifyListeners(new RconExceptionEvent( commandSender.getRconConnection(), e)); } } } if (voteAction.getCommandSender() instanceof ShellCommandSender) { ShellCommandSender commandSender = (ShellCommandSender) voteAction .getCommandSender(); HashMap<String, String> environment = new HashMap<String, String>(); environment.put("voteServiceName", params[0]); environment.put("voteUserName", params[1]); environment.put("voteAddress", params[2]); environment.put("voteTimestamp", params[3]); for (String command : voteAction.getCommands()) { notifyListeners(new SendingShellCommandEvent(command)); try { commandSender.sendCommand(command, environment); notifyListeners(new ShellCommandSentEvent()); } catch (Exception e) { notifyListeners(new ShellCommandExceptionEvent(e)); } } } } } else { notifyListeners(new InvalidRequestEvent(socket, requestString)); } } catch (SocketTimeoutException e) { notifyListeners(new ReadTimedOutExceptionEvent(socket, e)); } catch (BadPaddingException e) { notifyListeners(new DecryptInputExceptionEvent(socket, e)); } catch (Exception e) { notifyListeners(new CommunicationExceptionEvent(socket, e)); } try { socket.close(); notifyListeners(new ConnectionClosedEvent(socket)); } catch (Exception e) { // IOException: catching just in case. Continue even if socket doesn't close. notifyListeners(new ConnectionCloseExceptionEvent(socket, e)); } } }); } catch (Exception e) { if (running) { // Show errors only while running, to hide error while stopping. notifyListeners(new ConnectionEstablishExceptionEvent(e)); } } } executorService.shutdown(); if (!executorService.isTerminated()) { notifyListeners(new ServerAwaitingTaskCompletionEvent()); try { executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); } catch (Exception e) { // InterruptedException: can't happen. } } notifyListeners(new ServerStoppedEvent()); } }).start(); }
From source file:org.apache.metron.profiler.client.window.WindowProcessor.java
/** * We've set a time unit. We support the timeunits provided by java.util.concurrent.TimeUnit * @param ctx/*from ww w .j av a2 s . c om*/ */ @Override public void exitTimeUnit(org.apache.metron.profiler.client.window.generated.WindowParser.TimeUnitContext ctx) { checkForException(ctx); switch (normalizeTimeUnit(ctx.getText())) { case "DAY": stack.push(new Token<>(TimeUnit.DAYS, TimeUnit.class)); break; case "HOUR": stack.push(new Token<>(TimeUnit.HOURS, TimeUnit.class)); break; case "MINUTE": stack.push(new Token<>(TimeUnit.MINUTES, TimeUnit.class)); break; case "SECOND": stack.push(new Token<>(TimeUnit.SECONDS, TimeUnit.class)); break; default: throw new IllegalStateException("Unsupported time unit: " + ctx.getText() + ". Supported units are limited to: day, hour, minute, second " + "with any pluralization or capitalization."); } }
From source file:org.opendaylight.controller.cluster.raft.RaftActorTest.java
@Test public void testRaftActorRecoveryWithPersistenceDisabled() throws Exception { new JavaTestKit(getSystem()) { {//from ww w .j a v a 2 s .co m String persistenceId = factory.generateActorId("follower-"); DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); TestActorRef<MockRaftActor> ref = factory.createTestActor(MockRaftActor.props(persistenceId, ImmutableMap.<String, String>builder().put("member1", "address").build(), config, new NonPersistentDataProvider()), persistenceId); MockRaftActor mockRaftActor = ref.underlyingActor(); mockRaftActor.waitForRecoveryComplete(); mockRaftActor.waitForInitializeBehaviorComplete(); assertEquals("getRaftState", RaftState.Follower, mockRaftActor.getRaftState()); } }; }
From source file:com.netflix.spinnaker.igor.travis.TravisBuildMonitor.java
private int buildCacheJobTTLSeconds() { return (int) TimeUnit.DAYS.toSeconds(travisProperties.getCachedJobTTLDays()); }
From source file:password.pwm.svc.stats.StatisticsManager.java
public void init(final PwmApplication pwmApplication) throws PwmException { for (final Statistic.EpsType type : Statistic.EpsType.values()) { for (final Statistic.EpsDuration duration : Statistic.EpsDuration.values()) { epsMeterMap.put(type.toString() + duration.toString(), new EventRateMeter(duration.getTimeDuration())); }//from w w w.jav a2 s. co m } status = STATUS.OPENING; this.localDB = pwmApplication.getLocalDB(); this.pwmApplication = pwmApplication; if (localDB == null) { LOGGER.error("LocalDB is not available, will remain closed"); status = STATUS.CLOSED; return; } { final String storedCummulativeBundleStr = localDB.get(LocalDB.DB.PWM_STATS, DB_KEY_CUMULATIVE); if (storedCummulativeBundleStr != null && storedCummulativeBundleStr.length() > 0) { try { statsCummulative = StatisticsBundle.input(storedCummulativeBundleStr); } catch (Exception e) { LOGGER.warn("error loading saved stored statistics: " + e.getMessage()); } } } { for (final Statistic.EpsType loopEpsType : Statistic.EpsType.values()) { for (final Statistic.EpsType loopEpsDuration : Statistic.EpsType.values()) { final String key = "EPS-" + loopEpsType.toString() + loopEpsDuration.toString(); final String storedValue = localDB.get(LocalDB.DB.PWM_STATS, key); if (storedValue != null && storedValue.length() > 0) { try { final EventRateMeter eventRateMeter = JsonUtil.deserialize(storedValue, EventRateMeter.class); epsMeterMap.put(loopEpsType.toString() + loopEpsDuration.toString(), eventRateMeter); } catch (Exception e) { LOGGER.error("unexpected error reading last EPS rate for " + loopEpsType + " from LocalDB: " + e.getMessage()); } } } } } { final String storedInitialString = localDB.get(LocalDB.DB.PWM_STATS, DB_KEY_INITIAL_DAILY_KEY); if (storedInitialString != null && storedInitialString.length() > 0) { initialDailyKey = new DailyKey(storedInitialString); } } { currentDailyKey = new DailyKey(new Date()); final String storedDailyStr = localDB.get(LocalDB.DB.PWM_STATS, currentDailyKey.toString()); if (storedDailyStr != null && storedDailyStr.length() > 0) { statsDaily = StatisticsBundle.input(storedDailyStr); } } try { localDB.put(LocalDB.DB.PWM_STATS, DB_KEY_TEMP, JavaHelper.toIsoDate(new Date())); } catch (IllegalStateException e) { LOGGER.error("unable to write to localDB, will remain closed, error: " + e.getMessage()); status = STATUS.CLOSED; return; } localDB.put(LocalDB.DB.PWM_STATS, DB_KEY_VERSION, DB_VALUE_VERSION); localDB.put(LocalDB.DB.PWM_STATS, DB_KEY_INITIAL_DAILY_KEY, initialDailyKey.toString()); { // setup a timer to roll over at 0 Zula and one to write current stats every 10 seconds executorService = JavaHelper.makeSingleThreadExecutorService(pwmApplication, this.getClass()); executorService.scheduleAtFixedRate(new FlushTask(), 10 * 1000, DB_WRITE_FREQUENCY_MS, TimeUnit.MILLISECONDS); final TimeDuration delayTillNextZulu = TimeDuration.fromCurrent(JavaHelper.nextZuluZeroTime()); executorService.scheduleAtFixedRate(new NightlyTask(), delayTillNextZulu.getTotalMilliseconds(), TimeUnit.DAYS.toMillis(1), TimeUnit.MILLISECONDS); } status = STATUS.OPEN; }
From source file:org.apache.rya.accumulo.mr.merge.util.TimeUtils.java
/** * Convert a millisecond duration to a string format. * @param durationMs A duration to convert to a string form. * @param showSign {@code true} to show if the duration is positive or negative. {@code false} * to not display the sign./*from w ww . j a va2 s . c o m*/ * @return A string of the form "X Days Y Hours Z Minutes A Seconds B Milliseconds". */ public static String getDurationBreakdown(final long durationMs, final boolean showSign) { long tempDurationMs = Math.abs(durationMs); final long days = TimeUnit.MILLISECONDS.toDays(tempDurationMs); tempDurationMs -= TimeUnit.DAYS.toMillis(days); final long hours = TimeUnit.MILLISECONDS.toHours(tempDurationMs); tempDurationMs -= TimeUnit.HOURS.toMillis(hours); final long minutes = TimeUnit.MILLISECONDS.toMinutes(tempDurationMs); tempDurationMs -= TimeUnit.MINUTES.toMillis(minutes); final long seconds = TimeUnit.MILLISECONDS.toSeconds(tempDurationMs); tempDurationMs -= TimeUnit.SECONDS.toMillis(seconds); final long milliseconds = TimeUnit.MILLISECONDS.toMillis(tempDurationMs); final StringBuilder sb = new StringBuilder(); if (tempDurationMs != 0 && showSign) { sb.append(tempDurationMs > 0 ? "+" : "-"); } if (days > 0) { sb.append(days); sb.append(days == 1 ? " Day " : " Days "); } if (hours > 0) { sb.append(hours); sb.append(hours == 1 ? " Hour " : " Hours "); } if (minutes > 0) { sb.append(minutes); sb.append(minutes == 1 ? " Minute " : " Minutes "); } if (seconds > 0) { sb.append(seconds); sb.append(seconds == 1 ? " Second " : " Seconds "); } if (milliseconds > 0 || (!showSign && sb.length() == 0) || (showSign && sb.length() == 1)) { // At least show the milliseconds if nothing else has been shown so far sb.append(milliseconds); sb.append(milliseconds == 1 ? " Millisecond" : " Milliseconds"); } return StringUtils.trim(sb.toString()); }
From source file:org.apache.bookkeeper.conf.ServerConfiguration.java
/** * Get wait time in millis for garbage collection of overreplicated ledgers * // w w w.j a v a 2s . com * @return gc wait time */ public long getGcOverreplicatedLedgerWaitTimeMillis() { return this.getLong(GC_OVERREPLICATED_LEDGER_WAIT_TIME, TimeUnit.DAYS.toMillis(1)); }
From source file:org.openhie.openempi.configuration.Configuration.java
private TimeUnit getTimeUnit(org.openhie.openempi.configuration.xml.ScheduledTask.TimeUnit.Enum timeUnit) { if (timeUnit == org.openhie.openempi.configuration.xml.ScheduledTask.TimeUnit.DAYS) { return TimeUnit.DAYS; } else if (timeUnit == org.openhie.openempi.configuration.xml.ScheduledTask.TimeUnit.HOURS) { return TimeUnit.HOURS; } else if (timeUnit == org.openhie.openempi.configuration.xml.ScheduledTask.TimeUnit.MICROSECONDS) { return TimeUnit.MICROSECONDS; } else if (timeUnit == org.openhie.openempi.configuration.xml.ScheduledTask.TimeUnit.MILLISECONDS) { return TimeUnit.MILLISECONDS; } else if (timeUnit == org.openhie.openempi.configuration.xml.ScheduledTask.TimeUnit.MINUTES) { return TimeUnit.MINUTES; } else if (timeUnit == org.openhie.openempi.configuration.xml.ScheduledTask.TimeUnit.NANOSECONDS) { return TimeUnit.NANOSECONDS; } else if (timeUnit == org.openhie.openempi.configuration.xml.ScheduledTask.TimeUnit.SECONDS) { return TimeUnit.SECONDS; }//from www. j a v a 2 s .c o m log.warn("An unknown time-unit was specified for a scheduled task of " + timeUnit + " so will resort to seconds as the default time unit."); return TimeUnit.SECONDS; }
From source file:com.yahoo.pulsar.broker.loadbalance.impl.SimpleLoadManagerImpl.java
public SimpleLoadManagerImpl(PulsarService pulsar) { this.policies = new SimpleResourceAllocationPolicies(pulsar); this.sortedRankings.set(new TreeMap<>()); this.currentLoadReports = new HashMap<>(); this.resourceUnitRankings = new HashMap<>(); this.loadBalancingMetrics.set(Lists.newArrayList()); this.realtimeResourceQuotas.set(new HashMap<>()); this.realtimeAvgResourceQuota = new ResourceQuota(); placementStrategy = new WRRPlacementStrategy(); lastLoadReport = new LoadReport(pulsar.getWebServiceAddress(), pulsar.getWebServiceAddressTls(), pulsar.getBrokerServiceUrl(), pulsar.getBrokerServiceUrlTls()); if (SystemUtils.IS_OS_LINUX) { brokerHostUsage = new LinuxBrokerHostUsageImpl(pulsar); } else {//ww w .j av a 2 s. c o m brokerHostUsage = new GenericBrokerHostUsageImpl(pulsar); } loadReportCacheZk = new ZooKeeperDataCache<LoadReport>(pulsar.getLocalZkCache()) { @Override public LoadReport deserialize(String key, byte[] content) throws Exception { return ObjectMapperFactory.getThreadLocal().readValue(content, LoadReport.class); } }; loadReportCacheZk.registerListener(this); this.dynamicConfigurationCache = new ZooKeeperDataCache<Map<String, String>>(pulsar.getLocalZkCache()) { @Override public Map<String, String> deserialize(String key, byte[] content) throws Exception { return ObjectMapperFactory.getThreadLocal().readValue(content, HashMap.class); } }; adminCache = CacheBuilder.newBuilder().removalListener(new RemovalListener<String, PulsarAdmin>() { public void onRemoval(RemovalNotification<String, PulsarAdmin> removal) { removal.getValue().close(); } }).expireAfterAccess(1, TimeUnit.DAYS).build(new CacheLoader<String, PulsarAdmin>() { @Override public PulsarAdmin load(String key) throws Exception { // key - broker name already is valid URL, has prefix "http://" return new PulsarAdmin(new URL(key), pulsar.getConfiguration().getBrokerClientAuthenticationPlugin(), pulsar.getConfiguration().getBrokerClientAuthenticationParameters()); } }); int entryExpiryTime = (int) pulsar.getConfiguration().getLoadBalancerSheddingGracePeriodMinutes(); unloadedHotNamespaceCache = CacheBuilder.newBuilder().expireAfterWrite(entryExpiryTime, TimeUnit.MINUTES) .build(new CacheLoader<String, Long>() { @Override public Long load(String key) throws Exception { return System.currentTimeMillis(); } }); availableActiveBrokers = new ZooKeeperChildrenCache(pulsar.getLocalZkCache(), LOADBALANCE_BROKERS_ROOT); availableActiveBrokers.registerListener(new ZooKeeperCacheListener<Set<String>>() { @Override public void onUpdate(String path, Set<String> data, Stat stat) { if (log.isDebugEnabled()) { log.debug("Update Received for path {}", path); } scheduler.submit(SimpleLoadManagerImpl.this::updateRanking); } }); scheduler = Executors.newScheduledThreadPool(1); this.pulsar = pulsar; }
From source file:org.apache.hadoop.hbase.PerformanceEvaluation2.java
private void doMultipleClients(final Test cmd, final List<TableSplit> splits, final int nthread) throws IOException { BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(nthread); final ThreadPoolExecutor services = new ThreadPoolExecutor(nthread, nthread, 10, TimeUnit.SECONDS, queue, new ThreadPoolExecutor.CallerRunsPolicy()); for (final TableSplit ts : splits) { services.submit(new Runnable() { @Override//from ww w .j a v a 2 s . com public void run() { try { long startTime = System.currentTimeMillis(); runOneClient(cmd, ts); long elapsedTime = System.currentTimeMillis() - startTime; LOG.info("Finished " + Thread.currentThread().getName() + " in " + elapsedTime + "ms for " + cmd.rows.get() + " rows and " + cmd.kvs.get() + " cols"); totalRowCount.add(cmd.rows.get()); totalKVCount.add(cmd.kvs.get()); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } }); } services.shutdown(); try { services.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); } catch (InterruptedException e) { e.printStackTrace(); } }