Example usage for java.util.concurrent TimeUnit DAYS

List of usage examples for java.util.concurrent TimeUnit DAYS

Introduction

In this page you can find the example usage for java.util.concurrent TimeUnit DAYS.

Prototype

TimeUnit DAYS

To view the source code for java.util.concurrent TimeUnit DAYS.

Click Source Link

Document

Time unit representing twenty four hours.

Usage

From source file:org.opendaylight.controller.cluster.raft.RaftActorTest.java

@Test
public void testFakeSnapshotsForLeaderWithInRealSnapshots() throws Exception {
    new JavaTestKit(getSystem()) {
        {//from   www.  j a va2s  .  c  o m
            String persistenceId = factory.generateActorId("leader-");
            String follower1Id = factory.generateActorId("follower-");

            ActorRef followerActor1 = factory.createActor(Props.create(MessageCollectorActor.class));

            DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
            config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
            config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));

            DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);

            Map<String, String> peerAddresses = new HashMap<>();
            peerAddresses.put(follower1Id, followerActor1.path().toString());

            TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
                    MockRaftActor.props(persistenceId, peerAddresses, config, dataPersistenceProvider),
                    persistenceId);

            MockRaftActor leaderActor = mockActorRef.underlyingActor();

            leaderActor.getRaftActorContext().setCommitIndex(4);
            leaderActor.getRaftActorContext().setLastApplied(4);
            leaderActor.getRaftActorContext().getTermInformation().update(1, persistenceId);

            leaderActor.waitForInitializeBehaviorComplete();

            // create 8 entries in the log - 0 to 4 are applied and will get picked up as part of the capture snapshot

            Leader leader = new Leader(leaderActor.getRaftActorContext());
            leaderActor.setCurrentBehavior(leader);
            assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());

            MockRaftActorContext.MockReplicatedLogBuilder logBuilder = new MockRaftActorContext.MockReplicatedLogBuilder();
            leaderActor.getRaftActorContext().setReplicatedLog(logBuilder.createEntries(0, 8, 1).build());

            assertEquals(8, leaderActor.getReplicatedLog().size());

            leaderActor.getRaftActorContext().getSnapshotManager()
                    .capture(new MockRaftActorContext.MockReplicatedLogEntry(1, 6,
                            new MockRaftActorContext.MockPayload("x")), 4);

            verify(leaderActor.snapshotCohortDelegate).createSnapshot(any(ActorRef.class));

            assertEquals(8, leaderActor.getReplicatedLog().size());

            assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
            //fake snapshot on index 5
            leaderActor.onReceiveCommand(new AppendEntriesReply(follower1Id, 1, true, 5, 1, (short) 0));

            assertEquals(8, leaderActor.getReplicatedLog().size());

            //fake snapshot on index 6
            assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
            leaderActor.onReceiveCommand(new AppendEntriesReply(follower1Id, 1, true, 6, 1, (short) 0));
            assertEquals(8, leaderActor.getReplicatedLog().size());

            assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());

            assertEquals(8, leaderActor.getReplicatedLog().size());

            ByteString snapshotBytes = fromObject(Arrays.asList(new MockRaftActorContext.MockPayload("foo-0"),
                    new MockRaftActorContext.MockPayload("foo-1"),
                    new MockRaftActorContext.MockPayload("foo-2"),
                    new MockRaftActorContext.MockPayload("foo-3"),
                    new MockRaftActorContext.MockPayload("foo-4")));

            leaderActor.getRaftActorContext().getSnapshotManager().persist(snapshotBytes.toByteArray(),
                    Runtime.getRuntime().totalMemory());

            assertTrue(leaderActor.getRaftActorContext().getSnapshotManager().isCapturing());

            // The commit is needed to complete the snapshot creation process
            leaderActor.getRaftActorContext().getSnapshotManager().commit(-1, -1);

            // capture snapshot reply should remove the snapshotted entries only
            assertEquals(3, leaderActor.getReplicatedLog().size());
            assertEquals(7, leaderActor.getReplicatedLog().lastIndex());

            // add another non-replicated entry
            leaderActor.getReplicatedLog()
                    .append(new ReplicatedLogImplEntry(8, 1, new MockRaftActorContext.MockPayload("foo-8")));

            //fake snapshot on index 7, since lastApplied = 7 , we would keep the last applied
            leaderActor.onReceiveCommand(new AppendEntriesReply(follower1Id, 1, true, 7, 1, (short) 0));
            assertEquals(2, leaderActor.getReplicatedLog().size());
            assertEquals(8, leaderActor.getReplicatedLog().lastIndex());

        }
    };
}

From source file:org.yccheok.jstock.gui.IndicatorScannerJPanel.java

private void initAlertDataStructures() {
    AlertStateManager oldAlertStateManager = alertStateManager;
    if (oldAlertStateManager != null) {
        oldAlertStateManager.dettachAll();
        oldAlertStateManager.clearState();
    }// w ww .jav a2s .co m

    final ExecutorService oldSystemTrayAlertPool = systemTrayAlertPool;
    final ExecutorService oldEmailAlertPool = emailAlertPool;

    Utils.getZoombiePool().execute(new Runnable() {
        @Override
        public void run() {
            if (oldSystemTrayAlertPool != null) {
                log.info("Prepare to shut down " + oldSystemTrayAlertPool + "...");
                oldSystemTrayAlertPool.shutdownNow();
                try {
                    oldSystemTrayAlertPool.awaitTermination(100, TimeUnit.DAYS);
                } catch (InterruptedException exp) {
                    log.error(null, exp);
                }
                log.info("Shut down " + oldSystemTrayAlertPool + " peacefully.");

                log.info("Prepare to shut down " + oldEmailAlertPool + "...");
            }

            if (oldEmailAlertPool != null) {
                oldEmailAlertPool.shutdownNow();
                try {
                    oldEmailAlertPool.awaitTermination(100, TimeUnit.DAYS);
                } catch (InterruptedException exp) {
                    log.error(null, exp);
                }
                log.info("Shut down " + oldEmailAlertPool + " peacefully.");
            }
        }
    });

    alertStateManager = new AlertStateManager();
    alertStateManager.attach(this);

    emailAlertPool = Executors.newFixedThreadPool(1);
    systemTrayAlertPool = Executors.newFixedThreadPool(1);
}

From source file:org.apache.druid.segment.realtime.appenderator.AppenderatorImpl.java

@Override
public void close() {
    if (!closed.compareAndSet(false, true)) {
        log.info("Appenderator already closed");
        return;//  ww w  . j a v a 2  s. co  m
    }

    log.info("Shutting down...");

    final List<ListenableFuture<?>> futures = Lists.newArrayList();
    for (Map.Entry<SegmentIdentifier, Sink> entry : sinks.entrySet()) {
        futures.add(abandonSegment(entry.getKey(), entry.getValue(), false));
    }

    try {
        Futures.allAsList(futures).get();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        log.warn(e, "Interrupted during close()");
    } catch (ExecutionException e) {
        log.warn(e, "Unable to abandon existing segments during close()");
    }

    try {
        shutdownExecutors();
        Preconditions.checkState(
                persistExecutor == null || persistExecutor.awaitTermination(365, TimeUnit.DAYS),
                "persistExecutor not terminated");
        Preconditions.checkState(pushExecutor == null || pushExecutor.awaitTermination(365, TimeUnit.DAYS),
                "pushExecutor not terminated");
        Preconditions.checkState(
                intermediateTempExecutor == null
                        || intermediateTempExecutor.awaitTermination(365, TimeUnit.DAYS),
                "intermediateTempExecutor not terminated");
        persistExecutor = null;
        pushExecutor = null;
        intermediateTempExecutor = null;
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new ISE("Failed to shutdown executors during close()");
    }

    // Only unlock if executors actually shut down.
    unlockBasePersistDirectory();
}

From source file:org.signserver.server.log.SystemLoggingTest.java

/**
 * Tests that importing a certificate chain to a token is audit logged
 * including the complete chain./*  ww  w.  j a  v a 2  s .co m*/
 * @throws Exception 
 */
@Test
public void test01LogCertChainInstalledToToken() throws Exception {
    LOG.info(">test01LogCertChainInstalledToToken");

    final String tokenName = "TestCryptoTokenP12_001";
    final String alias = "testkeyalias10";

    try {
        setupCryptoToken(WORKERID_CRYPTOWORKER1, tokenName, "foo123");
        workerSession.generateSignerKey(WORKERID_CRYPTOWORKER1, "RSA", "512", alias, null);

        PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithRSA", "CN=testkeyalias10,C=SE", null);
        ICertReqData req = workerSession.getCertificateRequest(WORKERID_CRYPTOWORKER1, certReqInfo, false);
        Base64SignerCertReqData reqData = (Base64SignerCertReqData) req;
        PKCS10CertificationRequest csr = new PKCS10CertificationRequest(
                Base64.decode(reqData.getBase64CertReq()));

        int linesBefore = readEntriesCount(auditLogFile);

        // Test with uploadSignerCertificateChain method (global scope)
        KeyPair issuerKeyPair = CryptoUtils.generateRSA(512);
        final X509Certificate issuerCert = new JcaX509CertificateConverter().getCertificate(
                new CertBuilder().setSelfSignKeyPair(issuerKeyPair).setSubject("CN=Issuer, C=SE").build());
        final X509Certificate cert = new JcaX509CertificateConverter()
                .getCertificate(new X509v3CertificateBuilder(new X500Name("CN=Issuer, C=SE"), BigInteger.ONE,
                        new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)),
                        csr.getSubject(), csr.getSubjectPublicKeyInfo())
                                .build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC")
                                        .build(issuerKeyPair.getPrivate())));

        workerSession.importCertificateChain(WORKERID_CRYPTOWORKER1,
                Arrays.asList(cert.getEncoded(), issuerCert.getEncoded()), alias, null);

        List<String> lines = readEntries(auditLogFile, linesBefore, 2);
        LOG.info(lines);

        String line = getTheLineContaining(lines, "EVENT: CERTCHAININSTALLED");
        assertNotNull("Contains event", line);
        assertTrue("Contains module", line.contains("MODULE: KEY_MANAGEMENT"));
        assertTrue("Contains worker id", line.contains("WORKER_ID: " + WORKERID_CRYPTOWORKER1));
        assertTrue("Contains crypto token", line.contains("CRYPTOTOKEN: " + tokenName));
        assertTrue("Contains key alias", line.contains("KEYALIAS: " + alias));
        assertTrue("Contains certificate",
                line.contains(new String(org.cesecore.util.CertTools
                        .getPemFromCertificateChain(Arrays.<Certificate>asList(cert, issuerCert)))
                                .replace("\r\n", "\n")));
    } finally {
        removeWorker(WORKERID_CRYPTOWORKER1);
        if (keystoreFile != null) {
            FileUtils.deleteQuietly(keystoreFile);
        }
    }
}

From source file:com.android.tv.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    if (DEBUG)/*  w  ww .  j ava2s.co  m*/
        Log.d(TAG, "onCreate()");
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M && !PermissionUtils.hasAccessAllEpg(this)) {
        Toast.makeText(this, R.string.msg_not_supported_device, Toast.LENGTH_LONG).show();
        finish();
        return;
    }
    boolean skipToShowOnboarding = getIntent().getAction() == Intent.ACTION_VIEW
            && TvContract.isChannelUriForPassthroughInput(getIntent().getData());
    if (Features.ONBOARDING_EXPERIENCE.isEnabled(this) && OnboardingUtils.needToShowOnboarding(this)
            && !skipToShowOnboarding && !TvCommonUtils.isRunningInTest()) {
        // TODO: The onboarding is turned off in test, because tests are broken by the
        // onboarding. We need to enable the feature for tests later.
        startActivity(OnboardingActivity.buildIntent(this, getIntent()));
        finish();
        return;
    }

    TvApplication tvApplication = (TvApplication) getApplication();
    tvApplication.getMainActivityWrapper().onMainActivityCreated(this);
    if (BuildConfig.ENG && SystemProperties.ALLOW_STRICT_MODE.getValue()) {
        Toast.makeText(this, "Using Strict Mode for eng builds", Toast.LENGTH_SHORT).show();
    }
    mTracker = tvApplication.getTracker();
    mTvInputManagerHelper = tvApplication.getTvInputManagerHelper();
    mTvInputManagerHelper.addCallback(mTvInputCallback);
    mUsbTunerInputId = UsbTunerTvInputService.getInputId(this);
    mChannelDataManager = tvApplication.getChannelDataManager();
    mProgramDataManager = tvApplication.getProgramDataManager();
    mProgramDataManager.addOnCurrentProgramUpdatedListener(Channel.INVALID_ID,
            mOnCurrentProgramUpdatedListener);
    mProgramDataManager.setPrefetchEnabled(true);
    mChannelTuner = new ChannelTuner(mChannelDataManager, mTvInputManagerHelper);
    mChannelTuner.addListener(mChannelTunerListener);
    mChannelTuner.start();
    mPipInputManager = new PipInputManager(this, mTvInputManagerHelper, mChannelTuner);
    mPipInputManager.start();
    mMemoryManageables.add(mProgramDataManager);
    mMemoryManageables.add(ImageCache.getInstance());
    mMemoryManageables.add(TvContentRatingCache.getInstance());
    if (CommonFeatures.DVR.isEnabled(this) && BuildCompat.isAtLeastN()) {
        mDvrManager = tvApplication.getDvrManager();
        mDvrDataManager = tvApplication.getDvrDataManager();
    }

    DisplayManager displayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
    Display display = displayManager.getDisplay(Display.DEFAULT_DISPLAY);
    Point size = new Point();
    display.getSize(size);
    int screenWidth = size.x;
    int screenHeight = size.y;
    mDefaultRefreshRate = display.getRefreshRate();

    mOverlayRootView = (OverlayRootView) getLayoutInflater().inflate(R.layout.overlay_root_view, null, false);
    setContentView(R.layout.activity_tv);
    mTvView = (TunableTvView) findViewById(R.id.main_tunable_tv_view);
    int shrunkenTvViewHeight = getResources().getDimensionPixelSize(R.dimen.shrunken_tvview_height);
    mTvView.initialize((AppLayerTvView) findViewById(R.id.main_tv_view), false, screenHeight,
            shrunkenTvViewHeight);
    mTvView.setOnUnhandledInputEventListener(new OnUnhandledInputEventListener() {
        @Override
        public boolean onUnhandledInputEvent(InputEvent event) {
            if (isKeyEventBlocked()) {
                return true;
            }
            if (event instanceof KeyEvent) {
                KeyEvent keyEvent = (KeyEvent) event;
                if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && keyEvent.isLongPress()) {
                    if (onKeyLongPress(keyEvent.getKeyCode(), keyEvent)) {
                        return true;
                    }
                }
                if (keyEvent.getAction() == KeyEvent.ACTION_UP) {
                    return onKeyUp(keyEvent.getKeyCode(), keyEvent);
                } else if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    return onKeyDown(keyEvent.getKeyCode(), keyEvent);
                }
            }
            return false;
        }
    });
    mTimeShiftManager = new TimeShiftManager(this, mTvView, mProgramDataManager, mTracker,
            new OnCurrentProgramUpdatedListener() {
                @Override
                public void onCurrentProgramUpdated(long channelId, Program program) {
                    updateMediaSession();
                    switch (mTimeShiftManager.getLastActionId()) {
                    case TimeShiftManager.TIME_SHIFT_ACTION_ID_REWIND:
                    case TimeShiftManager.TIME_SHIFT_ACTION_ID_FAST_FORWARD:
                    case TimeShiftManager.TIME_SHIFT_ACTION_ID_JUMP_TO_PREVIOUS:
                    case TimeShiftManager.TIME_SHIFT_ACTION_ID_JUMP_TO_NEXT:
                        updateChannelBannerAndShowIfNeeded(UPDATE_CHANNEL_BANNER_REASON_FORCE_SHOW);
                        break;
                    default:
                        updateChannelBannerAndShowIfNeeded(UPDATE_CHANNEL_BANNER_REASON_UPDATE_INFO);
                        break;
                    }
                }
            });

    mPipView = (TunableTvView) findViewById(R.id.pip_tunable_tv_view);
    mPipView.initialize((AppLayerTvView) findViewById(R.id.pip_tv_view), true, screenHeight,
            shrunkenTvViewHeight);

    if (!PermissionUtils.hasAccessWatchedHistory(this)) {
        WatchedHistoryManager watchedHistoryManager = new WatchedHistoryManager(getApplicationContext());
        watchedHistoryManager.start();
        mTvView.setWatchedHistoryManager(watchedHistoryManager);
    }
    mTvViewUiManager = new TvViewUiManager(this, mTvView, mPipView,
            (FrameLayout) findViewById(android.R.id.content), mTvOptionsManager);

    mPipView.setFixedSurfaceSize(screenWidth / 2, screenHeight / 2);
    mPipView.setBlockScreenType(TunableTvView.BLOCK_SCREEN_TYPE_SHRUNKEN_TV_VIEW);

    ViewGroup sceneContainer = (ViewGroup) findViewById(R.id.scene_container);
    mChannelBannerView = (ChannelBannerView) getLayoutInflater().inflate(R.layout.channel_banner,
            sceneContainer, false);
    mKeypadChannelSwitchView = (KeypadChannelSwitchView) getLayoutInflater()
            .inflate(R.layout.keypad_channel_switch, sceneContainer, false);
    InputBannerView inputBannerView = (InputBannerView) getLayoutInflater().inflate(R.layout.input_banner,
            sceneContainer, false);
    SelectInputView selectInputView = (SelectInputView) getLayoutInflater().inflate(R.layout.select_input,
            sceneContainer, false);
    selectInputView.setOnInputSelectedCallback(new OnInputSelectedCallback() {
        @Override
        public void onTunerInputSelected() {
            Channel currentChannel = mChannelTuner.getCurrentChannel();
            if (currentChannel != null && !currentChannel.isPassthrough()) {
                hideOverlays();
            } else {
                tuneToLastWatchedChannelForTunerInput();
            }
        }

        @Override
        public void onPassthroughInputSelected(TvInputInfo input) {
            Channel currentChannel = mChannelTuner.getCurrentChannel();
            String currentInputId = currentChannel == null ? null : currentChannel.getInputId();
            if (TextUtils.equals(input.getId(), currentInputId)) {
                hideOverlays();
            } else {
                tuneToChannel(Channel.createPassthroughChannel(input.getId()));
            }
        }

        private void hideOverlays() {
            getOverlayManager().hideOverlays(TvOverlayManager.FLAG_HIDE_OVERLAYS_KEEP_DIALOG
                    | TvOverlayManager.FLAG_HIDE_OVERLAYS_KEEP_SIDE_PANELS
                    | TvOverlayManager.FLAG_HIDE_OVERLAYS_KEEP_PROGRAM_GUIDE
                    | TvOverlayManager.FLAG_HIDE_OVERLAYS_KEEP_MENU
                    | TvOverlayManager.FLAG_HIDE_OVERLAYS_KEEP_FRAGMENT);
        }
    });
    mSearchFragment = new ProgramGuideSearchFragment();
    mOverlayManager = new TvOverlayManager(this, mChannelTuner, mKeypadChannelSwitchView, mChannelBannerView,
            inputBannerView, selectInputView, sceneContainer, mSearchFragment);

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mAudioFocusStatus = AudioManager.AUDIOFOCUS_LOSS;

    mMediaSession = new MediaSession(this, MEDIA_SESSION_TAG);
    mMediaSession.setCallback(new MediaSession.Callback() {
        @Override
        public boolean onMediaButtonEvent(Intent mediaButtonIntent) {
            // Consume the media button event here. Should not send it to other apps.
            return true;
        }
    });
    mMediaSession
            .setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mNowPlayingCardWidth = getResources().getDimensionPixelSize(R.dimen.notif_card_img_max_width);
    mNowPlayingCardHeight = getResources().getDimensionPixelSize(R.dimen.notif_card_img_height);

    mTvViewUiManager.restoreDisplayMode(false);
    if (!handleIntent(getIntent())) {
        finish();
        return;
    }

    mAudioCapabilitiesReceiver = new AudioCapabilitiesReceiver(this,
            new AudioCapabilitiesReceiver.OnAc3PassthroughCapabilityChangeListener() {
                @Override
                public void onAc3PassthroughCapabilityChange(boolean capability) {
                    mAc3PassthroughSupported = capability;
                }
            });
    mAudioCapabilitiesReceiver.register();

    mAccessibilityManager = (AccessibilityManager) getSystemService(Context.ACCESSIBILITY_SERVICE);
    mSendConfigInfoRecurringRunner = new RecurringRunner(this, TimeUnit.DAYS.toMillis(1),
            new SendConfigInfoRunnable(mTracker, mTvInputManagerHelper), null);
    mSendConfigInfoRecurringRunner.start();
    mChannelStatusRecurringRunner = SendChannelStatusRunnable.startChannelStatusRecurringRunner(this, mTracker,
            mChannelDataManager);

    // To avoid not updating Rating systems when changing language.
    mTvInputManagerHelper.getContentRatingsManager().update();

    initForTest();
}

From source file:org.apache.druid.segment.realtime.appenderator.AppenderatorImpl.java

/**
 * Unannounce the segments and wait for outstanding persists to finish.
 * Do not unlock base persist dir as we are not waiting for push executor to shut down
 * relying on current JVM to shutdown to not cause any locking problem if the task is restored.
 * In case when task is restored and current task is still active because of push executor (which it shouldn't be
 * since push executor starts daemon threads) then the locking should fail and new task should fail to start.
 * This also means that this method should only be called when task is shutting down.
 *///from   w w w .j a  va 2s  .  c o m
@Override
public void closeNow() {
    if (!closed.compareAndSet(false, true)) {
        log.info("Appenderator already closed");
        return;
    }

    log.info("Shutting down immediately...");
    for (Map.Entry<SegmentIdentifier, Sink> entry : sinks.entrySet()) {
        try {
            segmentAnnouncer.unannounceSegment(entry.getValue().getSegment());
        } catch (Exception e) {
            log.makeAlert(e, "Failed to unannounce segment[%s]", schema.getDataSource())
                    .addData("identifier", entry.getKey().getIdentifierAsString()).emit();
        }
    }
    try {
        shutdownExecutors();
        // We don't wait for pushExecutor to be terminated. See Javadoc for more details.
        Preconditions.checkState(
                persistExecutor == null || persistExecutor.awaitTermination(365, TimeUnit.DAYS),
                "persistExecutor not terminated");
        Preconditions.checkState(
                intermediateTempExecutor == null
                        || intermediateTempExecutor.awaitTermination(365, TimeUnit.DAYS),
                "intermediateTempExecutor not terminated");
        persistExecutor = null;
        intermediateTempExecutor = null;
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new ISE("Failed to shutdown executors during close()");
    }
}

From source file:org.apache.hadoop.yarn.client.cli.TopCLI.java

String getHeader(QueueMetrics queueMetrics, NodesInformation nodes) {
    StringBuilder ret = new StringBuilder();
    String queue = "root";
    if (!queues.isEmpty()) {
        queue = StringUtils.join(queues, ",");
    }/* ww w  .ja va2 s.  c o m*/
    long now = Time.now();
    long uptime = 0L;
    if (rmStartTime != -1) {
        uptime = now - rmStartTime;
    }
    long days = TimeUnit.MILLISECONDS.toDays(uptime);
    long hours = TimeUnit.MILLISECONDS.toHours(uptime)
            - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(uptime));
    long minutes = TimeUnit.MILLISECONDS.toMinutes(uptime)
            - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(uptime));
    String uptimeStr = String.format("%dd, %d:%d", days, hours, minutes);
    String currentTime = DateFormatUtils.ISO_TIME_NO_T_FORMAT.format(now);

    ret.append(CLEAR_LINE);
    ret.append(limitLineLength(String.format("YARN top - %s, up %s, %d active users, queue(s): %s%n",
            currentTime, uptimeStr, queueMetrics.activeUsers, queue), terminalWidth, true));

    ret.append(CLEAR_LINE);
    ret.append(limitLineLength(
            String.format(
                    "NodeManager(s): %d total, %d active, %d unhealthy, %d decommissioned,"
                            + " %d lost, %d rebooted%n",
                    nodes.totalNodes, nodes.runningNodes, nodes.unhealthyNodes, nodes.decommissionedNodes,
                    nodes.lostNodes, nodes.rebootedNodes),
            terminalWidth, true));

    ret.append(CLEAR_LINE);
    ret.append(limitLineLength(String.format(
            "Queue(s) Applications: %d running, %d submitted, %d pending,"
                    + " %d completed, %d killed, %d failed%n",
            queueMetrics.appsRunning, queueMetrics.appsSubmitted, queueMetrics.appsPending,
            queueMetrics.appsCompleted, queueMetrics.appsKilled, queueMetrics.appsFailed), terminalWidth,
            true));

    ret.append(CLEAR_LINE);
    ret.append(limitLineLength(
            String.format("Queue(s) Mem(GB): %d available," + " %d allocated, %d pending, %d reserved%n",
                    queueMetrics.availableMemoryGB, queueMetrics.allocatedMemoryGB,
                    queueMetrics.pendingMemoryGB, queueMetrics.reservedMemoryGB),
            terminalWidth, true));

    ret.append(CLEAR_LINE);
    ret.append(limitLineLength(
            String.format("Queue(s) VCores: %d available," + " %d allocated, %d pending, %d reserved%n",
                    queueMetrics.availableVCores, queueMetrics.allocatedVCores, queueMetrics.pendingVCores,
                    queueMetrics.reservedVCores),
            terminalWidth, true));

    ret.append(CLEAR_LINE);
    ret.append(limitLineLength(String.format("Queue(s) Containers: %d allocated, %d pending, %d reserved%n",
            queueMetrics.allocatedContainers, queueMetrics.pendingContainers, queueMetrics.reservedContainers),
            terminalWidth, true));
    return ret.toString();
}

From source file:org.opendaylight.controller.cluster.raft.RaftActorServerConfigurationSupportTest.java

@Test
public void testAddServerWithNoLeader() {
    LOG.info("testAddServerWithNoLeader starting");

    setupNewFollower();//from   ww w . j  av  a 2 s  .co m
    DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
    configParams.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));

    TestActorRef<MockRaftActor> noLeaderActor = actorFactory.createTestActor(MockRaftActor.builder()
            .id(LEADER_ID).peerAddresses(ImmutableMap.of(FOLLOWER_ID, followerActor.path().toString()))
            .config(configParams).persistent(Optional.of(false)).props()
            .withDispatcher(Dispatchers.DefaultDispatcherId()), actorFactory.generateActorId(LEADER_ID));
    noLeaderActor.underlyingActor().waitForInitializeBehaviorComplete();

    noLeaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true),
            testKit.getRef());
    AddServerReply addServerReply = testKit.expectMsgClass(testKit.duration("5 seconds"), AddServerReply.class);
    assertEquals("getStatus", ServerChangeStatus.NO_LEADER, addServerReply.getStatus());

    LOG.info("testAddServerWithNoLeader ending");
}

From source file:org.opendaylight.controller.cluster.raft.RaftActorTest.java

@Test
public void testFakeSnapshotsForFollowerWithInRealSnapshots() throws Exception {
    new JavaTestKit(getSystem()) {
        {//from  www .  ja  v  a  2 s.  c o  m
            String persistenceId = factory.generateActorId("follower-");
            String leaderId = factory.generateActorId("leader-");

            ActorRef leaderActor1 = factory.createActor(Props.create(MessageCollectorActor.class));

            DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
            config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
            config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));

            DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);

            Map<String, String> peerAddresses = new HashMap<>();
            peerAddresses.put(leaderId, leaderActor1.path().toString());

            TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
                    MockRaftActor.props(persistenceId, peerAddresses, config, dataPersistenceProvider),
                    persistenceId);

            MockRaftActor followerActor = mockActorRef.underlyingActor();
            followerActor.getRaftActorContext().setCommitIndex(4);
            followerActor.getRaftActorContext().setLastApplied(4);
            followerActor.getRaftActorContext().getTermInformation().update(1, persistenceId);

            followerActor.waitForInitializeBehaviorComplete();

            Follower follower = new Follower(followerActor.getRaftActorContext());
            followerActor.setCurrentBehavior(follower);
            assertEquals(RaftState.Follower, followerActor.getCurrentBehavior().state());

            // create 6 entries in the log - 0 to 4 are applied and will get picked up as part of the capture snapshot
            MockRaftActorContext.MockReplicatedLogBuilder logBuilder = new MockRaftActorContext.MockReplicatedLogBuilder();
            followerActor.getRaftActorContext().setReplicatedLog(logBuilder.createEntries(0, 6, 1).build());

            // log has indices 0-5
            assertEquals(6, followerActor.getReplicatedLog().size());

            //snapshot on 4
            followerActor.getRaftActorContext().getSnapshotManager()
                    .capture(new MockRaftActorContext.MockReplicatedLogEntry(1, 5,
                            new MockRaftActorContext.MockPayload("D")), 4);

            verify(followerActor.snapshotCohortDelegate).createSnapshot(any(ActorRef.class));

            assertEquals(6, followerActor.getReplicatedLog().size());

            //fake snapshot on index 6
            List<ReplicatedLogEntry> entries = Arrays
                    .asList((ReplicatedLogEntry) new MockRaftActorContext.MockReplicatedLogEntry(1, 6,
                            new MockRaftActorContext.MockPayload("foo-6")));
            followerActor.onReceiveCommand(new AppendEntries(1, leaderId, 5, 1, entries, 5, 5, (short) 0));
            assertEquals(7, followerActor.getReplicatedLog().size());

            //fake snapshot on index 7
            assertEquals(RaftState.Follower, followerActor.getCurrentBehavior().state());

            entries = Arrays.asList((ReplicatedLogEntry) new MockRaftActorContext.MockReplicatedLogEntry(1, 7,
                    new MockRaftActorContext.MockPayload("foo-7")));
            followerActor.onReceiveCommand(new AppendEntries(1, leaderId, 6, 1, entries, 6, 6, (short) 0));
            assertEquals(8, followerActor.getReplicatedLog().size());

            assertEquals(RaftState.Follower, followerActor.getCurrentBehavior().state());

            ByteString snapshotBytes = fromObject(Arrays.asList(new MockRaftActorContext.MockPayload("foo-0"),
                    new MockRaftActorContext.MockPayload("foo-1"),
                    new MockRaftActorContext.MockPayload("foo-2"),
                    new MockRaftActorContext.MockPayload("foo-3"),
                    new MockRaftActorContext.MockPayload("foo-4")));
            followerActor.onReceiveCommand(new CaptureSnapshotReply(snapshotBytes.toByteArray()));
            assertTrue(followerActor.getRaftActorContext().getSnapshotManager().isCapturing());

            // The commit is needed to complete the snapshot creation process
            followerActor.getRaftActorContext().getSnapshotManager().commit(-1, -1);

            // capture snapshot reply should remove the snapshotted entries only till replicatedToAllIndex
            assertEquals(3, followerActor.getReplicatedLog().size()); //indexes 5,6,7 left in the log
            assertEquals(7, followerActor.getReplicatedLog().lastIndex());

            entries = Arrays.asList((ReplicatedLogEntry) new MockRaftActorContext.MockReplicatedLogEntry(1, 8,
                    new MockRaftActorContext.MockPayload("foo-7")));
            // send an additional entry 8 with leaderCommit = 7
            followerActor.onReceiveCommand(new AppendEntries(1, leaderId, 7, 1, entries, 7, 7, (short) 0));

            // 7 and 8, as lastapplied is 7
            assertEquals(2, followerActor.getReplicatedLog().size());

        }
    };
}

From source file:org.nd4j.util.StringUtils.java

public static TimeUnit stringToTimeUnit(String str) {
    switch (str.toLowerCase()) {
    case "ms":
    case "millisecond":
    case "milliseconds":
        return TimeUnit.MILLISECONDS;
    case "s":
    case "sec":
    case "second":
    case "seconds":
        return TimeUnit.SECONDS;
    case "min":
    case "minute":
    case "minutes":
        return TimeUnit.MINUTES;
    case "h":
    case "hour":
    case "hours":
        return TimeUnit.HOURS;
    case "day":
    case "days":
        return TimeUnit.DAYS;
    default://w w  w .j a  va  2  s. com
        throw new RuntimeException("Unknown time unit: \"" + str + "\"");
    }
}