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:com.ok2c.lightmtp.impl.protocol.ExtendedSendHeloCodec.java

@Override
public void produceData(final IOSession iosession, final ClientState sessionState)
        throws IOException, SMTPProtocolException {
    Args.notNull(iosession, "IO session");
    Args.notNull(sessionState, "Session state");

    SessionOutputBuffer buf = this.iobuffers.getOutbuf();

    String myHelo = heloName;//from  ww w  . j  a  v a2  s .  c  o  m
    if (myHelo == null) {
        myHelo = AddressUtils.resolveLocalDomain(iosession.getLocalAddress());
    }
    switch (this.codecState) {
    case EHLO_READY:
        SMTPCommand ehlo = new SMTPCommand("EHLO", myHelo);
        this.writer.write(ehlo, buf);
        this.codecState = CodecState.EHLO_RESPONSE_EXPECTED;
        break;
    case HELO_READY:
        SMTPCommand helo = new SMTPCommand("HELO", myHelo);
        this.writer.write(helo, buf);
        this.codecState = CodecState.HELO_RESPONSE_EXPECTED;
        break;
    }

    if (buf.hasData()) {
        buf.flush(iosession.channel());
    }
    if (!buf.hasData()) {
        iosession.clearEvent(SelectionKey.OP_WRITE);
    }
}

From source file:com.ok2c.lightmtp.impl.protocol.AuthCodec.java

@Override
public void reset(final IOSession iosession, final ClientState state)
        throws IOException, SMTPProtocolException {
    this.parser.reset();
    this.writer.reset();
    this.codecState = CodecState.AUTH_READY;
    this.lineBuf.clear();
    iosession.setEvent(SelectionKey.OP_WRITE);

}

From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.OutgoingConnectionThread.java

@Override
public void run() {

    while (!isInterrupted()) {

        synchronized (this.pendingConnectionRequests) {

            if (!this.pendingConnectionRequests.isEmpty()) {

                final OutgoingConnection outgoingConnection = this.pendingConnectionRequests.poll();
                try {
                    final SocketChannel socketChannel = SocketChannel.open();
                    socketChannel.configureBlocking(false);
                    final SelectionKey key = socketChannel.register(this.selector, SelectionKey.OP_CONNECT);
                    socketChannel.connect(outgoingConnection.getConnectionAddress());
                    key.attach(outgoingConnection);
                } catch (final IOException ioe) {
                    // IOException is reported by separate thread to avoid deadlocks
                    final Runnable reporterThread = new Runnable() {

                        @Override
                        public void run() {
                            outgoingConnection.reportConnectionProblem(ioe);
                        }//  w ww  . j ava2  s.c om
                    };
                    new Thread(reporterThread).start();
                }
            }
        }

        synchronized (this.pendingWriteEventSubscribeRequests) {

            if (!this.pendingWriteEventSubscribeRequests.isEmpty()) {
                final SelectionKey oldSelectionKey = this.pendingWriteEventSubscribeRequests.poll();
                final OutgoingConnection outgoingConnection = (OutgoingConnection) oldSelectionKey.attachment();
                final SocketChannel socketChannel = (SocketChannel) oldSelectionKey.channel();

                try {
                    final SelectionKey newSelectionKey = socketChannel.register(this.selector,
                            SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                    newSelectionKey.attach(outgoingConnection);
                    outgoingConnection.setSelectionKey(newSelectionKey);
                } catch (final IOException ioe) {
                    // IOException is reported by separate thread to avoid deadlocks
                    final Runnable reporterThread = new Runnable() {

                        @Override
                        public void run() {
                            outgoingConnection.reportTransmissionProblem(ioe);
                        }
                    };
                    new Thread(reporterThread).start();
                }
            }
        }

        synchronized (this.connectionsToClose) {

            final Iterator<Map.Entry<OutgoingConnection, Long>> closeIt = this.connectionsToClose.entrySet()
                    .iterator();
            final long now = System.currentTimeMillis();
            while (closeIt.hasNext()) {

                final Map.Entry<OutgoingConnection, Long> entry = closeIt.next();
                if ((entry.getValue().longValue() + MIN_IDLE_TIME_BEFORE_CLOSE) < now) {
                    final OutgoingConnection outgoingConnection = entry.getKey();
                    closeIt.remove();
                    // Create new thread to close connection to avoid deadlocks
                    final Runnable closeThread = new Runnable() {

                        @Override
                        public void run() {
                            try {
                                outgoingConnection.closeConnection();
                            } catch (IOException ioe) {
                                outgoingConnection.reportTransmissionProblem(ioe);
                            }
                        }
                    };

                    new Thread(closeThread).start();
                }

            }
        }

        try {
            this.selector.select(10);
        } catch (IOException e) {
            LOG.error(e);
        }

        final Iterator<SelectionKey> iter = this.selector.selectedKeys().iterator();

        while (iter.hasNext()) {
            final SelectionKey key = iter.next();

            iter.remove();
            if (key.isValid()) {
                if (key.isConnectable()) {
                    doConnect(key);
                } else {
                    if (key.isReadable()) {
                        doRead(key);
                        // A read will always result in an exception, so the write key will not be valid anymore
                        continue;
                    }
                    if (key.isWritable()) {
                        doWrite(key);
                    }
                }
            } else {
                LOG.error("Received invalid key: " + key);
            }
        }
    }

    // Finally, try to close the selector
    try {
        this.selector.close();
    } catch (IOException ioe) {
        LOG.debug(StringUtils.stringifyException(ioe));
    }
}

From source file:com.ok2c.lightmtp.impl.protocol.SendLocalHeloCodec.java

@Override
public void consumeData(final IOSession iosession, final ClientState sessionState)
        throws IOException, SMTPProtocolException {
    Args.notNull(iosession, "IO session");
    Args.notNull(sessionState, "Session state");

    SessionInputBuffer buf = this.iobuffers.getInbuf();

    int bytesRead = buf.fill(iosession.channel());
    SMTPReply reply = this.parser.parse(buf, bytesRead == -1);

    if (reply != null) {
        switch (this.codecState) {
        case SERVICE_READY_EXPECTED:
            if (reply.getCode() == SMTPCodes.SERVICE_READY) {
                this.codecState = CodecState.LHLO_READY;
                iosession.setEvent(SelectionKey.OP_WRITE);
            } else {
                this.codecState = CodecState.COMPLETED;
                sessionState.setReply(reply);
            }/*from  ww w .  java2s  .co  m*/
            break;
        case LHLO_RESPONSE_EXPECTED:
            if (reply.getCode() == SMTPCodes.OK) {

                Set<String> extensions = sessionState.getExtensions();

                List<String> lines = reply.getLines();
                if (lines.size() > 1) {
                    for (int i = 1; i < lines.size(); i++) {
                        String line = lines.get(i);
                        extensions.add(line.toUpperCase(Locale.US));
                    }
                }
            }
            this.codecState = CodecState.COMPLETED;
            sessionState.setReply(reply);
            break;
        default:
            if (reply.getCode() == SMTPCodes.ERR_TRANS_SERVICE_NOT_AVAILABLE) {
                sessionState.setReply(reply);
                this.codecState = CodecState.COMPLETED;
            } else {
                throw new SMTPProtocolException("Unexpected reply: " + reply);
            }
        }
    } else {
        if (bytesRead == -1 && !sessionState.isTerminated()) {
            throw new UnexpectedEndOfStreamException();
        }
    }
}

From source file:com.ok2c.lightmtp.impl.protocol.SendDataCodec.java

@Override
public void reset(final IOSession iosession, final ClientState sessionState)
        throws IOException, SMTPProtocolException {
    Args.notNull(iosession, "IO session");
    Args.notNull(sessionState, "Session state");
    if (sessionState.getRequest() == null) {
        throw new IllegalArgumentException("Delivery request may not be null");
    }//from www . jav  a 2  s .c  o m

    DeliveryRequest request = sessionState.getRequest();

    this.parser.reset();
    this.contentBuf.clear();
    this.lineBuf.clear();
    this.recipients.clear();
    if (this.mode.equals(DataAckMode.PER_RECIPIENT)) {
        this.recipients.addAll(request.getRecipients());
    }

    this.content = request.getContent();
    this.contentChannel = this.content.channel();
    this.contentSent = false;
    this.codecState = CodecState.CONTENT_READY;

    iosession.setEvent(SelectionKey.OP_WRITE);
}

From source file:com.l2jfree.network.mmocore.ReadWriteThread.java

private static String describeInterestOps(int interestOps) {
    final TreeSet<String> result = new TreeSet<String>();
    if ((interestOps & SelectionKey.OP_ACCEPT) != 0)
        result.add("ACCEPT");
    if ((interestOps & SelectionKey.OP_CONNECT) != 0)
        result.add("CONNECT");
    if ((interestOps & SelectionKey.OP_READ) != 0)
        result.add("READ");
    if ((interestOps & SelectionKey.OP_WRITE) != 0)
        result.add("WRITE");
    return StringUtils.join(result, "|");
}

From source file:com.ok2c.lightmtp.impl.protocol.PipeliningSendEnvelopCodec.java

@Override
public void produceData(final IOSession iosession, final ClientState sessionState)
        throws IOException, SMTPProtocolException {
    Args.notNull(iosession, "IO session");
    Args.notNull(sessionState, "Session state");
    if (sessionState.getRequest() == null) {
        if (sessionState.isTerminated()) {
            this.codecState = CodecState.COMPLETED;
        }//from  www. j  av  a  2s. co  m
        return;
    }

    SessionOutputBuffer buf = this.iobuffers.getOutbuf();
    DeliveryRequest request = sessionState.getRequest();

    switch (this.codecState) {
    case MAIL_REQUEST_READY:
        SMTPCommand mailFrom = new SMTPCommand("MAIL", "FROM:<" + request.getSender() + ">");
        this.writer.write(mailFrom, buf);

        this.recipients.addAll(request.getRecipients());

        for (String recipient : request.getRecipients()) {
            SMTPCommand rcptTo = new SMTPCommand("RCPT", "TO:<" + recipient + ">");
            this.writer.write(rcptTo, buf);
        }
        SMTPCommand data = new SMTPCommand("DATA");
        this.writer.write(data, buf);
        this.codecState = CodecState.MAIL_RESPONSE_EXPECTED;
        break;
    }

    if (buf.hasData()) {
        buf.flush(iosession.channel());
    }
    if (!buf.hasData()) {
        iosession.clearEvent(SelectionKey.OP_WRITE);
    }
}

From source file:com.byteatebit.nbserver.task.TestWriteMessageTask.java

@Test
public void testWriteMessageInParts() throws IOException {
    SocketChannel socket = mock(SocketChannel.class);
    ByteArrayOutputStream messageStream = new ByteArrayOutputStream();
    String messagePart1 = "messagePart1 ";
    String messagePart2 = "messagePart2";
    String message = messagePart1 + messagePart2;
    when(socket.write(any(ByteBuffer.class))).then(new Answer<Integer>() {
        @Override/*from www  .  j a v  a  2  s.c  om*/
        public Integer answer(InvocationOnMock invocationOnMock) throws Throwable {
            ByteBuffer buffer = (ByteBuffer) invocationOnMock.getArguments()[0];
            for (int i = 0; i < messagePart1.length(); i++)
                messageStream.write(buffer.get());
            return messagePart1.length();
        }
    }).then(new Answer<Integer>() {
        @Override
        public Integer answer(InvocationOnMock invocationOnMock) throws Throwable {
            ByteBuffer buffer = (ByteBuffer) invocationOnMock.getArguments()[0];
            for (int i = 0; i < messagePart2.length(); i++)
                messageStream.write(buffer.get());
            return messagePart2.length();
        }
    });
    INbContext nbContext = mock(INbContext.class);
    SelectionKey selectionKey = mock(SelectionKey.class);
    when(selectionKey.channel()).thenReturn(socket);
    when(selectionKey.isValid()).thenReturn(true);
    when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_WRITE);

    WriteMessageTask writeTask = WriteMessageTask.Builder.builder().withByteBuffer(ByteBuffer.allocate(100))
            .build();
    List<String> callbackInvoked = new ArrayList<>();
    Runnable callback = () -> callbackInvoked.add("");
    Consumer<Exception> exceptionHandler = e -> Assert.fail(e.getMessage());
    writeTask.writeMessage(message.getBytes(StandardCharsets.UTF_8), nbContext, socket, callback,
            exceptionHandler);
    verify(nbContext, times(1)).register(any(SocketChannel.class), eq(SelectionKey.OP_WRITE), any(), any());
    // simulate first write
    writeTask.write(selectionKey, callback, exceptionHandler);
    verify(selectionKey, times(0)).interestOps(0);
    // simulate second write
    writeTask.write(selectionKey, callback, exceptionHandler);
    verify(selectionKey, times(1)).interestOps(0);

    Assert.assertEquals(message, messageStream.toString(StandardCharsets.UTF_8));
    Assert.assertEquals(1, callbackInvoked.size());
}

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();//from   w ww  .  ja va 2s . c  om
            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:com.ok2c.lightmtp.impl.protocol.SimpleSendEnvelopCodec.java

@Override
public void produceData(final IOSession iosession, final ClientState sessionState)
        throws IOException, SMTPProtocolException {
    Args.notNull(iosession, "IO session");
    Args.notNull(sessionState, "Session state");
    if (sessionState.getRequest() == null) {
        if (sessionState.isTerminated()) {
            this.codecState = CodecState.COMPLETED;
        }/* ww  w  .j  av  a  2s .  c  om*/
        return;
    }

    SessionOutputBuffer buf = this.iobuffers.getOutbuf();
    DeliveryRequest request = sessionState.getRequest();

    switch (this.codecState) {
    case MAIL_REQUEST_READY:
        SMTPCommand mailFrom = new SMTPCommand("MAIL", "FROM:<" + request.getSender() + ">");
        this.writer.write(mailFrom, buf);

        this.codecState = CodecState.MAIL_RESPONSE_EXPECTED;
        iosession.setEvent(SelectionKey.OP_READ);
        break;
    case RCPT_REQUEST_READY:
        String recipient = this.recipients.getFirst();

        SMTPCommand rcptTo = new SMTPCommand("RCPT", "TO:<" + recipient + ">");
        this.writer.write(rcptTo, buf);

        this.codecState = CodecState.RCPT_RESPONSE_EXPECTED;
        break;
    case DATA_REQUEST_READY:
        SMTPCommand data = new SMTPCommand("DATA");
        this.writer.write(data, buf);
        this.codecState = CodecState.DATA_RESPONSE_EXPECTED;
        break;
    }

    if (buf.hasData()) {
        buf.flush(iosession.channel());
    }
    if (!buf.hasData()) {
        iosession.clearEvent(SelectionKey.OP_WRITE);
    }
}