Example usage for java.nio.channels SelectionKey OP_WRITE

List of usage examples for java.nio.channels SelectionKey OP_WRITE

Introduction

In this page you can find the example usage for java.nio.channels SelectionKey OP_WRITE.

Prototype

int OP_WRITE

To view the source code for java.nio.channels SelectionKey OP_WRITE.

Click Source Link

Document

Operation-set bit for write operations.

Usage

From source file:org.cloudata.core.commitlog.pipe.CloseState.java

public boolean writeToNext(Context ctx) throws IOException {
    LOG.debug("writeToNext");

    if (!ctx.isLastPipe) {
        LOG.debug("not last pipe");
        ByteBuffer msg = closeMessage.duplicate();
        msg.position(ctx.closeMessagePos);
        try {//  ww  w. ja  va 2  s  .  c  o m
            ctx.closeMessagePos = ctx.nextChannel.write(msg);
        } catch (IOException e) {
            throw new PipeNormallyClosed();
        }

        if (msg.hasRemaining()) {
            ctx.deregisterFromSelect(ctx.nextChannel, SelectionKey.OP_WRITE);
            return false;
        }
    } else {
        LOG.debug("send ok ack to prev");
        ctx.closeMessagePos = 0;
        ctx.ack.clear();
        ctx.ack.put(Constants.PIPE_DISCONNECT_OK);
        ctx.ack.flip();
        return writeToPrev(ctx);
    }

    return true;
}

From source file:org.cloudata.core.commitlog.pipe.InitState.java

public boolean writeToPrev(Pipe.Context ctx) throws IOException {
    if (ctx.msg.write(ctx.prevChannel)) {
        ctx.deregisterFromSelect(ctx.prevChannel, SelectionKey.OP_WRITE);
        ctx.changePipeState(RunState.instance());
        return true;
    } else {/*from  ww  w. ja v a2  s  .  c  o m*/
        ctx.registerToSelect(ctx.prevChannel, SelectionKey.OP_WRITE);
        return false;
    }
}

From source file:org.cloudata.core.commitlog.pipe.InitState.java

public boolean writeToNext(Pipe.Context ctx) throws IOException {
    if (ctx.msg.write(ctx.nextChannel)) {
        try {//from w ww  . j a v  a2s  .  c  o m
            testProxy.clearWriteProcess(ctx);
        } catch (UndeclaredThrowableException e) {
            ProxyExceptionHelper.handleException(e, LOG);
        }
        return true;
    } else {
        ctx.registerToSelect(ctx.nextChannel, SelectionKey.OP_WRITE);
        return false;
    }
}

From source file:org.cloudata.core.commitlog.pipe.InitState.java

public void clearWriteProcess(Pipe.Context ctx) throws IOException {
    ctx.deregisterFromSelect(ctx.nextChannel, SelectionKey.OP_WRITE);
    ctx.msg.clear();
}

From source file:org.cloudata.core.commitlog.pipe.PipeState.java

protected boolean writeAckToPrev(Pipe.Context ctx) throws IOException {
    ctx.prevChannel.write(ctx.ack);//  w  w  w.j  a  v  a 2s  .c o m

    if (ctx.ack.hasRemaining()) {
        if (!ctx.selectingWritePrev) {
            ctx.registerToSelect(ctx.prevChannel, SelectionKey.OP_WRITE);
            ctx.selectingWritePrev = true;
        }

        LOG.info("ack will be sent in next select time!!");
        return false;
    } else {
        ctx.ack.clear();

        if (ctx.selectingWritePrev) {
            ctx.deregisterFromSelect(ctx.prevChannel, SelectionKey.OP_WRITE);
        }

        return true;
    }
}

From source file:org.cloudata.core.commitlog.pipe.RunState.java

public boolean writeToNext(Pipe.Context ctx) throws IOException {
    if (ctx.isLastPipe && ctx.status.dataReceived) {
        if (ctx.status.scheduled == false) {
            try {
                testProxy.writeToLogFile(ctx);
            } catch (UndeclaredThrowableException e) {
                LOG.error("error in scheduling write", e);
                ProxyExceptionHelper.handleException(e, LOG);
            }//from   w ww  . j  a  v  a2s. c o  m
        } else {
            LOG.warn("tried to schedule again.");
        }

        return true;
    }

    if (ctx.nextChannel != null && ctx.bulk.isWrittingDone() == false) {
        if (ctx.bulk.write(ctx.nextChannel) == OperationResult.partially) {
            if (ctx.selectingWriteNext == false) {
                ctx.registerToSelect(ctx.nextChannel, SelectionKey.OP_WRITE);
                ctx.selectingWriteNext = true;
            }

            return false;
        } else if (ctx.status.inReceivingData == false && ctx.bulk.isWrittingDone()) {
            if (ctx.status.scheduled == false) {
                try {
                    testProxy.writeToLogFile(ctx);
                } catch (UndeclaredThrowableException e) {
                    LOG.error("error in scheduling write", e);
                    ProxyExceptionHelper.handleException(e, LOG);
                }
            } else {
                LOG.warn("tried to schedule again..");
            }

            if (ctx.selectingWriteNext) {
                ctx.deregisterFromSelect(ctx.nextChannel, SelectionKey.OP_WRITE);
                ctx.selectingWriteNext = false;
            }
        }
    }

    return true;
}

From source file:org.commoncrawl.io.internal.NIOSocketSelector.java

/** register a socket for WRITE events */
public void registerForWrite(NIOClientSocket theSocket) throws IOException {
    registerSocket(theSocket, SelectionKey.OP_WRITE);
}

From source file:org.commoncrawl.io.internal.NIOSocketSelector.java

/** register a socket for READ AND WRITE events */
public void registerForReadAndWrite(NIOClientSocket theSocket) throws IOException {
    registerSocket(theSocket, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}

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

protected void doScan() {

    try {/* w w  w.  ja v a 2s  .com*/

        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());
    }

}

From source file:org.eclipsetrader.directa.internal.core.BrokerConnector.java

@Override
public void run() {
    Selector socketSelector;//from w w w.jav  a 2 s.c o m
    ByteBuffer dst = ByteBuffer.wrap(new byte[2048]);
    List<Position> positions = new ArrayList<Position>();

    try {
        // Create a non-blocking socket channel
        socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);

        socketChannel.socket().setReceiveBufferSize(32768);
        socketChannel.socket().setSoLinger(true, 1);
        socketChannel.socket().setSoTimeout(0x15f90);
        socketChannel.socket().setReuseAddress(true);

        // Kick off connection establishment
        socketChannel.connect(new InetSocketAddress(server, port));

        // Create a new selector
        socketSelector = SelectorProvider.provider().openSelector();

        // Register the server socket channel, indicating an interest in
        // accepting new connections
        socketChannel.register(socketSelector, SelectionKey.OP_READ | SelectionKey.OP_CONNECT);
    } catch (Exception e) {
        Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error connecting to orders monitor", //$NON-NLS-1$
                e);
        Activator.log(status);
        return;
    }

    for (;;) {
        try {
            if (socketSelector.select(30 * 1000) == 0) {
                logger.trace(">" + HEARTBEAT); //$NON-NLS-1$
                socketChannel.write(ByteBuffer.wrap(new String(HEARTBEAT + "\r\n").getBytes())); //$NON-NLS-1$
            }
        } catch (Exception e) {
            break;
        }

        // Iterate over the set of keys for which events are available
        Iterator<SelectionKey> selectedKeys = socketSelector.selectedKeys().iterator();
        while (selectedKeys.hasNext()) {
            SelectionKey key = selectedKeys.next();
            selectedKeys.remove();

            if (!key.isValid()) {
                continue;
            }

            try {
                // Check what event is available and deal with it
                if (key.isConnectable()) {
                    // Finish the connection. If the connection operation failed
                    // this will raise an IOException.
                    try {
                        socketChannel.finishConnect();
                    } catch (IOException e) {
                        // Cancel the channel's registration with our selector
                        key.cancel();
                        return;
                    }

                    // Register an interest in writing on this channel
                    key.interestOps(SelectionKey.OP_WRITE);
                }
                if (key.isWritable()) {
                    logger.trace(">" + LOGIN + WebConnector.getInstance().getUser()); //$NON-NLS-1$
                    socketChannel.write(ByteBuffer.wrap(
                            new String(LOGIN + WebConnector.getInstance().getUser() + "\r\n").getBytes())); //$NON-NLS-1$

                    // Register an interest in reading on this channel
                    key.interestOps(SelectionKey.OP_READ);
                }
                if (key.isReadable()) {
                    dst.clear();
                    int readed = socketChannel.read(dst);
                    if (readed > 0) {
                        String[] s = new String(dst.array(), 0, readed).split("\r\n"); //$NON-NLS-1$
                        for (int i = 0; i < s.length; i++) {
                            logger.trace("<" + s[i]); //$NON-NLS-1$

                            if (s[i].endsWith(";" + WebConnector.getInstance().getUser() + ";")) { //$NON-NLS-1$ //$NON-NLS-2$
                                logger.trace(">" + UNKNOWN70); //$NON-NLS-1$
                                socketChannel.write(ByteBuffer.wrap(new String(UNKNOWN70 + "\r\n").getBytes())); //$NON-NLS-1$
                                logger.trace(">" + UNKNOWN55); //$NON-NLS-1$
                                socketChannel.write(ByteBuffer.wrap(new String(UNKNOWN55 + "\r\n").getBytes())); //$NON-NLS-1$
                            }

                            if (s[i].indexOf(";6;5;") != -1 || s[i].indexOf(";8;0;") != -1) { //$NON-NLS-1$ //$NON-NLS-2$
                                try {
                                    OrderMonitor monitor = parseOrderLine(s[i]);

                                    OrderDelta[] delta;
                                    synchronized (orders) {
                                        if (!orders.contains(monitor)) {
                                            orders.add(monitor);
                                            delta = new OrderDelta[] {
                                                    new OrderDelta(OrderDelta.KIND_ADDED, monitor) };
                                        } else {
                                            delta = new OrderDelta[] {
                                                    new OrderDelta(OrderDelta.KIND_UPDATED, monitor) };
                                        }
                                    }
                                    fireUpdateNotifications(delta);

                                    if (monitor.getFilledQuantity() != null
                                            && monitor.getAveragePrice() != null) {
                                        Account account = WebConnector.getInstance().getAccount();
                                        account.updatePosition(monitor);
                                    }
                                } catch (ParseException e) {
                                    Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0,
                                            "Error parsing line: " + s[i], e); //$NON-NLS-1$
                                    Activator.log(status);
                                }
                            }
                            if (s[i].indexOf(";6;0;") != -1) { //$NON-NLS-1$
                                updateStatusLine(s[i]);
                            }
                            if (s[i].indexOf(";7;0;") != -1) { //$NON-NLS-1$
                                try {
                                    positions.add(new Position(s[i]));
                                } catch (Exception e) {
                                    Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0,
                                            "Error parsing line: " + s[i], e); //$NON-NLS-1$
                                    Activator.log(status);
                                }
                            }
                            if (s[i].indexOf(";7;9;") != -1) { //$NON-NLS-1$
                                Account account = WebConnector.getInstance().getAccount();
                                account.setPositions(positions.toArray(new Position[positions.size()]));
                                positions.clear();
                            }
                        }
                    }
                }
            } catch (Exception e) {
                Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Connection error", e); //$NON-NLS-1$
                Activator.log(status);
            }
        }
    }
}