當前位置: 首頁>>代碼示例>>Java>>正文


Java Future.setHandler方法代碼示例

本文整理匯總了Java中io.vertx.core.Future.setHandler方法的典型用法代碼示例。如果您正苦於以下問題:Java Future.setHandler方法的具體用法?Java Future.setHandler怎麽用?Java Future.setHandler使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在io.vertx.core.Future的用法示例。


在下文中一共展示了Future.setHandler方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: connect

import io.vertx.core.Future; //導入方法依賴的package包/類
@Override
public RpcClient connect(final JsonObject config,
                         final JsonObject data,
                         final Handler<AsyncResult<JsonObject>> handler) {
    final Record record = RpcHelper.getRecord(config);
    // Service Configuration
    final String name = config.getString(Key.NAME);
    final String address = config.getString(Key.ADDR);

    final JsonObject normalized = RpcHelper.normalize(name, config, record);
    this.holder = lookupHolder(this.vertx, name, normalized);
    // Get Channel
    final IpcType type = Types.fromStr(IpcType.class, config.getString(Key.TYPE));
    final RpcStub stub = getStub(type);
    // Future result return to client.
    final IpcData request = new IpcData();
    request.setType(type);
    request.setAddress(address);
    // The same operation for request.
    DataEncap.in(request, record);
    DataEncap.in(request, Envelop.success(data));
    LOGGER.info(Info.CLIENT_TRAFFIC, request.toString());
    final Future<JsonObject> future = stub.traffic(request);
    future.setHandler(res -> handler.handle(Future.succeededFuture(res.result())));
    return this;
}
 
開發者ID:silentbalanceyh,項目名稱:vertx-zero,代碼行數:27,代碼來源:RpcClientImpl.java

示例2: doSync

import io.vertx.core.Future; //導入方法依賴的package包/類
/**
 * Perform operations synchronously and wait for those operations to finish for a number of seconds.
 *
 * @param consumer Used to signal that the return result of this method is ready and can be
 *     returned from the function in a normal procedural style.
 * @param wait The number of seconds to wait for the operations to complete or null which will
 *     wait forever.
 * @param <T> The type that will be returned from the method i.e. the type produced by the
 *     consumer.
 * @return Returns the specified type of <T> if the consumer produces a result successfully, if
 *     the consumer fails then null will be returned.
 * @throws InterruptedException Due to the mechanics of {@code CountDownLatch}, a interrupt may be
 *     signalled, see {@link CountDownLatch}.
 */
public static <T> T doSync(Consumer<Future<T>> consumer, Integer wait)
    throws InterruptedException {
  AtomicReference<T> reference = new AtomicReference<>();
  final CountDownLatch countDownLatch = new CountDownLatch(1);
  final Future<T> callbackFuture = Future.future();
  consumer.accept(callbackFuture);

  callbackFuture.setHandler(
      e -> {
        if (e.succeeded()) {
          reference.set(e.result());
        }
        countDownLatch.countDown();
      });

  if (wait == null) {
    countDownLatch.await();
  } else {
    countDownLatch.await(wait, TimeUnit.SECONDS);
  }

  return reference.get();
}
 
開發者ID:StephenFox1995,項目名稱:vertx-sync,代碼行數:38,代碼來源:Sync.java

示例3: test_helloWorld

import io.vertx.core.Future; //導入方法依賴的package包/類
@Test
public void test_helloWorld(TestContext context) {
	Async async = context.async();
	
	GraphQLObjectType query = GraphQLObjectType.newObject()
	        .name("query")
	        .field(GraphQLFieldDefinition.newFieldDefinition()
	                .name("hello")
	                .type(Scalars.GraphQLString)
	                .dataFetcher(environment -> {
	        			return "world";
	        		}))
	        .build(); 
	
	GraphQLSchema schema = GraphQLSchema.newSchema()
			.query(query)
			.build();
	
	AsyncGraphQLExec asyncGraphQL = AsyncGraphQLExec.create(schema);
	Future<JsonObject> queryResult = asyncGraphQL.executeQuery("query { hello }", null, null, null);
	queryResult.setHandler(res -> {
		JsonObject json = res.result();
		context.assertEquals(new JsonObject().put("hello", "world"), json);
		async.complete();
	});
}
 
開發者ID:tibor-kocsis,項目名稱:vertx-graphql-utils,代碼行數:27,代碼來源:AsyncGraphQLExecTest.java

示例4: consumeWeatherData

import io.vertx.core.Future; //導入方法依賴的package包/類
/**
 * consumeWeatherData connects the WeatherDataConsumer to the hono server to read from TENANT_ID.
 * @throws Exception N/A
 */
private void consumeWeatherData() throws Exception {
    final Future<MessageConsumer> consumerFuture = Future.future();

    consumerFuture.setHandler(result -> {
        if (!result.succeeded()) {
            System.err.println("honoClient could not create telemetry consumer : " + result.cause());
        }
        latch.countDown();
    });

    final Future<HonoClient> connectionTracker = Future.future();

    honoClient.connect(new ProtonClientOptions(), connectionTracker.completer());

    connectionTracker.compose(honoClient -> {
                honoClient.createTelemetryConsumer(TENANT_ID,
                        msg -> handleWeatherMessage(msg), consumerFuture.completer());
            },
            consumerFuture);

    latch.await();
    //If consumer connects, then reads information.
    if (consumerFuture.succeeded())
        System.in.read();
    //Closes AMQP connection with hono server.
    vertx.close();
}
 
開發者ID:rhiot,項目名稱:hono-weather-demo,代碼行數:32,代碼來源:WeatherDataConsumer.java

示例5: testDeployInvalidConfig

import io.vertx.core.Future; //導入方法依賴的package包/類
@Test
public void testDeployInvalidConfig(TestContext testContext) throws Exception {
	Future<Void> future = Future.future();

	future.setHandler(testContext.asyncAssertFailure(res -> {
		Assert.assertFalse(vtxDeployer.isVertxSetup());
		Assert.assertTrue("Non-existing configuration", Exception.class.isInstance(res));
	}));

	vtxDeployer.setup("sample/non-existing.json", future);
}
 
開發者ID:mustertech,項目名稱:rms-deployer,代碼行數:12,代碼來源:VtxDeployerTest.java

示例6: getServiceRef

import io.vertx.core.Future; //導入方法依賴的package包/類
void getServiceRef(JsonObject filter, String breakerName, Handler<AsyncResult<LookupResult>> handler) {
  if (breakerName != null) {
    CircuitBreaker breaker = breakerMap.computeIfAbsent(breakerName, createBreaker);
    AtomicBoolean resolved = new AtomicBoolean();
    Future<Void> f = breaker.execute(fut -> getServiceRef(filter, ar -> {
      resolved.set(true);
      if (ar.succeeded()) {
        handler.handle(Future.succeededFuture(new LookupResult(fut, ar.result())));
      } else {
        fut.fail(ar.cause());
        handler.handle(Future.failedFuture(ar.cause()));
      }
    }));
    f.setHandler(ar -> {
      if (resolved.compareAndSet(false, true)) {
        handler.handle(ar.map(null));
      }
    });
  } else {
    getServiceRef(filter, ar -> {
      if (ar.succeeded()) {
        handler.handle(Future.succeededFuture(new LookupResult(null, ar.result())));
      } else {
        handler.handle(Future.failedFuture(ar.cause()));
      }
    });
  }
}
 
開發者ID:vietj,項目名稱:vertx-service-flow,代碼行數:29,代碼來源:FlowImpl.java

示例7: test_helloWorldCollectionAsync

import io.vertx.core.Future; //導入方法依賴的package包/類
@Test
public void test_helloWorldCollectionAsync(TestContext context) {
	Async async = context.async();
	
	AsyncDataFetcher<List<String>> asyncDataFetcher = (env, handler) -> {
		vertx.<List<String>> executeBlocking(fut -> {
			fut.complete(Arrays.asList("a", "b", "c"));
		}, handler);
	};
	
	GraphQLObjectType query = GraphQLObjectType.newObject()
	        .name("query")
	        .field(GraphQLFieldDefinition.newFieldDefinition()
	                .name("helloList")
	                .type(new GraphQLList(Scalars.GraphQLString))
	                .dataFetcher(asyncDataFetcher))
	        .build(); 
	
	GraphQLSchema schema = GraphQLSchema.newSchema()
			.query(query)
			.build();
	
	AsyncGraphQLExec asyncGraphQL = AsyncGraphQLExec.create(schema);
	Future<JsonObject> queryResult = asyncGraphQL.executeQuery("query { helloList }", null, null, null);
	queryResult.setHandler(res -> {
		JsonObject json = res.result();
		JsonArray jsonArray = json.getJsonArray("helloList");
		JsonArray expected = new JsonArray(Arrays.asList("a", "b", "c"));
		context.assertEquals(expected, jsonArray);
		async.complete();
	});
}
 
開發者ID:tibor-kocsis,項目名稱:vertx-graphql-utils,代碼行數:33,代碼來源:AsyncGraphQLExecTest.java

示例8: test_failureSimpleDataFetcher

import io.vertx.core.Future; //導入方法依賴的package包/類
@Test
	public void test_failureSimpleDataFetcher(TestContext context) {
		Async async = context.async();
		
		GraphQLObjectType query = GraphQLObjectType.newObject()
		        .name("query")
		        .field(GraphQLFieldDefinition.newFieldDefinition()
		                .name("hello")
		                .type(Scalars.GraphQLString)
		                .dataFetcher(environment -> {
		        			throw new RuntimeException("TestFailure");
		        		}))
		        .build(); 
		
		GraphQLSchema schema = GraphQLSchema.newSchema()
				.query(query)
				.build();
		
		AsyncGraphQLExec asyncGraphQL = AsyncGraphQLExec.create(schema);
		Future<JsonObject> queryResult = asyncGraphQL.executeQuery("query { hello }", null, null, null);
		queryResult.setHandler(res -> {
			context.assertTrue(res.failed());
			context.assertEquals(AsyncExecutionException.class, res.cause().getClass());
			List<GraphQLError> errors = ((AsyncExecutionException) res.cause()).getErrors();
//			System.out.println(errors);
			context.assertEquals(1, errors.size());
			context.assertEquals(ExceptionWhileDataFetching.class, errors.get(0).getClass());
			context.assertEquals("TestFailure", ((ExceptionWhileDataFetching) errors.get(0)).getException().getMessage());
			
			async.complete();
		});
	}
 
開發者ID:tibor-kocsis,項目名稱:vertx-graphql-utils,代碼行數:33,代碼來源:AsyncGraphQLExecTest.java

示例9: authorise

import io.vertx.core.Future; //導入方法依賴的package包/類
/**
	 * 訪問控製的邏輯:
	 * 當某個用戶訪問某個資源的時候,如果有權限訪問,那麽直接返回一個true的字符串,其它結果都會認為是無權訪問
	 * @param user
	 * @param permission
	 * @param h
	 */
	public void authorise(User user,String permission, Handler<AsyncResult<Boolean>> h){
		
		String uri = authMgr.getAuthorisationUrl();
				
		App authapp = authMgr.authApp;
		JsonObject pricipal = user.principal().copy();
		
		pricipal.put("permission", authapp.offsetUrl(permission));
//		System.out.println("authorise uri: "+uri);
		Future<HttpResponse<Buffer>> fu = authMgr.authApp.doGet(uri, pricipal);
		fu.setHandler(res->{
			if(res.succeeded()){
				HttpResponse<Buffer> appResponse = res.result();
				
				String u = appResponse.bodyAsString();
				
				if("true".equalsIgnoreCase(u))
					h.handle(Future.succeededFuture(true));
				else
					h.handle(Future.succeededFuture(false));
			}else{
				h.handle(Future.failedFuture(res.cause()));
			}
		});
		
		
	}
 
開發者ID:troopson,項目名稱:etagate,代碼行數:35,代碼來源:GateAuthProvider.java

示例10: test_invalidQuery

import io.vertx.core.Future; //導入方法依賴的package包/類
@Test
	public void test_invalidQuery(TestContext context) {
		Async async = context.async();
		
		// complete the execution with a failedFuture
		AsyncDataFetcher<String> asyncDataFetcher = (env, handler) -> {
			handler.handle(Future.failedFuture(new RuntimeException("TestFailure")));
		};
		
		GraphQLObjectType query = GraphQLObjectType.newObject()
		        .name("query")
		        .field(GraphQLFieldDefinition.newFieldDefinition()
		                .name("hello")
		                .type(Scalars.GraphQLString)
		                .dataFetcher(asyncDataFetcher))
		        .build(); 
		
		GraphQLSchema schema = GraphQLSchema.newSchema()
				.query(query)
				.build();
		
		AsyncGraphQLExec asyncGraphQL = AsyncGraphQLExec.create(schema);
		Future<JsonObject> queryResult = asyncGraphQL.executeQuery("query { hello ", null, null, null);
		queryResult.setHandler(res -> {
			context.assertTrue(res.failed());
			context.assertEquals(AsyncExecutionException.class, res.cause().getClass());
			List<GraphQLError> errors = ((AsyncExecutionException) res.cause()).getErrors();
//			System.out.println(errors);
			context.assertEquals(1, errors.size());
			context.assertEquals(InvalidSyntaxError.class, errors.get(0).getClass());
			async.complete();
		});
	}
 
開發者ID:tibor-kocsis,項目名稱:vertx-graphql-utils,代碼行數:34,代碼來源:AsyncGraphQLExecTest.java

示例11: testRepeatUndeployAll

import io.vertx.core.Future; //導入方法依賴的package包/類
@Test
public void testRepeatUndeployAll(TestContext testContext) throws Exception {
	Future<Void> future = Future.future();

	future.setHandler(testContext.asyncAssertFailure(res -> {
		Assert.assertFalse(vtxDeployer.isVertxSetup());
		Assert.assertTrue("Setup not done!", Exception.class.isInstance(res));
	}));

	vtxDeployer.undeployAll(future);
}
 
開發者ID:mustertech,項目名稱:rms-deployer,代碼行數:12,代碼來源:VtxDeployerTest.java

示例12: test_vertxCallbackAsyncTest

import io.vertx.core.Future; //導入方法依賴的package包/類
@Test
public void test_vertxCallbackAsyncTest(TestContext context) {
	Async async = context.async();
	
	context.assertTrue(vertx.getOrCreateContext().isEventLoopContext());
	long threadId = Thread.currentThread().getId();
	
	AsyncDataFetcher<String> asyncDataFetcher = (env, handler) -> {
		context.assertTrue(vertx.getOrCreateContext().isEventLoopContext());
		context.assertEquals(threadId, Thread.currentThread().getId());
		
		vertx.<String> executeBlocking(fut -> {
			context.assertNotEquals(threadId, Thread.currentThread().getId());
			fut.complete("world");
		}, handler);
	};
	
	GraphQLObjectType query = GraphQLObjectType.newObject()
	        .name("query")
	        .field(GraphQLFieldDefinition.newFieldDefinition()
	                .name("hello")
	                .type(Scalars.GraphQLString)
	                .dataFetcher(asyncDataFetcher))
	        .build(); 
	
	GraphQLSchema schema = GraphQLSchema.newSchema()
			.query(query)
			.build();
	
	AsyncGraphQLExec asyncGraphQL = AsyncGraphQLExec.create(schema);
	Future<JsonObject> queryResult = asyncGraphQL.executeQuery("query { hello }", null, null, null);
	queryResult.setHandler(res -> {
		context.assertTrue(vertx.getOrCreateContext().isEventLoopContext());
       	context.assertEquals(threadId, Thread.currentThread().getId());
		async.complete();
	});
}
 
開發者ID:tibor-kocsis,項目名稱:vertx-graphql-utils,代碼行數:38,代碼來源:VertxThreadTest.java

示例13: isComponentDeployed

import io.vertx.core.Future; //導入方法依賴的package包/類
/**
 * Check whether a component of given name, is deployed
 *
 * @param name   Name of the component to be checked for deployment
 * @param future Future to provide the status, whether the given component is deployed
 * @see <a href="http://vertx.io/docs/apidocs/io/vertx/core/Future.html" target="_blank">Future</a>
 */
public void isComponentDeployed(final String name, Future<Boolean> future) {
	Future<JsonObject> recFuture = Future.future();

	recFuture.setHandler(recRes -> {
		if (recRes.succeeded()) {
			future.complete(true);
			return;
		}

		future.complete(false);
	});

	this.deployRecords.getRecord(name, recFuture);
}
 
開發者ID:mustertech,項目名稱:rms-deployer,代碼行數:22,代碼來源:VtxDeployer.java

示例14: anotherStart

import io.vertx.core.Future; //導入方法依賴的package包/類
public void anotherStart(Future<Void> startFuture) throws Exception {
  // tag::another-start[]
  Future<Void> steps = prepareDatabase().compose(v -> startHttpServer());
  steps.setHandler(ar -> {  // <1>
    if (ar.succeeded()) {
      startFuture.complete();
    } else {
      startFuture.fail(ar.cause());
    }
  });
  // end::another-start[]
}
 
開發者ID:vert-x3,項目名稱:vertx-guide-for-java-devs,代碼行數:13,代碼來源:MainVerticle.java

示例15: testNoUndeploy

import io.vertx.core.Future; //導入方法依賴的package包/類
@Test
public void testNoUndeploy(TestContext testContext) throws Exception {
	Future<Void> setupFuture = Future.future();
	Future<Void> deployFuture = Future.future();
	Future<Integer> countFuture = Future.future();
	Future<Boolean> isDeployedFuture = Future.future();

	isDeployedFuture.setHandler(testContext.asyncAssertSuccess(res -> {
		Assert.assertTrue(res.booleanValue());
	}));

	countFuture.setHandler(testContext.asyncAssertSuccess(res -> {
		Assert.assertEquals(2, res.longValue());
		vtxDeployer.isComponentDeployed("org.mustertech.rms.examples.basic.HelloVerticle1", isDeployedFuture);
	}));

	deployFuture.setHandler(testContext.asyncAssertSuccess(res -> {
		vtxDeployer.deploymentCount(countFuture);
	}));

	setupFuture.setHandler(testContext.asyncAssertSuccess(res -> {
		Assert.assertTrue(vtxDeployer.isVertxSetup());
		vtxDeployer.deployAll(deployFuture);
	}));

	vtxDeployer.setup("sample/no-cluster.json", setupFuture);
}
 
開發者ID:mustertech,項目名稱:rms-deployer,代碼行數:28,代碼來源:VtxDeployerTest.java


注:本文中的io.vertx.core.Future.setHandler方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。