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

The following examples show how to use com.google.common.util.concurrent.SettableFuture#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConsultantTest.java    From consultant with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 5_000)
public void verifyInitialConfigLoad() throws Exception {
	httpBuilder.onGet("/v1/kv/config/oauth/?recurse=true", request -> {
		CloseableHttpResponse response = mock(CloseableHttpResponse.class);
		when(response.getFirstHeader(eq("X-Consul-Index"))).thenReturn(new BasicHeader("X-Consul-Index", "1000"));
		when(response.getStatusLine()).thenReturn(createStatus(200, "OK"));
		when(response.getEntity()).thenReturn(toJson(ImmutableMap.of("config/oauth/some.key", "some-value")));
		return response;
	});

	SettableFuture<Properties> future = SettableFuture.create();

	consultant = Consultant.builder()
			.usingHttpClient(httpBuilder.create())
			.withConsulHost("http://localhost")
			.identifyAs("oauth", "eu-central", "web-1", "master")
			.onValidConfig(future::set)
			.build();

	Properties properties = future.get();
	assertEquals("some-value", properties.getProperty("some.key"));
}
 
Example 2
Source File: ConfigUpdaterTest.java    From consultant with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 10_000)
public void verifyFolderIsIgnored() throws Exception {
	CloseableHttpResponse response = mock(CloseableHttpResponse.class);
	when(response.getFirstHeader(eq("X-Consul-Index"))).thenReturn(new BasicHeader("X-Consul-Index", "1000"));
	when(response.getStatusLine()).thenReturn(createStatus(200, "OK"));
	when(response.getEntity()).thenReturn(toJson(ImmutableMap.of("some-prefix/oauth/", "some-value",
			"some-prefix/oauth/some.key", "some-value")));

	when(http.execute(any())).thenReturn(response);

	SettableFuture<Properties> future = SettableFuture.create();
	ConfigUpdater updater = new ConfigUpdater(executor, http, null, null, id, objectMapper, null, future::set,
			"some-prefix");

	updater.run();

	Properties properties = future.get();
	assertEquals(properties.keySet(), Sets.newHashSet("some.key"));
}
 
Example 3
Source File: ThriftTransactionServerTest.java    From phoenix-tephra with Apache License 2.0 6 votes vote down vote up
private void expireZkSession(ZKClientService zkClientService) throws Exception {
  ZooKeeper zooKeeper = zkClientService.getZooKeeperSupplier().get();
  final SettableFuture<?> connectFuture = SettableFuture.create();
  Watcher watcher = new Watcher() {
    @Override
    public void process(WatchedEvent event) {
      if (event.getState() == Event.KeeperState.SyncConnected) {
        connectFuture.set(null);
      }
    }
  };

  // Create another Zookeeper session with the same sessionId so that the original one expires.
  ZooKeeper dupZookeeper =
    new ZooKeeper(zkClientService.getConnectString(), zooKeeper.getSessionTimeout(), watcher,
                  zooKeeper.getSessionId(), zooKeeper.getSessionPasswd());
  connectFuture.get(30, TimeUnit.SECONDS);
  Assert.assertEquals("Failed to re-create current session", dupZookeeper.getState(), ZooKeeper.States.CONNECTED);
  dupZookeeper.close();
}
 
Example 4
Source File: AirplaneModeAndroidTest.java    From firebase-jobdispatcher-android with Apache License 2.0 6 votes vote down vote up
private void waitForSomeNetworkToConnect() throws Exception {
  final SettableFuture<Void> future = SettableFuture.create();

  ConnectivityManager.NetworkCallback cb =
      new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(Network network) {
          NetworkInfo netInfo = connManager.getNetworkInfo(network);
          if (netInfo != null && netInfo.isConnected()) {
            future.set(null);
          }
        }
      };

  connManager.requestNetwork(
      new NetworkRequest.Builder().addCapability(NET_CAPABILITY_INTERNET).build(), cb);

  try {
    future.get(NETWORK_STATE_CHANGE_TIMEOUT_SECONDS, TimeUnit.SECONDS);
  } finally {
    connManager.unregisterNetworkCallback(cb);
  }
}
 
Example 5
Source File: TestBatch.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@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 6
Source File: GracePeriodTest.java    From helios with Apache License 2.0 5 votes vote down vote up
private Answer<?> futureAnswer(final SettableFuture<?> future) {
  return new Answer<Object>() {
    @Override
    public Object answer(final InvocationOnMock invocation) throws Throwable {
      return future.get();
    }
  };
}
 
Example 7
Source File: AddKeeperCommandTest.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckStateCommandNoDelay() throws Exception {

	int sleepTime = 2000;
	SlaveRole keeperRole = new SlaveRole(SERVER_ROLE.KEEPER, "localhost", randomPort(), MASTER_STATE.REDIS_REPL_CONNECTED, 0);
	Server server = startServer(keeperPort, new Callable<String>() {
		@Override
		public String call() throws Exception {
			sleep(sleepTime);
			return ByteBufUtils.readToString(keeperRole.format());
		}
	});

	SettableFuture<Boolean> objectSettableFuture = SettableFuture.create();

	executors.execute(new AbstractExceptionLogTask() {
		@Override
		public void doRun() throws Exception {

			AddKeeperCommand.CheckStateCommand checkStateCommand = new AddKeeperCommand.CheckStateCommand(new KeeperMeta().setIp("127.0.0.1").setPort(server.getPort()), scheduled);
			checkStateCommand.doExecute();
			objectSettableFuture.set(true);
		}
	});

	//should return immediately
	objectSettableFuture.get(500, TimeUnit.MILLISECONDS);
}
 
Example 8
Source File: TestReentrantBoundedExecutor.java    From presto with Apache License 2.0 5 votes vote down vote up
@Test
public void testReentrantBoundedExecutor()
        throws ExecutionException, InterruptedException
{
    AtomicInteger callCounter = new AtomicInteger();
    SettableFuture<Object> future = SettableFuture.create();
    Executor reentrantExecutor = new ReentrantBoundedExecutor(newCachedThreadPool(), 1);
    reentrantExecutor.execute(() -> {
        callCounter.incrementAndGet();
        reentrantExecutor.execute(() -> {
            callCounter.incrementAndGet();
            future.set(null);
        });
        try {
            future.get();
        }
        catch (Exception ignored) {
        }
    });
    future.get();

    SettableFuture<Object> secondFuture = SettableFuture.create();
    reentrantExecutor.execute(() -> secondFuture.set(null));
    secondFuture.get();

    assertEquals(callCounter.get(), 2);
}
 
Example 9
Source File: TestProtocolBusService.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void testAddServiceListener() throws Exception {
   Address destination = Address.fromString("PROT:ZWAV-ABC-1234:" + ProtocolDeviceId.fromBytes(new byte [] { 22 }).getRepresentation());
   ProtocolMessage protocolMessage = ProtocolMessage.createProtocolMessage(
         Address.fromString("DRIV:dev:6ff3a5ff-4650-4ce7-82e0-682a58392316"),
         destination,
         ZWaveProtocol.INSTANCE,
         new ZWaveCommandMessage()
   );
   final SettableFuture<Boolean> future = SettableFuture.create();
   ProtocolBusService protocolBusService = ServiceLocator.getInstance(ProtocolBusService.class);
   protocolBusService.addProtocolListener(new ProtocolBusListener() {

      @Override
      public void onMessage(ClientToken ct, ProtocolMessage msg) {
         try {
            Assert.assertEquals("Client Token key should be hub ID", "ABC-1234", ct.getRepresentation());
            Assert.assertEquals("PROT:ZWAV-ABC-1234:FgAAAAAAAAAAAAAAAAAAAAAAAAA=", msg.getDestination().getRepresentation());
            Assert.assertEquals("DRIV:dev:6ff3a5ff-4650-4ce7-82e0-682a58392316", msg.getSource().getRepresentation());
            Assert.assertEquals(destination, msg.getDestination());
            future.set(true);
         }
         catch(Throwable t) {
            future.setException(t);
         }
      }

   });

   protocolBus.send(protocolMessage);
   boolean messageReceivedFlag = future.get(300, TimeUnit.MILLISECONDS);

   Assert.assertTrue("Message should have arrived.", messageReceivedFlag);
}
 
Example 10
Source File: TestWithNetworkConnections.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
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 11
Source File: TcpServerIntegrationTest.java    From spring-boot-netty with MIT License 5 votes vote down vote up
@Test
public void testMultipleHandlersWorkForMultipleMessages() throws Exception {
    tcpServer.addHandler("echoDecoder", EchoServerDecoder::new);
    tcpServer.addHandler("echoEncoder", EchoServerEncoder::new);
    tcpServer.addHandler("echoHandler", EchoServerHandler::new);
    tcpServer.start().get(30, TimeUnit.SECONDS);

    final SettableFuture<Long> responseHolder1 = SettableFuture.create();
    final SettableFuture<Long> responseHolder2 = SettableFuture.create();
    final ServerClient client = new ServerClient(40000, "localhost",
            new EchoClientHandler(responseHolder1, responseHolder2));

    client.connect().get(30, TimeUnit.SECONDS);

    final ByteBuf msg1 = copyLong(1L);
    final ByteBuf msg2 = copyLong(2L);
    client.writeAndFlush(msg1).syncUninterruptibly();
    client.writeAndFlush(msg2).syncUninterruptibly();

    Futures.successfulAsList(responseHolder1, responseHolder2).get(30, TimeUnit.SECONDS);

    final long actual1 = responseHolder1.get(30, TimeUnit.SECONDS);
    final long actual2 = responseHolder2.get(30, TimeUnit.SECONDS);
    assertEquals(1L, actual1);
    assertEquals(2L, actual2);

    client.disconnect();
    tcpServer.stop();
}
 
Example 12
Source File: PersistentEphemeralNode.java    From curator-extensions with Apache License 2.0 5 votes vote down vote up
private String getActualPath() throws ExecutionException, InterruptedException {
    String path = _sync._nodePath;
    if (path != null) {
        return path;
    }

    SettableFuture<String> future = SettableFuture.create();

    while (!future.isDone()) {
        waitThenGetActualPath(future);
    }

    return future.get();
}
 
Example 13
Source File: ApolloConfigWrapperTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Test
public void assertAddChangeListener() throws Exception {
    final SettableFuture<ConfigChangeEvent> future = SettableFuture.create();
    ConfigChangeListener listener = future::set;
    configWrapper.addChangeListener(listener, Collections.singleton("test.children.2"));
    embeddedApollo.addOrModifyProperty("orchestration", "test.children.2", "value3");
    ConfigChangeEvent changeEvent = future.get(5, TimeUnit.SECONDS);
    assertTrue(changeEvent.isChanged("test.children.2"));
    assertThat(changeEvent.getChange("test.children.2").getOldValue(), is("value2"));
    assertThat(changeEvent.getChange("test.children.2").getNewValue(), is("value3"));
    assertThat(changeEvent.getChange("test.children.2").getChangeType(), is(PropertyChangeType.MODIFIED));
}
 
Example 14
Source File: XdsTestClient.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
private void runQps() throws InterruptedException, ExecutionException {
  final SettableFuture<Void> failure = SettableFuture.create();
  final class PeriodicRpc implements Runnable {

    @Override
    public void run() {
      final long requestId;
      final Set<XdsStatsWatcher> savedWatchers = new HashSet<>();
      synchronized (lock) {
        currentRequestId += 1;
        requestId = currentRequestId;
        savedWatchers.addAll(watchers);
      }

      SimpleRequest request = SimpleRequest.newBuilder().setFillServerId(true).build();
      ManagedChannel channel = channels.get((int) (requestId % channels.size()));
      final ClientCall<SimpleRequest, SimpleResponse> call =
          channel.newCall(
              TestServiceGrpc.getUnaryCallMethod(),
              CallOptions.DEFAULT.withDeadlineAfter(rpcTimeoutSec, TimeUnit.SECONDS));
      call.start(
          new ClientCall.Listener<SimpleResponse>() {
            private String hostname;

            @Override
            public void onMessage(SimpleResponse response) {
              hostname = response.getHostname();
              // TODO(ericgribkoff) Currently some test environments cannot access the stats RPC
              // service and rely on parsing stdout.
              if (printResponse) {
                System.out.println(
                    "Greeting: Hello world, this is "
                        + hostname
                        + ", from "
                        + call.getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR));
              }
            }

            @Override
            public void onClose(Status status, Metadata trailers) {
              if (printResponse && !status.isOk()) {
                logger.log(Level.WARNING, "Greeting RPC failed with status {0}", status);
              }
              for (XdsStatsWatcher watcher : savedWatchers) {
                watcher.rpcCompleted(requestId, hostname);
              }
            }
          },
          new Metadata());

      call.sendMessage(request);
      call.request(1);
      call.halfClose();
    }
  }

  long nanosPerQuery = TimeUnit.SECONDS.toNanos(1) / qps;
  ListenableScheduledFuture<?> future =
      exec.scheduleAtFixedRate(new PeriodicRpc(), 0, nanosPerQuery, TimeUnit.NANOSECONDS);

  Futures.addCallback(
      future,
      new FutureCallback<Object>() {

        @Override
        public void onFailure(Throwable t) {
          failure.setException(t);
        }

        @Override
        public void onSuccess(Object o) {}
      },
      MoreExecutors.directExecutor());

  failure.get();
}
 
Example 15
Source File: PersistentPathChildrenCacheTest.java    From helios with Apache License 2.0 4 votes vote down vote up
@Test
public void verifyNodesAreRetainedWhenZkGoesDown() throws Exception {
  // Create two nodes
  final String foo1 = "/foos/foo1";
  final String foo2 = "/foos/foo2";
  final Set<String> paths = ImmutableSet.of(foo1, foo2);
  for (final String path : paths) {
    ensure(path, new DataPojo(path));
  }

  // Wait for the cache to pick them up
  Polling.await(5, MINUTES, new Callable<Object>() {
    @Override
    public Object call() throws Exception {
      return cache.getNodes().keySet().equals(paths) ? true : null;
    }
  });

  verify(listener, atLeastOnce()).nodesChanged(cache);

  // Wait for connection to be lost
  final SettableFuture<Void> connectionLost = SettableFuture.create();
  doAnswer(new Answer<Object>() {
    @Override
    public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {
      if (invocationOnMock.getArguments()[0] == ConnectionState.LOST) {
        connectionLost.set(null);
      }
      return null;
    }
  }).when(listener).connectionStateChanged(any(ConnectionState.class));

  // Take down zk
  zk.stop();
  connectionLost.get(5, MINUTES);

  // Keep probing for 30 seconds to build some confidence that the snapshot is not going away
  for (int i = 0; i < 30; i++) {
    Thread.sleep(1000);
    assertEquals(paths, cache.getNodes().keySet());
  }
}
 
Example 16
Source File: TestNSG.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@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 String asgName = SdkContext.randomResourceName("asg", 8);
    final Region region = Region.US_WEST;
    final SettableFuture<NetworkSecurityGroup> nsgFuture = SettableFuture.create();

    ApplicationSecurityGroup asg = nsgs.manager().applicationSecurityGroups().define(asgName)
            .withRegion(region)
            .withNewResourceGroup(resourceGroupName)
            .create();
    // Create
    Observable<Indexable> resourceStream = nsgs.define(newName)
            .withRegion(region)
            .withExistingResourceGroup(resourceGroupName)
            .defineRule("rule1")
                .allowOutbound()
                .fromAnyAddress()
                .fromPort(80)
                .toAnyAddress()
                .toPort(80)
                .withProtocol(SecurityRuleProtocol.TCP)
                .attach()
            .defineRule("rule2")
                .allowInbound()
                .withSourceApplicationSecurityGroup(asg.id())
                .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()));

    Assert.assertEquals(1, nsg.securityRules().get("rule2").sourceApplicationSecurityGroupIds().size());
    Assert.assertEquals(asg.id(), nsg.securityRules().get("rule2").sourceApplicationSecurityGroupIds().iterator().next());

    return nsg;
}
 
Example 17
Source File: ServerContextLookupOperationTest.java    From azure-devops-intellij with MIT License 4 votes vote down vote up
@Test
public void getRepositoriesAsync() throws ExecutionException, InterruptedException {
    // Create context
    URI serverUri = URI.create("http://server");
    AuthenticationInfo info = new AuthenticationInfo("", "", "", "");
    TeamProjectCollectionReference collection = new TeamProjectCollectionReference();
    ServerContext context = new ServerContextBuilder().type(ServerContext.Type.TFS).authentication(info).uri(serverUri).collection(collection).build();
    MockServerContextLookupOperation operation = new MockServerContextLookupOperation(Collections.singletonList(context), ServerContextLookupOperation.ContextScope.REPOSITORY);

    // create 3 repos 2 from same project
    String repoName1 = "repo1";
    String repoName2 = "repo2";
    String repoName3 = "repo3";
    String projectName1 = "project1";
    String projectName2 = "project2";
    TeamProjectReference project1 = new TeamProjectReference();
    project1.setName(projectName1);
    TeamProjectReference project2 = new TeamProjectReference();
    project2.setName(projectName2);
    GitRepository repo1 = new GitRepository();
    repo1.setName(repoName1);
    repo1.setProjectReference(project1);
    repo1.setRemoteUrl("http://server/_git/repo1");
    GitRepository repo2 = new GitRepository();
    repo2.setName(repoName2);
    repo2.setProjectReference(project2);
    repo2.setRemoteUrl("http://server/_git/repo2");
    GitRepository repo3 = new GitRepository();
    repo3.setName(repoName3);
    repo3.setProjectReference(project1);
    repo3.setRemoteUrl("http://server/_git/repo3");

    // add these repos to the Mock operation as our results
    operation.addRepository(repo1);
    operation.addRepository(repo2);
    operation.addRepository(repo3);

    // set up listener
    final SettableFuture<Boolean> startedCalled = SettableFuture.create();
    final SettableFuture<Boolean> completedCalled = SettableFuture.create();
    final SettableFuture<Boolean> canceledCalled = SettableFuture.create();
    final SettableFuture<List<ServerContext>> results = SettableFuture.create();
    setupListener(operation, startedCalled, completedCalled, canceledCalled, results);

    // do lookup
    operation.doWorkAsync(Operation.EMPTY_INPUTS);

    // Verify results
    List<ServerContext> newContexts = results.get();
    Assert.assertEquals(3, newContexts.size());
    Assert.assertEquals(repo1, newContexts.get(0).getGitRepository());
    Assert.assertEquals(repo2, newContexts.get(1).getGitRepository());
    Assert.assertEquals(repo3, newContexts.get(2).getGitRepository());
    Assert.assertTrue(startedCalled.get());
    Assert.assertTrue(completedCalled.get());
    Assert.assertFalse(canceledCalled.isDone());

    // cancel remaining futures
    canceledCalled.cancel(true);
}
 
Example 18
Source File: RemoteConfigRepositoryTest.java    From apollo with Apache License 2.0 4 votes vote down vote up
@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(5000, 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"));
}
 
Example 19
Source File: RemoteExecutionStrategyTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void testCancellationDuringExecute() throws Exception {
  SettableFuture<Runnable> completer = SettableFuture.create();

  clients =
      new SimpleRemoteExecutionClients() {
        @Override
        public ExecutionHandle execute() {
          SettableFuture<ExecutionResult> result = SettableFuture.create();
          completer.set(
              () -> {
                try {
                  result.get();
                } catch (InterruptedException | ExecutionException e) {
                  throw new IllegalStateException();
                }
              });
          return new ExecutionHandle() {
            @Override
            public ListenableFuture<ExecutionResult> getResult() {
              return result;
            }

            @Override
            public ListenableFuture<ExecuteOperationMetadata> getExecutionStarted() {
              return SettableFuture.create();
            }

            @Override
            public void cancel() {
              result.setException(new IllegalAccessException());
            }
          };
        }
      };
  StrategyBuildResult strategyBuildResult = beginBuild();
  completer.get(2, TimeUnit.SECONDS);
  boolean cancelled = strategyBuildResult.cancelIfNotComplete(new Throwable());
  assertTrue(cancelled);

  // The server should have received indication that the client cancelled the call.
  expectedException.expect(IllegalStateException.class);
  completer.get().run();
}
 
Example 20
Source File: TestHiveSplitSource.java    From presto with Apache License 2.0 4 votes vote down vote up
@Test
public void testReaderWaitsForSplits()
        throws Exception
{
    HiveSplitSource hiveSplitSource = HiveSplitSource.allAtOnce(
            SESSION,
            "database",
            "table",
            10,
            10,
            DataSize.of(1, MEGABYTE),
            Integer.MAX_VALUE,
            new TestingHiveSplitLoader(),
            Executors.newFixedThreadPool(5),
            new CounterStat());

    SettableFuture<ConnectorSplit> splits = SettableFuture.create();

    // create a thread that will get a split
    CountDownLatch started = new CountDownLatch(1);
    Thread getterThread = new Thread(new Runnable()
    {
        @Override
        public void run()
        {
            try {
                started.countDown();
                List<ConnectorSplit> batch = getSplits(hiveSplitSource, 1);
                assertEquals(batch.size(), 1);
                splits.set(batch.get(0));
            }
            catch (Throwable e) {
                splits.setException(e);
            }
        }
    });
    getterThread.start();

    try {
        // wait for the thread to be started
        assertTrue(started.await(1, TimeUnit.SECONDS));

        // sleep for a bit, and assure the thread is blocked
        TimeUnit.MILLISECONDS.sleep(200);
        assertTrue(!splits.isDone());

        // add a split
        hiveSplitSource.addToQueue(new TestSplit(33));

        // wait for thread to get the split
        ConnectorSplit split = splits.get(800, TimeUnit.MILLISECONDS);
        assertEquals(((HiveSplit) split).getSchema().getProperty("id"), "33");
    }
    finally {
        // make sure the thread exits
        getterThread.interrupt();
    }
}