List of usage examples for java.util.concurrent CompletableFuture completedFuture
public static <U> CompletableFuture<U> completedFuture(U value)
From source file:org.apache.flink.client.program.rest.RestClusterClientTest.java
@Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); when(mockRestfulGateway.requestRestAddress(any(Time.class))) .thenReturn(CompletableFuture.completedFuture(REST_ADDRESS)); final Configuration config = new Configuration(); config.setString(JobManagerOptions.ADDRESS, "localhost"); config.setInteger(RestOptions.RETRY_MAX_ATTEMPTS, 10); config.setLong(RestOptions.RETRY_DELAY, 0); restServerEndpointConfiguration = RestServerEndpointConfiguration.fromConfiguration(config); mockGatewayRetriever = () -> CompletableFuture.completedFuture(mockRestfulGateway); executor = Executors/* w w w . ja va 2 s . co m*/ .newSingleThreadExecutor(new ExecutorThreadFactory(RestClusterClientTest.class.getSimpleName())); final RestClient restClient = new RestClient(RestClientConfiguration.fromConfiguration(config), executor) { @Override public <M extends MessageHeaders<R, P, U>, U extends MessageParameters, R extends RequestBody, P extends ResponseBody> CompletableFuture<P> sendRequest( final String targetAddress, final int targetPort, final M messageHeaders, final U messageParameters, final R request) throws IOException { if (failHttpRequest.test(messageHeaders, messageParameters, request)) { return FutureUtils.completedExceptionally(new IOException("expected")); } else { return super.sendRequest(targetAddress, targetPort, messageHeaders, messageParameters, request); } } }; restClusterClient = new RestClusterClient<>(config, restClient, StandaloneClusterId.getInstance(), (attempt) -> 0, null); jobGraph = new JobGraph("testjob"); jobId = jobGraph.getJobID(); }
From source file:org.apache.flink.client.program.rest.RestClusterClientTest.java
/** * Tests that the send operation is being retried. *//* w ww .jav a 2s . com*/ @Test public void testRetriableSendOperationIfConnectionErrorOrServiceUnavailable() throws Exception { final PingRestHandler pingRestHandler = new PingRestHandler( FutureUtils.completedExceptionally( new RestHandlerException("test exception", HttpResponseStatus.SERVICE_UNAVAILABLE)), CompletableFuture.completedFuture(EmptyResponseBody.getInstance())); try (final TestRestServerEndpoint restServerEndpoint = createRestServerEndpoint(pingRestHandler)) { final AtomicBoolean firstPollFailed = new AtomicBoolean(); failHttpRequest = (messageHeaders, messageParameters, requestBody) -> messageHeaders instanceof PingRestHandlerHeaders && !firstPollFailed.getAndSet(true); restClusterClient.sendRequest(PingRestHandlerHeaders.INSTANCE).get(); } }
From source file:org.apache.flink.runtime.rest.RestServerEndpointITCase.java
@Before public void setup() throws Exception { config.setString(WebOptions.UPLOAD_DIR, temporaryFolder.newFolder().getCanonicalPath()); defaultSSLContext = SSLContext.getDefault(); defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory(); final SSLContext sslClientContext = SSLUtils.createRestClientSSLContext(config); if (sslClientContext != null) { SSLContext.setDefault(sslClientContext); HttpsURLConnection.setDefaultSSLSocketFactory(sslClientContext.getSocketFactory()); }// www.j av a 2 s .com RestServerEndpointConfiguration serverConfig = RestServerEndpointConfiguration.fromConfiguration(config); RestClientConfiguration clientConfig = RestClientConfiguration.fromConfiguration(config); final String restAddress = "http://localhost:1234"; RestfulGateway mockRestfulGateway = mock(RestfulGateway.class); when(mockRestfulGateway.requestRestAddress(any(Time.class))) .thenReturn(CompletableFuture.completedFuture(restAddress)); final GatewayRetriever<RestfulGateway> mockGatewayRetriever = () -> CompletableFuture .completedFuture(mockRestfulGateway); testHandler = new TestHandler(CompletableFuture.completedFuture(restAddress), mockGatewayRetriever, RpcUtils.INF_TIMEOUT); TestVersionHandler testVersionHandler = new TestVersionHandler( CompletableFuture.completedFuture(restAddress), mockGatewayRetriever, RpcUtils.INF_TIMEOUT); TestVersionSelectionHandler1 testVersionSelectionHandler1 = new TestVersionSelectionHandler1( CompletableFuture.completedFuture(restAddress), mockGatewayRetriever, RpcUtils.INF_TIMEOUT); TestVersionSelectionHandler2 testVersionSelectionHandler2 = new TestVersionSelectionHandler2( CompletableFuture.completedFuture(restAddress), mockGatewayRetriever, RpcUtils.INF_TIMEOUT); testUploadHandler = new TestUploadHandler(CompletableFuture.completedFuture(restAddress), mockGatewayRetriever, RpcUtils.INF_TIMEOUT); final StaticFileServerHandler<RestfulGateway> staticFileServerHandler = new StaticFileServerHandler<>( mockGatewayRetriever, CompletableFuture.completedFuture(restAddress), RpcUtils.INF_TIMEOUT, temporaryFolder.getRoot()); final List<Tuple2<RestHandlerSpecification, ChannelInboundHandler>> handlers = Arrays.asList( Tuple2.of(new TestHeaders(), testHandler), Tuple2.of(TestUploadHeaders.INSTANCE, testUploadHandler), Tuple2.of(testVersionHandler.getMessageHeaders(), testVersionHandler), Tuple2.of(testVersionSelectionHandler1.getMessageHeaders(), testVersionSelectionHandler1), Tuple2.of(testVersionSelectionHandler2.getMessageHeaders(), testVersionSelectionHandler2), Tuple2.of(WebContentHandlerSpecification.getInstance(), staticFileServerHandler)); serverEndpoint = new TestRestServerEndpoint(serverConfig, handlers); restClient = new TestRestClient(clientConfig); serverEndpoint.start(); serverAddress = serverEndpoint.getServerAddress(); }
From source file:org.apache.flink.runtime.rest.RestServerEndpointITCase.java
/** * Tests that request are handled as individual units which don't interfere with each other. * This means that request responses can overtake each other. *///from www. j a va 2s . c om @Test public void testRequestInterleaving() throws Exception { final HandlerBlocker handlerBlocker = new HandlerBlocker(timeout); testHandler.handlerBody = id -> { if (id == 1) { handlerBlocker.arriveAndBlock(); } return CompletableFuture.completedFuture(new TestResponse(id)); }; // send first request and wait until the handler blocks final CompletableFuture<TestResponse> response1 = sendRequestToTestHandler(new TestRequest(1)); handlerBlocker.awaitRequestToArrive(); // send second request and verify response final CompletableFuture<TestResponse> response2 = sendRequestToTestHandler(new TestRequest(2)); assertEquals(2, response2.get().id); // wake up blocked handler handlerBlocker.unblockRequest(); // verify response to first request assertEquals(1, response1.get().id); }
From source file:org.apache.flink.runtime.rest.RestServerEndpointITCase.java
/** * Tests that responses larger than {@link #TEST_REST_MAX_CONTENT_LENGTH} are rejected. *//*ww w . j av a 2 s. co m*/ @Test public void testShouldRespectMaxContentLengthLimitForResponses() throws Exception { testHandler.handlerBody = id -> CompletableFuture .completedFuture(new TestResponse(id, createStringOfSize(TEST_REST_MAX_CONTENT_LENGTH))); try { sendRequestToTestHandler(new TestRequest(1)).get(); fail("Expected exception not thrown"); } catch (final ExecutionException e) { final Throwable throwable = ExceptionUtils.stripExecutionException(e); assertThat(throwable, instanceOf(TooLongFrameException.class)); assertThat(throwable.getMessage(), containsString("Try to raise")); } }
From source file:org.apache.hadoop.hbase.AsyncMetaTableAccessor.java
public static CompletableFuture<Boolean> tableExists(RawAsyncTable metaTable, TableName tableName) { if (tableName.equals(META_TABLE_NAME)) { return CompletableFuture.completedFuture(true); }//w w w . j av a 2 s .c o m return getTableState(metaTable, tableName).thenApply(Optional::isPresent); }
From source file:org.apache.hadoop.hbase.client.AsyncMetaRegionLocator.java
CompletableFuture<HRegionLocation> getRegionLocation() { for (;;) {// w w w . j a va2s. co m HRegionLocation metaRegionLocation = this.metaRegionLocation.get(); if (metaRegionLocation != null) { return CompletableFuture.completedFuture(metaRegionLocation); } if (LOG.isTraceEnabled()) { LOG.trace("Meta region location cache is null, try fetching from registry."); } if (metaRelocateFuture.compareAndSet(null, new CompletableFuture<>())) { if (LOG.isDebugEnabled()) { LOG.debug("Start fetching meta region location from registry."); } CompletableFuture<HRegionLocation> future = metaRelocateFuture.get(); registry.getMetaRegionLocation().whenComplete((locs, error) -> { if (error != null) { if (LOG.isDebugEnabled()) { LOG.debug("Failed to fetch meta region location from registry", error); } metaRelocateFuture.getAndSet(null).completeExceptionally(error); return; } HRegionLocation loc = locs.getDefaultRegionLocation(); if (LOG.isDebugEnabled()) { LOG.debug("The fetched meta region location is " + loc); } // Here we update cache before reset future, so it is possible that someone can get a // stale value. Consider this: // 1. update cache // 2. someone clear the cache and relocate again // 3. the metaRelocateFuture is not null so the old future is used. // 4. we clear metaRelocateFuture and complete the future in it with the value being // cleared in step 2. // But we do not think it is a big deal as it rarely happens, and even if it happens, the // caller will retry again later, no correctness problems. this.metaRegionLocation.set(loc); metaRelocateFuture.set(null); future.complete(loc); }); } else { CompletableFuture<HRegionLocation> future = metaRelocateFuture.get(); if (future != null) { return future; } } } }
From source file:org.apache.hadoop.hbase.client.AsyncNonMetaRegionLocator.java
private CompletableFuture<HRegionLocation> getRegionLocationInternal(TableName tableName, byte[] row, RegionLocateType locateType) {/*w w w . j av a 2 s . co m*/ // AFTER should be convert to CURRENT before calling this method assert !locateType.equals(RegionLocateType.AFTER); TableCache tableCache = getTableCache(tableName); HRegionLocation loc = locateInCache(tableCache, tableName, row, locateType); if (loc != null) { return CompletableFuture.completedFuture(loc); } CompletableFuture<HRegionLocation> future; LocateRequest req; boolean sendRequest = false; synchronized (tableCache) { // check again loc = locateInCache(tableCache, tableName, row, locateType); if (loc != null) { return CompletableFuture.completedFuture(loc); } req = new LocateRequest(row, locateType); future = tableCache.allRequests.get(req); if (future == null) { future = new CompletableFuture<>(); tableCache.allRequests.put(req, future); if (tableCache.hasQuota(maxConcurrentLocateRequestPerTable) && !tableCache.isPending(req)) { tableCache.send(req); sendRequest = true; } } } if (sendRequest) { locateInMeta(tableName, req); } return future; }
From source file:org.apache.hadoop.hbase.client.example.AsyncClientExample.java
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "NP_NONNULL_PARAM_VIOLATION", justification = "it is valid to pass NULL to CompletableFuture#completedFuture") private CompletableFuture<Void> closeConn() { CompletableFuture<AsyncConnection> f = future.get(); if (f == null) { return CompletableFuture.completedFuture(null); }//from ww w . j a v a 2s .c om CompletableFuture<Void> closeFuture = new CompletableFuture<>(); addListener(f, (conn, error) -> { if (error == null) { IOUtils.closeQuietly(conn); } closeFuture.complete(null); }); return closeFuture; }
From source file:org.apache.hadoop.hbase.client.RawAsyncHBaseAdmin.java
@Override public CompletableFuture<Boolean> tableExists(TableName tableName) { if (TableName.isMetaTableName(tableName)) { return CompletableFuture.completedFuture(true); }/*from w ww. j a v a 2 s. c o m*/ return AsyncMetaTableAccessor.tableExists(metaTable, tableName); }