Java Code Examples for com.google.common.util.concurrent.SettableFuture.get()

The following are Jave code examples for showing how to use get() of the com.google.common.util.concurrent.SettableFuture class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: hashsdn-controller   File: DeleteNestedAugmentationListenParentTest.java   Source Code and License Vote up 6 votes
@Test
public void deleteChildListenParent() throws InterruptedException, ExecutionException, TimeoutException {
    DataBroker dataBroker = testContext.getDataBroker();
    final WriteTransaction initTx = dataBroker.newWriteOnlyTransaction();

    initTx.put(LogicalDatastoreType.OPERATIONAL, LIST11_PATH, createList11(), true);
    initTx.submit().get(5, TimeUnit.SECONDS);

    final SettableFuture<AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject>> event = SettableFuture.create();
    dataBroker.registerDataChangeListener(LogicalDatastoreType.OPERATIONAL, LIST11_PATH,
        change -> event.set(change), DataChangeScope.SUBTREE);

    final WriteTransaction deleteTx = dataBroker.newWriteOnlyTransaction();
    deleteTx.delete(LogicalDatastoreType.OPERATIONAL, LIST11_PATH.augmentation(List11SimpleAugment.class));
    deleteTx.submit().get(5, TimeUnit.SECONDS);

    AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> receivedEvent = event.get();
    assertFalse(receivedEvent.getRemovedPaths().contains(TLL_COMPLEX_AUGMENT_PATH));
}
 
Example 2
Project: azure-libraries-for-java   File: TestBatch.java   Source Code and License Vote up 6 votes
@Override
public BatchAccount createResource(BatchAccounts resources) throws Exception {
    final String batchAccountName = "batch" + this.testId;
    final BatchAccount[] batchAccounts = new BatchAccount[1];
    final SettableFuture<BatchAccount> future = SettableFuture.create();


    Observable<Indexable> resourceStream = resources.define(batchAccountName)
            .withRegion(Region.INDIA_CENTRAL)
            .withNewResourceGroup()
            .withTag("mytag", "testtag")
            .createAsync();

    Utils.<BatchAccount>rootResource(resourceStream)
            .subscribe(new Action1<BatchAccount>() {
                @Override
                public void call(BatchAccount batchAccount) {
                    future.set(batchAccount);
                }
            });

    batchAccounts[0] = future.get();
    Assert.assertNull(batchAccounts[0].autoStorage());

    return batchAccounts[0];
}
 
Example 3
Project: buckaroo   File: CacheTasksTest.java   Source Code and License Vote up 6 votes
@Test
public void downloadUsingCacheFailsWhenTheHashIsIncorrect() throws Exception {

    final FileSystem fs = Jimfs.newFileSystem();

    final RemoteFile remoteFile = RemoteFile.of(
        new URI("https://raw.githubusercontent.com/njlr/test-lib-a/3af013452fe6b448b1cb33bb81bb19da690ec764/BUCK"),
        HashCode.fromString("aaaaaaaaaaaaaa4f244296b0fba7a70166dea49c9e8d3eacda58d67a"));

    final Path cachePath = CacheTasks.getCachePath(fs, remoteFile);

    final SettableFuture<Throwable> futureException = SettableFuture.create();

    CacheTasks.downloadToCache(fs, remoteFile).subscribe(
        next -> {},
        error -> {
            futureException.set(error);
        },
        () -> {});

    final Throwable exception = futureException.get(5000L, TimeUnit.MILLISECONDS);

    assertTrue(exception instanceof DownloadFileException);
    assertTrue(exception.getCause() instanceof HashMismatchException);
}
 
Example 4
Project: buckaroo   File: GitHubGitProviderTest.java   Source Code and License Vote up 6 votes
@Test
public void fetchFailsWhenThereAreNoReleases() throws Exception {

    final FileSystem fs = Jimfs.newFileSystem();

    final RecipeSource recipeSource = GitProviderRecipeSource.of(fs, GitHubGitProvider.of());

    final Single<Recipe> task = recipeSource.fetch(
        RecipeIdentifier.of("github", "njlr", "test-lib-no-releases"))
        .result();

    final SettableFuture<Throwable> futureException = SettableFuture.create();

    task.subscribe(
        result -> {
        }, error -> {
            futureException.set(error);
        });

    final Throwable exception = futureException.get(90, TimeUnit.SECONDS);

    assertTrue(exception instanceof RecipeFetchException);
}
 
Example 5
Project: buckaroo   File: LazyCookbookRecipeSourceTest.java   Source Code and License Vote up 6 votes
@Test
public void givesInformativeParseErrors() throws Exception {

    final FileSystem fs = Jimfs.newFileSystem();

    EvenMoreFiles.writeFile(
        fs.getPath(System.getProperty("user.home"), ".buckaroo", "buckaroo-recipes", "recipes", "org", "example.json"),
        "{ \"content\": \"this is an invalid recipe\" }");

    final RecipeSource recipeSource = LazyCookbookRecipeSource.of(
        fs.getPath(System.getProperty("user.home"), ".buckaroo", "buckaroo-recipes"));

    final SettableFuture<Throwable> futureError = SettableFuture.create();

    recipeSource.fetch(RecipeIdentifier.of(Identifier.of("org"), Identifier.of("example")))
        .result()
        .subscribe(x -> {

        }, error -> {
            futureError.set(error);
        });

    final Throwable exception = futureError.get(5000L, TimeUnit.MILLISECONDS);

    assertTrue(exception instanceof RecipeFetchException);
}
 
Example 6
Project: hashsdn-controller   File: WildcardedDataChangeListenerTest.java   Source Code and License Vote up 6 votes
@Test
public void testSeparateWrites() throws InterruptedException, TimeoutException, ExecutionException {

    DataBroker dataBroker = testContext.getDataBroker();

    final SettableFuture<AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject>> eventFuture =
            SettableFuture.create();
    dataBroker.registerDataChangeListener(LogicalDatastoreType.OPERATIONAL, DEEP_WILDCARDED_PATH,
        dataChangeEvent -> eventFuture.set(dataChangeEvent), DataChangeScope.SUBTREE);

    final WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
    transaction.put(LogicalDatastoreType.OPERATIONAL, NODE_0_CWU_PATH, CWU, true);
    transaction.put(LogicalDatastoreType.OPERATIONAL, NODE_0_LVU_PATH, LVU, true);
    transaction.put(LogicalDatastoreType.OPERATIONAL, NODE_1_LVU_PATH, LVU, true);
    transaction.submit().get(5, TimeUnit.SECONDS);

    AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> event = eventFuture.get(1000, TimeUnit.MILLISECONDS);

    validateEvent(event);
}
 
Example 7
Project: creacoinj   File: TestWithNetworkConnections.java   Source Code and License Vote up 5 votes
private void outboundPingAndWait(final InboundMessageQueuer p, long nonce) throws Exception {
    // Send a ping and wait for it to get to the other side
    SettableFuture<Void> pingReceivedFuture = SettableFuture.create();
    p.mapPingFutures.put(nonce, pingReceivedFuture);
    p.peer.sendMessage(new Ping(nonce));
    pingReceivedFuture.get();
    p.mapPingFutures.remove(nonce);
}
 
Example 8
Project: azure-libraries-for-java   File: TestRedis.java   Source Code and License Vote up 5 votes
@Override
public RedisCache createResource(RedisCaches resources) throws Exception {
    final String redisName = "redis" + this.testId;
    final RedisCache[] redisCaches = new RedisCache[1];
    final SettableFuture<RedisCache> future = SettableFuture.create();

    Observable<Indexable> resourceStream = resources.define(redisName)
            .withRegion(Region.US_EAST)
            .withNewResourceGroup()
            .withStandardSku()
            .withTag("mytag", "testtag")
            .createAsync();

    Utils.<RedisCache>rootResource(resourceStream)
            .subscribe(new Action1<RedisCache>() {
                @Override
                public void call(RedisCache redisCache) {
                    future.set(redisCache);
                }
            });

    redisCaches[0] = future.get();

    Assert.assertEquals(redisCaches[0].name(), redisName);

    return redisCaches[0];
}
 
Example 9
Project: azure-libraries-for-java   File: TestVirtualMachine.java   Source Code and License Vote up 5 votes
@Override
public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception {
    final String vmName = "vm" + this.testId;
    final VirtualMachine[] vms = new VirtualMachine[1];
    final SettableFuture<VirtualMachine> future = SettableFuture.create();

    Observable<Indexable> resourceStream = virtualMachines.define(vmName)
            .withRegion(Region.US_EAST)
            .withNewResourceGroup()
            .withNewPrimaryNetwork("10.0.0.0/28")
            .withPrimaryPrivateIPAddressDynamic()
            .withoutPrimaryPublicIPAddress()
            .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER)
            .withAdminUsername("testuser")
            .withAdminPassword("12NewPA$$w0rd!")
            .withNewDataDisk(150)
            .withSize(VirtualMachineSizeTypes.STANDARD_D1_V2)
            .createAsync();

    Utils.<VirtualMachine>rootResource(resourceStream)
            .subscribe(new Action1<VirtualMachine>() {
                @Override
                public void call(VirtualMachine virtualMachine) {
                    future.set(virtualMachine);
                }
            });
    vms[0] = future.get();

    Assert.assertEquals(1, vms[0].dataDisks().size());
    VirtualMachineDataDisk dataDisk = vms[0].dataDisks().values().iterator().next();
    Assert.assertEquals(150, dataDisk.size());
    Assert.assertEquals(128, vms[0].osDiskSize());
    Disk osDisk = virtualMachines.manager().disks().getById(vms[0].osDiskId());
    Assert.assertNotNull(osDisk);
    Assert.assertEquals(128, osDisk.sizeInGB());

    return vms[0];
}
 
Example 10
Project: buckaroo   File: InstallExistingTasksTest.java   Source Code and License Vote up 5 votes
@Test
public void failsGracefullyForIncorrectHashes() throws Exception {

    final FileSystem fs = Jimfs.newFileSystem();

    final DependencyLocks locks = DependencyLocks.of(ImmutableList.of(
        DependencyLock.of(
            RecipeIdentifier.of("loopperfect", "valuable"),
            ResolvedDependency.of(Either.right(
                RemoteArchive.of(
                    new URI("https://github.com/LoopPerfect/valuable/archive/v0.1.0.zip"),
                    HashCode.fromString("aaaaaaaaaaaaaaaaaaaaaaa71dd4a1fd3400f1d04b84954beb2f514ec69934c0"),
                    "valuable-0.1.0"))))));

    EvenMoreFiles.writeFile(fs.getPath("buckaroo.json"), Serializers.serialize(Project.of()));
    EvenMoreFiles.writeFile(fs.getPath("buckaroo.lock.json"), Serializers.serialize(locks));

    final SettableFuture<Throwable> futureException = SettableFuture.create();

    InstallExistingTasks.installExistingDependenciesInWorkingDirectory(fs)
        .subscribe(
            next -> {

            }, error -> {
                futureException.set(error);
            }, () -> {

            });

    final Throwable exception = futureException.get(5000L, TimeUnit.MILLISECONDS);

    assertTrue(exception instanceof DownloadFileException);
    assertTrue(exception.getCause() instanceof HashMismatchException);
}
 
Example 11
Project: hashsdn-controller   File: WriteParentListenAugmentTest.java   Source Code and License Vote up 5 votes
@Test
public void writeNodeListenAugment() throws Exception {

    final SettableFuture<AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject>> event = SettableFuture.create();
    DataBroker dataBroker = testContext.getDataBroker();
    ListenerRegistration<org.opendaylight.controller.md.sal.binding.api.DataChangeListener> dclRegistration =
            dataBroker.registerDataChangeListener(LogicalDatastoreType.OPERATIONAL, AUGMENT_WILDCARDED_PATH,
                change -> event.set(change), DataChangeScope.SUBTREE);

    final WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();

    TopLevelList tll = new TopLevelListBuilder() //
            .setKey(TLL_KEY) //
            .addAugmentation(TreeComplexUsesAugment.class, treeComplexUsesAugment("one")).build();
    transaction.put(LogicalDatastoreType.OPERATIONAL, TLL_INSTANCE_ID_BA, tll, true);
    transaction.submit().get(5, TimeUnit.SECONDS);

    AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> receivedEvent = event.get(1000, TimeUnit.MILLISECONDS);
    assertTrue(receivedEvent.getCreatedData().containsKey(AUGMENT_TLL_PATH));

    dclRegistration.close();

    final WriteTransaction transaction2 = dataBroker.newWriteOnlyTransaction();
    transaction2.put(LogicalDatastoreType.OPERATIONAL, AUGMENT_TLL_PATH, treeComplexUsesAugment("two"));
    transaction2.submit().get(5, TimeUnit.SECONDS);

    TreeComplexUsesAugment readedAug = dataBroker.newReadOnlyTransaction().read(
            LogicalDatastoreType.OPERATIONAL, AUGMENT_TLL_PATH).checkedGet(5, TimeUnit.SECONDS).get();
    assertEquals("two", readedAug.getContainerWithUses().getLeafFromGrouping());
}
 
Example 12
Project: amazon-gamelift-serversdk-java   File: AuxProxyMessageSender.java   Source Code and License Vote up 5 votes
public synchronized <T extends GenericOutcome> T emitEvent(Message message,
                                              Ack ack,
                                              SettableFuture<T> future,
                                              T genericError) {

    socket.emit(message.getDescriptorForType().getFullName(), ack, message.toByteArray());
    try {
        return future.get(30, TimeUnit.SECONDS);
    } catch (Throwable e) {
        genericError.setError(new GameLiftError(genericError.getError().getErrorType(), e));
        return genericError;
    }
}
 
Example 13
Project: hashsdn-controller   File: WildcardedDataChangeListenerTest.java   Source Code and License Vote up 5 votes
@Test
public void testNoChangeOnReplaceWithSameValue() throws InterruptedException, TimeoutException, ExecutionException {

    DataBroker dataBroker = testContext.getDataBroker();

    // We wrote initial state NODE_0_FLOW
    final WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
    transaction.put(LogicalDatastoreType.OPERATIONAL, NODE_0_LVU_PATH, LVU, true);
    transaction.submit().get(5, TimeUnit.SECONDS);

    // We registered DataChangeListener
    final SettableFuture<AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject>> eventFuture =
            SettableFuture.create();
    dataBroker.registerDataChangeListener(LogicalDatastoreType.OPERATIONAL, DEEP_WILDCARDED_PATH,
        dataChangeEvent -> eventFuture.set(dataChangeEvent), DataChangeScope.SUBTREE);
    assertFalse(eventFuture.isDone());

    final WriteTransaction secondTx = dataBroker.newWriteOnlyTransaction();
    secondTx.put(LogicalDatastoreType.OPERATIONAL, NODE_0_LVU_PATH, LVU, true);
    secondTx.put(LogicalDatastoreType.OPERATIONAL, NODE_1_LVU_PATH, LVU, true);
    secondTx.submit().get(5, TimeUnit.SECONDS);

    AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> event = eventFuture.get(1000, TimeUnit.MILLISECONDS);
    assertNotNull(event);
    // Data change should contains NODE_1 Flow - which was added
    assertTrue(event.getCreatedData().containsKey(NODE_1_LVU_PATH));
    // Data change must not containe NODE_0 Flow which was replaced with same value.
    assertFalse(event.getUpdatedData().containsKey(NODE_0_LVU_PATH));
}
 
Example 14
Project: apollo-custom   File: ConfigIntegrationTest.java   Source Code and License Vote up 5 votes
@Test
public void testLongPollRefresh() throws Exception {
  final String someKey = "someKey";
  final String someValue = "someValue";
  final String anotherValue = "anotherValue";
  long someNotificationId = 1;

  long pollTimeoutInMS = 50;
  Map<String, String> configurations = Maps.newHashMap();
  configurations.put(someKey, someValue);
  ApolloConfig apolloConfig = assembleApolloConfig(configurations);
  ContextHandler configHandler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
  ContextHandler pollHandler =
      mockPollNotificationHandler(pollTimeoutInMS, HttpServletResponse.SC_OK,
          Lists.newArrayList(
              new ApolloConfigNotification(apolloConfig.getNamespaceName(), someNotificationId)),
          false);

  startServerWithHandlers(configHandler, pollHandler);

  Config config = ConfigService.getAppConfig();
  assertEquals(someValue, config.getProperty(someKey, null));

  final SettableFuture<Boolean> longPollFinished = SettableFuture.create();

  config.addChangeListener(new ConfigChangeListener() {
    @Override
    public void onChange(ConfigChangeEvent changeEvent) {
      longPollFinished.set(true);
    }
  });

  apolloConfig.getConfigurations().put(someKey, anotherValue);

  longPollFinished.get(pollTimeoutInMS * 20, TimeUnit.MILLISECONDS);

  assertEquals(anotherValue, config.getProperty(someKey, null));
}
 
Example 15
Project: apollo-custom   File: RemoteConfigLongPollServiceTest.java   Source Code and License Vote up 5 votes
@Test
public void testSubmitLongPollNamespaceWith304Response() throws Exception {
  RemoteConfigRepository someRepository = mock(RemoteConfigRepository.class);
  final String someNamespace = "someNamespace";

  when(pollResponse.getStatusCode()).thenReturn(HttpServletResponse.SC_NOT_MODIFIED);
  final SettableFuture<Boolean> longPollFinished = SettableFuture.create();

  doAnswer(new Answer<HttpResponse<List<ApolloConfigNotification>>>() {
    @Override
    public HttpResponse<List<ApolloConfigNotification>> answer(InvocationOnMock invocation)
        throws Throwable {
      try {
        TimeUnit.MILLISECONDS.sleep(50);
      } catch (InterruptedException e) {
      }
      HttpRequest request = invocation.getArgumentAt(0, HttpRequest.class);

      assertTrue(request.getUrl().contains(someServerUrl + "/notifications/v2?"));
      assertTrue(request.getUrl().contains("appId=" + someAppId));
      assertTrue(request.getUrl().contains("cluster=" + someCluster));
      assertTrue(request.getUrl().contains("notifications="));
      assertTrue(request.getUrl().contains(someNamespace));

      longPollFinished.set(true);
      return pollResponse;
    }
  }).when(httpUtil).doGet(any(HttpRequest.class), eq(responseType));

  remoteConfigLongPollService.submit(someNamespace, someRepository);

  longPollFinished.get(5000, TimeUnit.MILLISECONDS);

  remoteConfigLongPollService.stopLongPollingRefresh();

  verify(someRepository, never()).onLongPollNotified(any(ServiceDTO.class), any(ApolloNotificationMessages.class));
}
 
Example 16
Project: apollo-custom   File: ReleaseMessageScannerTest.java   Source Code and License Vote up 5 votes
@Test
public void testScanMessageAndNotifyMessageListener() throws Exception {
  SettableFuture<ReleaseMessage> someListenerFuture = SettableFuture.create();
  ReleaseMessageListener someListener = (message, channel) -> someListenerFuture.set(message);
  releaseMessageScanner.addMessageListener(someListener);

  String someMessage = "someMessage";
  long someId = 100;
  ReleaseMessage someReleaseMessage = assembleReleaseMessage(someId, someMessage);

  when(releaseMessageRepository.findFirst500ByIdGreaterThanOrderByIdAsc(0L)).thenReturn(
      Lists.newArrayList(someReleaseMessage));

  ReleaseMessage someListenerMessage =
      someListenerFuture.get(5000, TimeUnit.MILLISECONDS);

  assertEquals(someMessage, someListenerMessage.getMessage());
  assertEquals(someId, someListenerMessage.getId());

  SettableFuture<ReleaseMessage> anotherListenerFuture = SettableFuture.create();
  ReleaseMessageListener anotherListener = (message, channel) -> anotherListenerFuture.set(message);
  releaseMessageScanner.addMessageListener(anotherListener);

  String anotherMessage = "anotherMessage";
  long anotherId = someId + 1;
  ReleaseMessage anotherReleaseMessage = assembleReleaseMessage(anotherId, anotherMessage);

  when(releaseMessageRepository.findFirst500ByIdGreaterThanOrderByIdAsc(someId)).thenReturn(
      Lists.newArrayList(anotherReleaseMessage));

  ReleaseMessage anotherListenerMessage =
      anotherListenerFuture.get(5000, TimeUnit.MILLISECONDS);

  assertEquals(anotherMessage, anotherListenerMessage.getMessage());
  assertEquals(anotherId, anotherListenerMessage.getId());

}
 
Example 17
Project: azure-libraries-for-java   File: TestNSG.java   Source Code and License Vote up 4 votes
@Override
public NetworkSecurityGroup createResource(NetworkSecurityGroups nsgs) throws Exception {
    final String newName = "nsg" + this.testId;
    final String resourceGroupName = "rg" + this.testId;
    final String nicName = "nic" + this.testId;
    final Region region = Region.US_WEST;
    final SettableFuture<NetworkSecurityGroup> nsgFuture = SettableFuture.create();
    // Create
    Observable<Indexable> resourceStream = nsgs.define(newName)
            .withRegion(region)
            .withNewResourceGroup(resourceGroupName)
            .defineRule("rule1")
                .allowOutbound()
                .fromAnyAddress()
                .fromPort(80)
                .toAnyAddress()
                .toPort(80)
                .withProtocol(SecurityRuleProtocol.TCP)
                .attach()
            .defineRule("rule2")
                .allowInbound()
                .fromAnyAddress()
                .fromAnyPort()
                .toAnyAddress()
                .toPortRange(22, 25)
                .withAnyProtocol()
                .withPriority(200)
                .withDescription("foo!!")
                .attach()
            .createAsync();

    Utils.<NetworkSecurityGroup>rootResource(resourceStream)
            .subscribe(new Subscriber<NetworkSecurityGroup>() {
                   @Override
                   public void onCompleted() {
                        System.out.print("completed");
                   }

                   @Override
                   public void onError(Throwable throwable) {
                        nsgFuture.setException(throwable);
                   }

                   @Override
                   public void onNext(NetworkSecurityGroup networkSecurityGroup) {
                        nsgFuture.set(networkSecurityGroup);
                   }
               });

    NetworkSecurityGroup nsg = nsgFuture.get();

    NetworkInterface nic = nsgs.manager().networkInterfaces().define(nicName)
            .withRegion(region)
            .withExistingResourceGroup(resourceGroupName)
            .withNewPrimaryNetwork("10.0.0.0/28")
            .withPrimaryPrivateIPAddressDynamic()
            .withExistingNetworkSecurityGroup(nsg)
            .create();

    nsg.refresh();

    // Verify
    Assert.assertTrue(nsg.region().equals(region));
    Assert.assertTrue(nsg.securityRules().size() == 2);

    // Confirm NIC association
    Assert.assertEquals(1,  nsg.networkInterfaceIds().size());
    Assert.assertTrue(nsg.networkInterfaceIds().contains(nic.id()));

    return nsg;
}
 
Example 18
Project: buckaroo   File: InstallTasksTest.java   Source Code and License Vote up 4 votes
@Test
public void failsGracefullyForIncorrectHashes() throws Exception {

    final FileSystem fs = Jimfs.newFileSystem();

    EvenMoreFiles.writeFile(fs.getPath("buckaroo.json"), Serializers.serialize(Project.of("test")));

    final Recipe recipe = Recipe.of(
        "Valuable",
        new URI("http://www.example.com"),
        ImmutableMap.of(
            SemanticVersion.of(1),
            RecipeVersion.of(
                RemoteArchive.of(
                    new URI("https://github.com/LoopPerfect/valuable/archive/v0.1.0.zip"),
                    HashCode.fromString("aaaaaaaaaaaaaaaaaaaaaaa71dd4a1fd3400f1d04b84954beb2f514ec69934c0"),
                    "valuable-0.1.0"))));

    EvenMoreFiles.writeFile(
        fs.getPath(System.getProperty("user.home"),
            ".buckaroo", "buckaroo-recipes", "recipes", "loopperfect", "valuable.json"),
        Serializers.serialize(recipe));

    final ImmutableList<PartialDependency> toInstall = ImmutableList.of(
        PartialDependency.of(Identifier.of("loopperfect"), Identifier.of("valuable")));

    final SettableFuture<Throwable> futureException = SettableFuture.create();

    InstallTasks.installDependencyInWorkingDirectory(fs, toInstall)
        .subscribe(
            next -> {

            }, error -> {
                futureException.set(error);
            }, () -> {

            });

    final Throwable exception = futureException.get(5000L, TimeUnit.MILLISECONDS);

    assertTrue(exception instanceof DownloadFileException);
    assertTrue(exception.getCause() instanceof HashMismatchException);
}
 
Example 19
Project: apollo-custom   File: ConfigIntegrationTest.java   Source Code and License Vote up 4 votes
@Test
public void testLongPollRefreshWithMultipleNamespacesAndOnlyOneNamespaceNotified() throws Exception {
  final String someKey = "someKey";
  final String someValue = "someValue";
  final String anotherValue = "anotherValue";
  long someNotificationId = 1;

  long pollTimeoutInMS = 50;
  Map<String, String> configurations = Maps.newHashMap();
  configurations.put(someKey, someValue);
  ApolloConfig apolloConfig = assembleApolloConfig(configurations);
  ContextHandler configHandler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
  ContextHandler pollHandler =
      mockPollNotificationHandler(pollTimeoutInMS, HttpServletResponse.SC_OK,
          Lists.newArrayList(
              new ApolloConfigNotification(apolloConfig.getNamespaceName(), someNotificationId)),
          false);

  startServerWithHandlers(configHandler, pollHandler);

  Config someOtherConfig = ConfigService.getConfig(someOtherNamespace);
  Config config = ConfigService.getAppConfig();
  assertEquals(someValue, config.getProperty(someKey, null));
  assertEquals(someValue, someOtherConfig.getProperty(someKey, null));

  final SettableFuture<Boolean> longPollFinished = SettableFuture.create();

  config.addChangeListener(new ConfigChangeListener() {
    @Override
    public void onChange(ConfigChangeEvent changeEvent) {
      longPollFinished.set(true);
    }
  });

  apolloConfig.getConfigurations().put(someKey, anotherValue);

  longPollFinished.get(5000, TimeUnit.MILLISECONDS);

  assertEquals(anotherValue, config.getProperty(someKey, null));

  TimeUnit.MILLISECONDS.sleep(pollTimeoutInMS * 10);
  assertEquals(someValue, someOtherConfig.getProperty(someKey, null));
}
 
Example 20
Project: apollo-custom   File: RemoteConfigRepositoryTest.java   Source Code and License Vote up 4 votes
@Test
public void testLongPollingRefresh() throws Exception {
  Map<String, String> configurations = ImmutableMap.of("someKey", "someValue");
  ApolloConfig someApolloConfig = assembleApolloConfig(configurations);

  when(someResponse.getStatusCode()).thenReturn(200);
  when(someResponse.getBody()).thenReturn(someApolloConfig);

  final SettableFuture<Boolean> longPollFinished = SettableFuture.create();
  RepositoryChangeListener someListener = mock(RepositoryChangeListener.class);
  doAnswer(new Answer<Void>() {

    @Override
    public Void answer(InvocationOnMock invocation) throws Throwable {
      longPollFinished.set(true);
      return null;
    }

  }).when(someListener).onRepositoryChange(any(String.class), any(Properties.class));

  RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace);
  remoteConfigRepository.addChangeListener(someListener);
  final ArgumentCaptor<Properties> captor = ArgumentCaptor.forClass(Properties.class);

  Map<String, String> newConfigurations = ImmutableMap.of("someKey", "anotherValue");
  ApolloConfig newApolloConfig = assembleApolloConfig(newConfigurations);

  ApolloNotificationMessages notificationMessages = new ApolloNotificationMessages();
  String someKey = "someKey";
  long someNotificationId = 1;
  notificationMessages.put(someKey, someNotificationId);

  ApolloConfigNotification someNotification = mock(ApolloConfigNotification.class);
  when(someNotification.getNamespaceName()).thenReturn(someNamespace);
  when(someNotification.getMessages()).thenReturn(notificationMessages);

  when(pollResponse.getStatusCode()).thenReturn(HttpServletResponse.SC_OK);
  when(pollResponse.getBody()).thenReturn(Lists.newArrayList(someNotification));
  when(someResponse.getBody()).thenReturn(newApolloConfig);

  longPollFinished.get(500, TimeUnit.MILLISECONDS);

  remoteConfigLongPollService.stopLongPollingRefresh();

  verify(someListener, times(1)).onRepositoryChange(eq(someNamespace), captor.capture());
  assertEquals(newConfigurations, captor.getValue());

  final ArgumentCaptor<HttpRequest> httpRequestArgumentCaptor = ArgumentCaptor.forClass(HttpRequest.class);
  verify(httpUtil, atLeast(2)).doGet(httpRequestArgumentCaptor.capture(), eq(ApolloConfig.class));

  HttpRequest request = httpRequestArgumentCaptor.getValue();

  assertTrue(request.getUrl().contains("messages=%7B%22details%22%3A%7B%22someKey%22%3A1%7D%7D"));
}