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:com.google.gerrit.acceptance.server.notedb.ChangeRebuilderIT.java

@Test
public void laterEventsDependingOnEarlierPatchSetDontIntefereWithOtherPatchSets() throws Exception {
    PushOneCommit.Result r1 = createChange();
    ChangeData cd = r1.getChange();// w  w  w  .  j  a va  2s  .c  om
    Change.Id id = cd.getId();
    amendChange(cd.change().getKey().get());
    TestTimeUtil.incrementClock(90, TimeUnit.DAYS);

    ReviewInput rin = ReviewInput.approve();
    rin.message = "Some very late message on PS1";
    gApi.changes().id(id.get()).revision(1).review(rin);

    checker.rebuildAndCheckChanges(id);
}

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

@Test
public void testRealSnapshotWhenReplicatedToAllIndexMinusOne() throws Exception {
    new JavaTestKit(getSystem()) {
        {/*from   w w w.  ja va 2s .c o m*/
            String persistenceId = factory.generateActorId("leader-");
            DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
            config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
            config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
            config.setSnapshotBatchCount(5);

            DataPersistenceProvider dataPersistenceProvider = new NonPersistentDataProvider();

            Map<String, String> peerAddresses = ImmutableMap.<String, String>builder().put("member1", "address")
                    .build();

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

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

            leaderActor.waitForInitializeBehaviorComplete();
            for (int i = 0; i < 4; i++) {
                leaderActor.getReplicatedLog().append(new MockRaftActorContext.MockReplicatedLogEntry(1, i,
                        new MockRaftActorContext.MockPayload("A")));
            }

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

            // Simulate an install snaphost to a follower.
            leaderActor.getRaftActorContext().getSnapshotManager()
                    .captureToInstall(leaderActor.getReplicatedLog().last(), -1, "member1");

            // Now send a CaptureSnapshotReply
            mockActorRef.tell(new CaptureSnapshotReply(fromObject("foo").toByteArray()), mockActorRef);

            // Trimming log in this scenario is a no-op
            assertEquals(-1, leaderActor.getReplicatedLog().getSnapshotIndex());
            assertTrue(leaderActor.getRaftActorContext().getSnapshotManager().isCapturing());
            assertEquals(-1, leader.getReplicatedToAllIndex());

        }
    };
}

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

@Test
public void testRemoveServer() throws Exception {
    LOG.info("testRemoveServer starting");

    DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
    configParams.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
    configParams.setCustomRaftPolicyImplementationClass(DisableElectionsRaftPolicy.class.getName());

    final String follower1ActorId = actorFactory.generateActorId(FOLLOWER_ID);
    final String follower1ActorPath = actorFactory.createTestActorPath(follower1ActorId);
    final String follower2ActorId = actorFactory.generateActorId(FOLLOWER_ID2);
    final String follower2ActorPath = actorFactory.createTestActorPath(follower2ActorId);
    RaftActorContext initialActorContext = new MockRaftActorContext();

    final String downNodeId = "downNode";
    TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
            MockLeaderRaftActor/*from   w w  w  .ja v a 2 s .c o m*/
                    .props(ImmutableMap.of(FOLLOWER_ID, follower1ActorPath, FOLLOWER_ID2, follower2ActorPath,
                            downNodeId, ""), initialActorContext)
                    .withDispatcher(Dispatchers.DefaultDispatcherId()),
            actorFactory.generateActorId(LEADER_ID));

    final ActorRef leaderCollector = newLeaderCollectorActor(leaderActor.underlyingActor());

    ActorRef follower1Collector = actorFactory.createActor(MessageCollectorActor.props(),
            actorFactory.generateActorId("collector"));
    final TestActorRef<CollectingMockRaftActor> follower1Actor = actorFactory
            .createTestActor(
                    CollectingMockRaftActor.props(FOLLOWER_ID,
                            ImmutableMap.of(LEADER_ID, leaderActor.path().toString(), FOLLOWER_ID2,
                                    follower2ActorPath, downNodeId, ""),
                            configParams, NO_PERSISTENCE, follower1Collector)
                            .withDispatcher(Dispatchers.DefaultDispatcherId()),
                    follower1ActorId);

    ActorRef follower2Collector = actorFactory.createActor(MessageCollectorActor.props(),
            actorFactory.generateActorId("collector"));
    final TestActorRef<CollectingMockRaftActor> follower2Actor = actorFactory
            .createTestActor(
                    CollectingMockRaftActor.props(FOLLOWER_ID2,
                            ImmutableMap.of(LEADER_ID, leaderActor.path().toString(), FOLLOWER_ID,
                                    follower1ActorPath, downNodeId, ""),
                            configParams, NO_PERSISTENCE, follower2Collector)
                            .withDispatcher(Dispatchers.DefaultDispatcherId()),
                    follower2ActorId);

    leaderActor.underlyingActor().waitForInitializeBehaviorComplete();
    follower1Actor.underlyingActor().waitForInitializeBehaviorComplete();
    follower2Actor.underlyingActor().waitForInitializeBehaviorComplete();

    leaderActor.tell(new RemoveServer(FOLLOWER_ID), testKit.getRef());
    RemoveServerReply removeServerReply = testKit.expectMsgClass(testKit.duration("5 seconds"),
            RemoveServerReply.class);
    assertEquals("getStatus", ServerChangeStatus.OK, removeServerReply.getStatus());

    ApplyState applyState = MessageCollectorActor.expectFirstMatching(leaderCollector, ApplyState.class);
    assertEquals(0L, applyState.getReplicatedLogEntry().getIndex());
    verifyServerConfigurationPayloadEntry(
            leaderActor.underlyingActor().getRaftActorContext().getReplicatedLog(), votingServer(LEADER_ID),
            votingServer(FOLLOWER_ID2), votingServer(downNodeId));

    applyState = MessageCollectorActor.expectFirstMatching(follower2Collector, ApplyState.class);
    assertEquals(0L, applyState.getReplicatedLogEntry().getIndex());
    verifyServerConfigurationPayloadEntry(
            leaderActor.underlyingActor().getRaftActorContext().getReplicatedLog(), votingServer(LEADER_ID),
            votingServer(FOLLOWER_ID2), votingServer(downNodeId));

    RaftActorBehavior currentBehavior = leaderActor.underlyingActor().getCurrentBehavior();
    assertTrue("Expected Leader", currentBehavior instanceof Leader);
    assertEquals("Follower ids size", 2, ((Leader) currentBehavior).getFollowerIds().size());

    MessageCollectorActor.expectFirstMatching(follower1Collector, ServerRemoved.class);

    LOG.info("testRemoveServer ending");
}

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

@Test
public void testRealSnapshotWhenReplicatedToAllIndexNotInReplicatedLog() throws Exception {
    new JavaTestKit(getSystem()) {
        {/*from w  ww  .ja v a2s . c o  m*/
            String persistenceId = factory.generateActorId("leader-");
            DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
            config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
            config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
            config.setSnapshotBatchCount(5);

            DataPersistenceProvider dataPersistenceProvider = new NonPersistentDataProvider();

            Map<String, String> peerAddresses = ImmutableMap.<String, String>builder().put("member1", "address")
                    .build();

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

            MockRaftActor leaderActor = mockActorRef.underlyingActor();
            leaderActor.getRaftActorContext().setCommitIndex(3);
            leaderActor.getRaftActorContext().setLastApplied(3);
            leaderActor.getRaftActorContext().getTermInformation().update(1, persistenceId);
            leaderActor.getReplicatedLog().setSnapshotIndex(3);

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

            // Persist another entry (this will cause a CaptureSnapshot to be triggered
            leaderActor.persistData(mockActorRef, new MockIdentifier("x"),
                    new MockRaftActorContext.MockPayload("duh"));

            // Now send a CaptureSnapshotReply
            mockActorRef.tell(new CaptureSnapshotReply(fromObject("foo").toByteArray()), mockActorRef);

            // Trimming log in this scenario is a no-op
            assertEquals(3, leaderActor.getReplicatedLog().getSnapshotIndex());
            assertTrue(leaderActor.getRaftActorContext().getSnapshotManager().isCapturing());
            assertEquals(3, leader.getReplicatedToAllIndex());

        }
    };
}

From source file:it.govpay.core.business.Pagamento.java

/**
 * La logica prevede di cercare i pendenti per stazione nell'intervallo da >> a.
 * Se nella risposta ci sono 500+ pendenti si dimezza l'intervallo.
 * Se a forza di dimezzare l'intervallo diventa di 1 giorno ed ancora ci sono 500+ risultati, 
 * si ripete la ricerca per quel giorno sulla lista di domini. Se anche in questo caso si hanno troppi risultati, 
 * pace, non e' possibile filtrare ulteriormente. 
 * //from   w  ww. j a  v a2s. c o m
 * @param client
 * @param intermediario
 * @param stazione
 * @param lstDomini
 * @param perDominio
 * @param da
 * @param a
 * @return
 */
private Map<String, String> acquisisciPendenti(NodoClient client, Intermediario intermediario,
        Stazione stazione, List<Dominio> lstDomini, boolean perDominio, Calendar da, Calendar a, long soglia) {
    GpContext ctx = GpThreadLocal.get();
    Map<String, String> statiRptPendenti = new HashMap<String, String>();

    // Ciclo sui domini, ma ciclo veramente solo se perDominio == true,
    // Altrimenti ci giro una sola volta

    for (Dominio dominio : lstDomini) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        NodoChiediListaPendentiRPT richiesta = new NodoChiediListaPendentiRPT();
        richiesta.setIdentificativoIntermediarioPA(intermediario.getCodIntermediario());
        richiesta.setIdentificativoStazioneIntermediarioPA(stazione.getCodStazione());
        richiesta.setPassword(stazione.getPassword());
        richiesta.setDimensioneLista(BigInteger.valueOf(soglia));
        richiesta.setRangeA(a.getTime());
        richiesta.setRangeDa(da.getTime());

        if (perDominio) {
            richiesta.setIdentificativoDominio(dominio.getCodDominio());
            log.debug("Richiedo la lista delle RPT pendenti (Dominio " + dominio.getCodDominio() + " dal "
                    + dateFormat.format(da.getTime()) + " al " + dateFormat.format(a.getTime()) + ")");
            ctx.log("pendenti.listaPendenti", dominio.getCodDominio(), dateFormat.format(da.getTime()),
                    dateFormat.format(a.getTime()));
        } else {
            log.debug("Richiedo la lista delle RPT pendenti (Stazione " + stazione.getCodStazione() + " dal "
                    + dateFormat.format(da.getTime()) + " al " + dateFormat.format(a.getTime()) + ")");
            ctx.log("pendenti.listaPendenti", stazione.getCodStazione(), dateFormat.format(da.getTime()),
                    dateFormat.format(a.getTime()));
        }

        NodoChiediListaPendentiRPTRisposta risposta = null;
        String transactionId = null;
        try {
            transactionId = GpThreadLocal.get().openTransaction();
            GpThreadLocal.get().setupNodoClient(stazione.getCodStazione(), null,
                    Azione.nodoChiediListaPendentiRPT);
            risposta = client.nodoChiediListaPendentiRPT(richiesta, intermediario.getDenominazione());
        } catch (Exception e) {
            log.warn("Errore durante la richiesta di lista pendenti", e);
            // Esco da ciclo while e procedo con il prossimo dominio.
            if (perDominio) {
                ctx.log("pendenti.listaPendentiDominioFail", dominio.getCodDominio(), e.getMessage());
                continue;
            } else {
                ctx.log("pendenti.listaPendentiFail", stazione.getCodStazione(), e.getMessage());
                break;
            }
        } finally {
            if (transactionId != null) {
                GpThreadLocal.get().closeTransaction(transactionId);
            }
        }

        if (risposta.getFault() != null) {
            log.warn("Ricevuto errore durante la richiesta di lista pendenti: "
                    + risposta.getFault().getFaultCode() + ": " + risposta.getFault().getFaultString());

            String fc = risposta.getFault().getFaultCode() != null ? risposta.getFault().getFaultCode() : "-";
            String fs = risposta.getFault().getFaultString() != null ? risposta.getFault().getFaultString()
                    : "-";
            String fd = risposta.getFault().getDescription() != null ? risposta.getFault().getDescription()
                    : "-";
            if (perDominio) {
                ctx.log("pendenti.listaPendentiDominioKo", dominio.getCodDominio(), fc, fs, fd);
                continue;
            } else {
                ctx.log("pendenti.listaPendentiKo", stazione.getCodStazione(), fc, fs, fd);
                break;
            }
        }

        if (risposta.getListaRPTPendenti() == null
                || risposta.getListaRPTPendenti().getRptPendente().isEmpty()) {
            log.debug("Lista pendenti vuota.");
            if (perDominio) {
                ctx.log("pendenti.listaPendentiDominioVuota", dominio.getCodDominio());
                continue;
            } else {
                ctx.log("pendenti.listaPendentiVuota", stazione.getCodStazione());
                break;
            }
        }

        if (risposta.getListaRPTPendenti().getTotRestituiti() >= soglia) {

            // Vedo quanto e' ampia la finestra per capire se dimezzarla o ciclare sui domini
            int finestra = (int) TimeUnit.DAYS.convert((a.getTimeInMillis() - da.getTimeInMillis()),
                    TimeUnit.MILLISECONDS);

            if (finestra > 1) {
                ctx.log("pendenti.listaPendentiPiena", stazione.getCodStazione(),
                        dateFormat.format(da.getTime()), dateFormat.format(a.getTime()));
                finestra = finestra / 2;
                Calendar mezzo = (Calendar) a.clone();
                mezzo.add(Calendar.DATE, -finestra);
                log.debug("Lista pendenti con troppi elementi. Ricalcolo la finestra: (dal "
                        + dateFormat.format(da.getTime()) + " a " + dateFormat.format(a.getTime()) + ")");
                statiRptPendenti.putAll(acquisisciPendenti(client, intermediario, stazione, lstDomini, false,
                        da, mezzo, soglia));
                mezzo.add(Calendar.DATE, 1);
                statiRptPendenti.putAll(acquisisciPendenti(client, intermediario, stazione, lstDomini, false,
                        mezzo, a, soglia));
                return statiRptPendenti;
            } else {
                if (perDominio) {
                    ctx.log("pendenti.listaPendentiDominioDailyPiena", dominio.getCodDominio(),
                            dateFormat.format(a.getTime()));
                    log.debug(
                            "Lista pendenti con troppi elementi, ma impossibile diminuire ulteriormente la finesta. Elenco accettato.");
                } else {
                    ctx.log("pendenti.listaPendentiDailyPiena", stazione.getCodStazione(),
                            dateFormat.format(a.getTime()));
                    log.debug("Lista pendenti con troppi elementi, scalo a dominio.");
                    return acquisisciPendenti(client, intermediario, stazione, lstDomini, true, da, a, soglia);
                }
            }
        }

        // Qui ci arrivo o se ho meno di 500 risultati oppure se sono in *giornaliero per dominio*
        for (TipoRPTPendente rptPendente : risposta.getListaRPTPendenti().getRptPendente()) {
            String rptKey = rptPendente.getIdentificativoUnivocoVersamento() + "@"
                    + rptPendente.getCodiceContestoPagamento();
            statiRptPendenti.put(rptKey, rptPendente.getStato());
        }

        // Se sto ricercando per stazione, esco.
        if (!perDominio) {
            return statiRptPendenti;
        }
    }
    return statiRptPendenti;
}

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

private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    isFormWindowClosedCalled = true;/*from  w ww .ja v  a  2s . c  om*/

    try {
        ExecutorService _stockInfoDatabaseMetaPool = this.stockInfoDatabaseMetaPool;
        this.stockInfoDatabaseMetaPool = null;

        _stockInfoDatabaseMetaPool.shutdownNow();

        // Always be the first statement. As no matter what happen, we must
        // save all the configuration files.
        this.save();

        if (this.needToSaveUserDefinedDatabase) {
            // We are having updated user database in memory.
            // Save it to disk.
            this.saveUserDefinedDatabaseAsCSV(jStockOptions.getCountry(), stockInfoDatabase);
        }

        // Hide the icon immediately.
        TrayIcon _trayIcon = trayIcon;
        if (_trayIcon != null) {
            SystemTray.getSystemTray().remove(_trayIcon);
            trayIcon = null;
        }

        dettachAllAndStopAutoCompleteJComboBox();
        this.indicatorPanel.dettachAllAndStopAutoCompleteJComboBox();

        log.info("latestNewsTask stop...");

        if (this.latestNewsTask != null) {
            this.latestNewsTask.cancel(true);
        }

        _stockInfoDatabaseMetaPool.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);

        // We suppose to call shutdownAll to clean up all network resources.
        // However, that will cause Exception in other threads if they are still using httpclient.
        // Exception in thread "Thread-4" java.lang.IllegalStateException: Connection factory has been shutdown.
        //
        // MultiThreadedHttpConnectionManager.shutdownAll();

        log.info("Widnow is closed.");
    } catch (Exception exp) {
        log.error("Unexpected error while trying to quit application", exp);
    }

    // All the above operations are done within try block, to ensure
    // System.exit(0) will always be called.
    //
    // Final clean up.
    System.exit(0);
}

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

private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    isFormWindowClosedCalled = true;//from w w  w .  ja v  a2 s.  com

    try {
        ExecutorService _stockInfoDatabaseMetaPool = this.stockInfoDatabaseMetaPool;
        this.stockInfoDatabaseMetaPool = null;

        _stockInfoDatabaseMetaPool.shutdownNow();

        // Always be the first statement. As no matter what happen, we must
        // save all the configuration files.
        this.save();

        if (this.needToSaveUserDefinedDatabase) {
            // We are having updated user database in memory.
            // Save it to disk.
            this.saveUserDefinedDatabaseAsCSV(jStockOptions.getCountry(), stockInfoDatabase);
        }

        // Hide the icon immediately.
        TrayIcon _trayIcon = trayIcon;
        if (_trayIcon != null) {
            SystemTray.getSystemTray().remove(_trayIcon);
            trayIcon = null;
        }

        dettachAllAndStopAutoCompleteJComboBox();
        this.indicatorPanel.dettachAllAndStopAutoCompleteJComboBox();

        log.info("latestNewsTask stop...");

        if (this.latestNewsTask != null) {
            this.latestNewsTask.cancel(true);
        }

        _stockInfoDatabaseMetaPool.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);

        // We suppose to call shutdownAll to clean up all network resources.
        // However, that will cause Exception in other threads if they are still using httpclient.
        // Exception in thread "Thread-4" java.lang.IllegalStateException: Connection factory has been shutdown.
        //
        // MultiThreadedHttpConnectionManager.shutdownAll();

        log.info("Widnow is closed.");
    } catch (Exception exp) {
        log.error("Unexpected error while trying to quit application", exp);
    }

    Platform.exit();

    // All the above operations are done within try block, to ensure
    // System.exit(0) will always be called.
    //
    // Final clean up.
    System.exit(0);
}

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

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

    DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
    configParams.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
    configParams.setCustomRaftPolicyImplementationClass(DisableElectionsRaftPolicy.class.getName());

    final String followerActorId = actorFactory.generateActorId(FOLLOWER_ID);
    final String followerActorPath = actorFactory.createTestActorPath(followerActorId);
    RaftActorContext initialActorContext = new MockRaftActorContext();

    TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
            MockLeaderRaftActor.props(ImmutableMap.of(FOLLOWER_ID, followerActorPath), initialActorContext)
                    .withDispatcher(Dispatchers.DefaultDispatcherId()),
            actorFactory.generateActorId(LEADER_ID));

    final ActorRef leaderCollector = newLeaderCollectorActor(leaderActor.underlyingActor());

    final ActorRef followerCollector = actorFactory.createActor(MessageCollectorActor.props(),
            actorFactory.generateActorId("collector"));
    actorFactory//w  w w .j  ava 2  s.c o m
            .createTestActor(CollectingMockRaftActor
                    .props(FOLLOWER_ID, ImmutableMap.of(LEADER_ID, leaderActor.path().toString()), configParams,
                            NO_PERSISTENCE, followerCollector)
                    .withDispatcher(Dispatchers.DefaultDispatcherId()), followerActorId);

    leaderActor.tell(new RemoveServer(LEADER_ID), testKit.getRef());
    RemoveServerReply removeServerReply = testKit.expectMsgClass(testKit.duration("5 seconds"),
            RemoveServerReply.class);
    assertEquals("getStatus", ServerChangeStatus.OK, removeServerReply.getStatus());

    final ApplyState applyState = MessageCollectorActor.expectFirstMatching(followerCollector,
            ApplyState.class);
    assertEquals(0L, applyState.getReplicatedLogEntry().getIndex());
    verifyServerConfigurationPayloadEntry(
            leaderActor.underlyingActor().getRaftActorContext().getReplicatedLog(), votingServer(FOLLOWER_ID));

    MessageCollectorActor.expectFirstMatching(leaderCollector, ServerRemoved.class);

    LOG.info("testRemoveServerLeader ending");
}

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

@Test
public void testSwitchBehavior() {
    String persistenceId = factory.generateActorId("leader-");
    DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
    config.setCustomRaftPolicyImplementationClass(
            "org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy");
    config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
    config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
    config.setSnapshotBatchCount(5);//  ww  w  . j a v  a  2 s.co m

    DataPersistenceProvider dataPersistenceProvider = new NonPersistentDataProvider();

    Map<String, String> peerAddresses = ImmutableMap.<String, String>builder().build();

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

    MockRaftActor leaderActor = mockActorRef.underlyingActor();

    leaderActor.waitForRecoveryComplete();

    leaderActor.handleCommand(new SwitchBehavior(RaftState.Follower, 100));

    assertEquals(100, leaderActor.getRaftActorContext().getTermInformation().getCurrentTerm());
    assertEquals(RaftState.Follower, leaderActor.getCurrentBehavior().state());

    leaderActor.handleCommand(new SwitchBehavior(RaftState.Leader, 110));

    assertEquals(110, leaderActor.getRaftActorContext().getTermInformation().getCurrentTerm());
    assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());

    leaderActor.handleCommand(new SwitchBehavior(RaftState.Candidate, 125));

    assertEquals(110, leaderActor.getRaftActorContext().getTermInformation().getCurrentTerm());
    assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());

    leaderActor.handleCommand(new SwitchBehavior(RaftState.IsolatedLeader, 125));

    assertEquals(110, leaderActor.getRaftActorContext().getTermInformation().getCurrentTerm());
    assertEquals(RaftState.Leader, leaderActor.getCurrentBehavior().state());
}

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

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

    DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
    configParams.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
    configParams.setCustomRaftPolicyImplementationClass(DisableElectionsRaftPolicy.class.getName());

    final String follower1ActorId = actorFactory.generateActorId(FOLLOWER_ID);
    final String follower1ActorPath = actorFactory.createTestActorPath(follower1ActorId);
    final String follower2ActorId = actorFactory.generateActorId(FOLLOWER_ID2);
    final String follower2ActorPath = actorFactory.createTestActorPath(follower2ActorId);

    TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory
            .createTestActor(//www.j av  a2  s .com
                    MockLeaderRaftActor
                            .props(ImmutableMap.of(FOLLOWER_ID, follower1ActorPath, FOLLOWER_ID2,
                                    follower2ActorPath), new MockRaftActorContext())
                            .withDispatcher(Dispatchers.DefaultDispatcherId()),
                    actorFactory.generateActorId(LEADER_ID));
    ActorRef leaderCollector = newLeaderCollectorActor(leaderActor.underlyingActor());

    ActorRef follower1Collector = actorFactory.createActor(MessageCollectorActor.props(),
            actorFactory.generateActorId("collector"));
    final TestActorRef<CollectingMockRaftActor> follower1RaftActor = actorFactory
            .createTestActor(CollectingMockRaftActor
                    .props(FOLLOWER_ID,
                            ImmutableMap.of(LEADER_ID, leaderActor.path().toString(), FOLLOWER_ID2,
                                    follower2ActorPath),
                            configParams, NO_PERSISTENCE, follower1Collector)
                    .withDispatcher(Dispatchers.DefaultDispatcherId()), follower1ActorId);

    ActorRef follower2Collector = actorFactory.createActor(MessageCollectorActor.props(),
            actorFactory.generateActorId("collector"));
    final TestActorRef<CollectingMockRaftActor> follower2RaftActor = actorFactory
            .createTestActor(CollectingMockRaftActor
                    .props(FOLLOWER_ID2,
                            ImmutableMap.of(LEADER_ID, leaderActor.path().toString(), FOLLOWER_ID,
                                    follower1ActorPath),
                            configParams, NO_PERSISTENCE, follower2Collector)
                    .withDispatcher(Dispatchers.DefaultDispatcherId()), follower2ActorId);

    // Send first ChangeServersVotingStatus message

    leaderActor.tell(new ChangeServersVotingStatus(ImmutableMap.of(FOLLOWER_ID, false, FOLLOWER_ID2, false)),
            testKit.getRef());
    ServerChangeReply reply = testKit.expectMsgClass(testKit.duration("5 seconds"), ServerChangeReply.class);
    assertEquals("getStatus", ServerChangeStatus.OK, reply.getStatus());

    final ApplyState applyState = MessageCollectorActor.expectFirstMatching(leaderCollector, ApplyState.class);
    assertEquals(0L, applyState.getReplicatedLogEntry().getIndex());
    verifyServerConfigurationPayloadEntry(
            leaderActor.underlyingActor().getRaftActorContext().getReplicatedLog(), votingServer(LEADER_ID),
            nonVotingServer(FOLLOWER_ID), nonVotingServer(FOLLOWER_ID2));

    MessageCollectorActor.expectFirstMatching(follower1Collector, ApplyState.class);
    verifyServerConfigurationPayloadEntry(
            follower1RaftActor.underlyingActor().getRaftActorContext().getReplicatedLog(),
            votingServer(LEADER_ID), nonVotingServer(FOLLOWER_ID), nonVotingServer(FOLLOWER_ID2));

    MessageCollectorActor.expectFirstMatching(follower2Collector, ApplyState.class);
    verifyServerConfigurationPayloadEntry(
            follower2RaftActor.underlyingActor().getRaftActorContext().getReplicatedLog(),
            votingServer(LEADER_ID), nonVotingServer(FOLLOWER_ID), nonVotingServer(FOLLOWER_ID2));

    MessageCollectorActor.clearMessages(leaderCollector);
    MessageCollectorActor.clearMessages(follower1Collector);
    MessageCollectorActor.clearMessages(follower2Collector);

    // Send second ChangeServersVotingStatus message

    leaderActor.tell(new ChangeServersVotingStatus(ImmutableMap.of(FOLLOWER_ID, true)), testKit.getRef());
    reply = testKit.expectMsgClass(testKit.duration("5 seconds"), ServerChangeReply.class);
    assertEquals("getStatus", ServerChangeStatus.OK, reply.getStatus());

    MessageCollectorActor.expectFirstMatching(leaderCollector, ApplyState.class);
    verifyServerConfigurationPayloadEntry(
            leaderActor.underlyingActor().getRaftActorContext().getReplicatedLog(), votingServer(LEADER_ID),
            votingServer(FOLLOWER_ID), nonVotingServer(FOLLOWER_ID2));

    MessageCollectorActor.expectFirstMatching(follower1Collector, ApplyState.class);
    verifyServerConfigurationPayloadEntry(
            follower1RaftActor.underlyingActor().getRaftActorContext().getReplicatedLog(),
            votingServer(LEADER_ID), votingServer(FOLLOWER_ID), nonVotingServer(FOLLOWER_ID2));

    MessageCollectorActor.expectFirstMatching(follower2Collector, ApplyState.class);
    verifyServerConfigurationPayloadEntry(
            follower2RaftActor.underlyingActor().getRaftActorContext().getReplicatedLog(),
            votingServer(LEADER_ID), votingServer(FOLLOWER_ID), nonVotingServer(FOLLOWER_ID2));

    LOG.info("testChangeServersVotingStatus ending");
}