Example usage for java.nio.channels Selector open

List of usage examples for java.nio.channels Selector open

Introduction

In this page you can find the example usage for java.nio.channels Selector open.

Prototype

public static Selector open() throws IOException 

Source Link

Document

Opens a selector.

Usage

From source file:co.elastic.tealess.SSLChecker.java

private void checkConnect(SSLReport sslReport, SocketChannel socket, long timeout) {
    final InetSocketAddress address = sslReport.getAddress();
    try {/* w  w w .jav  a2s .  c  om*/
        logger.trace("Connecting to {}", address);
        Selector selector = Selector.open();
        SelectionKey sk = socket.register(selector, SelectionKey.OP_CONNECT);
        socket.connect(address);
        selector.select(timeout);
        if (!sk.isConnectable()) {
            sslReport.setFailed(new SocketTimeoutException());
            return;
        }
        if (socket.isConnectionPending()) {
            socket.finishConnect();
        }
    } catch (ConnectException e) {
        logger.debug("Connection failed to {}: {}", address, e);
        sslReport.setFailed(e);
        return;
    } catch (IOException e) {
        logger.error("Failed connecting to {}: {}", address, e);
        sslReport.setFailed(e);
        return;
    }

    logger.debug("Connection successful to {}", address);
}

From source file:org.apache.nifi.io.nio.ChannelListener.java

public ChannelListener(final int threadPoolSize, final StreamConsumerFactory consumerFactory,
        final BufferPool bufferPool, int timeout, TimeUnit unit, final boolean readSingleDatagram)
        throws IOException {
    this.executor = Executors.newScheduledThreadPool(threadPoolSize + 1); // need to allow for long running ChannelDispatcher thread
    this.serverSocketSelector = Selector.open();
    this.socketChannelSelector = Selector.open();
    this.bufferPool = bufferPool;
    this.initialBufferPoolSize = bufferPool.size();
    channelDispatcher = new ChannelDispatcher(serverSocketSelector, socketChannelSelector, executor,
            consumerFactory, bufferPool, timeout, unit, readSingleDatagram);
    executor.schedule(channelDispatcher, 50, TimeUnit.MILLISECONDS);
}

From source file:ca.wumbo.doommanager.server.ServerManager.java

/**
 * Starts up the channels and selectors for net connections. This must be
 * called before executing the run() method. This is synchronized, though
 * multiple threads should not be calling initialize on this anyways.
 * /*from   w w w .  j av  a2s .c  o  m*/
 * @throws IOException
 *       If any errors occur while setting up the connection handling.
 * 
 * @throws IllegalArgumentException
 *       If the IP is empty upon   extraction from the socket channel.
 * 
 * @throws RuntimeException
 *       If there are multiple attempts to initialize the server.
 */
public void initialize() throws IOException {
    if (isInitialized)
        throw new RuntimeException("Attempting to initialize a server when it already has been.");

    log.trace("Initializing Server Manager.");
    listenPort = config.getServerConfig().getPort();
    selector = Selector.open();

    // Attempt to open a channel.
    log.debug("Attempting to bind server to port {}.", listenPort);
    serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.configureBlocking(false);
    serverSocketChannel.socket().bind(new InetSocketAddress(listenPort));
    log.info("Successfully bound server to port {}.", listenPort);

    isInitialized = true;
}

From source file:org.apache.axis2.transport.udp.IODispatcher.java

/**
 * Constructor.//from w w  w . j  ava 2  s  .  c om
 * 
 * @param callback
 * @throws IOException if the {@link Selector} instance could not be created
 */
public IODispatcher(DatagramDispatcherCallback callback) throws IOException {
    this.callback = callback;
    selector = Selector.open();
}

From source file:org.gcaldaemon.core.ldap.LDAPListener.java

LDAPListener(ContactLoader loader, FilterMask[] hosts, FilterMask[] addresses, int port) throws Exception {

    // Starting server
    log.info("LDAP server starting on port " + port + "...");

    // Store pointers
    this.loader = loader;
    this.hosts = hosts;
    this.addresses = addresses;

    // Allocate an unbound server socket channel
    serverChannel = ServerSocketChannel.open();

    // Get the associated ServerSocket to bind it with
    ServerSocket serverSocket = serverChannel.socket();

    // Set the port the server channel will listen to
    serverSocket.bind(new InetSocketAddress(port));

    // Set non-blocking mode for the listening socket
    serverChannel.configureBlocking(false);

    // Create a new Selector for use below
    selector = Selector.open();

    // Register the ServerSocketChannel with the Selector
    serverChannel.register(selector, SelectionKey.OP_ACCEPT);

    // Start thread
    start();/*  ww w. java2s .  co  m*/
}

From source file:HttpDownloadManager.java

public HttpDownloadManager(Logger log) throws IOException {
    if (log == null)
        log = Logger.getLogger(this.getClass().getName());
    this.log = log;
    selector = Selector.open(); // create Selector
    buffer = ByteBuffer.allocateDirect(64 * 1024); // allocate buffer
    pendingDownloads = Collections.synchronizedList(new ArrayList());
    this.start(); // start thread
}

From source file:org.openhab.binding.keba.handler.KeContactP20Handler.java

@Override
public void initialize() {
    logger.debug("Initializing KEBA KeContact P20 handler.");

    try {/*  w w w  . ja va2  s  .  com*/
        selector = Selector.open();
    } catch (IOException e) {
        logger.error("An exception occurred while registering the selector: '{}'", e.getMessage());
    }

    configureListener(LISTENER_PORT_NUMBER);

    if (getConfig().get(IP_ADDRESS) != null && !getConfig().get(IP_ADDRESS).equals("")) {

        establishConnection();

        if (listeningJob == null || listeningJob.isCancelled()) {
            try {
                listeningJob = scheduler.scheduleWithFixedDelay(listeningRunnable, 0,
                        CONNECTION_REFRESH_INTERVAL, TimeUnit.MILLISECONDS);
            } catch (Exception e) {
                updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE,
                        "An exception occurred while scheduling the connection job");
            }
        }
        if (pollingJob == null || pollingJob.isCancelled()) {
            try {
                pollingJob = scheduler.scheduleWithFixedDelay(pollingRunnable, 0,
                        ((BigDecimal) getConfig().get(POLLING_REFRESH_INTERVAL)).intValue(), TimeUnit.SECONDS);
            } catch (Exception e) {
                updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE,
                        "An exception occurred while scheduling the polling job");
            }
        }
    } else {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
                "IP address or port number not set");
    }

}

From source file:com.offbynull.portmapper.common.UdpCommunicator.java

@Override
protected void startUp() throws Exception {
    selector = Selector.open();

    for (DatagramChannel channel : sendQueue.keySet()) {
        channel.register(selector, SelectionKey.OP_READ);
    }/*from   w ww. ja va2 s. c  o m*/
}

From source file:net.lightbody.bmp.proxy.jetty.http.nio.SocketChannelOutputStream.java

private void flushBuffer() throws IOException {
    while (_flush.hasRemaining()) {
        int len = _channel.write(_flush);
        if (len < 0)
            throw new IOException("EOF");
        if (len == 0) {
            // write channel full.  Try letting other threads have a go.
            Thread.yield();/*ww  w . j av a2 s  .  c o m*/
            len = _channel.write(_flush);
            if (len < 0)
                throw new IOException("EOF");
            if (len == 0) {
                // still full.  need to  block until it is writable.
                if (_selector == null) {
                    _selector = Selector.open();
                    _channel.register(_selector, SelectionKey.OP_WRITE);
                }

                _selector.select();
            }
        }
    }
}

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

@Override
public void open(final InetAddress nicAddress, final int port, final int maxBufferSize) throws IOException {
    stopped = false;//from   w w  w. j  a  va2 s  . c o m
    datagramChannel = DatagramChannel.open();
    datagramChannel.configureBlocking(false);

    if (maxBufferSize > 0) {
        datagramChannel.setOption(StandardSocketOptions.SO_RCVBUF, maxBufferSize);
        final int actualReceiveBufSize = datagramChannel.getOption(StandardSocketOptions.SO_RCVBUF);
        if (actualReceiveBufSize < maxBufferSize) {
            logger.warn("Attempted to set Socket Buffer Size to " + maxBufferSize
                    + " bytes but could only set to " + actualReceiveBufSize
                    + "bytes. You may want to consider changing the Operating System's "
                    + "maximum receive buffer");
        }
    }

    // we don't have to worry about nicAddress being null here because InetSocketAddress already handles it
    datagramChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    datagramChannel.socket().bind(new InetSocketAddress(nicAddress, port));

    // if a sending host and port were provided then connect to that specific address to only receive
    // datagrams from that host/port, otherwise we can receive datagrams from any host/port
    if (sendingHost != null && sendingPort != null) {
        datagramChannel.connect(new InetSocketAddress(sendingHost, sendingPort));
    }

    selector = Selector.open();
    datagramChannel.register(selector, SelectionKey.OP_READ);
}