当前位置: 首页>>代码示例>>Java>>正文


Java DefaultPromise类代码示例

本文整理汇总了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();
}
 
开发者ID:HubSpot,项目名称:NioSmtpClient,代码行数:23,代码来源:SmtpSessionTest.java

示例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]);
}
 
开发者ID:wuyinxian124,项目名称:netty4.0.27Learn,代码行数:27,代码来源:ThreadPerChannelEventLoopGroupTest.java

示例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());
            }
          }
        }
      });
}
 
开发者ID:xjdr,项目名称:xio,代码行数:19,代码来源:XioConnectionPool.java

示例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());
                }
              });
}
 
开发者ID:xjdr,项目名称:xio,代码行数:17,代码来源:UnpooledNode.java

示例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;
}
 
开发者ID:xjdr,项目名称:xio,代码行数:27,代码来源:UnpooledNode.java

示例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());
}
 
开发者ID:opendaylight,项目名称:bgpcep,代码行数:20,代码来源:FiniteStateMachineTest.java

示例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;
}
 
开发者ID:pmarches,项目名称:peercentrum-core,代码行数:21,代码来源:NetworkClientTCPConnection.java

示例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;
}
 
开发者ID:pmarches,项目名称:peercentrum-core,代码行数:21,代码来源:NetworkClientTCPConnection.java

示例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();
}
 
开发者ID:lettuce-io,项目名称:lettuce-core,代码行数:20,代码来源:FuturesTest.java

示例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());
    }
}
 
开发者ID:nailed,项目名称:nailed,代码行数:27,代码来源:NailedMapLoader.java

示例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;
}
 
开发者ID:nailed,项目名称:nailed,代码行数:18,代码来源:NailedScheduler.java

示例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;
    }
 
开发者ID:talentchain,项目名称:talchain,代码行数:15,代码来源:NetStore.java

示例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();
}
 
开发者ID:HubSpot,项目名称:NioSmtpClient,代码行数:16,代码来源:SmtpSessionTest.java

示例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());
}
 
开发者ID:SecureSmartHome,项目名称:SecureSmartHome,代码行数:34,代码来源:ServerTest.java

示例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;
}
 
开发者ID:rollenholt-SourceReading,项目名称:redisson,代码行数:34,代码来源:CommandExecutorService.java


注:本文中的io.netty.util.concurrent.DefaultPromise类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。