本文整理汇总了Java中io.netty.util.concurrent.DefaultPromise类的典型用法代码示例。如果您正苦于以下问题:Java DefaultPromise类的具体用法?Java DefaultPromise怎么用?Java DefaultPromise使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
DefaultPromise类属于io.netty.util.concurrent包,在下文中一共展示了DefaultPromise类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: itReturnsTheStartTlsResponseIfTheTlsHandshakeSucceeds
import io.netty.util.concurrent.DefaultPromise; //导入依赖的package包/类
@Test
public void itReturnsTheStartTlsResponseIfTheTlsHandshakeSucceeds() throws Exception {
CompletableFuture<SmtpClientResponse> f = session.startTls();
responseFuture.complete(Lists.newArrayList(OK_RESPONSE));
// respond to the ehlo sent after starttls
secondResponseFuture.complete(Lists.newArrayList(new DefaultSmtpResponse(250,
"smtp.example.com Hello client.example.com",
"AUTH PLAIN LOGIN",
"PIPELINING")));
// the handshake succeeds
SslHandler sslHandler = getSslHandler();
((DefaultPromise<Channel>) sslHandler.handshakeFuture()).setSuccess(channel);
assertThat(f.isDone()).isTrue();
assertThat(f.get().getResponses().get(0).code()).isEqualTo(OK_RESPONSE.code());
// check EHLO is parsed again
assertThat(session.getEhloResponse().isSupported(Extension.PIPELINING)).isTrue();
assertThat(session.getEhloResponse().isSupported(Extension.STARTTLS)).isFalse();
}
示例2: testTerminationFutureSuccessReflectively
import io.netty.util.concurrent.DefaultPromise; //导入依赖的package包/类
@Test
public void testTerminationFutureSuccessReflectively() throws Exception {
Field terminationFutureField =
ThreadPerChannelEventLoopGroup.class.getDeclaredField("terminationFuture");
terminationFutureField.setAccessible(true);
final Exception[] exceptionHolder = new Exception[1];
for (int i = 0; i < 2; i++) {
ThreadPerChannelEventLoopGroup loopGroup = new ThreadPerChannelEventLoopGroup(64);
Promise<?> promise = new DefaultPromise<Void>(GlobalEventExecutor.INSTANCE) {
@Override
public Promise<Void> setSuccess(Void result) {
try {
return super.setSuccess(result);
} catch (IllegalStateException e) {
exceptionHolder[0] = e;
throw e;
}
}
};
terminationFutureField.set(loopGroup, promise);
runTest(loopGroup);
}
// The global event executor will not terminate, but this will give the test a chance to fail.
GlobalEventExecutor.INSTANCE.awaitTermination(100, TimeUnit.MILLISECONDS);
assertNull(exceptionHolder[0]);
}
示例3: acquireWithRetry
import io.netty.util.concurrent.DefaultPromise; //导入依赖的package包/类
private void acquireWithRetry(AsyncRetryLoop retry, DefaultPromise<Channel> result) {
Future<Channel> poolResult = simpleChannelPool.acquire();
poolResult.addListener(
new FutureListener<Channel>() {
public void operationComplete(Future<Channel> f) {
if (f.isSuccess()) {
result.setSuccess(f.getNow());
} else {
// deal with connection failure here.
if (retry.canRetry()) {
retry.attempt(() -> acquireWithRetry(retry, result));
} else {
result.setFailure(f.cause());
}
}
}
});
}
示例4: writeAndFlush
import io.netty.util.concurrent.DefaultPromise; //导入依赖的package包/类
private void writeAndFlush(Object message, DefaultPromise<Void> promise) {
Channel channel = channelResult.channel();
channel
.writeAndFlush(message)
.addListener(
(ChannelFutureListener)
channelFuture -> {
if (channelFuture.isSuccess()) {
log.debug("write finished for " + message);
promise.setSuccess(null);
} else {
log.error("Write error: ", channelFuture.cause());
promise.setFailure(channelFuture.cause());
}
});
}
示例5: send
import io.netty.util.concurrent.DefaultPromise; //导入依赖的package包/类
public Future<Void> send(Object message) {
DefaultPromise<Void> promise = new DefaultPromise<>(eventLoopGroup().next());
log.debug("Acquiring Node: " + this);
if (channelResult == null) {
channelResult = bootstrap.clone().connect();
}
if (channelResult.isSuccess()) {
writeAndFlush(message, promise);
} else {
channelResult.addListener(
(ChannelFutureListener)
channelFuture -> {
if (channelFuture.isSuccess()) {
log.debug("connection achieved " + message);
writeAndFlush(message, promise);
} else {
log.error("connection error: ", channelFuture.cause());
promise.setFailure(channelFuture.cause());
}
});
}
return promise;
}
示例6: testEstablishTLS
import io.netty.util.concurrent.DefaultPromise; //导入依赖的package包/类
/**
* Establish PCEPS TLS connection with peer
*/
@Test
public void testEstablishTLS() {
final DefaultPCEPSessionNegotiator negotiator = new DefaultPCEPSessionNegotiator(new DefaultPromise<>(GlobalEventExecutor.INSTANCE),
this.channel, this.listener, (short) 1, 20, new OpenBuilder().setKeepalive((short) 1).build(),
SslContextFactoryTest.createTlsConfig());
negotiator.channelActive(null);
assertEquals(1, this.msgsSend.size());
assertTrue(this.msgsSend.get(0) instanceof Starttls);
assertEquals(DefaultPCEPSessionNegotiator.State.START_TLS_WAIT, negotiator.getState());
negotiator.handleMessage(this.startTlsMsg);
assertEquals(DefaultPCEPSessionNegotiator.State.OPEN_WAIT, negotiator.getState());
assertEquals(2, this.msgsSend.size());
assertTrue(this.msgsSend.get(1) instanceof Open);
negotiator.handleMessage(this.openMsg);
assertEquals(DefaultPCEPSessionNegotiator.State.KEEP_WAIT, negotiator.getState());
}
示例7: sendRequestBytes
import io.netty.util.concurrent.DefaultPromise; //导入依赖的package包/类
public Future<ByteBuf> sendRequestBytes(ApplicationIdentifier destinationApp, ByteBuf applicationSpecificBytesToSend, boolean expectResponse) {
PB.HeaderMsg.Builder headerBuilder=PB.HeaderMsg.newBuilder();
headerBuilder.setDestinationApplicationId(ByteString.copyFrom(destinationApp.getBytes()));
int thisRequestNumber=requestNumberGenerator.incrementAndGet();
headerBuilder.setRequestNumber(thisRequestNumber);
DefaultPromise<ByteBuf> responseFuture = new DefaultPromise<ByteBuf>(socketChannelFuture.channel().eventLoop());
if(expectResponse){
pendingRequests.put(thisRequestNumber, responseFuture);
}
else{
responseFuture.setSuccess(Unpooled.EMPTY_BUFFER);
}
HeaderAndPayload headerAndPayload = new HeaderAndPayload(headerBuilder, applicationSpecificBytesToSend);
socketChannelFuture.syncUninterruptibly(); //wait for connection to be up //FIXME Is the Sync right???
socketChannelFuture.channel().writeAndFlush(headerAndPayload);
socketChannelFuture.channel().read();
return responseFuture;
}
示例8: sendRequestMsg
import io.netty.util.concurrent.DefaultPromise; //导入依赖的package包/类
public <T extends MessageLite> Future<T> sendRequestMsg(ApplicationIdentifier applicationId, MessageLite appSpecificRequestMsg, final Class<T> appSpecificResponseClass) {
ByteBuf appSpecificProtobufBytes=ProtobufByteBufCodec.encodeNoLengthPrefix(appSpecificRequestMsg);
Future<ByteBuf> responseBytesFuture = sendRequestBytes(applicationId, appSpecificProtobufBytes);
//FIXME should we release() something?
//FIXME Hum, is that the proper thread to do the decoding?
final DefaultPromise<T> responseFuture = new DefaultPromise<T>(GlobalEventExecutor.INSTANCE);
responseBytesFuture.addListener(new GenericFutureListener<Future<? super ByteBuf>>() {
@Override
public void operationComplete(Future<? super ByteBuf> future) throws Exception {
if(future.isSuccess()==false){
responseFuture.setFailure(future.cause());
return;
}
T decodedAppSpecificResponse=(T) ProtobufByteBufCodec.decodeNoLengthPrefix((ByteBuf) future.get(), appSpecificResponseClass);
responseFuture.setSuccess(decodedAppSpecificResponse);
}
});
return responseFuture;
}
示例9: regularUse
import io.netty.util.concurrent.DefaultPromise; //导入依赖的package包/类
@Test
public void regularUse() {
final DefaultPromise<Boolean> target = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
Futures.PromiseAggregator<Boolean, Promise<Boolean>> sut = new Futures.PromiseAggregator<>(
target);
sut.expectMore(1);
sut.arm();
DefaultPromise<Boolean> part = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
sut.add(part);
assertThat(target.isDone()).isFalse();
part.setSuccess(true);
Wait.untilTrue(target::isDone).waitOrTimeout();
assertThat(target.isDone()).isTrue();
}
示例10: createLobbyMap
import io.netty.util.concurrent.DefaultPromise; //导入依赖的package包/类
public NailedMap createLobbyMap(){
int id = nextMapId.getAndIncrement();
final Promise<Void> finishPromise = new DefaultPromise<Void>(NailedScheduler.instance().getExecutor().next());
final File baseDir = new File(mapsDir, "lobby");
NailedScheduler.instance().submit(new Runnable() {
@Override
public void run() {
baseDir.mkdir();
getLobbyMappack().prepareWorld(baseDir, finishPromise);
}
});
try{
finishPromise.get();
}catch(Exception e){
logger.error("Exception while waiting for the promise to finish", e);
}
NailedMap map = new NailedMap(id, getLobbyMappack(), baseDir);
if(finishPromise.isSuccess()){
this.registerMap(map);
this.loadMappackWorlds(map, getLobbyMappack(), "lobby");
return map;
}else{
logger.warn("Loading of map {} with mappack {} failed.", map, getLobbyMappack());
throw new MappackLoadingFailedException("Map loading failed", finishPromise.cause());
}
}
示例11: submitSync
import io.netty.util.concurrent.DefaultPromise; //导入依赖的package包/类
@Nonnull
@Override
public <T> Future<T> submitSync(@Nonnull final Runnable task, final T result) {
final DefaultPromise<T> future = new DefaultPromise<T>(this.executor.next());
this.executionQueue.add(new Runnable() {
@Override
public void run() {
try{
task.run();
future.setSuccess(result);
}catch(Exception e){
future.setFailure(e);
}
}
});
return future;
}
示例12: getAsync
import io.netty.util.concurrent.DefaultPromise; //导入依赖的package包/类
public synchronized Future<Chunk> getAsync(Key key) {
Chunk chunk = localStore.get(key);
Promise<Chunk> ret = new DefaultPromise<Chunk>() {};
if (chunk == null) {
// long timeout = 0; // TODO
ChunkRequest chunkRequest = new ChunkRequest();
chunkRequest.localRequesters.add(ret);
chunkRequestMap.put(key, chunkRequest);
startSearch(-1, key, timeout);
} else {
ret.setSuccess(chunk);
}
return ret;
}
示例13: itFailsTheFutureIfTheTlsHandshakeFails
import io.netty.util.concurrent.DefaultPromise; //导入依赖的package包/类
@Test
public void itFailsTheFutureIfTheTlsHandshakeFails() throws Exception {
CompletableFuture<SmtpClientResponse> f = session.startTls();
responseFuture.complete(Lists.newArrayList(OK_RESPONSE));
SslHandler sslHandler = getSslHandler();
// fail the handshake
Exception testException = new Exception();
((DefaultPromise<Channel>) sslHandler.handshakeFuture()).setFailure(testException);
assertThat(f.isCompletedExceptionally()).isTrue();
assertThatThrownBy(f::get).hasCause(testException);
verify(channel).close();
}
示例14: testSerialRoundTrip
import io.netty.util.concurrent.DefaultPromise; //导入依赖的package包/类
public void testSerialRoundTrip() throws InterruptedException, ExecutionException {
final BlockingQueue<Object> serverQueue = new LinkedBlockingQueue<>();
final BlockingQueue<Object> clientQueue = new LinkedBlockingQueue<>();
final Promise<SocketChannel> serverChannel = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
final Promise<SocketChannel> clientChannel = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
SimpleContainer serverContainer = new SimpleContainer();
addContext(serverContainer);
Server server = new TestServer(serverQueue, serverChannel);
serverContainer.register(UDPDiscoveryServer.KEY, new UDPDiscoveryServer());
serverContainer.register(Server.KEY, server);
try {
SimpleContainer clientContainer = new SimpleContainer();
addContext(clientContainer);
Client client = new TestClient(clientQueue, clientChannel);
clientContainer.register(UDPDiscoveryClient.KEY, new UDPDiscoveryClient());
clientContainer.register(Client.KEY, client);
try {
serverChannel.await(1000);
clientChannel.await(1000);
runRoundTripTests(serverQueue, clientQueue, serverChannel, clientChannel);
} finally {
clientContainer.unregister(Client.KEY);
client.awaitShutdown();
}
} finally {
shutdownServer(serverContainer);
}
assertTrue(serverQueue.isEmpty());
assertTrue(clientQueue.isEmpty());
}
示例15: readAllAsync
import io.netty.util.concurrent.DefaultPromise; //导入依赖的package包/类
public <T, R> Future<Collection<R>> readAllAsync(RedisCommand<T> command, Object ... params) {
final Promise<Collection<R>> mainPromise = connectionManager.newPromise();
Promise<R> promise = new DefaultPromise<R>() {
Queue<R> results = new ConcurrentLinkedQueue<R>();
AtomicInteger counter = new AtomicInteger(connectionManager.getEntries().keySet().size());
@Override
public Promise<R> setSuccess(R result) {
if (result instanceof Collection) {
results.addAll((Collection)result);
} else {
results.add(result);
}
if (counter.decrementAndGet() == 0
&& !mainPromise.isDone()) {
mainPromise.setSuccess(results);
}
return this;
}
@Override
public Promise<R> setFailure(Throwable cause) {
mainPromise.setFailure(cause);
return this;
}
};
for (Integer slot : connectionManager.getEntries().keySet()) {
async(true, slot, null, connectionManager.getCodec(), command, params, promise, 0);
}
return mainPromise;
}