示例#1
0
  @Test
  public void testAdamUpdater() {
    INDArray m, v;
    double lr = 0.01;
    int iteration = 0;
    double beta1 = 0.8;
    double beta2 = 0.888;

    NeuralNetConfiguration conf =
        new NeuralNetConfiguration.Builder()
            .learningRate(lr)
            .iterations(iteration)
            .adamMeanDecay(beta1)
            .adamVarDecay(beta2)
            .layer(
                new DenseLayer.Builder()
                    .nIn(nIn)
                    .nOut(nOut)
                    .updater(org.deeplearning4j.nn.conf.Updater.ADAM)
                    .build())
            .build();

    int numParams = LayerFactories.getFactory(conf).initializer().numParams(conf, true);
    INDArray params = Nd4j.create(1, numParams);
    Layer layer = LayerFactories.getFactory(conf).create(conf, null, 0, params, true);
    Updater updater = UpdaterCreator.getUpdater(layer);
    int updaterStateSize = updater.stateSizeForLayer(layer);
    INDArray updaterState = Nd4j.create(1, updaterStateSize);
    updater.setStateViewArray(layer, updaterState, true);

    updater.update(layer, gradient, iteration, 1);

    double beta1t = FastMath.pow(beta1, iteration);
    double beta2t = FastMath.pow(beta2, iteration);
    double alphat = lr * FastMath.sqrt(1 - beta2t) / (1 - beta1t);
    if (Double.isNaN(alphat) || alphat == 0.0) alphat = epsilon;

    Gradient gradientDup = new DefaultGradient();
    gradientDup.setGradientFor(DefaultParamInitializer.WEIGHT_KEY, weightGradient);
    gradientDup.setGradientFor(DefaultParamInitializer.BIAS_KEY, biasGradient);

    for (Map.Entry<String, INDArray> entry : gradientDup.gradientForVariable().entrySet()) {
      val = entry.getValue();
      m = Nd4j.zeros(val.shape());
      v = Nd4j.zeros(val.shape());

      m.muli(beta1).addi(val.mul(1.0 - beta1));
      v.muli(beta2).addi(val.mul(val).mul(1.0 - beta2));
      gradExpected = m.mul(alphat).divi(Transforms.sqrt(v).addi(epsilon));
      if (!gradExpected.equals(gradient.getGradientFor(entry.getKey()))) {
        System.out.println(Arrays.toString(gradExpected.dup().data().asFloat()));
        System.out.println(
            Arrays.toString(gradient.getGradientFor(entry.getKey()).dup().data().asFloat()));
      }
      assertEquals(gradExpected, gradient.getGradientFor(entry.getKey()));
    }

    assertEquals(beta1, layer.conf().getLayer().getAdamMeanDecay(), 1e-4);
    assertEquals(beta2, layer.conf().getLayer().getAdamVarDecay(), 1e-4);
  }
  @Test
  public void getStudyConfiguration() throws Exception {
    StudyConfigurationManager studyConfigurationManager =
        new CatalogStudyConfigurationManager(catalogManager, sessionId);

    StudyConfiguration studyConfiguration =
        studyConfigurationManager.getStudyConfiguration(studyId, null).first();
    Study study = catalogManager.getStudy(studyId, sessionId).first();
    assertEquals(study.getAlias(), studyConfiguration.getStudyName());
    assertEquals(study.getId(), studyConfiguration.getStudyId());

    assertTrue(studyConfiguration.getIndexedFiles().isEmpty());
    assertTrue(studyConfiguration.getInvalidStats().isEmpty());

    for (Map.Entry<String, Integer> entry : studyConfiguration.getFileIds().entrySet()) {
      File file = catalogManager.getFile(entry.getValue(), sessionId).first();

      assertEquals(file.getName(), entry.getKey());
      assertEquals(
          new HashSet<>(file.getSampleIds()),
          studyConfiguration.getSamplesInFiles().get(file.getId()));
      assertTrue(studyConfiguration.getHeaders().containsKey(file.getId()));
      assertTrue(!studyConfiguration.getHeaders().get(file.getId()).isEmpty());
    }
  }
示例#3
0
  public void testIteration() {
    assertTrue(_nbhm.isEmpty());
    assertThat(_nbhm.put("k1", "v1"), nullValue());
    assertThat(_nbhm.put("k2", "v2"), nullValue());

    String str1 = "";
    for (Iterator<Map.Entry<String, String>> i = _nbhm.entrySet().iterator(); i.hasNext(); ) {
      Map.Entry<String, String> e = i.next();
      str1 += e.getKey();
    }
    assertThat("found all entries", str1, anyOf(is("k1k2"), is("k2k1")));

    String str2 = "";
    for (Iterator<String> i = _nbhm.keySet().iterator(); i.hasNext(); ) {
      String key = i.next();
      str2 += key;
    }
    assertThat("found all keys", str2, anyOf(is("k1k2"), is("k2k1")));

    String str3 = "";
    for (Iterator<String> i = _nbhm.values().iterator(); i.hasNext(); ) {
      String val = i.next();
      str3 += val;
    }
    assertThat("found all vals", str3, anyOf(is("v1v2"), is("v2v1")));

    assertThat(
        "toString works", _nbhm.toString(), anyOf(is("{k1=v1, k2=v2}"), is("{k2=v2, k1=v1}")));
  }
示例#4
0
  @Test
  public void testGetConnection() {

    String url = "jdbc:mysql://10.112.1.110:3306/test_mysql";
    String driver = "com.mysql.jdbc.Driver";
    String user = "******";
    String passwd = "111111";

    try {
      Class.forName(driver);
    } catch (Exception e) {
      System.out.println("Get Connection failed!!!");
    }

    try {
      Connection con = DriverManager.getConnection(url, user, passwd);

      System.out.println("Get Connection Success!!!");

      Properties properties = con.getClientInfo();
      Iterator<Map.Entry<Object, Object>> it = properties.entrySet().iterator();
      while (it.hasNext()) {
        Map.Entry<Object, Object> entry = it.next();
        System.out.println(entry.getKey() + "---------------" + entry.getValue());
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
示例#5
0
  @Test
  public void testSGDUpdater() {
    double lr = 0.05;

    NeuralNetConfiguration conf =
        new NeuralNetConfiguration.Builder()
            .learningRate(lr)
            .layer(
                new DenseLayer.Builder()
                    .nIn(nIn)
                    .nOut(nOut)
                    .updater(org.deeplearning4j.nn.conf.Updater.SGD)
                    .build())
            .build();

    int numParams = LayerFactories.getFactory(conf).initializer().numParams(conf, true);
    INDArray params = Nd4j.create(1, numParams);
    Layer layer = LayerFactories.getFactory(conf).create(conf, null, 0, params, true);
    Updater updater = UpdaterCreator.getUpdater(layer);

    updater.update(layer, gradient, -1, 1);

    Gradient gradientDup = new DefaultGradient();
    gradientDup.setGradientFor(DefaultParamInitializer.WEIGHT_KEY, weightGradient.dup());
    gradientDup.setGradientFor(DefaultParamInitializer.BIAS_KEY, biasGradient.dup());

    for (Map.Entry<String, INDArray> entry : gradientDup.gradientForVariable().entrySet()) {
      val = entry.getValue();
      gradExpected = val.mul(lr);
      assertEquals(gradExpected, gradient.getGradientFor(entry.getKey()));
    }
    assertEquals(lr, layer.conf().getLayer().getLearningRate(), 1e-4);
  }
示例#6
0
  @Test
  public void compact() {
    Map<Long, Long> recids = new HashMap<Long, Long>();
    for (Long l = 0L; l < 1000; l++) {
      recids.put(l, engine.put(l, Serializer.LONG_SERIALIZER));
    }

    engine.commit();
    engine.compact();

    for (Map.Entry<Long, Long> e : recids.entrySet()) {
      Long recid = e.getValue();
      Long value = e.getKey();
      assertEquals(value, engine.get(recid, Serializer.LONG_SERIALIZER));
    }
  }
示例#7
0
  @Test
  public void testRMSPropUpdater() {
    double lr = 0.01;
    double rmsDecay = 0.25;
    Map<String, INDArray> lastG = new HashMap<>();

    NeuralNetConfiguration conf =
        new NeuralNetConfiguration.Builder()
            .learningRate(lr)
            .rmsDecay(rmsDecay)
            .layer(
                new DenseLayer.Builder()
                    .nIn(nIn)
                    .nOut(nOut)
                    .updater(org.deeplearning4j.nn.conf.Updater.RMSPROP)
                    .build())
            .build();

    int numParams = LayerFactories.getFactory(conf).initializer().numParams(conf, true);
    INDArray params = Nd4j.create(1, numParams);
    Layer layer = LayerFactories.getFactory(conf).create(conf, null, 0, params, true);
    Updater updater = UpdaterCreator.getUpdater(layer);
    int updaterStateSize = updater.stateSizeForLayer(layer);
    INDArray updaterState = Nd4j.create(1, updaterStateSize);
    updater.setStateViewArray(layer, updaterState, true);

    updater.update(layer, gradient, -1, 1);

    Gradient gradientDup = new DefaultGradient();
    gradientDup.setGradientFor(DefaultParamInitializer.WEIGHT_KEY, weightGradient.dup());
    gradientDup.setGradientFor(DefaultParamInitializer.BIAS_KEY, biasGradient.dup());

    for (Map.Entry<String, INDArray> entry : gradientDup.gradientForVariable().entrySet()) {
      key = entry.getKey();
      val = entry.getValue();
      INDArray lastGTmp = lastG.get(key);

      if (lastGTmp == null) lastGTmp = Nd4j.zeros(val.shape());

      lastGTmp.muli(rmsDecay).addi(val.mul(val).muli(1 - rmsDecay));
      gradExpected = val.mul(lr).div(Transforms.sqrt(lastGTmp.add(Nd4j.EPS_THRESHOLD)));

      assertEquals(gradExpected, gradient.getGradientFor(entry.getKey()));
      lastG.put(key, lastGTmp);
    }
    assertEquals(rmsDecay, layer.conf().getLayer().getRmsDecay(), 1e-4);
  }
示例#8
0
  @Test
  public void getDistinctKeysAndCounts_SortByKeyDescending() {

    Connection connection = null;
    ResultSet resultSet = null;
    try {
      ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
      initWithTestData(connectionManager);

      connection = connectionManager.getConnection(null);
      resultSet = DBQueries.getDistinctKeysAndCounts(true, NAME, connection);

      Map<String, Integer> resultSetToMap = resultSetToMap(resultSet);
      assertEquals(3, resultSetToMap.size());

      Iterator<Map.Entry<String, Integer>> entriesIterator = resultSetToMap.entrySet().iterator();

      Map.Entry entry = entriesIterator.next();
      assertEquals("gps", entry.getKey());
      assertEquals(1, entry.getValue());

      entry = entriesIterator.next();
      assertEquals("airbags", entry.getKey());
      assertEquals(1, entry.getValue());

      entry = entriesIterator.next();
      assertEquals("abs", entry.getKey());
      assertEquals(2, entry.getValue());

    } finally {
      DBUtils.closeQuietly(resultSet);
      DBUtils.closeQuietly(connection);
    }
  }
示例#9
0
  @Test
  public void compact() {
    e = openEngine();
    Map<Long, Long> recids = new HashMap<Long, Long>();
    for (Long l = 0L; l < 1000; l++) {
      recids.put(l, e.put(l, Serializer.LONG));
    }

    e.commit();
    e.compact();

    for (Map.Entry<Long, Long> m : recids.entrySet()) {
      Long recid = m.getValue();
      Long value = m.getKey();
      assertEquals(value, e.get(recid, Serializer.LONG));
    }
    e.close();
  }
示例#10
0
  @Test
  public void testNestorovsUpdater() {
    double lr = 1e-2;
    double mu = 0.6;
    INDArray v, vPrev;

    NeuralNetConfiguration conf =
        new NeuralNetConfiguration.Builder()
            .learningRate(lr)
            .momentum(mu)
            .layer(
                new DenseLayer.Builder()
                    .nIn(nIn)
                    .nOut(nOut)
                    .updater(org.deeplearning4j.nn.conf.Updater.NESTEROVS)
                    .build())
            .build();

    int numParams = LayerFactories.getFactory(conf).initializer().numParams(conf, true);
    INDArray params = Nd4j.create(1, numParams);
    Layer layer = LayerFactories.getFactory(conf).create(conf, null, 0, params, true);
    Updater updater = UpdaterCreator.getUpdater(layer);
    int updaterStateSize = updater.stateSizeForLayer(layer);
    INDArray updaterState = Nd4j.create(1, updaterStateSize);
    updater.setStateViewArray(layer, updaterState, true);

    updater.update(layer, gradient, -1, 1);

    Gradient gradientDup = new DefaultGradient();
    gradientDup.setGradientFor(DefaultParamInitializer.WEIGHT_KEY, weightGradient.dup());
    gradientDup.setGradientFor(DefaultParamInitializer.BIAS_KEY, biasGradient.dup());

    for (Map.Entry<String, INDArray> entry : gradientDup.gradientForVariable().entrySet()) {
      val = entry.getValue();
      v = Nd4j.zeros(val.shape());
      vPrev = v;
      v = vPrev.mul(mu).subi(val.mul(lr));
      gradExpected = vPrev.muli(mu).addi(v.mul(-mu - 1));

      assertEquals(gradExpected, gradient.getGradientFor(entry.getKey()));
    }

    assertEquals(mu, layer.conf().getLayer().getMomentum(), 1e-4);
  }
 @Test
 public void testMultiMapEntrySet() {
   HazelcastClient hClient = getHazelcastClient();
   MultiMap<String, String> map = hClient.getMultiMap("testMultiMapEntrySet");
   map.put("Hello", "World");
   map.put("Hello", "Europe");
   map.put("Hello", "America");
   map.put("Hello", "Asia");
   map.put("Hello", "Africa");
   map.put("Hello", "Antarctica");
   map.put("Hello", "Australia");
   Set<Map.Entry<String, String>> entries = map.entrySet();
   assertEquals(7, entries.size());
   int itCount = 0;
   for (Map.Entry<String, String> entry : entries) {
     assertEquals("Hello", entry.getKey());
     itCount++;
   }
   assertEquals(7, itCount);
 }
 public void doFunctionalQueryTest(IMap imap) {
   Employee em = new Employee("joe", 33, false, 14.56);
   imap.put("1", new Employee("joe", 33, false, 14.56));
   imap.put("2", new Employee("ali", 23, true, 15.00));
   for (int i = 3; i < 103; i++) {
     imap.put(
         String.valueOf(i), new Employee("name" + i, i % 60, ((i % 2) == 1), Double.valueOf(i)));
   }
   Set<Map.Entry> entries = imap.entrySet();
   assertEquals(102, entries.size());
   int itCount = 0;
   for (Map.Entry entry : entries) {
     Employee c = (Employee) entry.getValue();
     itCount++;
   }
   assertEquals(102, itCount);
   EntryObject e = new PredicateBuilder().getEntryObject();
   Predicate predicate = e.is("active").and(e.get("age").equal(23));
   entries = imap.entrySet(predicate);
   assertEquals(3, entries.size());
   for (Map.Entry entry : entries) {
     Employee c = (Employee) entry.getValue();
     assertEquals(c.getAge(), 23);
     assertTrue(c.isActive());
   }
   imap.remove("2");
   entries = imap.entrySet(predicate);
   assertEquals(2, entries.size());
   for (Map.Entry entry : entries) {
     Employee c = (Employee) entry.getValue();
     assertEquals(c.getAge(), 23);
     assertTrue(c.isActive());
   }
 }
示例#13
0
  @Test
  public void testAdaGradUpdater() {
    double lr = 1e-2;

    NeuralNetConfiguration conf =
        new NeuralNetConfiguration.Builder()
            .learningRate(lr)
            .layer(
                new DenseLayer.Builder()
                    .nIn(nIn)
                    .nOut(nOut)
                    .updater(org.deeplearning4j.nn.conf.Updater.ADAGRAD)
                    .build())
            .build();

    int numParams = LayerFactories.getFactory(conf).initializer().numParams(conf, true);
    INDArray params = Nd4j.create(1, numParams);
    Layer layer = LayerFactories.getFactory(conf).create(conf, null, 0, params, true);
    Updater updater = UpdaterCreator.getUpdater(layer);
    int updaterStateSize = updater.stateSizeForLayer(layer);
    INDArray updaterState = Nd4j.create(1, updaterStateSize);
    updater.setStateViewArray(layer, updaterState, true);

    updater.update(layer, gradient, -1, 1);

    Gradient gradientDup = new DefaultGradient();
    gradientDup.setGradientFor(DefaultParamInitializer.WEIGHT_KEY, weightGradient);
    gradientDup.setGradientFor(DefaultParamInitializer.BIAS_KEY, biasGradient);

    for (Map.Entry<String, INDArray> entry : gradientDup.gradientForVariable().entrySet()) {
      val = entry.getValue();
      gradExpected = Transforms.sqrt(val.mul(val).add(epsilon)).rdiv(lr).mul(val);
      assertEquals(gradExpected, gradient.getGradientFor(entry.getKey()));
    }
    assertEquals(lr, layer.conf().getLayer().getLearningRate(), 1e-4);
  }
示例#14
0
  @Test
  public void findSmaller() {

    for (int i = 0; i < 10000; i += 3) {
      m.put(i, "aa" + i);
    }

    for (int i = 0; i < 10000; i += 1) {
      Integer s = i - i % 3;
      Map.Entry e = m.findSmaller(i, true);
      assertEquals(s, e != null ? e.getKey() : null);
    }

    assertEquals(9999, m.findSmaller(100000, true).getKey());

    assertNull(m.findSmaller(0, false));
    for (int i = 1; i < 10000; i += 1) {
      Integer s = i - i % 3;
      if (s == i) s -= 3;
      Map.Entry e = m.findSmaller(i, false);
      assertEquals(s, e != null ? e.getKey() : null);
    }
    assertEquals(9999, m.findSmaller(100000, false).getKey());
  }
示例#15
0
  @Test
  public void testAdaDeltaUpdate() {
    INDArray dxSquared;
    Map<String, INDArray> msg = new HashMap<>();
    Map<String, INDArray> msdx = new HashMap<>();

    double rho = 0.85;

    NeuralNetConfiguration conf =
        new NeuralNetConfiguration.Builder()
            .rho(rho)
            .layer(
                new DenseLayer.Builder()
                    .nIn(nIn)
                    .nOut(nOut)
                    .updater(org.deeplearning4j.nn.conf.Updater.ADADELTA)
                    .build())
            .build();

    int numParams = LayerFactories.getFactory(conf).initializer().numParams(conf, true);
    INDArray params = Nd4j.create(1, numParams);
    Layer layer = LayerFactories.getFactory(conf).create(conf, null, 0, params, true);
    Updater updater = UpdaterCreator.getUpdater(layer);
    int updaterStateSize = updater.stateSizeForLayer(layer);
    INDArray updaterState = Nd4j.create(1, updaterStateSize);
    updater.setStateViewArray(layer, updaterState, true);

    Gradient gradientDup = new DefaultGradient();
    gradientDup.setGradientFor(DefaultParamInitializer.WEIGHT_KEY, weightGradient.dup());
    gradientDup.setGradientFor(DefaultParamInitializer.BIAS_KEY, biasGradient.dup());

    for (int i = 0; i < 2; i++) {
      updater.update(layer, gradient, i, 1);

      // calculations for one iteration / update

      for (Map.Entry<String, INDArray> entry : gradientDup.gradientForVariable().entrySet()) {
        key = entry.getKey();
        val = entry.getValue();
        INDArray msgTmp = msg.get(key);
        INDArray msdxTmp = msdx.get(key);

        if (msgTmp == null) {
          msgTmp = Nd4j.zeros(val.shape());
          msdxTmp = Nd4j.zeros(val.shape());
        }

        msgTmp.muli(rho);
        msgTmp.addi(1 - rho).muli(val.mul(val));

        gradExpected =
            Transforms.sqrt(msdxTmp.add(Nd4j.EPS_THRESHOLD))
                .divi(Transforms.sqrt(msgTmp.add(Nd4j.EPS_THRESHOLD)))
                .muli(val);
        gradientDup.setGradientFor(key, gradExpected);
        assertEquals(gradExpected, gradient.getGradientFor(entry.getKey()));

        msdxTmp.muli(rho);
        dxSquared = gradExpected.mul(gradExpected);
        msdxTmp.addi(dxSquared.muli(1 - rho));

        msg.put(key, msgTmp);
        msdx.put(key, msdxTmp);
      }
      assertEquals(rho, layer.conf().getLayer().getRho(), 1e-4);
    }
  }
  /** Test pending ranges and write endpoints when multiple nodes are on the move simultaneously */
  @Test
  public void testSimultaneousMove() throws UnknownHostException {
    StorageService ss = StorageService.instance;
    final int RING_SIZE = 10;
    TokenMetadata tmd = ss.getTokenMetadata();
    tmd.clearUnsafe();
    IPartitioner partitioner = RandomPartitioner.instance;
    VersionedValue.VersionedValueFactory valueFactory =
        new VersionedValue.VersionedValueFactory(partitioner);

    ArrayList<Token> endpointTokens = new ArrayList<Token>();
    ArrayList<Token> keyTokens = new ArrayList<Token>();
    List<InetAddress> hosts = new ArrayList<InetAddress>();
    List<UUID> hostIds = new ArrayList<UUID>();

    // create a ring or 10 nodes
    Util.createInitialRing(ss, partitioner, endpointTokens, keyTokens, hosts, hostIds, RING_SIZE);

    // nodes 6, 8 and 9 leave
    final int[] LEAVING = new int[] {6, 8, 9};
    for (int leaving : LEAVING)
      ss.onChange(
          hosts.get(leaving),
          ApplicationState.STATUS,
          valueFactory.leaving(Collections.singleton(endpointTokens.get(leaving))));

    // boot two new nodes with keyTokens.get(5) and keyTokens.get(7)
    InetAddress boot1 = InetAddress.getByName("127.0.1.1");
    Gossiper.instance.initializeNodeUnsafe(boot1, UUID.randomUUID(), 1);
    Gossiper.instance.injectApplicationState(
        boot1,
        ApplicationState.TOKENS,
        valueFactory.tokens(Collections.singleton(keyTokens.get(5))));
    ss.onChange(
        boot1,
        ApplicationState.STATUS,
        valueFactory.bootstrapping(Collections.<Token>singleton(keyTokens.get(5))));
    InetAddress boot2 = InetAddress.getByName("127.0.1.2");
    Gossiper.instance.initializeNodeUnsafe(boot2, UUID.randomUUID(), 1);
    Gossiper.instance.injectApplicationState(
        boot2,
        ApplicationState.TOKENS,
        valueFactory.tokens(Collections.singleton(keyTokens.get(7))));
    ss.onChange(
        boot2,
        ApplicationState.STATUS,
        valueFactory.bootstrapping(Collections.<Token>singleton(keyTokens.get(7))));

    Collection<InetAddress> endpoints = null;

    /* don't require test update every time a new keyspace is added to test/conf/cassandra.yaml */
    Map<String, AbstractReplicationStrategy> keyspaceStrategyMap =
        new HashMap<String, AbstractReplicationStrategy>();
    for (int i = 1; i <= 4; i++) {
      keyspaceStrategyMap.put(
          "LeaveAndBootstrapTestKeyspace" + i,
          getStrategy("LeaveAndBootstrapTestKeyspace" + i, tmd));
    }

    // pre-calculate the results.
    Map<String, Multimap<Token, InetAddress>> expectedEndpoints =
        new HashMap<String, Multimap<Token, InetAddress>>();
    expectedEndpoints.put(KEYSPACE1, HashMultimap.<Token, InetAddress>create());
    expectedEndpoints.get(KEYSPACE1).putAll(new BigIntegerToken("5"), makeAddrs("127.0.0.2"));
    expectedEndpoints.get(KEYSPACE1).putAll(new BigIntegerToken("15"), makeAddrs("127.0.0.3"));
    expectedEndpoints.get(KEYSPACE1).putAll(new BigIntegerToken("25"), makeAddrs("127.0.0.4"));
    expectedEndpoints.get(KEYSPACE1).putAll(new BigIntegerToken("35"), makeAddrs("127.0.0.5"));
    expectedEndpoints.get(KEYSPACE1).putAll(new BigIntegerToken("45"), makeAddrs("127.0.0.6"));
    expectedEndpoints
        .get(KEYSPACE1)
        .putAll(new BigIntegerToken("55"), makeAddrs("127.0.0.7", "127.0.0.8", "127.0.1.1"));
    expectedEndpoints.get(KEYSPACE1).putAll(new BigIntegerToken("65"), makeAddrs("127.0.0.8"));
    expectedEndpoints
        .get(KEYSPACE1)
        .putAll(new BigIntegerToken("75"), makeAddrs("127.0.0.9", "127.0.1.2", "127.0.0.1"));
    expectedEndpoints
        .get(KEYSPACE1)
        .putAll(new BigIntegerToken("85"), makeAddrs("127.0.0.10", "127.0.0.1"));
    expectedEndpoints.get(KEYSPACE1).putAll(new BigIntegerToken("95"), makeAddrs("127.0.0.1"));
    expectedEndpoints.put(KEYSPACE2, HashMultimap.<Token, InetAddress>create());
    expectedEndpoints.get(KEYSPACE2).putAll(new BigIntegerToken("5"), makeAddrs("127.0.0.2"));
    expectedEndpoints.get(KEYSPACE2).putAll(new BigIntegerToken("15"), makeAddrs("127.0.0.3"));
    expectedEndpoints.get(KEYSPACE2).putAll(new BigIntegerToken("25"), makeAddrs("127.0.0.4"));
    expectedEndpoints.get(KEYSPACE2).putAll(new BigIntegerToken("35"), makeAddrs("127.0.0.5"));
    expectedEndpoints.get(KEYSPACE2).putAll(new BigIntegerToken("45"), makeAddrs("127.0.0.6"));
    expectedEndpoints
        .get(KEYSPACE2)
        .putAll(new BigIntegerToken("55"), makeAddrs("127.0.0.7", "127.0.0.8", "127.0.1.1"));
    expectedEndpoints.get(KEYSPACE2).putAll(new BigIntegerToken("65"), makeAddrs("127.0.0.8"));
    expectedEndpoints
        .get(KEYSPACE2)
        .putAll(new BigIntegerToken("75"), makeAddrs("127.0.0.9", "127.0.1.2", "127.0.0.1"));
    expectedEndpoints
        .get(KEYSPACE2)
        .putAll(new BigIntegerToken("85"), makeAddrs("127.0.0.10", "127.0.0.1"));
    expectedEndpoints.get(KEYSPACE2).putAll(new BigIntegerToken("95"), makeAddrs("127.0.0.1"));
    expectedEndpoints.put(KEYSPACE3, HashMultimap.<Token, InetAddress>create());
    expectedEndpoints
        .get(KEYSPACE3)
        .putAll(
            new BigIntegerToken("5"),
            makeAddrs("127.0.0.2", "127.0.0.3", "127.0.0.4", "127.0.0.5", "127.0.0.6"));
    expectedEndpoints
        .get(KEYSPACE3)
        .putAll(
            new BigIntegerToken("15"),
            makeAddrs(
                "127.0.0.3",
                "127.0.0.4",
                "127.0.0.5",
                "127.0.0.6",
                "127.0.0.7",
                "127.0.1.1",
                "127.0.0.8"));
    expectedEndpoints
        .get(KEYSPACE3)
        .putAll(
            new BigIntegerToken("25"),
            makeAddrs(
                "127.0.0.4",
                "127.0.0.5",
                "127.0.0.6",
                "127.0.0.7",
                "127.0.0.8",
                "127.0.1.2",
                "127.0.0.1",
                "127.0.1.1"));
    expectedEndpoints
        .get(KEYSPACE3)
        .putAll(
            new BigIntegerToken("35"),
            makeAddrs(
                "127.0.0.5",
                "127.0.0.6",
                "127.0.0.7",
                "127.0.0.8",
                "127.0.0.9",
                "127.0.1.2",
                "127.0.0.1",
                "127.0.0.2",
                "127.0.1.1"));
    expectedEndpoints
        .get(KEYSPACE3)
        .putAll(
            new BigIntegerToken("45"),
            makeAddrs(
                "127.0.0.6",
                "127.0.0.7",
                "127.0.0.8",
                "127.0.0.9",
                "127.0.0.10",
                "127.0.1.2",
                "127.0.0.1",
                "127.0.0.2",
                "127.0.1.1",
                "127.0.0.3"));
    expectedEndpoints
        .get(KEYSPACE3)
        .putAll(
            new BigIntegerToken("55"),
            makeAddrs(
                "127.0.0.7",
                "127.0.0.8",
                "127.0.0.9",
                "127.0.0.10",
                "127.0.0.1",
                "127.0.0.2",
                "127.0.0.3",
                "127.0.0.4",
                "127.0.1.1",
                "127.0.1.2"));
    expectedEndpoints
        .get(KEYSPACE3)
        .putAll(
            new BigIntegerToken("65"),
            makeAddrs(
                "127.0.0.8",
                "127.0.0.9",
                "127.0.0.10",
                "127.0.0.1",
                "127.0.0.2",
                "127.0.1.2",
                "127.0.0.3",
                "127.0.0.4"));
    expectedEndpoints
        .get(KEYSPACE3)
        .putAll(
            new BigIntegerToken("75"),
            makeAddrs(
                "127.0.0.9",
                "127.0.0.10",
                "127.0.0.1",
                "127.0.0.2",
                "127.0.0.3",
                "127.0.1.2",
                "127.0.0.4",
                "127.0.0.5"));
    expectedEndpoints
        .get(KEYSPACE3)
        .putAll(
            new BigIntegerToken("85"),
            makeAddrs(
                "127.0.0.10", "127.0.0.1", "127.0.0.2", "127.0.0.3", "127.0.0.4", "127.0.0.5"));
    expectedEndpoints
        .get(KEYSPACE3)
        .putAll(
            new BigIntegerToken("95"),
            makeAddrs("127.0.0.1", "127.0.0.2", "127.0.0.3", "127.0.0.4", "127.0.0.5"));
    expectedEndpoints.put(KEYSPACE4, HashMultimap.<Token, InetAddress>create());
    expectedEndpoints
        .get(KEYSPACE4)
        .putAll(new BigIntegerToken("5"), makeAddrs("127.0.0.2", "127.0.0.3", "127.0.0.4"));
    expectedEndpoints
        .get(KEYSPACE4)
        .putAll(new BigIntegerToken("15"), makeAddrs("127.0.0.3", "127.0.0.4", "127.0.0.5"));
    expectedEndpoints
        .get(KEYSPACE4)
        .putAll(new BigIntegerToken("25"), makeAddrs("127.0.0.4", "127.0.0.5", "127.0.0.6"));
    expectedEndpoints
        .get(KEYSPACE4)
        .putAll(
            new BigIntegerToken("35"),
            makeAddrs("127.0.0.5", "127.0.0.6", "127.0.0.7", "127.0.1.1", "127.0.0.8"));
    expectedEndpoints
        .get(KEYSPACE4)
        .putAll(
            new BigIntegerToken("45"),
            makeAddrs(
                "127.0.0.6", "127.0.0.7", "127.0.0.8", "127.0.1.2", "127.0.0.1", "127.0.1.1"));
    expectedEndpoints
        .get(KEYSPACE4)
        .putAll(
            new BigIntegerToken("55"),
            makeAddrs(
                "127.0.0.7",
                "127.0.0.8",
                "127.0.0.9",
                "127.0.0.1",
                "127.0.0.2",
                "127.0.1.1",
                "127.0.1.2"));
    expectedEndpoints
        .get(KEYSPACE4)
        .putAll(
            new BigIntegerToken("65"),
            makeAddrs(
                "127.0.0.8", "127.0.0.9", "127.0.0.10", "127.0.1.2", "127.0.0.1", "127.0.0.2"));
    expectedEndpoints
        .get(KEYSPACE4)
        .putAll(
            new BigIntegerToken("75"),
            makeAddrs(
                "127.0.0.9", "127.0.0.10", "127.0.0.1", "127.0.1.2", "127.0.0.2", "127.0.0.3"));
    expectedEndpoints
        .get(KEYSPACE4)
        .putAll(
            new BigIntegerToken("85"),
            makeAddrs("127.0.0.10", "127.0.0.1", "127.0.0.2", "127.0.0.3"));
    expectedEndpoints
        .get(KEYSPACE4)
        .putAll(new BigIntegerToken("95"), makeAddrs("127.0.0.1", "127.0.0.2", "127.0.0.3"));

    PendingRangeCalculatorService.instance.blockUntilFinished();

    for (Map.Entry<String, AbstractReplicationStrategy> keyspaceStrategy :
        keyspaceStrategyMap.entrySet()) {
      String keyspaceName = keyspaceStrategy.getKey();
      AbstractReplicationStrategy strategy = keyspaceStrategy.getValue();

      for (int i = 0; i < keyTokens.size(); i++) {
        endpoints =
            tmd.getWriteEndpoints(
                keyTokens.get(i), keyspaceName, strategy.getNaturalEndpoints(keyTokens.get(i)));
        assertEquals(
            expectedEndpoints.get(keyspaceName).get(keyTokens.get(i)).size(), endpoints.size());
        assertTrue(
            expectedEndpoints.get(keyspaceName).get(keyTokens.get(i)).containsAll(endpoints));
      }

      // just to be sure that things still work according to the old tests, run them:
      if (strategy.getReplicationFactor() != 3) continue;
      // tokens 5, 15 and 25 should go three nodes
      for (int i = 0; i < 3; ++i) {
        endpoints =
            tmd.getWriteEndpoints(
                keyTokens.get(i), keyspaceName, strategy.getNaturalEndpoints(keyTokens.get(i)));
        assertEquals(3, endpoints.size());
        assertTrue(endpoints.contains(hosts.get(i + 1)));
        assertTrue(endpoints.contains(hosts.get(i + 2)));
        assertTrue(endpoints.contains(hosts.get(i + 3)));
      }

      // token 35 should go to nodes 4, 5, 6, 7 and boot1
      endpoints =
          tmd.getWriteEndpoints(
              keyTokens.get(3), keyspaceName, strategy.getNaturalEndpoints(keyTokens.get(3)));
      assertEquals(5, endpoints.size());
      assertTrue(endpoints.contains(hosts.get(4)));
      assertTrue(endpoints.contains(hosts.get(5)));
      assertTrue(endpoints.contains(hosts.get(6)));
      assertTrue(endpoints.contains(hosts.get(7)));
      assertTrue(endpoints.contains(boot1));

      // token 45 should go to nodes 5, 6, 7, 0, boot1 and boot2
      endpoints =
          tmd.getWriteEndpoints(
              keyTokens.get(4), keyspaceName, strategy.getNaturalEndpoints(keyTokens.get(4)));
      assertEquals(6, endpoints.size());
      assertTrue(endpoints.contains(hosts.get(5)));
      assertTrue(endpoints.contains(hosts.get(6)));
      assertTrue(endpoints.contains(hosts.get(7)));
      assertTrue(endpoints.contains(hosts.get(0)));
      assertTrue(endpoints.contains(boot1));
      assertTrue(endpoints.contains(boot2));

      // token 55 should go to nodes 6, 7, 8, 0, 1, boot1 and boot2
      endpoints =
          tmd.getWriteEndpoints(
              keyTokens.get(5), keyspaceName, strategy.getNaturalEndpoints(keyTokens.get(5)));
      assertEquals(7, endpoints.size());
      assertTrue(endpoints.contains(hosts.get(6)));
      assertTrue(endpoints.contains(hosts.get(7)));
      assertTrue(endpoints.contains(hosts.get(8)));
      assertTrue(endpoints.contains(hosts.get(0)));
      assertTrue(endpoints.contains(hosts.get(1)));
      assertTrue(endpoints.contains(boot1));
      assertTrue(endpoints.contains(boot2));

      // token 65 should go to nodes 7, 8, 9, 0, 1 and boot2
      endpoints =
          tmd.getWriteEndpoints(
              keyTokens.get(6), keyspaceName, strategy.getNaturalEndpoints(keyTokens.get(6)));
      assertEquals(6, endpoints.size());
      assertTrue(endpoints.contains(hosts.get(7)));
      assertTrue(endpoints.contains(hosts.get(8)));
      assertTrue(endpoints.contains(hosts.get(9)));
      assertTrue(endpoints.contains(hosts.get(0)));
      assertTrue(endpoints.contains(hosts.get(1)));
      assertTrue(endpoints.contains(boot2));

      // token 75 should to go nodes 8, 9, 0, 1, 2 and boot2
      endpoints =
          tmd.getWriteEndpoints(
              keyTokens.get(7), keyspaceName, strategy.getNaturalEndpoints(keyTokens.get(7)));
      assertEquals(6, endpoints.size());
      assertTrue(endpoints.contains(hosts.get(8)));
      assertTrue(endpoints.contains(hosts.get(9)));
      assertTrue(endpoints.contains(hosts.get(0)));
      assertTrue(endpoints.contains(hosts.get(1)));
      assertTrue(endpoints.contains(hosts.get(2)));
      assertTrue(endpoints.contains(boot2));

      // token 85 should go to nodes 9, 0, 1 and 2
      endpoints =
          tmd.getWriteEndpoints(
              keyTokens.get(8), keyspaceName, strategy.getNaturalEndpoints(keyTokens.get(8)));
      assertEquals(4, endpoints.size());
      assertTrue(endpoints.contains(hosts.get(9)));
      assertTrue(endpoints.contains(hosts.get(0)));
      assertTrue(endpoints.contains(hosts.get(1)));
      assertTrue(endpoints.contains(hosts.get(2)));

      // token 95 should go to nodes 0, 1 and 2
      endpoints =
          tmd.getWriteEndpoints(
              keyTokens.get(9), keyspaceName, strategy.getNaturalEndpoints(keyTokens.get(9)));
      assertEquals(3, endpoints.size());
      assertTrue(endpoints.contains(hosts.get(0)));
      assertTrue(endpoints.contains(hosts.get(1)));
      assertTrue(endpoints.contains(hosts.get(2)));
    }

    // Now finish node 6 and node 9 leaving, as well as boot1 (after this node 8 is still
    // leaving and boot2 in progress
    ss.onChange(
        hosts.get(LEAVING[0]),
        ApplicationState.STATUS,
        valueFactory.left(
            Collections.singleton(endpointTokens.get(LEAVING[0])), Gossiper.computeExpireTime()));
    ss.onChange(
        hosts.get(LEAVING[2]),
        ApplicationState.STATUS,
        valueFactory.left(
            Collections.singleton(endpointTokens.get(LEAVING[2])), Gossiper.computeExpireTime()));
    ss.onChange(
        boot1,
        ApplicationState.STATUS,
        valueFactory.normal(Collections.singleton(keyTokens.get(5))));

    // adjust precalcuated results.  this changes what the epected endpoints are.
    expectedEndpoints
        .get(KEYSPACE1)
        .get(new BigIntegerToken("55"))
        .removeAll(makeAddrs("127.0.0.7", "127.0.0.8"));
    expectedEndpoints
        .get(KEYSPACE1)
        .get(new BigIntegerToken("85"))
        .removeAll(makeAddrs("127.0.0.10"));
    expectedEndpoints
        .get(KEYSPACE2)
        .get(new BigIntegerToken("55"))
        .removeAll(makeAddrs("127.0.0.7", "127.0.0.8"));
    expectedEndpoints
        .get(KEYSPACE2)
        .get(new BigIntegerToken("85"))
        .removeAll(makeAddrs("127.0.0.10"));
    expectedEndpoints
        .get(KEYSPACE3)
        .get(new BigIntegerToken("15"))
        .removeAll(makeAddrs("127.0.0.7", "127.0.0.8"));
    expectedEndpoints
        .get(KEYSPACE3)
        .get(new BigIntegerToken("25"))
        .removeAll(makeAddrs("127.0.0.7", "127.0.1.2", "127.0.0.1"));
    expectedEndpoints
        .get(KEYSPACE3)
        .get(new BigIntegerToken("35"))
        .removeAll(makeAddrs("127.0.0.7", "127.0.0.2"));
    expectedEndpoints
        .get(KEYSPACE3)
        .get(new BigIntegerToken("45"))
        .removeAll(makeAddrs("127.0.0.7", "127.0.0.10", "127.0.0.3"));
    expectedEndpoints
        .get(KEYSPACE3)
        .get(new BigIntegerToken("55"))
        .removeAll(makeAddrs("127.0.0.7", "127.0.0.10", "127.0.0.4"));
    expectedEndpoints
        .get(KEYSPACE3)
        .get(new BigIntegerToken("65"))
        .removeAll(makeAddrs("127.0.0.10"));
    expectedEndpoints
        .get(KEYSPACE3)
        .get(new BigIntegerToken("75"))
        .removeAll(makeAddrs("127.0.0.10"));
    expectedEndpoints
        .get(KEYSPACE3)
        .get(new BigIntegerToken("85"))
        .removeAll(makeAddrs("127.0.0.10"));
    expectedEndpoints
        .get(KEYSPACE4)
        .get(new BigIntegerToken("35"))
        .removeAll(makeAddrs("127.0.0.7", "127.0.0.8"));
    expectedEndpoints
        .get(KEYSPACE4)
        .get(new BigIntegerToken("45"))
        .removeAll(makeAddrs("127.0.0.7", "127.0.1.2", "127.0.0.1"));
    expectedEndpoints
        .get(KEYSPACE4)
        .get(new BigIntegerToken("55"))
        .removeAll(makeAddrs("127.0.0.2", "127.0.0.7"));
    expectedEndpoints
        .get(KEYSPACE4)
        .get(new BigIntegerToken("65"))
        .removeAll(makeAddrs("127.0.0.10"));
    expectedEndpoints
        .get(KEYSPACE4)
        .get(new BigIntegerToken("75"))
        .removeAll(makeAddrs("127.0.0.10"));
    expectedEndpoints
        .get(KEYSPACE4)
        .get(new BigIntegerToken("85"))
        .removeAll(makeAddrs("127.0.0.10"));

    PendingRangeCalculatorService.instance.blockUntilFinished();

    for (Map.Entry<String, AbstractReplicationStrategy> keyspaceStrategy :
        keyspaceStrategyMap.entrySet()) {
      String keyspaceName = keyspaceStrategy.getKey();
      AbstractReplicationStrategy strategy = keyspaceStrategy.getValue();

      for (int i = 0; i < keyTokens.size(); i++) {
        endpoints =
            tmd.getWriteEndpoints(
                keyTokens.get(i), keyspaceName, strategy.getNaturalEndpoints(keyTokens.get(i)));
        assertEquals(
            expectedEndpoints.get(keyspaceName).get(keyTokens.get(i)).size(), endpoints.size());
        assertTrue(
            expectedEndpoints.get(keyspaceName).get(keyTokens.get(i)).containsAll(endpoints));
      }

      if (strategy.getReplicationFactor() != 3) continue;
      // leave this stuff in to guarantee the old tests work the way they were supposed to.
      // tokens 5, 15 and 25 should go three nodes
      for (int i = 0; i < 3; ++i) {
        endpoints =
            tmd.getWriteEndpoints(
                keyTokens.get(i), keyspaceName, strategy.getNaturalEndpoints(keyTokens.get(i)));
        assertEquals(3, endpoints.size());
        assertTrue(endpoints.contains(hosts.get(i + 1)));
        assertTrue(endpoints.contains(hosts.get(i + 2)));
        assertTrue(endpoints.contains(hosts.get(i + 3)));
      }

      // token 35 goes to nodes 4, 5 and boot1
      endpoints =
          tmd.getWriteEndpoints(
              keyTokens.get(3), keyspaceName, strategy.getNaturalEndpoints(keyTokens.get(3)));
      assertEquals(3, endpoints.size());
      assertTrue(endpoints.contains(hosts.get(4)));
      assertTrue(endpoints.contains(hosts.get(5)));
      assertTrue(endpoints.contains(boot1));

      // token 45 goes to nodes 5, boot1 and node7
      endpoints =
          tmd.getWriteEndpoints(
              keyTokens.get(4), keyspaceName, strategy.getNaturalEndpoints(keyTokens.get(4)));
      assertEquals(3, endpoints.size());
      assertTrue(endpoints.contains(hosts.get(5)));
      assertTrue(endpoints.contains(boot1));
      assertTrue(endpoints.contains(hosts.get(7)));

      // token 55 goes to boot1, 7, boot2, 8 and 0
      endpoints =
          tmd.getWriteEndpoints(
              keyTokens.get(5), keyspaceName, strategy.getNaturalEndpoints(keyTokens.get(5)));
      assertEquals(5, endpoints.size());
      assertTrue(endpoints.contains(boot1));
      assertTrue(endpoints.contains(hosts.get(7)));
      assertTrue(endpoints.contains(boot2));
      assertTrue(endpoints.contains(hosts.get(8)));
      assertTrue(endpoints.contains(hosts.get(0)));

      // token 65 goes to nodes 7, boot2, 8, 0 and 1
      endpoints =
          tmd.getWriteEndpoints(
              keyTokens.get(6), keyspaceName, strategy.getNaturalEndpoints(keyTokens.get(6)));
      assertEquals(5, endpoints.size());
      assertTrue(endpoints.contains(hosts.get(7)));
      assertTrue(endpoints.contains(boot2));
      assertTrue(endpoints.contains(hosts.get(8)));
      assertTrue(endpoints.contains(hosts.get(0)));
      assertTrue(endpoints.contains(hosts.get(1)));

      // token 75 goes to nodes boot2, 8, 0, 1 and 2
      endpoints =
          tmd.getWriteEndpoints(
              keyTokens.get(7), keyspaceName, strategy.getNaturalEndpoints(keyTokens.get(7)));
      assertEquals(5, endpoints.size());
      assertTrue(endpoints.contains(boot2));
      assertTrue(endpoints.contains(hosts.get(8)));
      assertTrue(endpoints.contains(hosts.get(0)));
      assertTrue(endpoints.contains(hosts.get(1)));
      assertTrue(endpoints.contains(hosts.get(2)));

      // token 85 goes to nodes 0, 1 and 2
      endpoints =
          tmd.getWriteEndpoints(
              keyTokens.get(8), keyspaceName, strategy.getNaturalEndpoints(keyTokens.get(8)));
      assertEquals(3, endpoints.size());
      assertTrue(endpoints.contains(hosts.get(0)));
      assertTrue(endpoints.contains(hosts.get(1)));
      assertTrue(endpoints.contains(hosts.get(2)));

      // token 95 goes to nodes 0, 1 and 2
      endpoints =
          tmd.getWriteEndpoints(
              keyTokens.get(9), keyspaceName, strategy.getNaturalEndpoints(keyTokens.get(9)));
      assertEquals(3, endpoints.size());
      assertTrue(endpoints.contains(hosts.get(0)));
      assertTrue(endpoints.contains(hosts.get(1)));
      assertTrue(endpoints.contains(hosts.get(2)));
    }
  }
  private BuildResult doRun(
      final OutputListenerImpl outputListener,
      OutputListenerImpl errorListener,
      BuildListenerImpl listener) {
    // Capture the current state of things that we will change during execution
    InputStream originalStdIn = System.in;
    Properties originalSysProperties = new Properties();
    originalSysProperties.putAll(System.getProperties());
    File originalUserDir = new File(originalSysProperties.getProperty("user.dir"));
    Map<String, String> originalEnv = new HashMap<String, String>(System.getenv());

    // Augment the environment for the execution
    System.setIn(getStdin());
    processEnvironment.maybeSetProcessDir(getWorkingDir());
    for (Map.Entry<String, String> entry : getEnvironmentVars().entrySet()) {
      processEnvironment.maybeSetEnvironmentVariable(entry.getKey(), entry.getValue());
    }
    Map<String, String> implicitJvmSystemProperties = getImplicitJvmSystemProperties();
    System.getProperties().putAll(implicitJvmSystemProperties);

    DefaultStartParameter parameter = new DefaultStartParameter();
    parameter.setCurrentDir(getWorkingDir());
    parameter.setShowStacktrace(ShowStacktrace.ALWAYS);

    CommandLineParser parser = new CommandLineParser();
    DefaultCommandLineConverter converter = new DefaultCommandLineConverter();
    converter.configure(parser);
    ParsedCommandLine parsedCommandLine = parser.parse(getAllArgs());

    BuildLayoutParameters layout = converter.getLayoutConverter().convert(parsedCommandLine);

    Map<String, String> properties = new HashMap<String, String>();
    new LayoutToPropertiesConverter().convert(layout, properties);
    converter.getSystemPropertiesConverter().convert(parsedCommandLine, properties);

    new PropertiesToStartParameterConverter().convert(properties, parameter);
    converter.convert(parsedCommandLine, parameter);

    DefaultGradleLauncherFactory factory =
        DeprecationLogger.whileDisabled(
            new Factory<DefaultGradleLauncherFactory>() {
              public DefaultGradleLauncherFactory create() {
                return (DefaultGradleLauncherFactory) GradleLauncher.getFactory();
              }
            });
    factory.addListener(listener);
    GradleLauncher gradleLauncher = factory.newInstance(parameter);
    gradleLauncher.addStandardOutputListener(outputListener);
    gradleLauncher.addStandardErrorListener(errorListener);
    try {
      return gradleLauncher.run();
    } finally {
      // Restore the environment
      System.setProperties(originalSysProperties);
      processEnvironment.maybeSetProcessDir(originalUserDir);
      for (String envVar : getEnvironmentVars().keySet()) {
        String oldValue = originalEnv.get(envVar);
        if (oldValue != null) {
          processEnvironment.maybeSetEnvironmentVariable(envVar, oldValue);
        } else {
          processEnvironment.maybeRemoveEnvironmentVariable(envVar);
        }
      }
      factory.removeListener(listener);
      System.setIn(originalStdIn);
    }
  }