@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(); }
@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]); }
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()); } } } }); }
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()); } }); }
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; }
/** * 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()); }
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; }
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; }
@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(); }
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()); } }
@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; }
@Nonnull @Override public <T> Future<T> submitSync(@Nonnull final Callable<T> task) { final DefaultPromise<T> future = new DefaultPromise<T>(this.executor.next()); this.executionQueue.add(new Runnable() { @Override public void run() { try{ future.setSuccess(task.call()); }catch(Exception e){ future.setFailure(e); } } }); return future; }
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; }
@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(); }
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()); }
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; }
public <T, R> Future<R> allAsync(boolean readOnlyMode, RedisCommand<T> command, final SlotCallback<T, R> callback, Object ... params) { final Promise<R> mainPromise = connectionManager.newPromise(); Promise<T> promise = new DefaultPromise<T>() { AtomicInteger counter = new AtomicInteger(connectionManager.getEntries().keySet().size()); @Override public Promise<T> setSuccess(T result) { if (callback != null) { callback.onSlotResult(result); } if (counter.decrementAndGet() == 0) { if (callback != null) { mainPromise.setSuccess(callback.onFinish()); } else { mainPromise.setSuccess(null); } } return this; } @Override public Promise<T> setFailure(Throwable cause) { mainPromise.setFailure(cause); return this; } }; for (Integer slot : connectionManager.getEntries().keySet()) { async(readOnlyMode, slot, null, connectionManager.getCodec(), command, params, promise, 0); } return mainPromise; }
public <T, R> Future<R> evalAllAsync(boolean readOnlyMode, RedisCommand<T> command, final SlotCallback<T, R> callback, String script, List<Object> keys, Object ... params) { final Promise<R> mainPromise = connectionManager.newPromise(); Promise<T> promise = new DefaultPromise<T>() { AtomicInteger counter = new AtomicInteger(connectionManager.getEntries().keySet().size()); @Override public Promise<T> setSuccess(T result) { callback.onSlotResult(result); if (counter.decrementAndGet() == 0 && !mainPromise.isDone()) { mainPromise.setSuccess(callback.onFinish()); } return this; } @Override public Promise<T> setFailure(Throwable cause) { mainPromise.setFailure(cause); return this; } }; List<Object> args = new ArrayList<Object>(2 + keys.size() + params.length); args.add(script); args.add(keys.size()); args.addAll(keys); args.addAll(Arrays.asList(params)); for (Integer slot : connectionManager.getEntries().keySet()) { async(readOnlyMode, slot, null, connectionManager.getCodec(), command, args.toArray(), promise, 0); } return mainPromise; }
@Override public Subscriber<Long> createSubscriber(WhiteboxSubscriberProbe<Long> probe) { final ClosedLoopChannel channel = new ClosedLoopChannel(); channel.config().setAutoRead(false); ChannelFuture registered = eventLoop.register(channel); final HandlerSubscriber<Long> subscriber = new HandlerSubscriber<>(registered.channel().eventLoop(), 2, 4); final ProbeHandler<Long> probeHandler = new ProbeHandler<>(probe, Long.class); final Promise<Void> handlersInPlace = new DefaultPromise<>(eventLoop.next()); registered.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { channel.pipeline().addLast("probe", probeHandler); channel.pipeline().addLast("subscriber", subscriber); handlersInPlace.setSuccess(null); // Channel needs to be active before the subscriber starts responding to demand channel.pipeline().fireChannelActive(); } }); if (workAroundIssue277) { try { // Wait for the pipeline to be setup, so we're ready to receive elements even if they aren't requested, // because https://github.com/reactive-streams/reactive-streams-jvm/issues/277 handlersInPlace.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } } return probeHandler.wrap(subscriber); }
@Override public boolean uninstall() { if (channelFuture instanceof DefaultPromise) { ((DefaultPromise) channelFuture).setUncancellable(); } bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); if(isOpenFlashPolicy){ flashPolicyServer.shutdown(); } return true; }
public void shutdown(){ if (channelFuture instanceof DefaultPromise) { ((DefaultPromise) channelFuture).setUncancellable(); } bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); }
@Test @SuppressWarnings("deprecation") public void makeContextAwareFutureListener() { RequestContext context = createContext(); Promise<String> promise = new DefaultPromise<>(ImmediateEventExecutor.INSTANCE); promise.addListener(context.makeContextAware((FutureListener<String>) f -> { assertCurrentContext(context); assertDepth(1); assertThat(f.getNow()).isEqualTo("success"); })); promise.setSuccess("success"); }
@Override public Promise<Boolean> release(EventExecutorGroup eventLoopGroup, long quietPeriod, long timeout, TimeUnit unit) { DefaultPromise<Boolean> result = new DefaultPromise<Boolean>(ImmediateEventExecutor.INSTANCE); result.setSuccess(true); return result; }
public Future<Void> send(Object message) { DefaultPromise<Void> promise = new DefaultPromise<>(eventLoopGroup.next()); log.debug("Acquiring Node: " + this); Future<Channel> channelResult = connectionPool.acquire(); channelResult.addListener( new FutureListener<Channel>() { public void operationComplete(Future<Channel> future) { if (future.isSuccess()) { Channel channel = future.getNow(); channel .writeAndFlush(message) .addListener( new ChannelFutureListener() { public void operationComplete(ChannelFuture channelFuture) { if (channelFuture.isSuccess()) { log.debug("write finished for " + message); promise.setSuccess(null); } else { log.error("Write error: ", channelFuture.cause()); promise.setFailure(channelFuture.cause()); } } }); } else { log.error("Could not connect to client for write: " + future.cause()); promise.setFailure(future.cause()); } } }); return promise; }
synchronized ServerBootstrap createServerBootstrap(final ChannelPipelineInitializer initializer) { final ServerBootstrap b = new ServerBootstrap(); b.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel ch) { initializer.initializeChannel(ch, new DefaultPromise<>(PCEPDispatcherImpl.this.executor)); } }); b.option(ChannelOption.SO_BACKLOG, SOCKET_BACKLOG_SIZE); b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); if (Epoll.isAvailable()) { b.channel(EpollServerSocketChannel.class); b.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED); } else { b.channel(NioServerSocketChannel.class); } if (!this.keys.isEmpty()) { if (Epoll.isAvailable()) { b.option(EpollChannelOption.TCP_MD5SIG, this.keys); } else { throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause()); } } // Make sure we are doing round-robin processing b.childOption(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1)); if (b.config().group() == null) { b.group(this.bossGroup, this.workerGroup); } return b; }
@Before public void setup() { final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.Open localPrefs = new OpenBuilder().setKeepalive( (short) 1).build(); this.serverSession = new DefaultPCEPSessionNegotiator(new DefaultPromise<>(GlobalEventExecutor.INSTANCE), this.channel, this.listener, (short) 1, 20, localPrefs); this.tlsSessionNegotiator = new DefaultPCEPSessionNegotiator(new DefaultPromise<>(GlobalEventExecutor.INSTANCE), this.channel, this.listener, (short) 1, 20, localPrefs, new TlsBuilder().build()); }
static ChannelHandler createServerChannelHandler(final ChannelPipelineInitializer initializer) { return new ChannelInitializer<SocketChannel>() { @Override @SuppressWarnings("unchecked") protected void initChannel(final SocketChannel channel) { initializer.initializeChannel(channel, new DefaultPromise<BGPSessionImpl>(GlobalEventExecutor.INSTANCE)); } }; }
@Test public void testDenyPeer() { this.clientSession = new BGPClientSessionNegotiator(new DefaultPromise<>(GlobalEventExecutor.INSTANCE), this.speakerListener, new StrictBGPPeerRegistry()); this.clientSession.channelActive(null); assertEquals(1, this.receivedMsgs.size()); assertTrue(this.receivedMsgs.get(0) instanceof Notify); }
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { HeaderAndPayload headerAndPayloadRead = (HeaderAndPayload) msg; int requestNumber=headerAndPayloadRead.header.getRequestNumber(); DefaultPromise<ByteBuf> responseFuture=pendingRequests.remove(requestNumber); if(responseFuture==null){ LOGGER.error("No pending request "+requestNumber); return; } responseFuture.setSuccess(headerAndPayloadRead.payload); }
public DefaultPromise<DHTSearch> searchNetwork(final KIdentifier idToSearch) { DHTSearch search=new DHTSearch(idToSearch); DefaultPromise<DHTSearch> promise = new DefaultPromise<DHTSearch>(){ }; //TODO run this in another thread search.addClosestNodes(buckets.getClosestNodeTo(search.searchedKey, 3)); //Prime the search with the local nodes.. while(search.isDone()==false){ performOneSearchIteration(search); } promise.setSuccess(search); return promise; }
@Test public void test() throws Exception { // TransientMockNetworkOfNodes mockNetwork=new TransientMockNetworkOfNodes(); PermanentMockNetwork mockNetwork=new PermanentMockNetwork(); SelfRegistrationDHT dht0=(SelfRegistrationDHT) mockNetwork.server[0].getApplicationHandler(SelfRegistrationDHT.APP_ID); DHTClient client0=dht0.dhtClient; // assertEquals(dht0.dhtClient.buckets.size(), mockNetwork.server[0].getNodeDatabase().size()); KIdentifier server1=new KIdentifier(mockNetwork.server[1].getLocalIdentifier()); List<KIdentifier> oneNode=client0.buckets.getClosestNodeTo(server1, 3); assertEquals(1, oneNode.size()); DefaultPromise<DHTSearch> searchNode0 = client0.searchNetwork(server1); assertTrue(searchNode0.get().isDone()); assertTrue(searchNode0.get().foundNode); assertNull(searchNode0.get().foundValue); KIdentifier server5=new KIdentifier(mockNetwork.server[5].getLocalIdentifier()); DefaultPromise<DHTSearch> searchNode5 = client0.searchNetwork(server5); assertTrue(searchNode5.get().isDone()); assertTrue(searchNode5.get().foundNode); assertNull(searchNode5.get().foundValue); KIdentifier storedKey1=new KIdentifier(PermanentMockNetwork.STORED_KEY1); DefaultPromise<DHTSearch> searchStoredKey1 = client0.searchNetwork(storedKey1); assertTrue(searchStoredKey1.get().isDone()); assertFalse(searchStoredKey1.get().foundNode); assertNotNull(searchStoredKey1.get().foundValue); }
@Test(expected = IllegalStateException.class) public void expectAfterArmed() { Futures.PromiseAggregator<Boolean, Promise<Boolean>> sut = new Futures.PromiseAggregator<>(new DefaultPromise<>( ImmediateEventExecutor.INSTANCE)); sut.arm(); sut.expectMore(1); }
@Test(expected = IllegalStateException.class) public void armTwice() { Futures.PromiseAggregator<Boolean, Promise<Boolean>> sut = new Futures.PromiseAggregator<>(new DefaultPromise<>( ImmediateEventExecutor.INSTANCE)); sut.arm(); sut.arm(); }
@Override public Promise<Boolean> release(EventExecutorGroup eventLoopGroup, long quietPeriod, long timeout, TimeUnit unit) { DefaultPromise<Boolean> result = new DefaultPromise<>(ImmediateEventExecutor.INSTANCE); result.setSuccess(true); return result; }
@Nonnull @Override public Future<Map> createMapFor(@Nonnull final Mappack mappack) { final int id = nextMapId.getAndIncrement(); final Promise<Map> allDonePromise = new DefaultPromise<Map>(NailedScheduler.instance().getExecutor().next()); final Promise<Void> finishPromise = new DefaultPromise<Void>(NailedScheduler.instance().getExecutor().next()); finishPromise.addListener(new FutureListener<Void>() { @Override public void operationComplete(Future<Void> future){ if(future.isSuccess()){ NailedScheduler.instance().executeSync(new Runnable() { @Override public void run() { NailedMap map = new NailedMap(id, mappack, new File(mapsDir, "map_" + id)); registerMap(map); loadMappackWorlds(map, mappack, "map_" + id); allDonePromise.setSuccess(map); } }); }else{ logger.warn("Loading of map " + mappack.getId() + "_" + id + " with mappack " + mappack.toString() + " failed. ", future.cause()); } } }); NailedScheduler.instance().submit(new Runnable(){ @Override public void run(){ File dir = new File(mapsDir, "map_" + id); dir.mkdir(); mappack.prepareWorld(dir, finishPromise); } }); return allDonePromise; }
Plugin(Project project, Revision revision, String path) throws Exception { requireNonNull(project, "project"); requireNonNull(revision, "revision"); requireNonNull(path, "path"); // Initialize the __UNSAFE__. engine.eval(SCRIPT_UNSAFE); // Provide the properties required to the plugin via the __UNSAFE__. unsafe = (ScriptObjectMirror) engine.get("__UNSAFE__"); unsafe.put("pluginRepository", project.metaRepo()); unsafe.put("pluginRevision", revision); unsafe.put("pluginPath", path); unsafe.put("eventLoop", jsEventLoop); final Logger pluginLogger = LoggerFactory.getLogger(loggerName(path)); unsafe.put("logger", pluginLogger); // Provide the promise to fulfill when plugin has been loaded completely. final String pluginInitPromiseKey = "pluginInitPromise"; final Promise<ScriptObjectMirror> pluginInitPromise = new DefaultPromise<>(jsEventLoop); unsafe.put(pluginInitPromiseKey, pluginInitPromise); // Run everything in the event loop from now on. jsEventLoop.submit(() -> { pluginLogger.info("Loading plugin: {} (revision: {})", path, revision.text()); // Polyfills for Nashorn engine.eval(SCRIPT_POLYFILL_CONSOLE); engine.eval(SCRIPT_POLYFILL_TIMEOUT); // Load require.js engine.eval(SCRIPT_REQUIRE); engine.eval(SCRIPT_REQUIRE_OVERRIDES); // Start the plugin up. engine.eval(SCRIPT_STARTUP); return null; }).syncUninterruptibly(); // Wait until all require()s are loaded. plugin = pluginInitPromise.syncUninterruptibly().getNow(); }
private DefaultPromise<WriteResult> writeResult() { return new DefaultPromise<WriteResult>(eventLoopGroup.next()); }