Example usage for javax.net.ssl SSLEngine setUseClientMode

List of usage examples for javax.net.ssl SSLEngine setUseClientMode

Introduction

In this page you can find the example usage for javax.net.ssl SSLEngine setUseClientMode.

Prototype

public abstract void setUseClientMode(boolean mode);

Source Link

Document

Configures the engine to use client (or server) mode when handshaking.

Usage

From source file:com.chiorichan.http.ssl.SniNegotiator.java

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (!handshaken && in.readableBytes() >= 5) {
        String hostname = sniHostNameFromHandshakeInfo(in);
        if (hostname != null)
            hostname = IDN.toASCII(hostname, IDN.ALLOW_UNASSIGNED).toLowerCase(Locale.US);
        this.hostname = hostname;

        selectedContext = SslManager.instance().map(hostname);

        if (handshaken) {
            SSLEngine engine = selectedContext.newEngine(ctx.alloc());

            List<String> supportedCipherSuites = Arrays.asList(engine.getSupportedCipherSuites());

            if (!supportedCipherSuites.containsAll(enabledCipherSuites))
                for (String cipher : enabledCipherSuites)
                    if (!supportedCipherSuites.contains(cipher)) {
                        NetworkManager.getLogger()
                                .severe(String.format(
                                        "The SSL/TLS cipher suite '%s' is not supported by SSL Provider %s",
                                        cipher, SslContext.defaultServerProvider().name()));
                        enabledCipherSuites.remove(cipher);
                    }/*from w w  w .  j  a v a2 s .com*/

            engine.setUseClientMode(false);
            engine.setEnabledCipherSuites(enabledCipherSuites.toArray(new String[0]));

            ctx.pipeline().replace(this, ctx.name(), new SslExceptionHandler(engine));
        }
    }
}

From source file:org.apache.flink.runtime.webmonitor.WebRuntimeMonitor.java

public WebRuntimeMonitor(Configuration config, LeaderRetrievalService leaderRetrievalService,
        ActorSystem actorSystem) throws IOException, InterruptedException {

    this.leaderRetrievalService = checkNotNull(leaderRetrievalService);
    this.timeout = AkkaUtils.getTimeout(config);
    this.retriever = new JobManagerRetriever(this, actorSystem, AkkaUtils.getTimeout(config), timeout);

    final WebMonitorConfig cfg = new WebMonitorConfig(config);

    final String configuredAddress = cfg.getWebFrontendAddress();

    final int configuredPort = cfg.getWebFrontendPort();
    if (configuredPort < 0) {
        throw new IllegalArgumentException("Web frontend port is invalid: " + configuredPort);
    }//from  w  w  w .j  a va2s  .  c  o  m

    final WebMonitorUtils.LogFileLocation logFiles = WebMonitorUtils.LogFileLocation.find(config);

    // create an empty directory in temp for the web server
    String rootDirFileName = "flink-web-" + UUID.randomUUID();
    webRootDir = new File(getBaseDir(config), rootDirFileName);
    LOG.info("Using directory {} for the web interface files", webRootDir);

    final boolean webSubmitAllow = cfg.isProgramSubmitEnabled();
    if (webSubmitAllow) {
        // create storage for uploads
        this.uploadDir = getUploadDir(config);
        // the upload directory should either 1. exist and writable or 2. can be created and writable
        if (!(uploadDir.exists() && uploadDir.canWrite()) && !(uploadDir.mkdir() && uploadDir.canWrite())) {
            throw new IOException(String.format("Jar upload directory %s cannot be created or is not writable.",
                    uploadDir.getAbsolutePath()));
        }
        LOG.info("Using directory {} for web frontend JAR file uploads", uploadDir);
    } else {
        this.uploadDir = null;
    }

    ExecutionGraphHolder currentGraphs = new ExecutionGraphHolder();

    // - Back pressure stats ----------------------------------------------

    stackTraceSamples = new StackTraceSampleCoordinator(actorSystem.dispatcher(), 60000);

    // Back pressure stats tracker config
    int cleanUpInterval = config.getInteger(ConfigConstants.JOB_MANAGER_WEB_BACK_PRESSURE_CLEAN_UP_INTERVAL,
            ConfigConstants.DEFAULT_JOB_MANAGER_WEB_BACK_PRESSURE_CLEAN_UP_INTERVAL);

    int refreshInterval = config.getInteger(ConfigConstants.JOB_MANAGER_WEB_BACK_PRESSURE_REFRESH_INTERVAL,
            ConfigConstants.DEFAULT_JOB_MANAGER_WEB_BACK_PRESSURE_REFRESH_INTERVAL);

    int numSamples = config.getInteger(ConfigConstants.JOB_MANAGER_WEB_BACK_PRESSURE_NUM_SAMPLES,
            ConfigConstants.DEFAULT_JOB_MANAGER_WEB_BACK_PRESSURE_NUM_SAMPLES);

    int delay = config.getInteger(ConfigConstants.JOB_MANAGER_WEB_BACK_PRESSURE_DELAY,
            ConfigConstants.DEFAULT_JOB_MANAGER_WEB_BACK_PRESSURE_DELAY);

    Time delayBetweenSamples = Time.milliseconds(delay);

    backPressureStatsTracker = new BackPressureStatsTracker(stackTraceSamples, cleanUpInterval, numSamples,
            delayBetweenSamples);

    // --------------------------------------------------------------------

    executorService = new ForkJoinPool();

    ExecutionContextExecutor context = ExecutionContext$.MODULE$.fromExecutor(executorService);

    // Config to enable https access to the web-ui
    boolean enableSSL = config.getBoolean(ConfigConstants.JOB_MANAGER_WEB_SSL_ENABLED,
            ConfigConstants.DEFAULT_JOB_MANAGER_WEB_SSL_ENABLED) && SSLUtils.getSSLEnabled(config);

    if (enableSSL) {
        LOG.info("Enabling ssl for the web frontend");
        try {
            serverSSLContext = SSLUtils.createSSLServerContext(config);
        } catch (Exception e) {
            throw new IOException("Failed to initialize SSLContext for the web frontend", e);
        }
    } else {
        serverSSLContext = null;
    }
    metricFetcher = new MetricFetcher(actorSystem, retriever, context);

    String defaultSavepointDir = config.getString(ConfigConstants.SAVEPOINT_DIRECTORY_KEY, null);

    JobCancellationWithSavepointHandlers cancelWithSavepoint = new JobCancellationWithSavepointHandlers(
            currentGraphs, context, defaultSavepointDir);
    RuntimeMonitorHandler triggerHandler = handler(cancelWithSavepoint.getTriggerHandler());
    RuntimeMonitorHandler inProgressHandler = handler(cancelWithSavepoint.getInProgressHandler());

    router = new Router()
            // config how to interact with this web server
            .GET("/config", handler(new DashboardConfigHandler(cfg.getRefreshInterval())))

            // the overview - how many task managers, slots, free slots, ...
            .GET("/overview", handler(new ClusterOverviewHandler(DEFAULT_REQUEST_TIMEOUT)))

            // job manager configuration
            .GET("/jobmanager/config", handler(new JobManagerConfigHandler(config)))

            // overview over jobs
            .GET("/joboverview", handler(new CurrentJobsOverviewHandler(DEFAULT_REQUEST_TIMEOUT, true, true)))
            .GET("/joboverview/running",
                    handler(new CurrentJobsOverviewHandler(DEFAULT_REQUEST_TIMEOUT, true, false)))
            .GET("/joboverview/completed",
                    handler(new CurrentJobsOverviewHandler(DEFAULT_REQUEST_TIMEOUT, false, true)))

            .GET("/jobs", handler(new CurrentJobIdsHandler(DEFAULT_REQUEST_TIMEOUT)))

            .GET("/jobs/:jobid", handler(new JobDetailsHandler(currentGraphs, metricFetcher)))
            .GET("/jobs/:jobid/vertices", handler(new JobDetailsHandler(currentGraphs, metricFetcher)))

            .GET("/jobs/:jobid/vertices/:vertexid",
                    handler(new JobVertexDetailsHandler(currentGraphs, metricFetcher)))
            .GET("/jobs/:jobid/vertices/:vertexid/subtasktimes",
                    handler(new SubtasksTimesHandler(currentGraphs)))
            .GET("/jobs/:jobid/vertices/:vertexid/taskmanagers",
                    handler(new JobVertexTaskManagersHandler(currentGraphs, metricFetcher)))
            .GET("/jobs/:jobid/vertices/:vertexid/accumulators",
                    handler(new JobVertexAccumulatorsHandler(currentGraphs)))
            .GET("/jobs/:jobid/vertices/:vertexid/checkpoints",
                    handler(new JobVertexCheckpointsHandler(currentGraphs)))
            .GET("/jobs/:jobid/vertices/:vertexid/backpressure",
                    handler(new JobVertexBackPressureHandler(currentGraphs, backPressureStatsTracker,
                            refreshInterval)))
            .GET("/jobs/:jobid/vertices/:vertexid/metrics", handler(new JobVertexMetricsHandler(metricFetcher)))
            .GET("/jobs/:jobid/vertices/:vertexid/subtasks/accumulators",
                    handler(new SubtasksAllAccumulatorsHandler(currentGraphs)))
            .GET("/jobs/:jobid/vertices/:vertexid/subtasks/:subtasknum",
                    handler(new SubtaskCurrentAttemptDetailsHandler(currentGraphs, metricFetcher)))
            .GET("/jobs/:jobid/vertices/:vertexid/subtasks/:subtasknum/attempts/:attempt",
                    handler(new SubtaskExecutionAttemptDetailsHandler(currentGraphs, metricFetcher)))
            .GET("/jobs/:jobid/vertices/:vertexid/subtasks/:subtasknum/attempts/:attempt/accumulators",
                    handler(new SubtaskExecutionAttemptAccumulatorsHandler(currentGraphs)))

            .GET("/jobs/:jobid/plan", handler(new JobPlanHandler(currentGraphs)))
            .GET("/jobs/:jobid/config", handler(new JobConfigHandler(currentGraphs)))
            .GET("/jobs/:jobid/exceptions", handler(new JobExceptionsHandler(currentGraphs)))
            .GET("/jobs/:jobid/accumulators", handler(new JobAccumulatorsHandler(currentGraphs)))
            .GET("/jobs/:jobid/checkpoints", handler(new JobCheckpointsHandler(currentGraphs)))
            .GET("/jobs/:jobid/metrics", handler(new JobMetricsHandler(metricFetcher)))

            .GET("/taskmanagers", handler(new TaskManagersHandler(DEFAULT_REQUEST_TIMEOUT, metricFetcher)))
            .GET("/taskmanagers/:" + TaskManagersHandler.TASK_MANAGER_ID_KEY + "/metrics",
                    handler(new TaskManagersHandler(DEFAULT_REQUEST_TIMEOUT, metricFetcher)))
            .GET("/taskmanagers/:" + TaskManagersHandler.TASK_MANAGER_ID_KEY + "/log",
                    new TaskManagerLogHandler(retriever, context, jobManagerAddressPromise.future(), timeout,
                            TaskManagerLogHandler.FileMode.LOG, config, enableSSL))
            .GET("/taskmanagers/:" + TaskManagersHandler.TASK_MANAGER_ID_KEY + "/stdout",
                    new TaskManagerLogHandler(retriever, context, jobManagerAddressPromise.future(), timeout,
                            TaskManagerLogHandler.FileMode.STDOUT, config, enableSSL))
            .GET("/taskmanagers/:" + TaskManagersHandler.TASK_MANAGER_ID_KEY + "/metrics",
                    handler(new TaskManagerMetricsHandler(metricFetcher)))

            // log and stdout
            .GET("/jobmanager/log",
                    logFiles.logFile == null ? new ConstantTextHandler("(log file unavailable)")
                            : new StaticFileServerHandler(retriever, jobManagerAddressPromise.future(), timeout,
                                    logFiles.logFile, enableSSL))

            .GET("/jobmanager/stdout",
                    logFiles.stdOutFile == null ? new ConstantTextHandler("(stdout file unavailable)")
                            : new StaticFileServerHandler(retriever, jobManagerAddressPromise.future(), timeout,
                                    logFiles.stdOutFile, enableSSL))

            .GET("/jobmanager/metrics", handler(new JobManagerMetricsHandler(metricFetcher)))

            // Cancel a job via GET (for proper integration with YARN this has to be performed via GET)
            .GET("/jobs/:jobid/yarn-cancel", handler(new JobCancellationHandler()))

            // DELETE is the preferred way of canceling a job (Rest-conform)
            .DELETE("/jobs/:jobid/cancel", handler(new JobCancellationHandler()))

            .GET("/jobs/:jobid/cancel-with-savepoint", triggerHandler)
            .GET("/jobs/:jobid/cancel-with-savepoint/target-directory/:targetDirectory", triggerHandler)
            .GET(JobCancellationWithSavepointHandlers.IN_PROGRESS_URL, inProgressHandler)

            // stop a job via GET (for proper integration with YARN this has to be performed via GET)
            .GET("/jobs/:jobid/yarn-stop", handler(new JobStoppingHandler()))

            // DELETE is the preferred way of stopping a job (Rest-conform)
            .DELETE("/jobs/:jobid/stop", handler(new JobStoppingHandler()));

    if (webSubmitAllow) {
        router
                // fetch the list of uploaded jars.
                .GET("/jars", handler(new JarListHandler(uploadDir)))

                // get plan for an uploaded jar
                .GET("/jars/:jarid/plan", handler(new JarPlanHandler(uploadDir)))

                // run a jar
                .POST("/jars/:jarid/run", handler(new JarRunHandler(uploadDir, timeout, config)))

                // upload a jar
                .POST("/jars/upload", handler(new JarUploadHandler(uploadDir)))

                // delete an uploaded jar from submission interface
                .DELETE("/jars/:jarid", handler(new JarDeleteHandler(uploadDir)));
    } else {
        router
                // send an Access Denied message (sort of)
                // Every other GET request will go to the File Server, which will not provide
                // access to the jar directory anyway, because it doesn't exist in webRootDir.
                .GET("/jars", handler(new JarAccessDeniedHandler()));
    }

    // this handler serves all the static contents
    router.GET("/:*", new StaticFileServerHandler(retriever, jobManagerAddressPromise.future(), timeout,
            webRootDir, enableSSL));

    // add shutdown hook for deleting the directories and remaining temp files on shutdown
    try {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                cleanup();
            }
        });
    } catch (IllegalStateException e) {
        // race, JVM is in shutdown already, we can safely ignore this
        LOG.debug("Unable to add shutdown hook, shutdown already in progress", e);
    } catch (Throwable t) {
        // these errors usually happen when the shutdown is already in progress
        LOG.warn("Error while adding shutdown hook", t);
    }

    ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) {
            Handler handler = new Handler(router);

            // SSL should be the first handler in the pipeline
            if (serverSSLContext != null) {
                SSLEngine sslEngine = serverSSLContext.createSSLEngine();
                sslEngine.setUseClientMode(false);
                ch.pipeline().addLast("ssl", new SslHandler(sslEngine));
            }

            ch.pipeline().addLast(new HttpServerCodec()).addLast(new ChunkedWriteHandler())
                    .addLast(new HttpRequestHandler(uploadDir)).addLast(handler.name(), handler)
                    .addLast(new PipelineErrorHandler(LOG));
        }
    };

    NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();

    this.bootstrap = new ServerBootstrap();
    this.bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(initializer);

    ChannelFuture ch;
    if (configuredAddress == null) {
        ch = this.bootstrap.bind(configuredPort);
    } else {
        ch = this.bootstrap.bind(configuredAddress, configuredPort);
    }
    this.serverChannel = ch.sync().channel();

    InetSocketAddress bindAddress = (InetSocketAddress) serverChannel.localAddress();
    String address = bindAddress.getAddress().getHostAddress();
    int port = bindAddress.getPort();

    LOG.info("Web frontend listening at " + address + ':' + port);
}

From source file:org.apache.hadoop.security.ssl.SSLFactory.java

/**
 * Returns a configured SSLEngine./*from  w  w  w . j  a  v  a  2s .  c  o  m*/
 *
 * @return the configured SSLEngine.
 * @throws GeneralSecurityException thrown if the SSL engine could not
 * be initialized.
 * @throws IOException thrown if and IO error occurred while loading
 * the server keystore.
 */
public SSLEngine createSSLEngine() throws GeneralSecurityException, IOException {
    SSLEngine sslEngine = context.createSSLEngine();
    if (mode == Mode.CLIENT) {
        sslEngine.setUseClientMode(true);
    } else {
        sslEngine.setUseClientMode(false);
        sslEngine.setNeedClientAuth(requireClientCert);
        disableExcludedCiphers(sslEngine);
    }
    sslEngine.setEnabledProtocols(enabledProtocols);
    return sslEngine;
}

From source file:org.apache.hc.client5.http.impl.auth.CredSspScheme.java

private SSLEngine createSSLEngine() {
    final SSLEngine sslEngine = sslContext.createSSLEngine();
    sslEngine.setUseClientMode(true);
    return sslEngine;
}

From source file:org.apache.james.imapserver.netty.IMAPServer.java

@Override
protected ChannelPipelineFactory createPipelineFactory(final ChannelGroup group) {

    return new ChannelPipelineFactory() {

        private final ChannelGroupHandler groupHandler = new ChannelGroupHandler(group);
        private final HashedWheelTimer timer = new HashedWheelTimer();

        private final TimeUnit TIMEOUT_UNIT = TimeUnit.SECONDS;

        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline pipeline = pipeline();
            pipeline.addLast(GROUP_HANDLER, groupHandler);
            pipeline.addLast("idleHandler", new IdleStateHandler(timer, 0, 0, timeout, TIMEOUT_UNIT));
            pipeline.addLast(TIMEOUT_HANDLER, new ImapIdleStateHandler());
            pipeline.addLast(CONNECTION_LIMIT_HANDLER,
                    new ConnectionLimitUpstreamHandler(IMAPServer.this.connectionLimit));

            pipeline.addLast(CONNECTION_LIMIT_PER_IP_HANDLER,
                    new ConnectionPerIpLimitUpstreamHandler(IMAPServer.this.connPerIP));

            // Add the text line decoder which limit the max line length,
            // don't strip the delimiter and use CRLF as delimiter
            // Use a SwitchableDelimiterBasedFrameDecoder, see JAMES-1436
            pipeline.addLast(FRAMER,/*  w  w w.j ava 2s  . c  o  m*/
                    new SwitchableDelimiterBasedFrameDecoder(maxLineLength, false, Delimiters.lineDelimiter()));

            Encryption secure = getEncryption();
            if (secure != null && !secure.isStartTLS()) {
                // We need to set clientMode to false.
                // See https://issues.apache.org/jira/browse/JAMES-1025
                SSLEngine engine = secure.getContext().createSSLEngine();
                engine.setUseClientMode(false);
                pipeline.addFirst(SSL_HANDLER, new SslHandler(engine));

            }
            pipeline.addLast(CONNECTION_COUNT_HANDLER, getConnectionCountHandler());

            pipeline.addLast(CHUNK_WRITE_HANDLER, new ChunkedWriteHandler());

            ExecutionHandler ehandler = getExecutionHandler();
            if (ehandler != null) {
                pipeline.addLast(EXECUTION_HANDLER, ehandler);

            }
            pipeline.addLast(REQUEST_DECODER,
                    new ImapRequestFrameDecoder(decoder, inMemorySizeLimit, literalSizeLimit));

            pipeline.addLast(CORE_HANDLER, createCoreHandler());
            return pipeline;
        }

    };
}

From source file:org.apache.nifi.processor.util.listen.dispatcher.SocketChannelDispatcher.java

@Override
public void run() {
    while (!stopped) {
        try {//from  ww w.j a  v  a2s .c o  m
            int selected = selector.select();
            // if stopped the selector could already be closed which would result in a ClosedSelectorException
            if (selected > 0 && !stopped) {
                Iterator<SelectionKey> selectorKeys = selector.selectedKeys().iterator();
                // if stopped we don't want to modify the keys because close() may still be in progress
                while (selectorKeys.hasNext() && !stopped) {
                    SelectionKey key = selectorKeys.next();
                    selectorKeys.remove();
                    if (!key.isValid()) {
                        continue;
                    }
                    if (key.isAcceptable()) {
                        // Handle new connections coming in
                        final ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                        final SocketChannel socketChannel = channel.accept();
                        // Check for available connections
                        if (currentConnections.incrementAndGet() > maxConnections) {
                            currentConnections.decrementAndGet();
                            logger.warn("Rejecting connection from {} because max connections has been met",
                                    new Object[] { socketChannel.getRemoteAddress().toString() });
                            IOUtils.closeQuietly(socketChannel);
                            continue;
                        }
                        logger.debug("Accepted incoming connection from {}",
                                new Object[] { socketChannel.getRemoteAddress().toString() });
                        // Set socket to non-blocking, and register with selector
                        socketChannel.configureBlocking(false);
                        SelectionKey readKey = socketChannel.register(selector, SelectionKey.OP_READ);

                        // Prepare the byte buffer for the reads, clear it out
                        ByteBuffer buffer = bufferPool.poll();
                        buffer.clear();
                        buffer.mark();

                        // If we have an SSLContext then create an SSLEngine for the channel
                        SSLSocketChannel sslSocketChannel = null;
                        if (sslContext != null) {
                            final SSLEngine sslEngine = sslContext.createSSLEngine();
                            sslEngine.setUseClientMode(false);

                            switch (clientAuth) {
                            case REQUIRED:
                                sslEngine.setNeedClientAuth(true);
                                break;
                            case WANT:
                                sslEngine.setWantClientAuth(true);
                                break;
                            case NONE:
                                sslEngine.setNeedClientAuth(false);
                                sslEngine.setWantClientAuth(false);
                                break;
                            }

                            sslSocketChannel = new SSLSocketChannel(sslEngine, socketChannel);
                        }

                        // Attach the buffer and SSLSocketChannel to the key
                        SocketChannelAttachment attachment = new SocketChannelAttachment(buffer,
                                sslSocketChannel);
                        readKey.attach(attachment);
                    } else if (key.isReadable()) {
                        // Clear out the operations the select is interested in until done reading
                        key.interestOps(0);
                        // Create a handler based on the protocol and whether an SSLEngine was provided or not
                        final Runnable handler;
                        if (sslContext != null) {
                            handler = handlerFactory.createSSLHandler(key, this, charset, eventFactory, events,
                                    logger);
                        } else {
                            handler = handlerFactory.createHandler(key, this, charset, eventFactory, events,
                                    logger);
                        }

                        // run the handler
                        executor.execute(handler);
                    }
                }
            }
            // Add back all idle sockets to the select
            SelectionKey key;
            while ((key = keyQueue.poll()) != null) {
                key.interestOps(SelectionKey.OP_READ);
            }
        } catch (IOException e) {
            logger.error("Error accepting connection from SocketChannel", e);
        }
    }
}

From source file:org.jenkinsci.remoting.protocol.impl.SSLEngineFilterLayerTest.java

@Theory
public void smokes(NetworkLayerFactory serverFactory, NetworkLayerFactory clientFactory) throws Exception {
    SSLEngine serverEngine = serverCtx.createSSLEngine();
    serverEngine.setUseClientMode(false);
    serverEngine.setNeedClientAuth(true);
    SSLEngine clientEngine = clientCtx.createSSLEngine();
    clientEngine.setUseClientMode(true);

    ProtocolStack<IOBufferMatcher> client = ProtocolStack
            .on(clientFactory.create(selector.hub(), serverToClient.source(), clientToServer.sink()))
            .filter(new SSLEngineFilterLayer(clientEngine, null)).build(new IOBufferMatcherLayer());

    ProtocolStack<IOBufferMatcher> server = ProtocolStack
            .on(serverFactory.create(selector.hub(), clientToServer.source(), serverToClient.sink()))
            .filter(new SSLEngineFilterLayer(serverEngine, null)).build(new IOBufferMatcherLayer());

    byte[] expected = "Here is some sample data".getBytes("UTF-8");
    ByteBuffer data = ByteBuffer.allocate(expected.length);
    data.put(expected);//from ww  w  . j a  v a2 s .  co m
    data.flip();
    server.get().send(data);
    client.get().awaitByteContent(is(expected));
    assertThat(client.get().asByteArray(), is(expected));
    server.get().close();
    client.get().awaitClose();
}

From source file:org.jenkinsci.remoting.protocol.impl.SSLEngineFilterLayerTest.java

@Theory
public void clientRejectsServer(NetworkLayerFactory serverFactory, NetworkLayerFactory clientFactory)
        throws Exception {
    SSLEngine serverEngine = serverCtx.createSSLEngine();
    serverEngine.setUseClientMode(false);
    serverEngine.setNeedClientAuth(true);
    SSLEngine clientEngine = clientCtx.createSSLEngine();
    clientEngine.setUseClientMode(true);

    ProtocolStack<IOBufferMatcher> client = ProtocolStack
            .on(clientFactory.create(selector.hub(), serverToClient.source(), clientToServer.sink()))
            .filter(new SSLEngineFilterLayer(clientEngine, new SSLEngineFilterLayer.Listener() {
                @Override// w  ww.  j  a  v  a 2  s . com
                public void onHandshakeCompleted(SSLSession session) throws ConnectionRefusalException {
                    throw new ConnectionRefusalException("Bad server");
                }
            })).build(new IOBufferMatcherLayer());

    ProtocolStack<IOBufferMatcher> server = ProtocolStack
            .on(serverFactory.create(selector.hub(), clientToServer.source(), serverToClient.sink()))
            .filter(new SSLEngineFilterLayer(serverEngine, null)).build(new IOBufferMatcherLayer());

    IOBufferMatcher clientMatcher = client.get();
    IOBufferMatcher serverMatcher = server.get();

    clientMatcher.awaitClose();
    serverMatcher.awaitClose();
    assertThat(clientMatcher.getCloseCause(), instanceOf(ConnectionRefusalException.class));
    assertThat(serverMatcher.getCloseCause(), instanceOf(ClosedChannelException.class));
}

From source file:org.jenkinsci.remoting.protocol.impl.SSLEngineFilterLayerTest.java

@Theory
public void serverRejectsClient(NetworkLayerFactory serverFactory, NetworkLayerFactory clientFactory)
        throws Exception {
    Logger.getLogger(name.getMethodName()).log(Level.INFO, "Starting test with server {0} client {1}",
            new Object[] { serverFactory.getClass().getSimpleName(),
                    clientFactory.getClass().getSimpleName(), });
    SSLEngine serverEngine = serverCtx.createSSLEngine();
    serverEngine.setUseClientMode(false);
    serverEngine.setNeedClientAuth(true);
    SSLEngine clientEngine = clientCtx.createSSLEngine();
    clientEngine.setUseClientMode(true);

    ProtocolStack<IOBufferMatcher> client = ProtocolStack
            .on(clientFactory.create(selector.hub(), serverToClient.source(), clientToServer.sink()))
            .filter(new SSLEngineFilterLayer(clientEngine, null)).build(new IOBufferMatcherLayer());

    ProtocolStack<IOBufferMatcher> server = ProtocolStack
            .on(serverFactory.create(selector.hub(), clientToServer.source(), serverToClient.sink()))
            .filter(new SSLEngineFilterLayer(serverEngine, new SSLEngineFilterLayer.Listener() {
                @Override/*from  w w  w .j a v a2  s  .  c o m*/
                public void onHandshakeCompleted(SSLSession session) throws ConnectionRefusalException {
                    throw new ConnectionRefusalException("Bad client");
                }
            })).build(new IOBufferMatcherLayer());

    IOBufferMatcher clientMatcher = client.get();
    IOBufferMatcher serverMatcher = server.get();

    Logger.getLogger(name.getMethodName()).log(Level.INFO, "Waiting for client close");
    clientMatcher.awaitClose();
    Logger.getLogger(name.getMethodName()).log(Level.INFO, "Waiting for server close");
    serverMatcher.awaitClose();
    assertThat(clientMatcher.getCloseCause(), instanceOf(ClosedChannelException.class));
    assertThat(serverMatcher.getCloseCause(), instanceOf(ConnectionRefusalException.class));
    Logger.getLogger(name.getMethodName()).log(Level.INFO, "Done");
}

From source file:org.jenkinsci.remoting.protocol.impl.SSLEngineFilterLayerTest.java

@Theory
public void untrustingClientDoesNotConnect(NetworkLayerFactory serverFactory, NetworkLayerFactory clientFactory)
        throws Exception {
    SSLEngine serverEngine = serverCtx.createSSLEngine();
    serverEngine.setUseClientMode(false);
    serverEngine.setNeedClientAuth(true);
    SSLEngine clientEngine = untrustingClientCtx.createSSLEngine();
    clientEngine.setUseClientMode(true);

    ProtocolStack<IOBufferMatcher> client = ProtocolStack
            .on(clientFactory.create(selector.hub(), serverToClient.source(), clientToServer.sink()))
            .filter(new SSLEngineFilterLayer(clientEngine, null)).build(new IOBufferMatcherLayer());

    ProtocolStack<IOBufferMatcher> server = ProtocolStack
            .on(serverFactory.create(selector.hub(), clientToServer.source(), serverToClient.sink()))
            .filter(new SSLEngineFilterLayer(serverEngine, null)).build(new IOBufferMatcherLayer());

    IOBufferMatcher clientMatcher = client.get();
    IOBufferMatcher serverMatcher = server.get();

    clientMatcher.awaitClose();//  w  w  w .  j  a  v a  2 s  . co m
    serverMatcher.awaitClose();
    assertThat(clientMatcher.getCloseCause(), instanceOf(SSLHandshakeException.class));
    assertThat(serverMatcher.getCloseCause(), instanceOf(ClosedChannelException.class));
}