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:Proxy.java

public void start() throws Exception {
    Map.Entry entry;/*from   w ww.jav  a2  s.com*/
    Selector selector;
    ServerSocketChannel sock_channel;
    MyInetSocketAddress key, value;

    if (remote != null && local != null)
        mappings.put(new InetSocketAddress(local, local_port), new InetSocketAddress(remote, remote_port));

    if (mapping_file != null) {
        try {
            populateMappings(mapping_file);
        } catch (Exception ex) {
            log("Failed reading " + mapping_file);
            throw ex;
        }
    }

    log("\nProxy started at " + new java.util.Date());

    if (verbose) {
        log("\nMappings:\n---------");
        for (Iterator it = mappings.entrySet().iterator(); it.hasNext();) {
            entry = (Map.Entry) it.next();
            log(toString((InetSocketAddress) entry.getKey()) + " <--> "
                    + toString((InetSocketAddress) entry.getValue()));
        }
        log("\n");
    }

    // 1. Create a Selector
    selector = Selector.open();

    // Create a thread pool (Executor)
    executor = new ThreadPoolExecutor(MIN_THREAD_POOL_SIZE, MAX_THREAD_POOL_SIZE, 30000, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue(1000));

    for (Iterator it = mappings.keySet().iterator(); it.hasNext();) {
        key = (MyInetSocketAddress) it.next();
        value = (MyInetSocketAddress) mappings.get(key);

        // if either source or destination are SSL, we cannot use JDK 1.4
        // NIO selectors, but have to fall back on separate threads per connection

        if (key.ssl() || value.ssl()) {
            // if(2 == 2) {
            SocketAcceptor acceptor = new SocketAcceptor(key, value);
            executor.execute(acceptor);
            continue;
        }

        // 2. Create a ServerSocketChannel
        sock_channel = ServerSocketChannel.open();
        sock_channel.configureBlocking(false);
        sock_channel.socket().bind(key);

        // 3. Register the selector with all server sockets. 'Key' is attachment, so we get it again on
        //    select(). That way we can associate it with the mappings hashmap to find the corresponding
        //    value
        sock_channel.register(selector, SelectionKey.OP_ACCEPT, key);
    }

    // 4. Start main loop. won't return until CTRL-C'ed        
    loop(selector);
}

From source file:voldemort.common.nio.AbstractSelectorManager.java

public AbstractSelectorManager(long maxHeartBeatTimeMs) {
    try {//from   w  w  w  . j  a va2  s . c  o  m
        this.selector = Selector.open();
    } catch (IOException e) {
        throw new VoldemortException(e);
    }

    this.isClosed = new AtomicBoolean(false);
    this.maxHeartBeatTimeMs = maxHeartBeatTimeMs;
}

From source file:com.app.services.ExecutorServiceThread.java

public void run() {

    // create a selector that will by used for multiplexing. The selector
    // registers the socketserverchannel as
    // well as all socketchannels that are created
    String CLIENTCHANNELNAME = "clientChannel";
    String SERVERCHANNELNAME = "serverChannel";
    String channelType = "channelType";

    ConcurrentHashMap<SelectionKey, Object> resultMap = new ConcurrentHashMap<SelectionKey, Object>();
    ClassLoader classLoader = null;
    ByteArrayOutputStream bstr;//from  w ww. j av a  2s.com
    ByteBuffer buffer = null;
    ByteBuffer lengthBuffer = ByteBuffer.allocate(4);
    int bytesRead;
    InputStream bais;
    ObjectInputStream ois;
    Object object;
    ExecutorServiceInfo executorServiceInfo = null;
    Random random = new Random(System.currentTimeMillis());
    // register the serversocketchannel with the selector. The OP_ACCEPT
    // option marks
    // a selection key as ready when the channel accepts a new connection.
    // When the
    // socket server accepts a connection this key is added to the list of
    // selected keys of the selector.
    // when asked for the selected keys, this key is returned and hence we
    // know that a new connection has been accepted.
    try {
        Selector selector = Selector.open();
        SelectionKey socketServerSelectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // SelectionKey socketServerSelectionKey1 =
        // channel.register(selector1,
        // SelectionKey.OP_ACCEPT);

        // set property in the key that identifies the channel
        Map<String, String> properties = new ConcurrentHashMap<String, String>();
        properties.put(channelType, SERVERCHANNELNAME);
        socketServerSelectionKey.attach(properties);
        // wait for the selected keys
        SelectionKey key = null;
        Set<SelectionKey> selectedKeys;
        // logger.info("Instance Number"+instanceNumber);
        Iterator<SelectionKey> iterator = null;
        SocketChannel clientChannel = null;
        while (true) {
            try {
                // the select method is a blocking method which returns when
                // atleast
                // one of the registered
                // channel is selected. In this example, when the socket
                // accepts
                // a
                // new connection, this method
                // will return. Once a socketclient is added to the list of
                // registered channels, then this method
                // would also return when one of the clients has data to be
                // read
                // or
                // written. It is also possible to perform a nonblocking
                // select
                // using the selectNow() function.
                // We can also specify the maximum time for which a select
                // function
                // can be blocked using the select(long timeout) function.

                if (selector.select() >= 0) {
                    selectedKeys = selector.selectedKeys();
                    iterator = selectedKeys.iterator();
                }
                while (iterator.hasNext()) {
                    try {
                        key = iterator.next();
                        // the selection key could either by the
                        // socketserver
                        // informing
                        // that a new connection has been made, or
                        // a socket client that is ready for read/write
                        // we use the properties object attached to the
                        // channel
                        // to
                        // find
                        // out the type of channel.
                        if (((Map) key.attachment()).get(channelType).equals(SERVERCHANNELNAME)) {
                            // a new connection has been obtained. This
                            // channel
                            // is
                            // therefore a socket server.
                            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                            // accept the new connection on the server
                            // socket.
                            // Since
                            // the
                            // server socket channel is marked as non
                            // blocking
                            // this channel will return null if no client is
                            // connected.
                            SocketChannel clientSocketChannel = serverSocketChannel.accept();

                            if (clientSocketChannel != null) {
                                // set the client connection to be non
                                // blocking
                                clientSocketChannel.configureBlocking(false);
                                SelectionKey clientKey = clientSocketChannel.register(selector,
                                        SelectionKey.OP_READ, SelectionKey.OP_WRITE);
                                Map<String, String> clientproperties = new ConcurrentHashMap<String, String>();
                                clientproperties.put(channelType, CLIENTCHANNELNAME);
                                clientKey.attach(clientproperties);
                                clientKey.interestOps(SelectionKey.OP_READ);
                                // clientSocketChannel.close();
                                // write something to the new created client
                                /*
                                 * CharBuffer buffer =
                                 * CharBuffer.wrap("Hello client"); while
                                 * (buffer.hasRemaining()) {
                                 * clientSocketChannel.write
                                 * (Charset.defaultCharset()
                                 * .encode(buffer)); }
                                 * clientSocketChannel.close();
                                 * buffer.clear();
                                 */
                            }

                        } else {
                            // data is available for read
                            // buffer for reading
                            clientChannel = (SocketChannel) key.channel();
                            if (key.isReadable()) {
                                // the channel is non blocking so keep it
                                // open
                                // till
                                // the
                                // count is >=0
                                clientChannel = (SocketChannel) key.channel();
                                if (resultMap.get(key) == null) {
                                    //log.info(key);
                                    bstr = new ByteArrayOutputStream();
                                    object = null;
                                    clientChannel.read(lengthBuffer);
                                    int length = lengthBuffer.getInt(0);
                                    lengthBuffer.clear();
                                    //log.info(length);
                                    buffer = ByteBuffer.allocate(length);
                                    if ((bytesRead = clientChannel.read(buffer)) > 0) {
                                        // buffer.flip();
                                        // System.out
                                        // .println(bytesRead);
                                        bstr.write(buffer.array(), 0, bytesRead);
                                        buffer.clear();
                                    }
                                    buffer.clear();
                                    //log.info("Message1"+new String(bstr
                                    //      .toByteArray()));
                                    bais = new ByteArrayInputStream(bstr.toByteArray());
                                    ois = new ObjectInputStream(bais); // Offending
                                    // line.
                                    // Produces
                                    // the
                                    // StreamCorruptedException.
                                    //log.info("In read obect");
                                    object = ois.readObject();
                                    //log.info("Class Cast");
                                    //log.info("Class Cast1");
                                    ois.close();
                                    byte[] params = bstr.toByteArray();
                                    bstr.close();
                                    //log.info("readObject");
                                    //log.info("After readObject");
                                    if (object instanceof CloseSocket) {
                                        resultMap.remove(key);
                                        clientChannel.close();
                                        key.cancel();
                                    }
                                    // clientChannel.close();
                                    String serviceurl = (String) object;
                                    String[] serviceRegistry = serviceurl.split("/");
                                    //log.info("classLoaderMap"
                                    //      + urlClassLoaderMap);
                                    //log.info(deployDirectory
                                    //      + "/" + serviceRegistry[0]);

                                    int servicenameIndex;
                                    //log.info(earServicesDirectory
                                    //      + "/" + serviceRegistry[0]
                                    //      + "/" + serviceRegistry[1]);
                                    if (serviceRegistry[0].endsWith(".ear")) {
                                        classLoader = (VFSClassLoader) urlClassLoaderMap.get(deployDirectory
                                                + "/" + serviceRegistry[0] + "/" + serviceRegistry[1]);
                                        servicenameIndex = 2;
                                    } else if (serviceRegistry[0].endsWith(".jar")) {
                                        classLoader = (WebClassLoader) urlClassLoaderMap
                                                .get(deployDirectory + "/" + serviceRegistry[0]);
                                        servicenameIndex = 1;
                                    } else {
                                        classLoader = (WebClassLoader) urlClassLoaderMap
                                                .get(deployDirectory + "/" + serviceRegistry[0]);
                                        servicenameIndex = 1;
                                    }
                                    String serviceName = serviceRegistry[servicenameIndex];
                                    // log.info("servicename:"+serviceName);;
                                    synchronized (executorServiceMap) {
                                        executorServiceInfo = (ExecutorServiceInfo) executorServiceMap
                                                .get(serviceName.trim());
                                    }
                                    ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = new ExecutorServiceInfoClassLoader();
                                    classLoaderExecutorServiceInfo.setClassLoader(classLoader);
                                    classLoaderExecutorServiceInfo.setExecutorServiceInfo(executorServiceInfo);
                                    resultMap.put(key, classLoaderExecutorServiceInfo);
                                    // key.interestOps(SelectionKey.OP_READ);
                                    // log.info("Key interested Ops");
                                    // continue;
                                }
                                //Thread.sleep(100);
                                /*
                                 * if (classLoader == null) throw new
                                 * Exception(
                                 * "Could able to obtain deployed class loader"
                                 * );
                                 */
                                /*
                                 * log.info(
                                 * "current context classloader" +
                                 * classLoader);
                                 */
                                //log.info("In rad object");
                                bstr = new ByteArrayOutputStream();
                                lengthBuffer.clear();
                                int numberofDataRead = clientChannel.read(lengthBuffer);
                                //log.info("numberofDataRead"
                                //      + numberofDataRead);
                                int length = lengthBuffer.getInt(0);
                                if (length <= 0) {
                                    iterator.remove();
                                    continue;
                                }
                                lengthBuffer.clear();
                                //log.info(length);
                                buffer = ByteBuffer.allocate(length);
                                buffer.clear();
                                if ((bytesRead = clientChannel.read(buffer)) > 0) {
                                    // buffer.flip();
                                    // System.out
                                    // .println(bytesRead);
                                    bstr.write(buffer.array(), 0, bytesRead);
                                    buffer.clear();
                                }
                                if (bytesRead <= 0 || bytesRead < length) {
                                    //log.info("bytesRead<length");
                                    iterator.remove();
                                    continue;
                                }
                                //log.info(new String(bstr
                                //   .toByteArray()));
                                bais = new ByteArrayInputStream(bstr.toByteArray());

                                ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = (ExecutorServiceInfoClassLoader) resultMap
                                        .get(key);
                                ois = new ClassLoaderObjectInputStream(
                                        (ClassLoader) classLoaderExecutorServiceInfo.getClassLoader(), bais); // Offending
                                // line.
                                // Produces
                                // the
                                // StreamCorruptedException.
                                object = ois.readObject();
                                ois.close();
                                bstr.close();
                                executorServiceInfo = classLoaderExecutorServiceInfo.getExecutorServiceInfo();
                                //System.out
                                //      .println("inputStream Read Object");
                                //log.info("Object="
                                //      + object.getClass());
                                // Thread.currentThread().setContextClassLoader(currentContextLoader);
                                if (object instanceof ExecutorParams) {
                                    ExecutorParams exeParams = (ExecutorParams) object;
                                    Object returnValue = null;

                                    //log.info("test socket1");
                                    String ataKey;
                                    ATAConfig ataConfig;
                                    ConcurrentHashMap ataServicesMap;
                                    Enumeration<NodeResourceInfo> noderesourceInfos = addressmap.elements();
                                    NodeResourceInfo noderesourceinfo = null;
                                    String ip = "";
                                    int port = 1000;
                                    long memavailable = 0;
                                    long memcurr = 0;
                                    if (noderesourceInfos.hasMoreElements()) {
                                        noderesourceinfo = noderesourceInfos.nextElement();
                                        if (noderesourceinfo.getMax() != null) {
                                            ip = noderesourceinfo.getHost();
                                            port = Integer.parseInt(noderesourceinfo.getPort());
                                            memavailable = Long.parseLong(noderesourceinfo.getMax())
                                                    - Long.parseLong(noderesourceinfo.getUsed());
                                            ;
                                        }
                                    }

                                    while (noderesourceInfos.hasMoreElements()) {
                                        noderesourceinfo = noderesourceInfos.nextElement();
                                        if (noderesourceinfo.getMax() != null) {
                                            memcurr = Long.parseLong(noderesourceinfo.getMax())
                                                    - Long.parseLong(noderesourceinfo.getUsed());
                                            if (memavailable <= memcurr) {
                                                ip = noderesourceinfo.getHost();
                                                port = Integer.parseInt(noderesourceinfo.getPort());
                                                memavailable = memcurr;
                                            }
                                        }
                                    }
                                    ATAExecutorServiceInfo servicesAvailable;
                                    Socket sock1 = new Socket(ip, port);
                                    OutputStream outputStr = sock1.getOutputStream();
                                    ObjectOutputStream objOutputStream = new ObjectOutputStream(outputStr);
                                    NodeInfo nodeInfo = new NodeInfo();
                                    nodeInfo.setClassNameWithPackage(
                                            executorServiceInfo.getExecutorServicesClass().getName());
                                    nodeInfo.setMethodName(executorServiceInfo.getMethod().getName());

                                    nodeInfo.setWebclassLoaderURLS(((WebClassLoader) classLoader).geturlS());
                                    NodeInfoMethodParam nodeInfoMethodParam = new NodeInfoMethodParam();
                                    nodeInfoMethodParam.setMethodParams(exeParams.getParams());
                                    nodeInfoMethodParam
                                            .setMethodParamTypes(executorServiceInfo.getMethodParams());
                                    //log.info("Serializable socket="+sock);
                                    //nodeInfo.setSock(sock);
                                    //nodeInfo.setOstream(sock.getOutputStream());
                                    objOutputStream.writeObject(nodeInfo);
                                    objOutputStream = new ObjectOutputStream(outputStr);
                                    objOutputStream.writeObject(nodeInfoMethodParam);
                                    ObjectInputStream objInputStream1 = new ObjectInputStream(
                                            sock1.getInputStream());
                                    returnValue = objInputStream1.readObject();
                                    objOutputStream.close();
                                    objInputStream1.close();
                                    sock1.close();
                                    /*returnValue = executorServiceInfo
                                          .getMethod()
                                          .invoke(executorServiceInfo
                                                .getExecutorServicesClass()
                                                .newInstance(),
                                                exeParams.getParams());*/
                                    // Thread.currentThread().setContextClassLoader(oldCL);

                                    //   log.info("Written Value="
                                    //         + returnValue.toString());
                                    resultMap.put(key, returnValue);
                                }
                                key.interestOps(SelectionKey.OP_WRITE);
                                //log.info("Key interested Ops1");
                            } else if (key.isWritable()) {
                                // the channel is non blocking so keep it
                                // open
                                // till the
                                // count is >=0
                                //log.info("In write");
                                ByteArrayOutputStream baos = new ByteArrayOutputStream(); // make
                                // a
                                // BAOS
                                // stream
                                ObjectOutputStream oos = new ObjectOutputStream(baos); // wrap and OOS around the
                                                                                       // stream
                                Object result = resultMap.get(key);
                                oos.writeObject(result); // write an object
                                // to
                                // the stream
                                oos.flush();
                                oos.close();
                                byte[] objData = baos.toByteArray(); // get
                                // the
                                // byte
                                // array
                                baos.close();
                                buffer = ByteBuffer.wrap(objData); // wrap
                                // around
                                // the
                                // data
                                buffer.rewind();
                                // buffer.flip(); //prep for writing
                                //log.info(new String(objData));
                                //while (buffer.hasRemaining())
                                clientChannel.write(buffer); // write
                                resultMap.remove(key);
                                buffer.clear();
                                key.cancel();
                                clientChannel.close();
                                //log.info("In write1");
                                numberOfServicesRequests++;
                                //log.info("Key interested Ops2");
                            }

                        }

                        iterator.remove();
                    } catch (Exception ex) {
                        log.error("Error in executing the executor services thread", ex);
                        //ex.printStackTrace();
                        key.cancel();
                        clientChannel.close();
                        resultMap.remove(key);
                        //ex.printStackTrace();
                    }

                }

            } catch (Exception ex) {
                log.error("Error in executing the executor services thread", ex);
                //ex.printStackTrace();
            }
        }
    } catch (Exception ex) {
        log.error("Error in executing the executor services thread", ex);
    }
}

From source file:org.openhab.io.transport.cul.internal.network.CULNetworkHandlerImpl.java

@Override
public void run() {
    logger.info("event loop starting");
    try {//from  ww w  . j av a2 s . co  m
        while (!Thread.interrupted()) { // reconnection loop
            try {
                selector = Selector.open();
                channel = SocketChannel.open();
                configureChannel(channel);

                channel.connect(address);
                channel.register(selector, SelectionKey.OP_CONNECT);

                while (!thread.isInterrupted() && channel.isOpen()) { // events multiplexing loop
                    if (selector.select() > 0) {
                        processSelectedKeys(selector.selectedKeys());
                    }
                }
            } catch (Exception e) {
                logger.warn("exception", e);
            } finally {
                connected.set(false);
                onDisconnected();
                writeBuf.clear();
                readBuf.clear();
                if (channel != null) {
                    channel.close();
                }
                if (selector != null) {
                    selector.close();
                }
                logger.info("connection closed");
            }

            try {
                Thread.sleep(reconnectInterval);
                if (reconnectInterval < MAXIMUM_RECONNECT_INTERVAL) {
                    reconnectInterval *= 2;
                }
                logger.info("reconnecting to {}", address);
            } catch (InterruptedException e) {
                break;
            }
        }
    } catch (Exception e) {
        logger.warn("unrecoverable error", e);
    }

    logger.info("event loop terminated");
}

From source file:com.openteach.diamond.network.waverider.network.DefaultNetWorkClient.java

private boolean connect() {
    try {/*from  ww  w. j  a v  a  2s.  co  m*/
        state.set(NetworkStateEnum.NETWORK_STATE_CONNECTING.value);
        socketChannel = SocketChannel.open();
        // 
        socketChannel.connect(new InetSocketAddress(hostName, port));
        // ??
        socketChannel.configureBlocking(false);
        selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_READ);
        opsChangeRequest = new SocketChannelOPSChangeRequest(socketChannel, 0);
        // 
        state.set(NetworkStateEnum.NETWORK_STATE_CONNECTED.value);
        logger.warn(String.format("Slave connected to %s", hostName));
        return true;
    } catch (IOException e) {
        logger.error("OOPSException", e);
    }
    state.set(NetworkStateEnum.NETWORK_STATE_DISCONNECT.value);
    return false;
}

From source file:org.openhab.binding.lifx.internal.LifxLightDiscovery.java

protected void doScan() {
    try {/*from w w  w  .j  a  v a 2  s.  co  m*/
        if (!isScanning) {
            isScanning = true;
            if (selector != null) {
                closeSelector(selector, LOG_ID);
            }

            logger.debug("The LIFX discovery service will use '{}' as source identifier",
                    Long.toString(sourceId, 16));

            Selector localSelector = Selector.open();
            selector = localSelector;

            broadcastKey = openBroadcastChannel(localSelector, LOG_ID, BROADCAST_PORT);
            networkJob = scheduler.schedule(this::receiveAndHandlePackets, 0, TimeUnit.MILLISECONDS);

            LifxSelectorContext selectorContext = new LifxSelectorContext(localSelector, sourceId,
                    sequenceNumberSupplier, LOG_ID, broadcastKey);
            broadcastPacket(selectorContext, new GetServiceRequest());
        } else {
            logger.info("A discovery scan for LIFX lights is already underway");
        }
    } catch (IOException e) {
        logger.debug("{} while discovering LIFX lights : {}", e.getClass().getSimpleName(), e.getMessage());
        isScanning = false;
    }
}

From source file:morphy.service.SocketConnectionService.java

private SocketConnectionService() {
    MorphyPreferences morphyPreferences = Morphy.getInstance().getMorphyPreferences();
    try {//from  w w  w  .j  a v a 2s  .c  o m
        maxCommunicationSizeBytes = morphyPreferences
                .getInt(PreferenceKeys.SocketConnectionServiceMaxCommunicationBytes);
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);

        /*Object obj = PreferenceService.getInstance().getProperty(PreferenceKeys.SocketConnectionServicePorts.toString());
        System.out.println(obj.getClass());
        if (obj instanceof java.util.ArrayList) {
           //System.out.println((java.util.ArrayList<String>)obj);
           String[] arr = ((java.util.ArrayList<String>)obj).toArray(new String[0]);
           System.out.println(java.util.Arrays.toString(arr));
           //serverSocketChannel.socket().
           for(int i=0;i<arr.length;i++) {
              serverSocketChannel.socket().bind( 
             new java.net.InetSocketAddress( Integer.parseInt(arr[i]) ));
              if (LOG.isInfoEnabled()) {
          LOG.info("Listening on port " + arr[i]);
              }
           }
        } else {
           if (LOG.isInfoEnabled()) {
              serverSocketChannel.socket().bind( new java.net.InetSocketAddress( 5000 ));
              LOG.info("LOAD CONFIG FAILED - Listening on port 5000");
           }
        }*/

        serverSocketChannel.socket().bind(new java.net.InetSocketAddress(
                morphyPreferences.getInt(PreferenceKeys.SocketConnectionServicePorts.toString())));
        serverSocketSelector = Selector.open();
        serverSocketChannel.register(serverSocketSelector, SelectionKey.OP_ACCEPT);

        selectionThread = new Thread(selectSocketRunnable);
        selectionThread.setPriority(Thread.MAX_PRIORITY);
        selectionThread.start();

        LOG.info("Initialized Socket Connection Service host:" + serverSocketChannel.socket().getInetAddress()
                + " " + serverSocketChannel.socket().getLocalPort());

        this.timesealCoder = new TimesealCoder();
    } catch (Throwable t) {
        if (LOG.isErrorEnabled())
            LOG.error("Error initializing SocketConnectionService", t);
    }
}

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

private void checkHandshake(SSLReport sslReport, SocketChannel socket) {
    final InetSocketAddress address = sslReport.getAddress();
    final String name = sslReport.getHostname();
    IOObserver ioObserver = new IOObserver();
    ObservingSSLEngine sslEngine = new ObservingSSLEngine(ctx.createSSLEngine(name, address.getPort()),
            ioObserver);/*from w  w w  .j  av  a 2s. c om*/
    sslReport.setIOObserver(ioObserver);
    sslEngine.setUseClientMode(true);

    try {
        sslEngine.beginHandshake();
    } catch (SSLException e) {
        sslReport.setFailed(e);
        Throwable cause = Blame.get(e);
        logger.warn("beginHandshake failed: [{}] {}", cause.getClass(), cause.getMessage());
    }

    // TODO: Is this enough bytes?
    int size = sslEngine.getSession().getApplicationBufferSize() * 2;
    ByteBuffer localText = ByteBuffer.allocate(size);
    ByteBuffer localWire = ByteBuffer.allocate(size);
    ByteBuffer peerText = ByteBuffer.allocate(size);
    ByteBuffer peerWire = ByteBuffer.allocate(size);

    // TODO: I wonder... do we need to send any data at all?
    localText.put("SSL TEST. HELLO.".getBytes());
    localText.flip();

    SSLEngineResult result;
    logger.info("Starting SSL handshake [{}] ", address);
    try {
        SSLEngineResult.HandshakeStatus state;
        state = sslEngine.getHandshakeStatus();
        while (state != FINISHED) {
            // XXX: Use a Selector to wait for data.
            //logger.trace("State: {} [{}]", state, address);
            switch (state) {
            case NEED_TASK:
                sslEngine.getDelegatedTask().run();
                state = sslEngine.getHandshakeStatus();
                break;
            case NEED_WRAP:
                localWire.clear();
                result = sslEngine.wrap(localText, localWire);
                state = result.getHandshakeStatus();
                localWire.flip();
                while (localWire.hasRemaining()) {
                    socket.write(localWire);
                    //logger.trace("Sent {} bytes [{}]", bytes, address);
                }
                localWire.compact();
                break;
            case NEED_UNWRAP:
                // Try reading until we get data.
                Selector selector = Selector.open();
                while (peerWire.position() == 0) {
                    socket.read(peerWire);
                    try {
                        Thread.currentThread().sleep(5);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("Read " + peerWire.position() + " bytes");
                peerWire.flip();
                result = sslEngine.unwrap(peerWire, peerText);
                state = result.getHandshakeStatus();
                peerWire.compact();
                break;
            }
        }
    } catch (IOException e) {
        sslReport.setFailed(e);
        sslReport.setSSLSession(sslEngine.getHandshakeSession());
        sslReport.setPeerCertificateDetails(peerCertificateDetails);
        logger.warn("beginHandshake failed", e);
        return;
    }

    logger.info("handshake completed [{}]", address);

    // Handshake OK!
    sslReport.setSSLSession(sslEngine.getSession());
}

From source file:org.openhab.binding.mart.handler.martHandler.java

@Override
public void initialize() {
    // TODO: Initialize the thing. If done set status to ONLINE to indicate proper working.
    logger.debug("Initializing Mart Smart Adapter handler '{}'", getThing().getUID());
    // Long running initialization should be done asynchronously in background.

    try {/*from   w  w w .  ja  v a2  s  .  c  o  m*/
        // open the selector
        selector = Selector.open();
    } catch (IOException e) {
        // TODO: handle exception
        logger.error("An IOException occurred while registering the selector: '{}'", e.getMessage());
    }

    // create a listener channel given a port number
    createListenerChannel(LISTENER_PORT_NUMBER);

    // returns the configuration of the thing .get the ip address of the thing
    if (getConfig().get(IP_ADDRESS) != null && getConfig().get(IP_ADDRESS) != "") {

        // establish a connection
        establishConnection();

        if (listeningJob == null || listeningJob.isCancelled()) {

            try {
                // Creates and executes a periodic action that becomes enabled first after the given initial delay,
                // and subsequently with the given delay between the termination of one execution and the
                // commencement
                // of the next
                // In this method, however, the period is interpreted as the delay between the end of the previous
                // execution,
                // until the start of the next. The delay is thus between finished executions, not between the
                // beginning of
                // executions
                listeningJob = scheduler.scheduleWithFixedDelay(listeningRunnable, INITIAL_DELAY,
                        CONNECTION_REFRESH_INTERVAL, TimeUnit.MILLISECONDS);
            } catch (Exception e) {
                updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE,
                        "An error occurred while scheduling the connection Job");
            }

        }

        if (pollingJob == null || pollingJob.isCancelled()) {
            try {
                pollingJob = scheduler.scheduleWithFixedDelay(pollingRunnable, INITIAL_DELAY,
                        ((BigDecimal) getConfig().get(POLLING_REFRESH_INTERVAL)).intValue(),
                        TimeUnit.MILLISECONDS);

            } catch (Exception e) {
                updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE,
                        "An error occurred while scheduling the connection Job");
            }
        }

    } else {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                "IP address or port number not set");
    }

}

From source file:org.eclipse.smarthome.binding.lifx.internal.LifxLightDiscovery.java

protected void doScan() {

    try {//from   www .j a v a 2 s.  co m

        if (!isScanning) {
            isScanning = true;
            if (selector != null) {
                selector.close();
            }

            if (broadcastChannel != null) {
                broadcastChannel.close();
            }

            selector = Selector.open();

            broadcastChannel = DatagramChannel.open(StandardProtocolFamily.INET)
                    .setOption(StandardSocketOptions.SO_REUSEADDR, true)
                    .setOption(StandardSocketOptions.SO_BROADCAST, true);
            broadcastChannel.configureBlocking(false);
            broadcastChannel.socket().setSoTimeout(BROADCAST_TIMEOUT);
            broadcastChannel.bind(new InetSocketAddress(BROADCAST_PORT));

            SelectionKey broadcastKey = broadcastChannel.register(selector,
                    SelectionKey.OP_READ | SelectionKey.OP_WRITE);

            networkJob = scheduler.schedule(networkRunnable, 0, TimeUnit.MILLISECONDS);

            source = UUID.randomUUID().getLeastSignificantBits() & (-1L >>> 32);
            logger.debug("The LIFX discovery service will use '{}' as source identifier",
                    Long.toString(source, 16));

            GetServiceRequest packet = new GetServiceRequest();
            packet.setSequence(SERVICE_REQUEST_SEQ_NO);
            packet.setSource(source);

            broadcastPacket(packet, broadcastKey);
        } else {
            logger.info("A discovery scan for LIFX light is already underway");
        }

    } catch (Exception e) {
        logger.debug("An exception occurred while discovering LIFX lights : '{}'", e.getMessage());
    }

}