Java Examples for java.nio.channels.NotYetConnectedException

The following java examples will help you to understand the usage of java.nio.channels.NotYetConnectedException. These source code samples are taken from different open source projects.

Example 1
Project: jsonapi-master  File: JSONWebSocketServer.java View source code
@Override
public void run() {
    String line = "";
    boolean continueSending = true;
    while ((line = s.nextLine()) != null && continueSending) {
        try {
            if (conn.isOpen()) {
                conn.send(line.trim() + "\r\n");
            } else {
                continueSending = false;
            }
        } catch (NotYetConnectedException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }
}
Example 2
Project: stetho-master  File: ChromePeerManager.java View source code
private void sendMessageToPeers(String method, Object params, @Nullable PendingRequestCallback callback) {
    JsonRpcPeer[] peers = getReceivingPeersSnapshot();
    for (JsonRpcPeer peer : peers) {
        try {
            peer.invokeMethod(method, params, callback);
        } catch (NotYetConnectedException e) {
            LogRedirector.e(TAG, "Error delivering data to Chrome", e);
        }
    }
}
Example 3
Project: DeviceConnect-Android-master  File: AWSIotWebSocketClient.java View source code
@Override
public void onOpen(final ServerHandshake handshakedata) {
    if (DEBUG) {
        Log.i(TAG, "Open the WebSocket. accessToken=" + mAccessToken);
    }
    try {
        send("{\"" + DConnectMessage.EXTRA_ACCESS_TOKEN + "\":\"" + mAccessToken + "\"}");
    } catch (NotYetConnectedException e) {
        if (DEBUG) {
            Log.e(TAG, "", e);
        }
    }
}
Example 4
Project: aerogear-android-push-simplepush-master  File: SimplePushWebsocketClient.java View source code
@Override
public void send(final String text) throws NotYetConnectedException {
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                connectionLatch.await(9000, TimeUnit.SECONDS);
                SimplePushWebsocketClient.super.send(text);
            } catch (InterruptedException ex) {
                Logger.getLogger(SimplePushWebsocketClient.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }).start();
}
Example 5
Project: mileniagrafter-master  File: RtmpHsa.java View source code
/**
	 * Sends first handshake chunk - 0x03 followed by 1536 bytes of random data, in this case zeros
	 * @throws IOException
	 */
public void sendStamp() throws IOException {
    try {
        // trying to write stamp buffer
        // if all is written, step to next phase
        socket.write(stampBuffer);
        if (!stampBuffer.hasRemaining())
            state = 1;
    } catch (NotYetConnectedException exception) {
        exception.printStackTrace();
    } catch (IOException exception) {
        throw exception;
    }
}
Example 6
Project: netty-learning-master  File: AbstractNioWorker.java View source code
protected static void cleanUpWriteBuffer(AbstractNioChannel<?> channel) {
    Exception cause = null;
    boolean fireExceptionCaught = false;
    // Clean up the stale messages in the write buffer.
    synchronized (channel.writeLock) {
        MessageEvent evt = channel.currentWriteEvent;
        if (evt != null) {
            // caused by fillStackTrace.
            if (channel.isOpen()) {
                cause = new NotYetConnectedException();
            } else {
                cause = new ClosedChannelException();
            }
            ChannelFuture future = evt.getFuture();
            if (channel.currentWriteBuffer != null) {
                channel.currentWriteBuffer.release();
                channel.currentWriteBuffer = null;
            }
            channel.currentWriteEvent = null;
            // Mark the event object for garbage collection.
            //noinspection UnusedAssignment
            evt = null;
            future.setFailure(cause);
            fireExceptionCaught = true;
        }
        Queue<MessageEvent> writeBuffer = channel.writeBufferQueue;
        for (; ; ) {
            evt = writeBuffer.poll();
            if (evt == null) {
                break;
            }
            // caused by fillStackTrace.
            if (cause == null) {
                if (channel.isOpen()) {
                    cause = new NotYetConnectedException();
                } else {
                    cause = new ClosedChannelException();
                }
                fireExceptionCaught = true;
            }
            evt.getFuture().setFailure(cause);
        }
    }
    if (fireExceptionCaught) {
        if (isIoThread(channel)) {
            fireExceptionCaught(channel, cause);
        } else {
            fireExceptionCaughtLater(channel, cause);
        }
    }
}
Example 7
Project: netty-master  File: KQueueDatagramChannel.java View source code
private boolean doWriteMessage(Object msg) throws Exception {
    final ByteBuf data;
    InetSocketAddress remoteAddress;
    if (msg instanceof AddressedEnvelope) {
        @SuppressWarnings("unchecked") AddressedEnvelope<ByteBuf, InetSocketAddress> envelope = (AddressedEnvelope<ByteBuf, InetSocketAddress>) msg;
        data = envelope.content();
        remoteAddress = envelope.recipient();
    } else {
        data = (ByteBuf) msg;
        remoteAddress = null;
    }
    final int dataLen = data.readableBytes();
    if (dataLen == 0) {
        return true;
    }
    if (remoteAddress == null) {
        remoteAddress = remote;
        if (remoteAddress == null) {
            throw new NotYetConnectedException();
        }
    }
    final int writtenBytes;
    if (data.hasMemoryAddress()) {
        long memoryAddress = data.memoryAddress();
        writtenBytes = socket.sendToAddress(memoryAddress, data.readerIndex(), data.writerIndex(), remoteAddress.getAddress(), remoteAddress.getPort());
    } else if (data instanceof CompositeByteBuf) {
        IovArray array = ((KQueueEventLoop) eventLoop()).cleanArray();
        array.add(data);
        int cnt = array.count();
        assert cnt != 0;
        writtenBytes = socket.sendToAddresses(array.memoryAddress(0), cnt, remoteAddress.getAddress(), remoteAddress.getPort());
    } else {
        ByteBuffer nioData = data.internalNioBuffer(data.readerIndex(), data.readableBytes());
        writtenBytes = socket.sendTo(nioData, nioData.position(), nioData.limit(), remoteAddress.getAddress(), remoteAddress.getPort());
    }
    return writtenBytes > 0;
}
Example 8
Project: netty3.9-note-master  File: AbstractNioWorker.java View source code
protected static void cleanUpWriteBuffer(AbstractNioChannel<?> channel) {
    Exception cause = null;
    boolean fireExceptionCaught = false;
    // Clean up the stale messages in the write buffer.
    synchronized (channel.writeLock) {
        MessageEvent evt = channel.currentWriteEvent;
        if (evt != null) {
            // caused by fillStackTrace.
            if (channel.isOpen()) {
                cause = new NotYetConnectedException();
            } else {
                cause = new ClosedChannelException();
            }
            ChannelFuture future = evt.getFuture();
            if (channel.currentWriteBuffer != null) {
                channel.currentWriteBuffer.release();
                channel.currentWriteBuffer = null;
            }
            channel.currentWriteEvent = null;
            // Mark the event object for garbage collection.
            //noinspection UnusedAssignment
            evt = null;
            future.setFailure(cause);
            fireExceptionCaught = true;
        }
        Queue<MessageEvent> writeBuffer = channel.writeBufferQueue;
        for (; ; ) {
            evt = writeBuffer.poll();
            if (evt == null) {
                break;
            }
            // caused by fillStackTrace.
            if (cause == null) {
                if (channel.isOpen()) {
                    cause = new NotYetConnectedException();
                } else {
                    cause = new ClosedChannelException();
                }
                fireExceptionCaught = true;
            }
            evt.getFuture().setFailure(cause);
        }
    }
    if (fireExceptionCaught) {
        if (isIoThread(channel)) {
            fireExceptionCaught(channel, cause);
        } else {
            fireExceptionCaughtLater(channel, cause);
        }
    }
}
Example 9
Project: netty4.0.27Learn-master  File: EpollDatagramChannel.java View source code
private boolean doWriteMessage(Object msg) throws Exception {
    final ByteBuf data;
    InetSocketAddress remoteAddress;
    if (msg instanceof AddressedEnvelope) {
        @SuppressWarnings("unchecked") AddressedEnvelope<ByteBuf, InetSocketAddress> envelope = (AddressedEnvelope<ByteBuf, InetSocketAddress>) msg;
        data = envelope.content();
        remoteAddress = envelope.recipient();
    } else {
        data = (ByteBuf) msg;
        remoteAddress = null;
    }
    final int dataLen = data.readableBytes();
    if (dataLen == 0) {
        return true;
    }
    if (remoteAddress == null) {
        remoteAddress = remote;
        if (remoteAddress == null) {
            throw new NotYetConnectedException();
        }
    }
    final int writtenBytes;
    if (data.hasMemoryAddress()) {
        long memoryAddress = data.memoryAddress();
        writtenBytes = Native.sendToAddress(fd().intValue(), memoryAddress, data.readerIndex(), data.writerIndex(), remoteAddress.getAddress(), remoteAddress.getPort());
    } else if (data instanceof CompositeByteBuf) {
        IovArray array = IovArrayThreadLocal.get((CompositeByteBuf) data);
        int cnt = array.count();
        assert cnt != 0;
        writtenBytes = Native.sendToAddresses(fd().intValue(), array.memoryAddress(0), cnt, remoteAddress.getAddress(), remoteAddress.getPort());
    } else {
        ByteBuffer nioData = data.internalNioBuffer(data.readerIndex(), data.readableBytes());
        writtenBytes = Native.sendTo(fd().intValue(), nioData, nioData.position(), nioData.limit(), remoteAddress.getAddress(), remoteAddress.getPort());
    }
    return writtenBytes > 0;
}
Example 10
Project: netty4study-master  File: LocalChannel.java View source code
@Override
protected void doWrite(ChannelOutboundBuffer in) throws Exception {
    if (state < 2) {
        throw new NotYetConnectedException();
    }
    if (state > 2) {
        throw new ClosedChannelException();
    }
    final LocalChannel peer = this.peer;
    final ChannelPipeline peerPipeline = peer.pipeline();
    final EventLoop peerLoop = peer.eventLoop();
    if (peerLoop == eventLoop()) {
        for (; ; ) {
            Object msg = in.current();
            if (msg == null) {
                break;
            }
            peer.inboundBuffer.add(msg);
            ReferenceCountUtil.retain(msg);
            in.remove();
        }
        finishPeerRead(peer, peerPipeline);
    } else {
        // Use a copy because the original msgs will be recycled by AbstractChannel.
        final Object[] msgsCopy = new Object[in.size()];
        for (int i = 0; i < msgsCopy.length; i++) {
            msgsCopy[i] = ReferenceCountUtil.retain(in.current());
            in.remove();
        }
        peerLoop.execute(new Runnable() {

            @Override
            public void run() {
                Collections.addAll(peer.inboundBuffer, msgsCopy);
                finishPeerRead(peer, peerPipeline);
            }
        });
    }
}
Example 11
Project: oobd-master  File: ComPort_Telnet.java View source code
public synchronized void write(String s) {
    try {
        Logger.getLogger(ComPort_Telnet.class.getName()).log(Level.INFO, "Telnet output:{0}", s);
        out.write(s.getBytes());
    // outStream.flush();
    } catch (IOException ex) {
        Logger.getLogger(ComPort_Telnet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NotYetConnectedException ex) {
        Logger.getLogger(ComPort_Telnet.class.getName()).log(Level.WARNING, null, ex);
    }
}
Example 12
Project: streamline-master  File: AbstractNioWorker.java View source code
protected void cleanUpWriteBuffer(AbstractNioChannel<?> channel) {
    Exception cause = null;
    boolean fireExceptionCaught = false;
    // Clean up the stale messages in the write buffer.
    synchronized (channel.writeLock) {
        MessageEvent evt = channel.currentWriteEvent;
        if (evt != null) {
            // caused by fillStackTrace.
            if (channel.isOpen()) {
                cause = new NotYetConnectedException();
            } else {
                cause = new ClosedChannelException();
            }
            ChannelFuture future = evt.getFuture();
            channel.currentWriteBuffer.release();
            channel.currentWriteBuffer = null;
            channel.currentWriteEvent = null;
            evt = null;
            future.setFailure(cause);
            fireExceptionCaught = true;
        }
        Queue<MessageEvent> writeBuffer = channel.writeBufferQueue;
        if (!writeBuffer.isEmpty()) {
            // caused by fillStackTrace.
            if (cause == null) {
                if (channel.isOpen()) {
                    cause = new NotYetConnectedException();
                } else {
                    cause = new ClosedChannelException();
                }
            }
            for (; ; ) {
                evt = writeBuffer.poll();
                if (evt == null) {
                    break;
                }
                evt.getFuture().setFailure(cause);
                fireExceptionCaught = true;
            }
        }
    }
    if (fireExceptionCaught) {
        if (isIoThread(channel)) {
            fireExceptionCaught(channel, cause);
        } else {
            fireExceptionCaughtLater(channel, cause);
        }
    }
}
Example 13
Project: Subspace-Mobile-master  File: Network.java View source code
public final void run() {
    ByteBuffer buffer = ByteBuffer.allocateDirect(MAX_UDP_PACKETSIZE);
    // subspace uses little endian
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    while (isRunning) {
        try {
            buffer.clear();
            int lengthOfData = channel.read(buffer);
            // ignore random empty packets
            if (lengthOfData > 0) {
                // increment packet count
                BytesIn += lengthOfData;
                packetInCount++;
                // flip buffer
                buffer.flip();
                // verbose
                if (LOG_RAW_PACKETS) {
                    Log.v(TAG, "R:" + Util.ToHex(buffer));
                }
                // send call back
                callback.Recv(buffer, true);
            }
        } catch (AsynchronousCloseException ioe) {
            Log.v(TAG, "Timeout exceeded, interrupted");
        } catch (ClosedChannelException cce) {
            Log.v(TAG, "Connection Closed by host, no response");
        } catch (PortUnreachableException pue) {
            Log.v(TAG, "Unable to connect, no response");
        } catch (NotYetConnectedException pue) {
            Log.v(TAG, "Unable to connect, no response");
        } catch (Exception ioe) {
            Log.e(TAG, Log.getStackTraceString(ioe));
        }
    }
}
Example 14
Project: cassandra-connector-java-master  File: CassandraConnection.java View source code
public CassandraFuture send(Request request) {
    if (!started.get()) {
        throw new NotYetConnectedException();
    }
    CassandraFuture future = newFuture(request);
    if (!initializer.startupFuture.await().isSuccess()) {
        future.setFailure(initializer.startupFuture.cause());
        return future;
    }
    if (!channel.isActive()) {
        future.setFailure(new ClosedChannelException());
        return future;
    }
    request.setCompression(options.getCompression() != Compression.NONE);
    futureMap.addFuture(future);
    channel.writeAndFlush(request);
    return future;
}
Example 15
Project: channelmanager2-master  File: AsynchSSLEngineImpl.java View source code
public void feedPlainPacket(ByteBuffer b, Object passThrough) {
    if (!isConnected)
        throw new NotYetConnectedException();
    else if (isClosing || isClosed) {
        throw new IllegalStateException(id + "SSLEngine is in the process of closing or is closed");
    } else if (runningRunnable)
        throw new IllegalStateException(id + "SSLListener was passed a Runnable object that" + " has not completed yet and must complete before encryption can continue");
    if (log.isLoggable(Level.FINE))
        log.fine(id + "feedPlainPacket [in-buffer] pos=" + b.position() + " lim=" + b.limit());
    HELPER.eraseBuffer(engineToSocketData);
    SSLEngineResult result;
    try {
        result = sslEngine.wrap(b, engineToSocketData);
    } catch (SSLException e) {
        throw new AsyncSSLEngineException(e);
    }
    Status status = result.getStatus();
    HandshakeStatus hsStatus = result.getHandshakeStatus();
    if (status != Status.OK)
        throw new RuntimeException("Bug, status=" + status + " instead of OK.  hsStatus=" + hsStatus + " Something went wrong and we could not encrypt the data");
    else if (b.hasRemaining())
        throw new RuntimeException(id + "Bug, should read all my data every time");
    HELPER.doneFillingBuffer(engineToSocketData);
    if (log.isLoggable(Level.FINE))
        log.fine(id + "SSLListener.packetEncrypted pos=" + engineToSocketData.position() + " lim=" + engineToSocketData.limit() + " hsStatus=" + hsStatus + " status=" + status);
    fireEncryptedPacketToListener(passThrough);
}
Example 16
Project: classlib6-master  File: SocketChannelImpl.java View source code
public int read(ByteBuffer dst) throws IOException {
    if (!isConnected())
        throw new NotYetConnectedException();
    byte[] data;
    int offset = 0;
    InputStream input = socket.getInputStream();
    int available = input.available();
    int len = dst.remaining();
    if ((!isBlocking()) && available == 0)
        return 0;
    if (dst.hasArray()) {
        offset = dst.arrayOffset() + dst.position();
        data = dst.array();
    } else {
        data = new byte[len];
    }
    int readBytes = 0;
    boolean completed = false;
    try {
        begin();
        socket.getPlainSocketImpl().setInChannelOperation(true);
        readBytes = input.read(data, offset, len);
        completed = true;
    } finally {
        end(completed);
        socket.getPlainSocketImpl().setInChannelOperation(false);
    }
    if (readBytes > 0)
        if (dst.hasArray()) {
            dst.position(dst.position() + readBytes);
        } else {
            dst.put(data, offset, readBytes);
        }
    return readBytes;
}
Example 17
Project: CoinJoin-master  File: PeerSocketHandler.java View source code
/**
     * Sends the given message to the peer. Due to the asynchronousness of network programming, there is no guarantee
     * the peer will have received it. Throws NotYetConnectedException if we are not yet connected to the remote peer.
     * TODO: Maybe use something other than the unchecked NotYetConnectedException here
     */
public void sendMessage(Message message) throws NotYetConnectedException {
    lock.lock();
    try {
        if (writeTarget == null)
            throw new NotYetConnectedException();
    } finally {
        lock.unlock();
    }
    // TODO: Some round-tripping could be avoided here
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        serializer.serialize(message, out);
        writeTarget.writeBytes(out.toByteArray());
    } catch (IOException e) {
        exceptionCaught(e);
    }
}
Example 18
Project: eucalyptus-fork-2.0-master  File: NioBootstrap.java View source code
@Override
public void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent e) throws Exception {
    ctx.sendUpstream(e);
    final Throwable cause = e.getCause();
    if (!(cause instanceof NotYetConnectedException) && !this.finished) {
        e.getChannel().close();
        this.finished = this.futureQueue.offer(Channels.failedFuture(e.getChannel(), cause));
        assert this.finished;
    }
}
Example 19
Project: Grizzly-master  File: SSLConnectorHandler.java View source code
/**
     * Read bytes. If blocking is set to <tt>true</tt>, a pool of temporary
     * {@link Selector} will be used to read bytes.
     * @param byteBuffer The byteBuffer to store bytes.
     * @param blocking <tt>true</tt> if a a pool of temporary Selector
     *        is required to handle a blocking read.
     * @return number of bytes read from a channel.
     * Be careful, because return value represents the length of encrypted data,
     * which was read from a channel. Don't use return value to determine the
     * availability of a decrypted data to process, but use byteBuffer.remaining().
     * @throws java.io.IOException
     */
@Override
public long read(ByteBuffer byteBuffer, boolean blocking) throws IOException {
    if (!isConnected) {
        throw new NotYetConnectedException();
    }
    if (blocking) {
        return SSLUtils.doSecureRead(underlyingChannel, sslEngine, byteBuffer, securedInputBuffer).bytesRead;
    } else {
        isAsyncReadQueueMode = false;
        int nRead = doReadAsync(byteBuffer);
        if (nRead == 0) {
            registerSelectionKeyFor(SelectionKey.OP_READ);
        }
        return nRead;
    }
}
Example 20
Project: grizzly-mirror-master  File: SSLConnectorHandler.java View source code
/**
     * Read bytes. If blocking is set to <tt>true</tt>, a pool of temporary
     * {@link Selector} will be used to read bytes.
     * @param byteBuffer The byteBuffer to store bytes.
     * @param blocking <tt>true</tt> if a a pool of temporary Selector
     *        is required to handle a blocking read.
     * @return number of bytes read from a channel.
     * Be careful, because return value represents the length of encrypted data,
     * which was read from a channel. Don't use return value to determine the
     * availability of a decrypted data to process, but use byteBuffer.remaining().
     * @throws java.io.IOException
     */
@Override
public long read(ByteBuffer byteBuffer, boolean blocking) throws IOException {
    if (!isConnected) {
        throw new NotYetConnectedException();
    }
    if (blocking) {
        return SSLUtils.doSecureRead(underlyingChannel, sslEngine, byteBuffer, securedInputBuffer).bytesRead;
    } else {
        isAsyncReadQueueMode = false;
        int nRead = doReadAsync(byteBuffer);
        if (nRead == 0) {
            registerSelectionKeyFor(SelectionKey.OP_READ);
        }
        return nRead;
    }
}
Example 21
Project: JamVM-PH-master  File: DatagramChannelImpl.java View source code
public long write(ByteBuffer[] srcs, int offset, int length) throws IOException {
    if (!isConnected())
        throw new NotYetConnectedException();
    if ((offset < 0) || (offset > srcs.length) || (length < 0) || (length > (srcs.length - offset)))
        throw new IndexOutOfBoundsException();
    /* We are connected, meaning we will write these bytes to
     * the host we connected to, so we don't need to explicitly
     * give the host. */
    return channel.writeGathering(srcs, offset, length);
}
Example 22
Project: jdk7u-jdk-master  File: Send.java View source code
void doTest(SocketAddress peerAddress) {
    SctpChannel channel = null;
    ByteBuffer buffer = ByteBuffer.allocate(Util.LARGE_BUFFER);
    MessageInfo info = MessageInfo.createOutgoing(null, 0);
    try {
        channel = SctpChannel.open();
        /* TEST 1: Verify NotYetConnectedException thrown */
        try {
            channel.send(buffer, info);
            fail("should have thrown NotYetConnectedException");
        } catch (NotYetConnectedException unused) {
            pass();
        } catch (IOException ioe) {
            unexpected(ioe);
        }
        channel.connect(peerAddress);
        /* Receive CommUp */
        channel.receive(buffer, null, handler);
        /* TEST 2: send small message */
        int streamNumber = 0;
        debug("sending on stream number: " + streamNumber);
        info = MessageInfo.createOutgoing(null, streamNumber);
        buffer.put(Util.SMALL_MESSAGE.getBytes("ISO-8859-1"));
        buffer.flip();
        int position = buffer.position();
        int remaining = buffer.remaining();
        debug("sending small message: " + buffer);
        int sent = channel.send(buffer, info);
        check(sent == remaining, "sent should be equal to remaining");
        check(buffer.position() == (position + sent), "buffers position should have been incremented by sent");
        buffer.clear();
        /* TEST 3: send large message */
        streamNumber = handler.maxOutStreams() - 1;
        debug("sending on stream number: " + streamNumber);
        info = MessageInfo.createOutgoing(null, streamNumber);
        buffer.put(Util.LARGE_MESSAGE.getBytes("ISO-8859-1"));
        buffer.flip();
        position = buffer.position();
        remaining = buffer.remaining();
        debug("sending large message: " + buffer);
        sent = channel.send(buffer, info);
        check(sent == remaining, "sent should be equal to remaining");
        check(buffer.position() == (position + sent), "buffers position should have been incremented by sent");
        /* TEST 4: InvalidStreamExcepton */
        streamNumber = handler.maxInStreams;
        info = MessageInfo.createOutgoing(null, streamNumber);
        buffer.clear();
        buffer.put(Util.SMALL_MESSAGE.getBytes("ISO-8859-1"));
        buffer.flip();
        position = buffer.position();
        remaining = buffer.remaining();
        debug("sending on stream number: " + streamNumber);
        debug("sending small message: " + buffer);
        try {
            sent = channel.send(buffer, info);
            fail("should have thrown InvalidStreamExcepton");
        } catch (InvalidStreamException ise) {
            pass();
        } catch (IOException ioe) {
            unexpected(ioe);
        }
        check(buffer.remaining() == remaining, "remaining should not be changed");
        check(buffer.position() == position, "buffers position should not be changed");
        /* TEST 5: Non blocking send should return zero if there is
               insufficient room in the underlying output buffer */
        buffer.clear();
        channel.configureBlocking(false);
        info = MessageInfo.createOutgoing(null, 1);
        buffer.put(Util.LARGE_MESSAGE.getBytes("ISO-8859-1"));
        buffer.flip();
        // do not loop forever
        int count = 0;
        do {
            position = buffer.position();
            remaining = buffer.remaining();
            debug("sending large message: " + buffer);
            sent = channel.send(buffer, info);
            if (sent == 0) {
                check(buffer.remaining() == remaining, "remaining should not be changed");
                check(buffer.position() == position, "buffers position should not be changed");
            }
            buffer.rewind();
        } while (sent != 0 && count++ < 100);
        /* TEST 6: ClosedChannelException */
        channel.close();
        try {
            channel.send(buffer, info);
            fail("should have thrown ClosedChannelException");
        } catch (ClosedChannelException cce) {
            pass();
        } catch (IOException ioe) {
            unexpected(ioe);
        }
        /* TEST 7: send without previous receive.
             * Verify that send can still throw InvalidStreamExcepton */
        debug("Opening new channel.");
        channel = SctpChannel.open(peerAddress, 0, 0);
        streamNumber = Short.MAX_VALUE - 1;
        info = MessageInfo.createOutgoing(null, streamNumber);
        buffer.clear();
        buffer.put(Util.SMALL_MESSAGE.getBytes("ISO-8859-1"));
        buffer.flip();
        position = buffer.position();
        remaining = buffer.remaining();
        debug("sending on stream number: " + streamNumber);
        debug("sending small message: " + buffer);
        try {
            sent = channel.send(buffer, info);
            fail("should have thrown InvalidStreamExcepton");
        } catch (InvalidStreamException ise) {
            pass();
        } catch (IOException ioe) {
            unexpected(ioe);
        }
        check(buffer.remaining() == remaining, "remaining should not be changed");
        check(buffer.position() == position, "buffers position should not be changed");
        /* Receive CommUp */
        channel.receive(buffer, null, handler);
        check(handler.receivedCommUp(), "should have received COMM_UP");
        /* TEST 8: Send to an invalid preferred SocketAddress */
        SocketAddress addr = new InetSocketAddress("123.123.123.123", 3456);
        info = MessageInfo.createOutgoing(addr, 0);
        debug("sending to " + addr);
        debug("sending small message: " + buffer);
        try {
            sent = channel.send(buffer, info);
            fail("Invalid address should have thrown an Exception.");
        } catch (Exception e) {
            pass();
            debug("OK, caught " + e);
        }
        /* TEST 9: Send from heap buffer to force implementation to
             * substitute with a native buffer, then check that its position
             * is updated correctly */
        buffer.clear();
        info = MessageInfo.createOutgoing(null, 0);
        buffer.put(Util.SMALL_MESSAGE.getBytes("ISO-8859-1"));
        buffer.flip();
        final int offset = 1;
        buffer.position(offset);
        remaining = buffer.remaining();
        debug("sending small message: " + buffer);
        try {
            sent = channel.send(buffer, info);
            check(sent == remaining, "sent should be equal to remaining");
            check(buffer.position() == (offset + sent), "buffers position should have been incremented by sent");
        } catch (IllegalArgumentException iae) {
            fail(iae + ", Error updating buffers position");
        }
    } catch (IOException ioe) {
        unexpected(ioe);
    } finally {
        clientFinishedLatch.countDown();
        try {
            serverFinishedLatch.await(10L, TimeUnit.SECONDS);
        } catch (InterruptedException ie) {
            unexpected(ie);
        }
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException e) {
                unexpected(e);
            }
        }
    }
}
Example 23
Project: jucy-master  File: MultiStandardConnection.java View source code
public void run() {
    try {
        // Create the selector
        synchronized (this) {
            if (selector == null) {
                selector = Selector.open();
            }
            notifyAll();
        }
        logger.debug("selector created");
        // Wait for events
        while (true) {
            try {
                // Wait for an event
                selector.select(100);
            } catch (IOException e) {
                logger.error("selector error", e);
            }
            runSubmitted();
            // Get list of selection keys with pending events
            Iterator<SelectionKey> it = selector.selectedKeys().iterator();
            // Process each key at a time
            while (it.hasNext()) {
                // Get the selection key
                SelectionKey selKey = it.next();
                // Remove it from the list to indicate that it is being processed
                it.remove();
                try {
                    processSelectionKey(selKey);
                } catch (IOException e) {
                    if (selKey.attachment() instanceof IUnblocking) {
                        ((IUnblocking) selKey.attachment()).onDisconnect();
                    } else {
                        logger.error("Exception received: " + e, e);
                    }
                } catch (CancelledKeyException ce) {
                    if (selKey.attachment() instanceof IUnblocking) {
                        ((IUnblocking) selKey.attachment()).onDisconnect();
                    } else {
                        logger.error("Exception received: " + ce, ce);
                    }
                } catch (NotYetConnectedException nyce) {
                    if (selKey.attachment() instanceof IUnblocking) {
                        ((IUnblocking) selKey.attachment()).onDisconnect();
                    } else {
                        logger.error("Exception received: " + nyce, nyce);
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.warn("Selection error, IO-Thread died ... restarting IO-Thread", e);
        start();
    }
}
Example 24
Project: openjdk-master  File: Send.java View source code
void doTest(SocketAddress peerAddress) {
    SctpChannel channel = null;
    ByteBuffer buffer = ByteBuffer.allocate(Util.LARGE_BUFFER);
    MessageInfo info = MessageInfo.createOutgoing(null, 0);
    try {
        channel = SctpChannel.open();
        /* TEST 1: Verify NotYetConnectedException thrown */
        try {
            channel.send(buffer, info);
            fail("should have thrown NotYetConnectedException");
        } catch (NotYetConnectedException unused) {
            pass();
        } catch (IOException ioe) {
            unexpected(ioe);
        }
        channel.connect(peerAddress);
        /* Receive CommUp */
        channel.receive(buffer, null, handler);
        /* TEST 2: send small message */
        int streamNumber = 0;
        debug("sending on stream number: " + streamNumber);
        info = MessageInfo.createOutgoing(null, streamNumber);
        buffer.put(Util.SMALL_MESSAGE.getBytes("ISO-8859-1"));
        buffer.flip();
        int position = buffer.position();
        int remaining = buffer.remaining();
        debug("sending small message: " + buffer);
        int sent = channel.send(buffer, info);
        check(sent == remaining, "sent should be equal to remaining");
        check(buffer.position() == (position + sent), "buffers position should have been incremented by sent");
        buffer.clear();
        /* TEST 3: send large message */
        streamNumber = handler.maxOutStreams() - 1;
        debug("sending on stream number: " + streamNumber);
        info = MessageInfo.createOutgoing(null, streamNumber);
        buffer.put(Util.LARGE_MESSAGE.getBytes("ISO-8859-1"));
        buffer.flip();
        position = buffer.position();
        remaining = buffer.remaining();
        debug("sending large message: " + buffer);
        sent = channel.send(buffer, info);
        check(sent == remaining, "sent should be equal to remaining");
        check(buffer.position() == (position + sent), "buffers position should have been incremented by sent");
        /* TEST 4: InvalidStreamExcepton */
        streamNumber = handler.maxInStreams;
        info = MessageInfo.createOutgoing(null, streamNumber);
        buffer.clear();
        buffer.put(Util.SMALL_MESSAGE.getBytes("ISO-8859-1"));
        buffer.flip();
        position = buffer.position();
        remaining = buffer.remaining();
        debug("sending on stream number: " + streamNumber);
        debug("sending small message: " + buffer);
        try {
            sent = channel.send(buffer, info);
            fail("should have thrown InvalidStreamExcepton");
        } catch (InvalidStreamException ise) {
            pass();
        } catch (IOException ioe) {
            unexpected(ioe);
        }
        check(buffer.remaining() == remaining, "remaining should not be changed");
        check(buffer.position() == position, "buffers position should not be changed");
        /* TEST 5: Non blocking send should return zero if there is
               insufficient room in the underlying output buffer */
        buffer.clear();
        channel.configureBlocking(false);
        info = MessageInfo.createOutgoing(null, 1);
        buffer.put(Util.LARGE_MESSAGE.getBytes("ISO-8859-1"));
        buffer.flip();
        // do not loop forever
        int count = 0;
        do {
            position = buffer.position();
            remaining = buffer.remaining();
            debug("sending large message: " + buffer);
            sent = channel.send(buffer, info);
            if (sent == 0) {
                check(buffer.remaining() == remaining, "remaining should not be changed");
                check(buffer.position() == position, "buffers position should not be changed");
            }
            buffer.rewind();
        } while (sent != 0 && count++ < 100);
        /* TEST 6: ClosedChannelException */
        channel.close();
        try {
            channel.send(buffer, info);
            fail("should have thrown ClosedChannelException");
        } catch (ClosedChannelException cce) {
            pass();
        } catch (IOException ioe) {
            unexpected(ioe);
        }
        /* TEST 7: send without previous receive.
             * Verify that send can still throw InvalidStreamExcepton */
        debug("Opening new channel.");
        channel = SctpChannel.open(peerAddress, 0, 0);
        streamNumber = Short.MAX_VALUE - 1;
        info = MessageInfo.createOutgoing(null, streamNumber);
        buffer.clear();
        buffer.put(Util.SMALL_MESSAGE.getBytes("ISO-8859-1"));
        buffer.flip();
        position = buffer.position();
        remaining = buffer.remaining();
        debug("sending on stream number: " + streamNumber);
        debug("sending small message: " + buffer);
        try {
            sent = channel.send(buffer, info);
            fail("should have thrown InvalidStreamExcepton");
        } catch (InvalidStreamException ise) {
            pass();
        } catch (IOException ioe) {
            unexpected(ioe);
        }
        check(buffer.remaining() == remaining, "remaining should not be changed");
        check(buffer.position() == position, "buffers position should not be changed");
        /* Receive CommUp */
        channel.receive(buffer, null, handler);
        check(handler.receivedCommUp(), "should have received COMM_UP");
        /* TEST 8: Send to an invalid preferred SocketAddress */
        SocketAddress addr = new InetSocketAddress("123.123.123.123", 3456);
        info = MessageInfo.createOutgoing(addr, 0);
        debug("sending to " + addr);
        debug("sending small message: " + buffer);
        try {
            sent = channel.send(buffer, info);
            fail("Invalid address should have thrown an Exception.");
        } catch (Exception e) {
            pass();
            debug("OK, caught " + e);
        }
        /* TEST 9: Send from heap buffer to force implementation to
             * substitute with a native buffer, then check that its position
             * is updated correctly */
        buffer.clear();
        info = MessageInfo.createOutgoing(null, 0);
        buffer.put(Util.SMALL_MESSAGE.getBytes("ISO-8859-1"));
        buffer.flip();
        final int offset = 1;
        buffer.position(offset);
        remaining = buffer.remaining();
        debug("sending small message: " + buffer);
        try {
            sent = channel.send(buffer, info);
            check(sent == remaining, "sent should be equal to remaining");
            check(buffer.position() == (offset + sent), "buffers position should have been incremented by sent");
        } catch (IllegalArgumentException iae) {
            fail(iae + ", Error updating buffers position");
        }
    } catch (IOException ioe) {
        unexpected(ioe);
    } finally {
        clientFinishedLatch.countDown();
        try {
            serverFinishedLatch.await(10L, TimeUnit.SECONDS);
        } catch (InterruptedException ie) {
            unexpected(ie);
        }
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException e) {
                unexpected(e);
            }
        }
    }
}
Example 25
Project: openjdk8-jdk-master  File: Send.java View source code
void doTest(SocketAddress peerAddress) {
    SctpChannel channel = null;
    ByteBuffer buffer = ByteBuffer.allocate(Util.LARGE_BUFFER);
    MessageInfo info = MessageInfo.createOutgoing(null, 0);
    try {
        channel = SctpChannel.open();
        /* TEST 1: Verify NotYetConnectedException thrown */
        try {
            channel.send(buffer, info);
            fail("should have thrown NotYetConnectedException");
        } catch (NotYetConnectedException unused) {
            pass();
        } catch (IOException ioe) {
            unexpected(ioe);
        }
        channel.connect(peerAddress);
        /* Receive CommUp */
        channel.receive(buffer, null, handler);
        /* TEST 2: send small message */
        int streamNumber = 0;
        debug("sending on stream number: " + streamNumber);
        info = MessageInfo.createOutgoing(null, streamNumber);
        buffer.put(Util.SMALL_MESSAGE.getBytes("ISO-8859-1"));
        buffer.flip();
        int position = buffer.position();
        int remaining = buffer.remaining();
        debug("sending small message: " + buffer);
        int sent = channel.send(buffer, info);
        check(sent == remaining, "sent should be equal to remaining");
        check(buffer.position() == (position + sent), "buffers position should have been incremented by sent");
        buffer.clear();
        /* TEST 3: send large message */
        streamNumber = handler.maxOutStreams() - 1;
        debug("sending on stream number: " + streamNumber);
        info = MessageInfo.createOutgoing(null, streamNumber);
        buffer.put(Util.LARGE_MESSAGE.getBytes("ISO-8859-1"));
        buffer.flip();
        position = buffer.position();
        remaining = buffer.remaining();
        debug("sending large message: " + buffer);
        sent = channel.send(buffer, info);
        check(sent == remaining, "sent should be equal to remaining");
        check(buffer.position() == (position + sent), "buffers position should have been incremented by sent");
        /* TEST 4: InvalidStreamExcepton */
        streamNumber = handler.maxInStreams;
        info = MessageInfo.createOutgoing(null, streamNumber);
        buffer.clear();
        buffer.put(Util.SMALL_MESSAGE.getBytes("ISO-8859-1"));
        buffer.flip();
        position = buffer.position();
        remaining = buffer.remaining();
        debug("sending on stream number: " + streamNumber);
        debug("sending small message: " + buffer);
        try {
            sent = channel.send(buffer, info);
            fail("should have thrown InvalidStreamExcepton");
        } catch (InvalidStreamException ise) {
            pass();
        } catch (IOException ioe) {
            unexpected(ioe);
        }
        check(buffer.remaining() == remaining, "remaining should not be changed");
        check(buffer.position() == position, "buffers position should not be changed");
        /* TEST 5: Non blocking send should return zero if there is
               insufficient room in the underlying output buffer */
        buffer.clear();
        channel.configureBlocking(false);
        info = MessageInfo.createOutgoing(null, 1);
        buffer.put(Util.LARGE_MESSAGE.getBytes("ISO-8859-1"));
        buffer.flip();
        // do not loop forever
        int count = 0;
        do {
            position = buffer.position();
            remaining = buffer.remaining();
            debug("sending large message: " + buffer);
            sent = channel.send(buffer, info);
            if (sent == 0) {
                check(buffer.remaining() == remaining, "remaining should not be changed");
                check(buffer.position() == position, "buffers position should not be changed");
            }
            buffer.rewind();
        } while (sent != 0 && count++ < 100);
        /* TEST 6: ClosedChannelException */
        channel.close();
        try {
            channel.send(buffer, info);
            fail("should have thrown ClosedChannelException");
        } catch (ClosedChannelException cce) {
            pass();
        } catch (IOException ioe) {
            unexpected(ioe);
        }
        /* TEST 7: send without previous receive.
             * Verify that send can still throw InvalidStreamExcepton */
        debug("Opening new channel.");
        channel = SctpChannel.open(peerAddress, 0, 0);
        streamNumber = Short.MAX_VALUE - 1;
        info = MessageInfo.createOutgoing(null, streamNumber);
        buffer.clear();
        buffer.put(Util.SMALL_MESSAGE.getBytes("ISO-8859-1"));
        buffer.flip();
        position = buffer.position();
        remaining = buffer.remaining();
        debug("sending on stream number: " + streamNumber);
        debug("sending small message: " + buffer);
        try {
            sent = channel.send(buffer, info);
            fail("should have thrown InvalidStreamExcepton");
        } catch (InvalidStreamException ise) {
            pass();
        } catch (IOException ioe) {
            unexpected(ioe);
        }
        check(buffer.remaining() == remaining, "remaining should not be changed");
        check(buffer.position() == position, "buffers position should not be changed");
        /* Receive CommUp */
        channel.receive(buffer, null, handler);
        check(handler.receivedCommUp(), "should have received COMM_UP");
        /* TEST 8: Send to an invalid preferred SocketAddress */
        SocketAddress addr = new InetSocketAddress("123.123.123.123", 3456);
        info = MessageInfo.createOutgoing(addr, 0);
        debug("sending to " + addr);
        debug("sending small message: " + buffer);
        try {
            sent = channel.send(buffer, info);
            fail("Invalid address should have thrown an Exception.");
        } catch (Exception e) {
            pass();
            debug("OK, caught " + e);
        }
        /* TEST 9: Send from heap buffer to force implementation to
             * substitute with a native buffer, then check that its position
             * is updated correctly */
        buffer.clear();
        info = MessageInfo.createOutgoing(null, 0);
        buffer.put(Util.SMALL_MESSAGE.getBytes("ISO-8859-1"));
        buffer.flip();
        final int offset = 1;
        buffer.position(offset);
        remaining = buffer.remaining();
        debug("sending small message: " + buffer);
        try {
            sent = channel.send(buffer, info);
            check(sent == remaining, "sent should be equal to remaining");
            check(buffer.position() == (offset + sent), "buffers position should have been incremented by sent");
        } catch (IllegalArgumentException iae) {
            fail(iae + ", Error updating buffers position");
        }
    } catch (IOException ioe) {
        unexpected(ioe);
    } finally {
        clientFinishedLatch.countDown();
        try {
            serverFinishedLatch.await(10L, TimeUnit.SECONDS);
        } catch (InterruptedException ie) {
            unexpected(ie);
        }
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException e) {
                unexpected(e);
            }
        }
    }
}
Example 26
Project: smartpaws-android-master  File: DataMan.java View source code
public static void getConvention(final String name, final ResponseHandler<Convention> response) throws NotYetConnectedException {
    Convention result = conventions.get(name);
    if (result != null) {
        response.result(result);
        return;
    }
    NetworkInfo.State state = isNetworkConnected();
    if (state.equals(NetworkInfo.State.DISCONNECTED) || state.equals(NetworkInfo.State.DISCONNECTING)) {
        result = DATABASE.getConvention(name);
        if (result != null) {
            conventions.put(name, result);
            response.result(result);
            return;
        }
        response.result(null);
    }
    HttpClient.get(name + ".json", null, new AsyncHttpResponseHandler() {

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            try {
                Convention convention = GSON.fromJson(new String(responseBody, "UTF-8"), Convention.class);
                conventions.put(name, convention);
                DATABASE.setConvention(name, convention);
                response.result(convention);
            } catch (Exception ex) {
                Log.e(APP_NAME, "", ex);
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            Log.e(APP_NAME, "HTTP Error: " + statusCode + "\nURL:" + "img/" + name + ".json", error);
        }
    });
}
Example 27
Project: WaarpR66-master  File: OpenR66ExceptionTrappedFactory.java View source code
/**
     * @param channel
     * @param throwable
     * @return the OpenR66Exception corresponding to the ExceptionEvent, or null if the exception
     *         should be ignored
     */
public static OpenR66Exception getExceptionFromTrappedException(Channel channel, Throwable throwable) {
    final Throwable e1 = throwable;
    if (e1 instanceof ConnectException) {
        final ConnectException e2 = (ConnectException) e1;
        logger.debug("Connection impossible since {} with Channel {}", e2.getMessage(), channel);
        return new OpenR66ProtocolNoConnectionException("Connection impossible", e2);
    } else if (e1 instanceof ChannelException) {
        final ChannelException e2 = (ChannelException) e1;
        logger.info("Connection (example: timeout) impossible since {} with Channel {}", e2.getMessage(), channel);
        return new OpenR66ProtocolNetworkException("Connection (example: timeout) impossible", e2);
    } else if (e1 instanceof CancelledKeyException) {
        final CancelledKeyException e2 = (CancelledKeyException) e1;
        logger.error("Connection aborted since {}", e2.getMessage());
        // Yes, No action
        return null;
    } else if (e1 instanceof ClosedChannelException) {
        logger.debug("Connection closed before end");
        return new OpenR66ProtocolBusinessNoWriteBackException("Connection closed before end", e1);
    } else if (e1 instanceof IllegalMonitorStateException) {
        logger.debug("Try to release a lock incorrectly", e1);
        return new OpenR66ProtocolBusinessNoWriteBackException("Ignored exception", e1);
    } else if (e1 instanceof OpenR66ProtocolBusinessCancelException) {
        final OpenR66ProtocolBusinessCancelException e2 = (OpenR66ProtocolBusinessCancelException) e1;
        logger.debug("Request is canceled: {}", e2.getMessage());
        return e2;
    } else if (e1 instanceof OpenR66ProtocolBusinessStopException) {
        final OpenR66ProtocolBusinessStopException e2 = (OpenR66ProtocolBusinessStopException) e1;
        logger.debug("Request is stopped: {}", e2.getMessage());
        return e2;
    } else if (e1 instanceof OpenR66ProtocolBusinessQueryAlreadyFinishedException) {
        final OpenR66ProtocolBusinessQueryAlreadyFinishedException e2 = (OpenR66ProtocolBusinessQueryAlreadyFinishedException) e1;
        logger.debug("Request is already finished: {}", e2.getMessage());
        return e2;
    } else if (e1 instanceof OpenR66ProtocolBusinessQueryStillRunningException) {
        final OpenR66ProtocolBusinessQueryStillRunningException e2 = (OpenR66ProtocolBusinessQueryStillRunningException) e1;
        logger.debug("Request is still running: {}", e2.getMessage());
        return e2;
    } else if (e1 instanceof OpenR66ProtocolBusinessRemoteFileNotFoundException) {
        final OpenR66ProtocolBusinessRemoteFileNotFoundException e2 = (OpenR66ProtocolBusinessRemoteFileNotFoundException) e1;
        logger.debug("Remote server did not find file: {}", e2.getMessage());
        return e2;
    } else if (e1 instanceof OpenR66ProtocolBusinessNoWriteBackException) {
        final OpenR66ProtocolBusinessNoWriteBackException e2 = (OpenR66ProtocolBusinessNoWriteBackException) e1;
        logger.error("Command Error Reply: {}", e2.getMessage());
        return e2;
    } else if (e1 instanceof OpenR66ProtocolShutdownException) {
        final OpenR66ProtocolShutdownException e2 = (OpenR66ProtocolShutdownException) e1;
        logger.debug("Command Shutdown {}", e2.getMessage());
        return e2;
    } else if (e1 instanceof OpenR66Exception) {
        final OpenR66Exception e2 = (OpenR66Exception) e1;
        logger.debug("Command Error Reply: {}", e2.getMessage());
        return e2;
    } else if (e1 instanceof BindException) {
        final BindException e2 = (BindException) e1;
        logger.debug("Address already in use {}", e2.getMessage());
        return new OpenR66ProtocolNetworkException("Address already in use", e2);
    } else if (e1 instanceof NotYetConnectedException) {
        final NotYetConnectedException e2 = (NotYetConnectedException) e1;
        logger.debug("Timeout occurs {}", e2.getMessage());
        return new OpenR66ProtocolNetworkException("Timeout occurs", e2);
    } else if (e1 instanceof ConnectException) {
        final ConnectException e2 = (ConnectException) e1;
        logger.debug("Timeout occurs {}", e2.getMessage());
        return new OpenR66ProtocolNetworkException("Timeout occurs", e2);
    } else if (e1 instanceof NullPointerException) {
        final NullPointerException e2 = (NullPointerException) e1;
        logger.error("Null pointer Exception", e2);
        return new OpenR66ProtocolSystemException("Null Pointer Exception", e2);
    } else if (e1 instanceof SSLException) {
        final SSLException e2 = (SSLException) e1;
        logger.debug("Connection aborted since SSL Error {} with Channel {}", e2.getMessage(), channel);
        return new OpenR66ProtocolBusinessNoWriteBackException("SSL Connection aborted", e2);
    } else if (e1 instanceof IOException) {
        final IOException e2 = (IOException) e1;
        logger.debug("Connection aborted since {} with Channel {}", e2.getMessage(), channel);
        if (channel.isActive()) {
            return new OpenR66ProtocolSystemException("Connection aborted due to " + e2.getMessage(), e2);
        } else {
            return new OpenR66ProtocolBusinessNoWriteBackException("Connection aborted due to " + e2.getMessage(), e2);
        }
    } else if (e1 instanceof RejectedExecutionException) {
        final RejectedExecutionException e2 = (RejectedExecutionException) e1;
        logger.debug("Connection aborted since {} with Channel {}", e2.getMessage(), channel);
        if (channel.isActive()) {
            return new OpenR66ProtocolSystemException("Execution aborted", e2);
        } else {
            return new OpenR66ProtocolBusinessNoWriteBackException("Execution aborted", e2);
        }
    } else if (e1 instanceof OutOfMemoryError) {
        final OpenR66ProtocolShutdownException e2 = new OpenR66ProtocolShutdownException("Restart since OOME raized", e1);
        logger.debug("Force Shutdown and Restart : {}", e2.getMessage());
        if (Configuration.configuration.getR66Mib() != null) {
            Configuration.configuration.getR66Mib().notifyWarning("OOME so shutdown and restart", e1.getMessage());
        }
        R66ShutdownHook.setRestart(true);
        return e2;
    } else {
        logger.error("Unexpected exception from Outband" + " Ref Channel: " + channel.toString(), e1);
    }
    if (Configuration.configuration.getR66Mib() != null) {
        Configuration.configuration.getR66Mib().notifyWarning("Unexpected exception", e1.getMessage());
    }
    return new OpenR66ProtocolSystemException("Unexpected exception: " + e1.getMessage(), e1);
}
Example 28
Project: android-libcore64-master  File: SocketChannelTest.java View source code
/*
     * Test method for 'java.nio.channels.SocketChannel.open()'
     */
public void testOpen() throws IOException {
    java.nio.ByteBuffer[] buf = new java.nio.ByteBuffer[1];
    buf[0] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL);
    MockSocketChannel testMSChannel = new MockSocketChannel(null);
    MockSocketChannel testMSChannelnotnull = new MockSocketChannel(SelectorProvider.provider());
    assertNull(testMSChannel.provider());
    assertNotNull(testMSChannelnotnull.provider());
    assertNotNull(this.channel1);
    assertEquals(this.channel1.provider(), testMSChannelnotnull.provider());
    try {
        this.channel1.write(buf);
        fail("Should throw NotYetConnectedException");
    } catch (NotYetConnectedException e) {
    }
}
Example 29
Project: Android-Wallet-2-App-master  File: PeerSocketHandler.java View source code
/**
     * Sends the given message to the peer. Due to the asynchronousness of network programming, there is no guarantee
     * the peer will have received it. Throws NotYetConnectedException if we are not yet connected to the remote peer.
     * TODO: Maybe use something other than the unchecked NotYetConnectedException here
     */
public void sendMessage(Message message) throws NotYetConnectedException {
    lock.lock();
    try {
        if (writeTarget == null)
            throw new NotYetConnectedException();
    } finally {
        lock.unlock();
    }
    // TODO: Some round-tripping could be avoided here
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        serializer.serialize(message, out);
        writeTarget.writeBytes(out.toByteArray());
    } catch (IOException e) {
        exceptionCaught(e);
    }
}
Example 30
Project: android_platform_libcore-master  File: OldSocketChannelTest.java View source code
public void testOpen() throws IOException {
    java.nio.ByteBuffer[] buf = new java.nio.ByteBuffer[1];
    buf[0] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL);
    MockSocketChannel testMSChannel = new MockSocketChannel(null);
    MockSocketChannel testMSChannelnotnull = new MockSocketChannel(SelectorProvider.provider());
    SocketChannel testSChannel = MockSocketChannel.open();
    assertTrue(testSChannel.isOpen());
    assertNull(testMSChannel.provider());
    assertNotNull(testSChannel.provider());
    assertEquals(SelectorProvider.provider(), testSChannel.provider());
    assertNotNull(testMSChannelnotnull.provider());
    assertEquals(this.channel1.provider(), testMSChannelnotnull.provider());
    try {
        this.channel1.write(buf);
        fail("Should throw NotYetConnectedException");
    } catch (NotYetConnectedException e) {
    }
}
Example 31
Project: ARTPart-master  File: SocketChannelTest.java View source code
/*
     * Test method for 'java.nio.channels.SocketChannel.open()'
     */
public void testOpen() throws IOException {
    java.nio.ByteBuffer[] buf = new java.nio.ByteBuffer[1];
    buf[0] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL);
    MockSocketChannel testMSChannel = new MockSocketChannel(null);
    MockSocketChannel testMSChannelnotnull = new MockSocketChannel(SelectorProvider.provider());
    assertNull(testMSChannel.provider());
    assertNotNull(testMSChannelnotnull.provider());
    assertNotNull(this.channel1);
    assertEquals(this.channel1.provider(), testMSChannelnotnull.provider());
    try {
        this.channel1.write(buf);
        fail("Should throw NotYetConnectedException");
    } catch (NotYetConnectedException e) {
    }
}
Example 32
Project: bitcoinj-master  File: PeerSocketHandler.java View source code
/**
     * Sends the given message to the peer. Due to the asynchronousness of network programming, there is no guarantee
     * the peer will have received it. Throws NotYetConnectedException if we are not yet connected to the remote peer.
     * TODO: Maybe use something other than the unchecked NotYetConnectedException here
     */
public void sendMessage(Message message) throws NotYetConnectedException {
    lock.lock();
    try {
        if (writeTarget == null)
            throw new NotYetConnectedException();
    } finally {
        lock.unlock();
    }
    // TODO: Some round-tripping could be avoided here
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        serializer.serialize(message, out);
        writeTarget.writeBytes(out.toByteArray());
    } catch (IOException e) {
        exceptionCaught(e);
    }
}
Example 33
Project: bitherj-master  File: PeerSocketHandler.java View source code
/**
     * Sends the given message to the peer. Due to the asynchronousness of network programming,
     * there is no guarantee
     * the peer will have received it. Throws NotYetConnectedException if we are not yet
     * connected to the remote peer.
     * TODO: Maybe use something other than the unchecked NotYetConnectedException here
     */
public void sendMessage(Message message) throws NotYetConnectedException {
    lock.lock();
    try {
        if (writeTarget == null) {
            throw new NotYetConnectedException();
        }
    } finally {
        lock.unlock();
    }
    // TODO: Some round-tripping could be avoided here
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        serializer.serialize(message, out);
        writeTarget.writeBytes(out.toByteArray());
    } catch (IOException e) {
        exceptionCaught(e);
    }
}
Example 34
Project: darkcoinj-master  File: PeerSocketHandler.java View source code
/**
     * Sends the given message to the peer. Due to the asynchronousness of network programming, there is no guarantee
     * the peer will have received it. Throws NotYetConnectedException if we are not yet connected to the remote peer.
     * TODO: Maybe use something other than the unchecked NotYetConnectedException here
     */
public void sendMessage(Message message) throws NotYetConnectedException {
    lock.lock();
    try {
        if (writeTarget == null)
            throw new NotYetConnectedException();
    } finally {
        lock.unlock();
    }
    // TODO: Some round-tripping could be avoided here
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        serializer.serialize(message, out);
        writeTarget.writeBytes(out.toByteArray());
    } catch (IOException e) {
        exceptionCaught(e);
    }
}
Example 35
Project: ecologylabFundamental-master  File: WebSocketOodssServer.java View source code
/**
	 * serialize the oodss message, attach the uid, convert to bytes, and send to the websocket client
	 * the bytes array has its first 8 bits dedicated to uid, and the rest bits to the body of the 
	 * serialized oodss message
	 * the message is encoded in UTF-8
	 * 
	 * @param uid
	 * 		uid of the request message
	 * @param message
	 * 		oodss message
	 * @param conn
	 * 		websocket client
	 */
private void createPacketFromMessageAndSend(long uid, ServiceMessage message, WebSocket conn) {
    StringBuilder messageStringBuilder = new StringBuilder();
    try {
        SimplTypesScope.serialize(message, messageStringBuilder, StringFormat.XML);
        String messageString = messageStringBuilder.toString();
        byte[] uidBytes = longToBytes(uid);
        byte[] messageBytes = messageString.getBytes("UTF-8");
        byte[] outMessage = new byte[uidBytes.length + messageBytes.length];
        System.arraycopy(uidBytes, 0, outMessage, 0, uidBytes.length);
        System.arraycopy(messageBytes, 0, outMessage, uidBytes.length, messageBytes.length);
        conn.send(outMessage);
    } catch (SIMPLTranslationException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (NotYetConnectedException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
Example 36
Project: Gaea-master  File: CSocket.java View source code
public int send(byte[] data) throws IOException, Throwable {
    try {
        synchronized (sendLockHelper) {
            int pakageSize = data.length + ProtocolConst.P_END_TAG.length;
            if (sendBuffer.capacity() < pakageSize) {
                throw new DataOverFlowException("数�包(size:" + pakageSize + ")超过最大�制,请修改或增加�置文件中的<SocketPool maxPakageSize=\"" + socketConfig.getMaxPakageSize() + "\"/>节点属性�");
            }
            int count = 0;
            sendBuffer.clear();
            sendBuffer.put(data);
            sendBuffer.put(ProtocolConst.P_END_TAG);
            sendBuffer.flip();
            int retryCount = 0;
            while (sendBuffer.hasRemaining()) {
                count += channel.write(sendBuffer);
                if (retryCount++ > 10) {
                    throw new Exception("retry write count(" + retryCount + ") above 10");
                }
            }
            return count;
        }
    } catch (IOException ex) {
        _connecting = false;
        throw ex;
    } catch (NotYetConnectedException ex) {
        _connecting = false;
        throw ex;
    }
}
Example 37
Project: GreenBits-master  File: PeerSocketHandler.java View source code
/**
     * Sends the given message to the peer. Due to the asynchronousness of network programming, there is no guarantee
     * the peer will have received it. Throws NotYetConnectedException if we are not yet connected to the remote peer.
     * TODO: Maybe use something other than the unchecked NotYetConnectedException here
     */
public void sendMessage(Message message) throws NotYetConnectedException {
    lock.lock();
    try {
        if (writeTarget == null)
            throw new NotYetConnectedException();
    } finally {
        lock.unlock();
    }
    // TODO: Some round-tripping could be avoided here
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        serializer.serialize(message, out);
        writeTarget.writeBytes(out.toByteArray());
    } catch (IOException e) {
        exceptionCaught(e);
    }
}
Example 38
Project: java-oss-lib-master  File: AsynchBuffer.java View source code
private void throwException(Exception x) throws TrendrrDisconnectedException, TrendrrException {
    if (x instanceof NotYetConnectedException) {
        throw new TrendrrDisconnectedException(x);
    }
    if (x instanceof ClosedChannelException) {
        throw new TrendrrDisconnectedException(x);
    }
    if (x instanceof SocketException) {
        throw new TrendrrDisconnectedException(x);
    }
    if (x instanceof AsynchronousCloseException) {
        throw new TrendrrDisconnectedException(x);
    }
    if (x instanceof ClosedByInterruptException) {
        throw new TrendrrDisconnectedException(x);
    }
    if (x instanceof TrendrrException) {
        throw (TrendrrException) x;
    }
    if (x instanceof IOException) {
        throw new TrendrrDisconnectedException(x);
    }
    throw new TrendrrException(x);
}
Example 39
Project: kdeconnect-android-master  File: LanLink.java View source code
//Blocking, do not call from main thread
private boolean sendPackageInternal(NetworkPackage np, final Device.SendPackageStatusCallback callback, PublicKey key) {
    if (socket == null) {
        Log.e("KDE/sendPackage", "Not yet connected");
        callback.onFailure(new NotYetConnectedException());
        return false;
    }
    try {
        //Prepare socket for the payload
        final ServerSocket server;
        if (np.hasPayload()) {
            server = LanLinkProvider.openServerSocketOnFreePort(LanLinkProvider.PAYLOAD_TRANSFER_MIN_PORT);
            JSONObject payloadTransferInfo = new JSONObject();
            payloadTransferInfo.put("port", server.getLocalPort());
            np.setPayloadTransferInfo(payloadTransferInfo);
        } else {
            server = null;
        }
        //Encrypt if key provided
        if (key != null) {
            np = RsaHelper.encrypt(np, key);
        }
        //Send body of the network package
        try {
            OutputStream writer = socket.getOutputStream();
            writer.write(np.serialize().getBytes(StringsHelper.UTF8));
            writer.flush();
        } catch (Exception e) {
            disconnect();
            throw e;
        }
        //Send payload
        if (server != null) {
            Socket payloadSocket = null;
            OutputStream outputStream = null;
            InputStream inputStream = null;
            try {
                //Wait a maximum of 10 seconds for the other end to establish a connection with our socket, close it afterwards
                server.setSoTimeout(10 * 1000);
                payloadSocket = server.accept();
                //Convert to SSL if needed
                if (socket instanceof SSLSocket) {
                    payloadSocket = SslHelper.convertToSslSocket(context, payloadSocket, getDeviceId(), true, false);
                }
                outputStream = payloadSocket.getOutputStream();
                inputStream = np.getPayload();
                Log.i("KDE/LanLink", "Beginning to send payload");
                byte[] buffer = new byte[4096];
                int bytesRead;
                long size = np.getPayloadSize();
                long progress = 0;
                long timeSinceLastUpdate = -1;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    //Log.e("ok",""+bytesRead);
                    progress += bytesRead;
                    outputStream.write(buffer, 0, bytesRead);
                    if (size > 0) {
                        if (timeSinceLastUpdate + 500 < System.currentTimeMillis()) {
                            //Report progress every half a second
                            long percent = ((100 * progress) / size);
                            callback.onProgressChanged((int) percent);
                            timeSinceLastUpdate = System.currentTimeMillis();
                        }
                    }
                }
                outputStream.flush();
                outputStream.close();
                Log.i("KDE/LanLink", "Finished sending payload (" + progress + " bytes written)");
            } finally {
                try {
                    server.close();
                } catch (Exception e) {
                }
                try {
                    payloadSocket.close();
                } catch (Exception e) {
                }
                try {
                    inputStream.close();
                } catch (Exception e) {
                }
                try {
                    outputStream.close();
                } catch (Exception e) {
                }
            }
        }
        callback.onSuccess();
        return true;
    } catch (Exception e) {
        if (callback != null) {
            callback.onFailure(e);
        }
        return false;
    } finally {
        //Make sure we close the payload stream, if any
        InputStream stream = np.getPayload();
        try {
            stream.close();
        } catch (Exception e) {
        }
    }
}
Example 40
Project: megacoinj-master  File: PeerSocketHandler.java View source code
/**
     * Sends the given message to the peer. Due to the asynchronousness of network programming, there is no guarantee
     * the peer will have received it. Throws NotYetConnectedException if we are not yet connected to the remote peer.
     * TODO: Maybe use something other than the unchecked NotYetConnectedException here
     */
public void sendMessage(Message message) throws NotYetConnectedException {
    lock.lock();
    try {
        if (writeTarget == null)
            throw new NotYetConnectedException();
    } finally {
        lock.unlock();
    }
    // TODO: Some round-tripping could be avoided here
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        serializer.serialize(message, out);
        writeTarget.writeBytes(out.toByteArray());
    } catch (IOException e) {
        exceptionCaught(e);
    }
}
Example 41
Project: NuBitsj-master  File: PeerSocketHandler.java View source code
/**
     * Sends the given message to the peer. Due to the asynchronousness of network programming, there is no guarantee
     * the peer will have received it. Throws NotYetConnectedException if we are not yet connected to the remote peer.
     * TODO: Maybe use something other than the unchecked NotYetConnectedException here
     */
public void sendMessage(Message message) throws NotYetConnectedException {
    lock.lock();
    try {
        if (writeTarget == null)
            throw new NotYetConnectedException();
    } finally {
        lock.unlock();
    }
    // TODO: Some round-tripping could be avoided here
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        serializer.serialize(message, out);
        writeTarget.writeBytes(out.toByteArray());
    } catch (IOException e) {
        exceptionCaught(e);
    }
}
Example 42
Project: open_robot-master  File: WebSocket.java View source code
/**
   * @return True if all of the text was sent to the client by this thread.
   *    False if some of the text had to be buffered to be sent later.
   */
public boolean send(String text) throws IOException {
    if (!this.handshakeComplete)
        throw new NotYetConnectedException();
    if (text == null)
        throw new NullPointerException("Cannot send 'null' data to a WebSocket.");
    // Get 'text' into a WebSocket "frame" of bytes
    byte[] textBytes = text.getBytes();
    ByteBuffer b = ByteBuffer.allocate(textBytes.length + 2);
    b.put(START_OF_FRAME);
    b.put(textBytes);
    b.put(END_OF_FRAME);
    b.rewind();
    // See if we have any backlog that needs to be sent first
    if (handleWrite()) {
        // Write the ByteBuffer to the socket
        this.socketChannel.write(b);
    }
    // If we didn't get it all sent, add it to the buffer of buffers
    if (b.remaining() > 0) {
        if (!this.bufferQueue.offer(b)) {
            throw new IOException("Buffers are full, message could not be sent to" + this.socketChannel.socket().getRemoteSocketAddress());
        }
        return false;
    }
    return true;
}
Example 43
Project: peercoinj-master  File: PeerSocketHandler.java View source code
/**
     * Sends the given message to the peer. Due to the asynchronousness of network programming, there is no guarantee
     * the peer will have received it. Throws NotYetConnectedException if we are not yet connected to the remote peer.
     * TODO: Maybe use something other than the unchecked NotYetConnectedException here
     */
public void sendMessage(Message message) throws NotYetConnectedException {
    lock.lock();
    try {
        if (writeTarget == null)
            throw new NotYetConnectedException();
    } finally {
        lock.unlock();
    }
    // TODO: Some round-tripping could be avoided here
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        serializer.serialize(message, out);
        writeTarget.writeBytes(out.toByteArray());
    } catch (IOException e) {
        exceptionCaught(e);
    }
}
Example 44
Project: robovm-master  File: SocketChannelTest.java View source code
/*
     * Test method for 'java.nio.channels.SocketChannel.open()'
     */
public void testOpen() throws IOException {
    java.nio.ByteBuffer[] buf = new java.nio.ByteBuffer[1];
    buf[0] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL);
    MockSocketChannel testMSChannel = new MockSocketChannel(null);
    MockSocketChannel testMSChannelnotnull = new MockSocketChannel(SelectorProvider.provider());
    assertNull(testMSChannel.provider());
    assertNotNull(testMSChannelnotnull.provider());
    assertNotNull(this.channel1);
    assertEquals(this.channel1.provider(), testMSChannelnotnull.provider());
    try {
        this.channel1.write(buf);
        fail("Should throw NotYetConnectedException");
    } catch (NotYetConnectedException e) {
    }
}
Example 45
Project: sgs-server-master  File: Reactor.java View source code
/**
     * Registers interest in an IO operation on the channel associated with
     * the given {@link AsyncKey}, returning a future representing the
     * result of the operation.
     * <p>
     * When the requested operation becomes ready, the given {@code task}
     * is invoked so that it may perform the IO operation.  The selector's
     * interest in all ready operations is cleared before dispatching to the
     * task.
     * <p>
     * Several checks are performed on the channel at this point to avoid
     * race conditions where the check succeeds but the condition
     * immediately becomes false. We lock both the {@code selectorLock} and
     * the {@code asyncKey} to ensure that we get a proper view of the state
     * when registering the operation, and so that if the state later
     * changes the operation will be terminated properly.
     * <p>
     * If the channel is closed, {@link ClosedAsynchronousChannelException}
     * is thrown.
     * <p>
     * Additional checks are performed on {@code SocketChannel}s:
     * <ul>
     * <li>
     * If the requested operation is {@code OP_READ} or {@code OP_WRITE}
     * and the channel is not connected, {@link NotYetConnectedException}
     * is thrown.
     * <li>
     * If the requested operation is {@code OP_CONNECT} and the channel is
     * already connected, {@link AlreadyConnectedException} is thrown.
     * </ul>
     * 
     * @param <R> the result type
     * @param asyncKey the key for async operations on the channel
     * @param op the {@link SelectionKey} operation requested
     * @param task the task to invoke when the operation becomes ready
     * 
     * @throws ClosedAsynchronousChannelException if the channel is closed
     * @throws NotYetConnectedException if a read or write operation is
     *         requested on an unconnected {@code SocketChannel}
     * @throws AlreadyConnectedException if a connect operation is requested
     *         on a connected {@code SocketChannel}
     */
<R> void awaitReady(ReactiveAsyncKey asyncKey, int op, AsyncOp<R> task) {
    synchronized (selectorLock) {
        selector.wakeup();
        int interestOps;
        synchronized (asyncKey) {
            SelectionKey key = asyncKey.key;
            if (key == null || (!key.isValid())) {
                throw new ClosedAsynchronousChannelException();
            }
            try {
                interestOps = key.interestOps();
            } catch (CancelledKeyException e) {
                throw new ClosedAsynchronousChannelException();
            }
            SelectableChannel channel = asyncKey.channel();
            // Only SocketChannel has any extra checks to do.
            if (channel instanceof SocketChannel) {
                switch(op) {
                    case OP_READ:
                    case OP_WRITE:
                        if (!((SocketChannel) channel).isConnected()) {
                            throw new NotYetConnectedException();
                        }
                        break;
                    case OP_CONNECT:
                        if (((SocketChannel) channel).isConnected()) {
                            throw new AlreadyConnectedException();
                        }
                        break;
                    default:
                        break;
                }
            }
            // Check that op isn't already in the interest set
            assert (interestOps & op) == 0;
            interestOps |= op;
            try {
                key.interestOps(interestOps);
            } catch (CancelledKeyException e) {
                throw new ClosedAsynchronousChannelException();
            }
        }
        if (log.isLoggable(Level.FINEST)) {
            log.log(Level.FINEST, "{0} awaitReady {1} : new {2} : added {3}", new Object[] { this, task, Util.formatOps(interestOps), Util.formatOps(op) });
        }
    }
}
Example 46
Project: TwoFactorBtcWallet-master  File: PeerSocketHandler.java View source code
/**
     * Sends the given message to the peer. Due to the asynchronousness of network programming, there is no guarantee
     * the peer will have received it. Throws NotYetConnectedException if we are not yet connected to the remote peer.
     * TODO: Maybe use something other than the unchecked NotYetConnectedException here
     */
public void sendMessage(Message message) throws NotYetConnectedException {
    lock.lock();
    try {
        if (writeTarget == null)
            throw new NotYetConnectedException();
    } finally {
        lock.unlock();
    }
    // TODO: Some round-tripping could be avoided here
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        serializer.serialize(message, out);
        writeTarget.writeBytes(out.toByteArray());
    } catch (IOException e) {
        exceptionCaught(e);
    }
}
Example 47
Project: dsys-snio-master  File: SelectorThreadImpl.java View source code
@Override
protected void runKey(final SelectionKey k) {
    try {
        if (k.isReadable()) {
            final Processor proc = (Processor) k.attachment();
            final KeyProcessor<?> keyproc = proc.getProcessor();
            try {
                if (keyproc.read(k) < 0) {
                    proc.close();
                }
            } catch (final IOException e) {
                proc.close();
            } catch (final NotYetConnectedException e) {
                e.printStackTrace();
                proc.close();
            }
        } else if (k.isConnectable()) {
            final Processor proc = (Processor) k.attachment();
            final KeyProcessor<?> processor = proc.getProcessor();
            processor.connect(k);
        }
    } catch (final CancelledKeyException e) {
        return;
    } catch (final IOException e) {
        e.printStackTrace();
        return;
    }
}
Example 48
Project: simple-netty-source-master  File: AbstractNioWorker.java View source code
protected static void cleanUpWriteBuffer(AbstractNioChannel<?> channel) {
    Exception cause = null;
    boolean fireExceptionCaught = false;
    // Clean up the stale messages in the write buffer.
    synchronized (channel.writeLock) {
        MessageEvent evt = channel.currentWriteEvent;
        if (evt != null) {
            // caused by fillStackTrace.
            if (channel.isOpen()) {
                cause = new NotYetConnectedException();
            } else {
                cause = new ClosedChannelException();
            }
            ChannelFuture future = evt.getFuture();
            if (channel.currentWriteBuffer != null) {
                channel.currentWriteBuffer.release();
                channel.currentWriteBuffer = null;
            }
            channel.currentWriteEvent = null;
            // Mark the event object for garbage collection.
            //noinspection UnusedAssignment
            evt = null;
            future.setFailure(cause);
            fireExceptionCaught = true;
        }
        Queue<MessageEvent> writeBuffer = channel.writeBufferQueue;
        for (; ; ) {
            evt = writeBuffer.poll();
            if (evt == null) {
                break;
            }
            // caused by fillStackTrace.
            if (cause == null) {
                if (channel.isOpen()) {
                    cause = new NotYetConnectedException();
                } else {
                    cause = new ClosedChannelException();
                }
                fireExceptionCaught = true;
            }
            evt.getFuture().setFailure(cause);
        }
    }
    if (fireExceptionCaught) {
        if (isIoThread(channel)) {
            fireExceptionCaught(channel, cause);
        } else {
            fireExceptionCaughtLater(channel, cause);
        }
    }
}
Example 49
Project: WaarpFtp-master  File: DataNetworkHandler.java View source code
/**
     * Default exception task: close the current connection after calling exceptionLocalCaught.
     * 
     */
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    if (session == null) {
        logger.debug("Error without any session active {}", cause);
        return;
    }
    Throwable e1 = cause;
    if (e1 instanceof ConnectException) {
        ConnectException e2 = (ConnectException) e1;
        logger.warn("Connection impossible since {}", e2.getMessage());
    } else if (e1 instanceof ChannelException) {
        ChannelException e2 = (ChannelException) e1;
        logger.warn("Connection (example: timeout) impossible since {}", e2.getMessage());
    } else if (e1 instanceof ClosedChannelException) {
        logger.debug("Connection closed before end");
    } else if (e1 instanceof InvalidArgumentException) {
        InvalidArgumentException e2 = (InvalidArgumentException) e1;
        logger.warn("Bad configuration in Codec in {}", e2.getMessage());
    } else if (e1 instanceof NullPointerException) {
        NullPointerException e2 = (NullPointerException) e1;
        logger.warn("Null pointer Exception", e2);
        try {
            if (dataBusinessHandler != null) {
                dataBusinessHandler.exceptionLocalCaught(e1);
                if (session.getDataConn() != null) {
                    if (session.getDataConn().checkCorrectChannel(ctx.channel())) {
                        session.getDataConn().getFtpTransferControl().setTransferAbortedFromInternal(true);
                    }
                }
            }
        } catch (NullPointerException e3) {
        }
        return;
    } else if (e1 instanceof CancelledKeyException) {
        CancelledKeyException e2 = (CancelledKeyException) e1;
        logger.warn("Connection aborted since {}", e2.getMessage());
        // No action
        return;
    } else if (e1 instanceof IOException) {
        IOException e2 = (IOException) e1;
        logger.warn("Connection aborted since {}", e2.getMessage());
    } else if (e1 instanceof NotYetConnectedException) {
        NotYetConnectedException e2 = (NotYetConnectedException) e1;
        logger.debug("Ignore this exception {}", e2.getMessage());
        return;
    } else if (e1 instanceof BindException) {
        BindException e2 = (BindException) e1;
        logger.warn("Address already in use {}", e2.getMessage());
    } else if (e1 instanceof ConnectException) {
        ConnectException e2 = (ConnectException) e1;
        logger.warn("Timeout occurs {}", e2.getMessage());
    } else {
        logger.warn("Unexpected exception from Outband: {}", e1.getMessage(), e1);
    }
    if (dataBusinessHandler != null) {
        dataBusinessHandler.exceptionLocalCaught(e1);
    }
    if (session.getDataConn().checkCorrectChannel(ctx.channel())) {
        session.getDataConn().getFtpTransferControl().setTransferAbortedFromInternal(true);
    }
}
Example 50
Project: webpie-master  File: Helper.java View source code
private static void read(SelectionKey key, SelectorManager2 mgr, BufferPool pool) throws IOException {
    log.trace(() -> key.attachment() + "reading data");
    WrapperAndListener struct = (WrapperAndListener) key.attachment();
    DataListener in = struct.getDataHandler();
    BasChannelImpl channel = (BasChannelImpl) struct.getChannel();
    //pressure in RAM so just wait until they re-registerForReads and they will get the data then
    if (!channel.isRegisteredForReads()) {
        //do not process reads if we were unregistered
        return;
    }
    ByteBuffer chunk = pool.nextBuffer(512);
    try {
        if (logBufferNextRead)
            log.info(channel + "buffer=" + chunk);
        int bytes = channel.readImpl(chunk);
        if (logBufferNextRead) {
            logBufferNextRead = false;
            log.info(channel + "buffer2=" + chunk);
        }
        processBytes(key, chunk, bytes, mgr);
    } catch (PortUnreachableException e) {
        log.trace(() -> "Client sent data to a host or port that is not listening " + "to udp, or udp can't get through to that machine", e);
        in.failure(channel, null, e);
    } catch (NotYetConnectedException e) {
        log.error("Can't read until UDPChannel is connected", e);
        in.failure(channel, null, e);
    } catch (IOException e) {
        process(key, mgr, in, channel, chunk, e);
    } catch (NioException e) {
        Throwable cause = e.getCause();
        if (cause instanceof IOException) {
            IOException ioExc = (IOException) cause;
            process(key, mgr, in, channel, chunk, ioExc);
        } else
            throw e;
    }
}
Example 51
Project: openhab2-master  File: KeContactP20Handler.java View source code
protected ByteBuffer onReadable(DatagramChannel theChannel, int bufferSize, InetAddress permittedClientAddress) {
    lock.lock();
    try {
        SelectionKey theSelectionKey = theChannel.keyFor(selector);
        if (theSelectionKey != null) {
            synchronized (selector) {
                try {
                    selector.selectNow();
                } catch (IOException e) {
                    logger.error("An exception occurred while selecting: {}", e.getMessage());
                }
            }
            Iterator<SelectionKey> it = selector.selectedKeys().iterator();
            while (it.hasNext()) {
                SelectionKey selKey = it.next();
                it.remove();
                if (selKey.isValid() && selKey.isReadable() && selKey == theSelectionKey) {
                    ByteBuffer readBuffer = ByteBuffer.allocate(bufferSize);
                    int numberBytesRead = 0;
                    boolean error = false;
                    if (selKey == listenerKey) {
                        try {
                            InetSocketAddress clientAddress = (InetSocketAddress) theChannel.receive(readBuffer);
                            if (clientAddress.getAddress().equals(permittedClientAddress)) {
                                logger.debug("Received {} on the listener port from {}", new String(readBuffer.array()), clientAddress);
                                numberBytesRead = readBuffer.position();
                            } else {
                                logger.warn("Received data from '{}' which is not the permitted remote address '{}'", clientAddress, permittedClientAddress);
                                return null;
                            }
                        } catch (Exception e) {
                            logger.error("An exception occurred while receiving data on the listener port: '{}'", e.getMessage());
                            error = true;
                        }
                    } else {
                        try {
                            numberBytesRead = theChannel.read(readBuffer);
                        } catch (NotYetConnectedException e) {
                            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "The remote host is not yet connected");
                            error = true;
                        } catch (PortUnreachableException e) {
                            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "The remote host is probably not a KEBA EV Charging station");
                            error = true;
                        } catch (IOException e) {
                            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "An IO exception occurred");
                            error = true;
                        }
                    }
                    if (numberBytesRead == -1) {
                        error = true;
                    }
                    if (error) {
                        logger.debug("Disconnecting '{}' because of a socket error", getThing().getUID().toString());
                        try {
                            theChannel.close();
                        } catch (IOException e) {
                            logger.error("An exception occurred while closing the channel '{}': {}", datagramChannel, e.getMessage());
                        }
                        onConnectionLost();
                    } else {
                        readBuffer.flip();
                        return readBuffer;
                    }
                }
            }
        }
        return null;
    } finally {
        lock.unlock();
    }
}
Example 52
Project: xtreemfs-master  File: RPCNIOSocketClient.java View source code
private void readConnection(SelectionKey key) {
    final RPCClientConnection con = (RPCClientConnection) key.attachment();
    final ChannelIO channel = con.getChannel();
    try {
        if (!channel.isShutdownInProgress()) {
            if (channel.doHandshake(key)) {
                while (true) {
                    ByteBuffer buf = null;
                    switch(con.getReceiveState()) {
                        case RECORD_MARKER:
                            {
                                buf = con.getResponseRecordMarker();
                                break;
                            }
                        case RPC_MESSAGE:
                            {
                                buf = con.getResponseBuffers()[1].getBuffer();
                                break;
                            }
                        case RPC_HEADER:
                            {
                                buf = con.getResponseBuffers()[0].getBuffer();
                                break;
                            }
                        case DATA:
                            {
                                buf = con.getResponseBuffers()[2].getBuffer();
                                break;
                            }
                    }
                    // read fragment header
                    final int numBytesRead = RPCNIOSocketServer.readData(key, channel, buf);
                    if (numBytesRead == -1) {
                        // connection closed
                        if (Logging.isInfo()) {
                            Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, "client closed connection (EOF): %s", channel.socket().getRemoteSocketAddress().toString());
                        }
                        closeConnection(key, "server (" + channel.socket().getRemoteSocketAddress().toString() + ") closed connection");
                        return;
                    }
                    if (buf.hasRemaining()) {
                        // not enough data...
                        break;
                    }
                    switch(con.getReceiveState()) {
                        case RECORD_MARKER:
                            {
                                buf.position(0);
                                final int hdrLen = buf.getInt();
                                final int msgLen = buf.getInt();
                                final int dataLen = buf.getInt();
                                if ((hdrLen <= 0) || (hdrLen >= RPCNIOSocketServer.MAX_FRAGMENT_SIZE) || (msgLen < 0) || (msgLen >= RPCNIOSocketServer.MAX_FRAGMENT_SIZE) || (dataLen < 0) || (dataLen >= RPCNIOSocketServer.MAX_FRAGMENT_SIZE)) {
                                    Logging.logMessage(Logging.LEVEL_ERROR, Category.net, this, "invalid record marker size (%d/%d/%d) received, closing connection to client %s", hdrLen, msgLen, dataLen, channel.socket().getRemoteSocketAddress().toString());
                                    closeConnection(key, "received invalid record marker from server (" + channel.socket().getRemoteSocketAddress().toString() + "), closed connection");
                                    return;
                                }
                                final ReusableBuffer[] buffers = new ReusableBuffer[] { BufferPool.allocate(hdrLen), ((msgLen > 0) ? BufferPool.allocate(msgLen) : null), ((dataLen > 0) ? BufferPool.allocate(dataLen) : null) };
                                con.setResponseBuffers(buffers);
                                con.setReceiveState(RPCNIOSocketServerConnection.ReceiveState.RPC_HEADER);
                                continue;
                            }
                        case RPC_HEADER:
                            {
                                if (con.getResponseBuffers()[1] != null) {
                                    con.setReceiveState(RPCNIOSocketServerConnection.ReceiveState.RPC_MESSAGE);
                                    continue;
                                } else if (con.getResponseBuffers()[2] != null) {
                                    // this is necessary, because we may receive some default 
                                    // instance of a message (empty) with data attached BUG #188
                                    con.setReceiveState(RPCNIOSocketServerConnection.ReceiveState.DATA);
                                    continue;
                                } else {
                                    break;
                                }
                            }
                        case RPC_MESSAGE:
                            {
                                if (con.getResponseBuffers()[2] != null) {
                                    con.setReceiveState(RPCNIOSocketServerConnection.ReceiveState.DATA);
                                    continue;
                                } else {
                                    break;
                                }
                            }
                    }
                    //assemble ServerRequest
                    con.setReceiveState(RPCNIOSocketServerConnection.ReceiveState.RECORD_MARKER);
                    con.getResponseRecordMarker().clear();
                    //assemble response...
                    assembleResponse(key, con);
                }
            }
        }
    } catch (IOException ex) {
        if (Logging.isDebug()) {
            Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, OutputUtils.stackTraceToString(ex));
        }
        closeConnection(key, "server closed connection (" + ex + ")");
    } catch (NotYetConnectedException e) {
        if (Logging.isDebug()) {
            Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, OutputUtils.stackTraceToString(e));
        }
        closeConnection(key, "server closed connection: " + e);
    }
}
Example 53
Project: i2p.i2p-master  File: EventPumper.java View source code
/**
     *  OP_READ will always be set before this is called.
     *  This method will disable the interest if no more reads remain because of inbound bandwidth throttling.
     *  High-frequency path in thread.
     */
private void processRead(SelectionKey key) {
    NTCPConnection con = (NTCPConnection) key.attachment();
    ByteBuffer buf = acquireBuf();
    try {
        int read = con.getChannel().read(buf);
        if (read < 0) {
            //_context.statManager().addRateData("ntcp.readEOF", 1);
            if (con.isInbound() && con.getMessagesReceived() <= 0) {
                InetAddress addr = con.getChannel().socket().getInetAddress();
                int count;
                if (addr != null) {
                    byte[] ip = addr.getAddress();
                    ByteArray ba = new ByteArray(ip);
                    count = _blockedIPs.increment(ba);
                    if (_log.shouldLog(Log.WARN))
                        _log.warn("Blocking IP " + Addresses.toString(ip) + " with count " + count + ": " + con);
                } else {
                    count = 1;
                    if (_log.shouldLog(Log.WARN))
                        _log.warn("EOF on inbound before receiving any: " + con);
                }
                _context.statManager().addRateData("ntcp.dropInboundNoMessage", count);
            } else {
                if (_log.shouldLog(Log.DEBUG))
                    _log.debug("EOF on " + con);
            }
            con.close();
            releaseBuf(buf);
        } else if (read == 0) {
            //if (_log.shouldLog(Log.DEBUG))
            //    _log.debug("nothing to read for " + con + ", but stay interested");
            // stay interested
            //key.interestOps(key.interestOps() | SelectionKey.OP_READ);
            releaseBuf(buf);
            // workaround for channel stuck returning 0 all the time, causing 100% CPU
            int consec = con.gotZeroRead();
            if (consec >= 5) {
                _context.statManager().addRateData("ntcp.zeroReadDrop", 1);
                if (_log.shouldLog(Log.WARN))
                    _log.warn("Fail safe zero read close " + con);
                con.close();
            } else {
                _context.statManager().addRateData("ntcp.zeroRead", consec);
                if (_log.shouldLog(Log.INFO))
                    _log.info("nothing to read for " + con + ", but stay interested");
            }
        } else {
            // clear counter for workaround above
            con.clearZeroRead();
            // ZERO COPY. The buffer will be returned in Reader.processRead()
            buf.flip();
            //con, buf);
            FIFOBandwidthLimiter.Request req = _context.bandwidthLimiter().requestInbound(read, "NTCP read");
            if (req.getPendingRequested() > 0) {
                // rare since we generally don't throttle inbound
                key.interestOps(key.interestOps() & ~SelectionKey.OP_READ);
                //if (_log.shouldLog(Log.DEBUG))
                //    _log.debug("bw throttled reading for " + con + ", so we don't want to read anymore");
                _context.statManager().addRateData("ntcp.queuedRecv", read);
                con.queuedRecv(buf, req);
            } else {
                // fully allocated
                //if (_log.shouldLog(Log.DEBUG))
                //    _log.debug("not bw throttled reading for " + con);
                // stay interested
                //key.interestOps(key.interestOps() | SelectionKey.OP_READ);
                con.recv(buf);
                _context.statManager().addRateData("ntcp.read", read);
            }
        }
    } catch (CancelledKeyException cke) {
        releaseBuf(buf);
        if (_log.shouldLog(Log.WARN))
            _log.warn("error reading on " + con, cke);
        con.close();
        _context.statManager().addRateData("ntcp.readError", 1);
    } catch (IOException ioe) {
        releaseBuf(buf);
        if (con.isInbound() && con.getMessagesReceived() <= 0) {
            InetAddress addr = con.getChannel().socket().getInetAddress();
            int count;
            if (addr != null) {
                byte[] ip = addr.getAddress();
                ByteArray ba = new ByteArray(ip);
                count = _blockedIPs.increment(ba);
                if (_log.shouldLog(Log.WARN))
                    _log.warn("Blocking IP " + Addresses.toString(ip) + " with count " + count + ": " + con);
            } else {
                count = 1;
                if (_log.shouldLog(Log.WARN))
                    _log.warn("IOE on inbound before receiving any: " + con);
            }
            _context.statManager().addRateData("ntcp.dropInboundNoMessage", count);
        } else {
            if (_log.shouldLog(Log.INFO))
                _log.info("error reading on " + con, ioe);
        }
        if (con.isEstablished()) {
            _context.statManager().addRateData("ntcp.readError", 1);
        } else {
            _context.statManager().addRateData("ntcp.connectFailedTimeoutIOE", 1);
            RouterIdentity rem = con.getRemotePeer();
            if (rem != null && !con.isInbound())
                _transport.markUnreachable(rem.calculateHash());
        }
        con.close();
    } catch (NotYetConnectedException nyce) {
        releaseBuf(buf);
        key.interestOps(key.interestOps() & ~SelectionKey.OP_READ);
        if (_log.shouldLog(Log.WARN))
            _log.warn("error reading on " + con, nyce);
    }
}
Example 54
Project: NLiveRoid-master  File: NioWorker.java View source code
private void cleanUpWriteBuffer(NioSocketChannel channel) {
    Log.d("NioWorker", "cleanUpWriteBuffer ");
    Exception cause = null;
    boolean fireExceptionCaught = false;
    // Clean up the stale messages in the write buffer.
    synchronized (channel.writeLock) {
        MessageEvent evt = channel.currentWriteEvent;
        if (evt != null) {
            // caused by fillStackTrace.
            if (channel.isOpen()) {
                cause = new NotYetConnectedException();
            } else {
                cause = new ClosedChannelException();
            }
            ChannelFuture future = evt.getFuture();
            channel.currentWriteBuffer.release();
            channel.currentWriteBuffer = null;
            channel.currentWriteEvent = null;
            evt = null;
            future.setFailure(cause);
            fireExceptionCaught = true;
        }
        Queue<MessageEvent> writeBuffer = channel.writeBuffer;
        if (!writeBuffer.isEmpty()) {
            // caused by fillStackTrace.
            if (cause == null) {
                if (channel.isOpen()) {
                    cause = new NotYetConnectedException();
                } else {
                    cause = new ClosedChannelException();
                }
            }
            for (; ; ) {
                evt = writeBuffer.poll();
                if (evt == null) {
                    break;
                }
                evt.getFuture().setFailure(cause);
                fireExceptionCaught = true;
            }
        }
    }
    if (fireExceptionCaught) {
        Log.d("NioWorker", "Exception ----- " + cause);
        if (//ç„¡é™?ループを防ã??
        cause == null || cause.getMessage() == null || cause.getMessage().contains("ClosedChannelException")) {
            Log.d("NioWorker", "Cause contains ClosedChannelException!!");
            return;
        }
        handler.exceptionCaught(new DefaultExceptionEvent(channel, cause));
    }
}
Example 55
Project: jruby-openssl-master  File: SSLSocket.java View source code
private IRubyObject connectImpl(final ThreadContext context, final boolean blocking, final boolean exception) {
    if (!sslContext.isProtocolForClient()) {
        throw newSSLError(context.runtime, "called a function you should not call");
    }
    try {
        if (!initialHandshake) {
            SSLEngine engine = ossl_ssl_setup(context);
            engine.setUseClientMode(true);
            engine.beginHandshake();
            handshakeStatus = engine.getHandshakeStatus();
            initialHandshake = true;
        }
        callRenegotiationCallback(context);
        final IRubyObject ex = doHandshake(blocking, exception);
        // :wait_readable | :wait_writable
        if (ex != null)
            return ex;
    } catch (SSLHandshakeException e) {
        forceClose();
        throw newSSLErrorFromHandshake(context.runtime, e);
    } catch (NoSuchAlgorithmException e) {
        debugStackTrace(context.runtime, e);
        forceClose();
        throw newSSLError(context.runtime, e);
    } catch (KeyManagementException e) {
        debugStackTrace(context.runtime, e);
        forceClose();
        throw newSSLError(context.runtime, e);
    } catch (IOException e) {
        forceClose();
        throw newSSLError(context.runtime, e);
    } catch (NotYetConnectedException e) {
        throw newErrnoEPIPEError(context.runtime, "SSL_connect");
    }
    return this;
}
Example 56
Project: ofcprobe-master  File: OFConnection1_zero.java View source code
@Override
public void send(OFMessage out) {
    packetOut(out);
    out.computeLength();
    if (this.sendFlag && !this.crashed) {
        try {
            if (//				if (this.dpidString.equals("001"))
            !out.getType().equals(OFType.PACKET_IN)) {
                logger.trace("[Switch#{}]: Outgoing: {}", this.dpidString, out.toString());
            }
            this.ofStream.write(out);
            while (this.ofStream.needsFlush()) {
                this.ofStream.flush();
            }
        } catch (IOException e) {
            this.runner.endSession();
            this.runner.evaluate();
            this.runner.report();
            logger.error("[Switch#{}]: " + Throwables.getStackTraceAsString(e), this.dpidString);
            logger.error("[Switch#{}]: Connection has been closed by Remotehost - Has Controller Crashed?", this.dpidString);
            logger.error("[Switch#{}]: Saving Data and Exiting ...", this.dpidString);
            this.crashed = true;
        } catch (NotYetConnectedException e) {
            logger.warn("[Switch#{}]: Connection has not yet been connected! Will retry in 5sec", this.dpidString);
            try {
                Thread.sleep(5000);
                send(out);
            } catch (InterruptedException ie) {
                logger.error("[Switch#{}]: Couldn't sleep... Going suicidal now!", this.dpidString);
                System.exit(1);
            }
        }
    }
}
Example 57
Project: alien-ofelia-conet-ccnx-master  File: CCNNetworkManager.java View source code
@Override
public void run() {
    boolean refreshError = false;
    if (_protocol == NetworkProtocol.UDP) {
        if (!_channel.isConnected()) {
            //we are not connected.  reconnect attempt is in the heartbeat function...
            _channel.heartbeat();
        }
    }
    if (!_channel.isConnected()) {
        //we tried to reconnect and failed, try again next loop
        Log.fine(Log.FAC_NETMANAGER, "Not Connected to ccnd, try again in {0}ms", CCNNetworkChannel.SOCKET_TIMEOUT);
        _lastHeartbeat = 0;
        if (_run)
            _periodicTimer.schedule(this, CCNNetworkChannel.SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);
        return;
    }
    long ourTime = System.currentTimeMillis();
    long minInterestRefreshTime = PERIOD + ourTime;
    // Re-express interests that need to be re-expressed
    try {
        for (Entry<InterestRegistration> entry : _myInterests.values()) {
            InterestRegistration reg = entry.value();
            // allow some slop for scheduling
            if (ourTime + 20 > reg.nextRefresh) {
                if (Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER))
                    Log.finer(Log.FAC_NETMANAGER, "Refresh interest: {0}", reg.interest);
                _lastHeartbeat = ourTime;
                reg.nextRefresh = ourTime + SystemConfiguration.INTEREST_REEXPRESSION_DEFAULT;
                ;
                try {
                    write(reg.interest);
                } catch (NotYetConnectedException nyce) {
                    refreshError = true;
                }
            }
            if (minInterestRefreshTime > reg.nextRefresh)
                minInterestRefreshTime = reg.nextRefresh;
        }
    } catch (ContentEncodingException xmlex) {
        Log.severe(Log.FAC_NETMANAGER, "PeriodicWriter interest refresh thread failure (Malformed datagram): {0}", xmlex.getMessage());
        Log.warningStackTrace(xmlex);
        refreshError = true;
    }
    // Re-express prefix registrations that need to be re-expressed
    // FIXME: The lifetime of a prefix is returned in seconds, not milliseconds.  The refresh code needs
    // to understand this.  This isn't a problem for now because the lifetime we request when we register a
    // prefix we use Integer.MAX_VALUE as the requested lifetime.
    // FIXME: so lets not go around the loop doing nothing... for now.
    long minFilterRefreshTime = PERIOD + ourTime;
    if (refreshError) {
        Log.warning(Log.FAC_NETMANAGER, "we have had an error when refreshing an interest or prefix registration...  do we need to reconnect to ccnd?");
    }
    long currentTime = System.currentTimeMillis();
    // TODO - do we want to keep this in permanently?
    if (_inHandler) {
        if (_currentHandler == _lastHandler) {
            long delta = currentTime - _timeForThisHandler;
            if (delta > SystemConfiguration.MAX_TIMEOUT) {
                // Print out what the thread was doing first
                Throwable t = new Throwable("Handler took too long to return - stack trace follows");
                t.setStackTrace(_thread.getStackTrace());
                Log.logStackTrace(Log.FAC_NETMANAGER, Level.SEVERE, t);
                _thread.interrupt();
            }
        } else {
            _lastHandler = _currentHandler;
            _timeForThisHandler = currentTime;
        }
    }
    // Calculate when we should next be run
    long checkInterestDelay = minInterestRefreshTime - currentTime;
    if (checkInterestDelay < 0)
        checkInterestDelay = 0;
    if (checkInterestDelay > PERIOD)
        checkInterestDelay = PERIOD;
    long checkPrefixDelay = minFilterRefreshTime - currentTime;
    if (checkPrefixDelay < 0)
        checkPrefixDelay = 0;
    if (checkPrefixDelay > PERIOD)
        checkPrefixDelay = PERIOD;
    long useMe;
    if (checkInterestDelay < checkPrefixDelay) {
        useMe = checkInterestDelay;
    } else {
        useMe = checkPrefixDelay;
    }
    if (_protocol == NetworkProtocol.UDP) {
        //we haven't sent anything...  maybe need to send a heartbeat
        if ((currentTime - _lastHeartbeat) >= CCNNetworkChannel.HEARTBEAT_PERIOD) {
            _lastHeartbeat = currentTime;
            _channel.heartbeat();
        }
        //now factor in heartbeat time
        long timeToHeartbeat = CCNNetworkChannel.HEARTBEAT_PERIOD - (currentTime - _lastHeartbeat);
        if (useMe > timeToHeartbeat)
            useMe = timeToHeartbeat;
    }
    if (useMe < 20) {
        useMe = 20;
    }
    if (_run)
        _periodicTimer.schedule(this, useMe, TimeUnit.MILLISECONDS);
}
Example 58
Project: android-sdk-sources-for-api-level-23-master  File: SocketChannelTest.java View source code
/*
     * Test method for 'java.nio.channels.SocketChannel.open()'
     */
public void testOpen() throws IOException {
    java.nio.ByteBuffer[] buf = new java.nio.ByteBuffer[1];
    buf[0] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL);
    MockSocketChannel testMSChannel = new MockSocketChannel(null);
    MockSocketChannel testMSChannelnotnull = new MockSocketChannel(SelectorProvider.provider());
    assertNull(testMSChannel.provider());
    assertNotNull(testMSChannelnotnull.provider());
    assertNotNull(this.channel1);
    assertEquals(this.channel1.provider(), testMSChannelnotnull.provider());
    try {
        this.channel1.write(buf);
        fail("Should throw NotYetConnectedException");
    } catch (NotYetConnectedException e) {
    }
}
Example 59
Project: BitNomen-master  File: CCNNetworkManager.java View source code
@Override
public void run() {
    boolean refreshError = false;
    if (_protocol == NetworkProtocol.UDP) {
        if (!_channel.isConnected()) {
            //we are not connected.  reconnect attempt is in the heartbeat function...
            _channel.heartbeat();
        }
    }
    if (!_channel.isConnected()) {
        //we tried to reconnect and failed, try again next loop
        Log.fine(Log.FAC_NETMANAGER, "Not Connected to ccnd, try again in {0}ms", CCNNetworkChannel.SOCKET_TIMEOUT);
        _lastHeartbeat = 0;
        if (_run)
            _periodicTimer.schedule(new PeriodicWriter(), CCNNetworkChannel.SOCKET_TIMEOUT);
        return;
    }
    long ourTime = System.currentTimeMillis();
    long minInterestRefreshTime = PERIOD + ourTime;
    // Re-express interests that need to be re-expressed
    try {
        for (Entry<InterestRegistration> entry : _myInterests.values()) {
            InterestRegistration reg = entry.value();
            // allow some slop for scheduling
            if (ourTime + 20 > reg.nextRefresh) {
                if (Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER))
                    Log.finer(Log.FAC_NETMANAGER, "Refresh interest: {0}", reg.interest);
                _lastHeartbeat = ourTime;
                reg.nextRefresh = ourTime + SystemConfiguration.INTEREST_REEXPRESSION_DEFAULT;
                ;
                try {
                    write(reg.interest);
                } catch (NotYetConnectedException nyce) {
                    refreshError = true;
                }
            }
            if (minInterestRefreshTime > reg.nextRefresh)
                minInterestRefreshTime = reg.nextRefresh;
        }
    } catch (ContentEncodingException xmlex) {
        Log.severe(Log.FAC_NETMANAGER, "PeriodicWriter interest refresh thread failure (Malformed datagram): {0}", xmlex.getMessage());
        Log.warningStackTrace(xmlex);
        refreshError = true;
    }
    // Re-express prefix registrations that need to be re-expressed
    // FIXME: The lifetime of a prefix is returned in seconds, not milliseconds.  The refresh code needs
    // to understand this.  This isn't a problem for now because the lifetime we request when we register a
    // prefix we use Integer.MAX_VALUE as the requested lifetime.
    // FIXME: so lets not go around the loop doing nothing... for now.
    long minFilterRefreshTime = PERIOD + ourTime;
    if (refreshError) {
        Log.warning(Log.FAC_NETMANAGER, "we have had an error when refreshing an interest or prefix registration...  do we need to reconnect to ccnd?");
    }
    long currentTime = System.currentTimeMillis();
    // TODO - do we want to keep this in permanently?
    if (_inHandler) {
        if (_currentHandler == _lastHandler) {
            long delta = currentTime - _timeForThisHandler;
            if (delta > SystemConfiguration.MAX_TIMEOUT) {
                // Print out what the thread was doing first
                Throwable t = new Throwable("Handler took too long to return - stack trace follows");
                t.setStackTrace(_thread.getStackTrace());
                Log.logStackTrace(Log.FAC_NETMANAGER, Level.SEVERE, t);
                _thread.interrupt();
            }
        } else {
            _lastHandler = _currentHandler;
            _timeForThisHandler = currentTime;
        }
    }
    // Calculate when we should next be run
    long checkInterestDelay = minInterestRefreshTime - currentTime;
    if (checkInterestDelay < 0)
        checkInterestDelay = 0;
    if (checkInterestDelay > PERIOD)
        checkInterestDelay = PERIOD;
    long checkPrefixDelay = minFilterRefreshTime - currentTime;
    if (checkPrefixDelay < 0)
        checkPrefixDelay = 0;
    if (checkPrefixDelay > PERIOD)
        checkPrefixDelay = PERIOD;
    long useMe;
    if (checkInterestDelay < checkPrefixDelay) {
        useMe = checkInterestDelay;
    } else {
        useMe = checkPrefixDelay;
    }
    if (_protocol == NetworkProtocol.UDP) {
        //we haven't sent anything...  maybe need to send a heartbeat
        if ((currentTime - _lastHeartbeat) >= CCNNetworkChannel.HEARTBEAT_PERIOD) {
            _lastHeartbeat = currentTime;
            _channel.heartbeat();
        }
        //now factor in heartbeat time
        long timeToHeartbeat = CCNNetworkChannel.HEARTBEAT_PERIOD - (currentTime - _lastHeartbeat);
        if (useMe > timeToHeartbeat)
            useMe = timeToHeartbeat;
    }
    if (useMe < 20) {
        useMe = 20;
    }
    if (_run)
        _periodicTimer.schedule(new PeriodicWriter(), useMe);
}
Example 60
Project: ccnx-master  File: CCNNetworkManager.java View source code
public void run() {
    boolean refreshError = false;
    if (_protocol == NetworkProtocol.UDP) {
        if (!_channel.isConnected()) {
            //we are not connected.  reconnect attempt is in the heartbeat function...
            _channel.heartbeat();
        }
    }
    if (!_channel.isConnected()) {
        //we tried to reconnect and failed, try again next loop
        Log.fine(Log.FAC_NETMANAGER, "Not Connected to ccnd, try again in {0}ms", CCNNetworkChannel.SOCKET_TIMEOUT);
        _lastHeartbeat = 0;
        if (_run)
            _periodicTimer.schedule(this, CCNNetworkChannel.SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);
        return;
    }
    long ourTime = System.currentTimeMillis();
    long minInterestRefreshTime = PERIOD + ourTime;
    // Re-express interests that need to be re-expressed
    try {
        for (Entry<InterestRegistration> entry : _myInterests.values()) {
            InterestRegistration reg = entry.value();
            // allow some slop for scheduling
            if (ourTime + 20 > reg.nextRefresh) {
                if (Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER))
                    Log.finer(Log.FAC_NETMANAGER, "Refresh interest: {0}", reg.interest);
                _lastHeartbeat = ourTime;
                reg.nextRefresh = ourTime + SystemConfiguration.INTEREST_REEXPRESSION_DEFAULT;
                ;
                try {
                    write(reg.interest);
                } catch (NotYetConnectedException nyce) {
                    refreshError = true;
                }
            }
            if (minInterestRefreshTime > reg.nextRefresh)
                minInterestRefreshTime = reg.nextRefresh;
        }
    } catch (ContentEncodingException xmlex) {
        Log.severe(Log.FAC_NETMANAGER, "PeriodicWriter interest refresh thread failure (Malformed datagram): {0}", xmlex.getMessage());
        Log.warningStackTrace(xmlex);
        refreshError = true;
    }
    // Re-express prefix registrations that need to be re-expressed
    // FIXME: The lifetime of a prefix is returned in seconds, not milliseconds.  The refresh code needs
    // to understand this.  This isn't a problem for now because the lifetime we request when we register a
    // prefix we use Integer.MAX_VALUE as the requested lifetime.
    long minFilterRefreshTime = PERIOD + ourTime;
    if (refreshError) {
        Log.warning(Log.FAC_NETMANAGER, "we have had an error when refreshing an interest or prefix registration...  do we need to reconnect to ccnd?");
    }
    long currentTime = System.currentTimeMillis();
    // TODO - do we want to keep this in permanently?
    if (_inHandler) {
        if (_currentHandler == _lastHandler) {
            long delta = currentTime - _timeForThisHandler;
            if (delta > SystemConfiguration.MAX_TIMEOUT) {
                // Print out what the thread was doing first
                Throwable t = new Throwable("Handler took too long to return - stack trace follows");
                t.setStackTrace(_thread.getStackTrace());
                Log.logStackTrace(Log.FAC_NETMANAGER, Level.SEVERE, t);
                _thread.interrupt();
            }
        } else {
            _lastHandler = _currentHandler;
            _timeForThisHandler = currentTime;
        }
    }
    // Calculate when we should next be run
    long checkInterestDelay = minInterestRefreshTime - currentTime;
    if (checkInterestDelay < 0)
        checkInterestDelay = 0;
    if (checkInterestDelay > PERIOD)
        checkInterestDelay = PERIOD;
    long checkPrefixDelay = minFilterRefreshTime - currentTime;
    if (checkPrefixDelay < 0)
        checkPrefixDelay = 0;
    if (checkPrefixDelay > PERIOD)
        checkPrefixDelay = PERIOD;
    long useMe;
    if (checkInterestDelay < checkPrefixDelay) {
        useMe = checkInterestDelay;
    } else {
        useMe = checkPrefixDelay;
    }
    if (_protocol == NetworkProtocol.UDP) {
        //we haven't sent anything...  maybe need to send a heartbeat
        if ((currentTime - _lastHeartbeat) >= CCNNetworkChannel.HEARTBEAT_PERIOD) {
            _lastHeartbeat = currentTime;
            _channel.heartbeat();
        }
        //now factor in heartbeat time
        long timeToHeartbeat = CCNNetworkChannel.HEARTBEAT_PERIOD - (currentTime - _lastHeartbeat);
        if (useMe > timeToHeartbeat)
            useMe = timeToHeartbeat;
    }
    if (useMe < 20) {
        useMe = 20;
    }
    if (_run)
        _periodicTimer.schedule(this, useMe, TimeUnit.MILLISECONDS);
}
Example 61
Project: openhab1-addons-master  File: AbstractSocketChannelBinding.java View source code
/**
     * @{inheritDoc}
     */
@Override
protected void execute() {
    // Cycle through the Items and setup channels if required
    for (P provider : providers) {
        for (String itemName : provider.getItemNames()) {
            for (Command aCommand : provider.getAllCommands(itemName)) {
                String remoteHost = provider.getHost(itemName, aCommand);
                String remotePort = provider.getPortAsString(itemName, aCommand);
                Direction direction = provider.getDirection(itemName, aCommand);
                InetSocketAddress remoteAddress = null;
                if (!(remoteHost.equals("*") || remotePort.equals("*"))) {
                    remoteAddress = new InetSocketAddress(remoteHost, Integer.parseInt(remotePort));
                }
                Channel newChannel = null;
                Channel existingChannel = null;
                if (useAddressMask && (remoteHost.equals("*") || remotePort.equals("*"))) {
                    newChannel = new Channel(itemName, aCommand, remoteHost, remotePort, provider.getDirection(itemName, aCommand), false, null, false, null);
                    existingChannel = channels.get(itemName, aCommand, direction, remoteHost, remotePort);
                } else {
                    newChannel = new Channel(itemName, aCommand, remoteAddress, provider.getDirection(itemName, aCommand), false, null, false, null);
                    existingChannel = channels.get(itemName, aCommand, direction, remoteAddress);
                }
                if (existingChannel == null) {
                    if (direction == Direction.IN) {
                        boolean assigned = false;
                        if (useAddressMask && (remoteHost.equals("*") || remotePort.equals("*"))) {
                            logger.warn("When using address masks we will not verify if we are already listening to similar incoming connections");
                            logger.info("We will accept data coming from the remote end {}:{}", remoteHost, remotePort);
                            channels.add(newChannel);
                        } else {
                            if (itemShareChannels) {
                                Channel firstChannel = channels.getFirstServed(itemName, direction, remoteAddress);
                                if (firstChannel != null) {
                                    newChannel.channel = firstChannel.channel;
                                    assigned = true;
                                }
                            }
                            if (bindingShareChannels) {
                                Channel firstChannel = channels.getFirstServed(direction, remoteAddress);
                                if (firstChannel != null) {
                                    newChannel.channel = firstChannel.channel;
                                    assigned = true;
                                }
                            }
                            if (directionsShareChannels) {
                                Channel firstChannel = channels.getFirstServed(remoteAddress);
                                if (firstChannel != null) {
                                    newChannel.channel = firstChannel.channel;
                                    assigned = true;
                                }
                            }
                            if (!assigned || newChannel.channel == null) {
                                if (channels.contains(itemName, aCommand, Direction.IN, remoteAddress)) {
                                    logger.warn("We already listen for incoming connections from {}", remoteAddress);
                                } else {
                                    logger.debug("Setting up the inbound channel {}", newChannel);
                                    channels.add(newChannel);
                                    logger.info("We will accept data coming from the remote end {}", remoteAddress);
                                }
                            }
                        }
                    } else if (direction == Direction.OUT) {
                        boolean assigned = false;
                        if (useAddressMask && (remoteHost.equals("*") || remotePort.equals("*"))) {
                            logger.error("We do not accept outgoing connections for Items that do use address masks");
                        } else {
                            channels.add(newChannel);
                            if (newChannel.channel == null) {
                                if (itemShareChannels) {
                                    Channel firstChannel = channels.getFirstServed(itemName, direction, remoteAddress);
                                    if (firstChannel != null) {
                                        newChannel.channel = firstChannel.channel;
                                        assigned = true;
                                    }
                                }
                                if (bindingShareChannels) {
                                    Channel firstChannel = channels.getFirstServed(direction, remoteAddress);
                                    if (firstChannel != null) {
                                        newChannel.channel = firstChannel.channel;
                                        assigned = true;
                                    }
                                }
                                if (directionsShareChannels) {
                                    Channel firstChannel = channels.getFirstServed(remoteAddress);
                                    if (firstChannel != null) {
                                        newChannel.channel = firstChannel.channel;
                                        assigned = true;
                                    }
                                }
                                if (assigned) {
                                    logger.debug("Setting up the outbound assigned channel {} ", newChannel);
                                }
                                synchronized (this) {
                                    if (!assigned || newChannel.channel == null) {
                                        SocketChannel newSocketChannel = null;
                                        try {
                                            newSocketChannel = SocketChannel.open();
                                        } catch (IOException e2) {
                                            logger.error("An exception occurred while opening a channel: {}", e2.getMessage());
                                        }
                                        try {
                                            newSocketChannel.socket().setKeepAlive(true);
                                            newSocketChannel.configureBlocking(false);
                                        } catch (IOException e) {
                                            logger.error("An exception occurred while configuring a channel: {}", e.getMessage());
                                        }
                                        synchronized (selector) {
                                            selector.wakeup();
                                            int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE | SelectionKey.OP_CONNECT;
                                            try {
                                                newSocketChannel.register(selector, interestSet);
                                            } catch (ClosedChannelException e1) {
                                                logger.error("An exception occurred while registering a selector: {}", e1.getMessage());
                                            }
                                        }
                                        newChannel.channel = newSocketChannel;
                                        logger.debug("Setting up the outbound channel {}", newChannel);
                                        try {
                                            logger.info("Connecting the channel {} ", newChannel);
                                            newSocketChannel.connect(remoteAddress);
                                        } catch (IOException e) {
                                            logger.error("An exception occurred while connecting a channel: {}", e.getMessage());
                                        }
                                    }
                                }
                            } else {
                                logger.info("There is already an active channel {} for the remote end {}", newChannel.channel, newChannel.remote);
                            }
                        }
                    }
                }
            }
        }
    }
    // Check on channels for which we have to process data
    synchronized (selector) {
        try {
            // Wait for an event
            selector.selectNow();
        } catch (IOException e) {
            logger.error("An exception occurred while Selecting ({})", e.getMessage());
        }
    }
    // Get list of selection keys with pending events
    Iterator<SelectionKey> it = selector.selectedKeys().iterator();
    // Process each key at a time
    while (it.hasNext()) {
        SelectionKey selKey = it.next();
        it.remove();
        if (selKey.isValid()) {
            if (selKey == listenerKey) {
                if (selKey.isAcceptable()) {
                    try {
                        SocketChannel newChannel = listenerChannel.accept();
                        logger.info("Received connection request from {}", newChannel.getRemoteAddress());
                        Channel firstChannel = channels.getFirstNotServed(Direction.IN, (InetSocketAddress) newChannel.getRemoteAddress());
                        if (firstChannel != null) {
                            if (firstChannel.direction == Direction.IN) {
                                if (useAddressMask && (firstChannel.host.equals("*") || firstChannel.port.equals("*"))) {
                                    logger.info("{}:{} is an allowed masked remote end. The channel will now be configured", firstChannel.host, firstChannel.port);
                                } else {
                                    logger.info("{} is an allowed remote end. The channel will now be configured", firstChannel.remote);
                                }
                                if (firstChannel.channel == null || !firstChannel.channel.isOpen()) {
                                    firstChannel.channel = newChannel;
                                    firstChannel.isBlocking = false;
                                    firstChannel.buffer = null;
                                    if (itemShareChannels) {
                                        channels.replace(firstChannel.item, firstChannel.direction, (InetSocketAddress) newChannel.getRemoteAddress(), firstChannel.channel);
                                    }
                                    if (bindingShareChannels) {
                                        channels.replace(firstChannel.direction, (InetSocketAddress) newChannel.getRemoteAddress(), firstChannel.channel);
                                    }
                                    if (directionsShareChannels) {
                                        channels.replace((InetSocketAddress) newChannel.getRemoteAddress(), firstChannel.channel);
                                    }
                                    try {
                                        newChannel.configureBlocking(false);
                                    // setKeepAlive(true);
                                    } catch (IOException e) {
                                        logger.error("An exception occurred while configuring a channel: {}", e.getMessage());
                                    }
                                    synchronized (selector) {
                                        selector.wakeup();
                                        try {
                                            newChannel.register(selector, newChannel.validOps());
                                        } catch (ClosedChannelException e1) {
                                            logger.error("An exception occurred while registering a selector: {}", e1.getMessage());
                                        }
                                    }
                                    Scheduler scheduler = null;
                                    try {
                                        scheduler = StdSchedulerFactory.getDefaultScheduler();
                                    } catch (SchedulerException e1) {
                                        logger.error("An exception occurred while getting the Quartz scheduler: {}", e1.getMessage());
                                    }
                                    JobDataMap map = new JobDataMap();
                                    map.put("Channel", firstChannel);
                                    map.put("Binding", this);
                                    JobDetail job = newJob(ConfigureJob.class).withIdentity(Integer.toHexString(hashCode()) + "-Configure-" + Long.toString(System.currentTimeMillis()), this.toString()).usingJobData(map).build();
                                    Trigger trigger = newTrigger().withIdentity(Integer.toHexString(hashCode()) + "-Configure-" + Long.toString(System.currentTimeMillis()), this.toString()).startNow().build();
                                    try {
                                        if (job != null && trigger != null && selKey != listenerKey) {
                                            scheduler.scheduleJob(job, trigger);
                                        }
                                    } catch (SchedulerException e) {
                                        logger.error("An exception occurred while scheduling a job with the Quartz Scheduler {}", e.getMessage());
                                    }
                                } else {
                                    logger.info("We previously already accepted a connection from the remote end {} for this channel. Goodbye", firstChannel.remote);
                                    newChannel.close();
                                }
                            } else {
                                logger.info("Disconnecting the remote end {} that tries to connect an outbound only port", newChannel.getRemoteAddress());
                                newChannel.close();
                            }
                        } else {
                            logger.info("Disconnecting the unallowed remote end {}", newChannel.getRemoteAddress());
                            newChannel.close();
                        }
                    } catch (IOException e) {
                        logger.error("An exception occurred while configuring a channel: {}", e.getMessage());
                    }
                }
            } else {
                SocketChannel theSocketChannel = (SocketChannel) selKey.channel();
                Channel theChannel = channels.get(theSocketChannel);
                if (selKey.isConnectable()) {
                    channels.setAllReconnecting(theSocketChannel, false);
                    boolean result = false;
                    boolean error = false;
                    try {
                        result = theSocketChannel.finishConnect();
                    } catch (NoConnectionPendingException e) {
                        logger.warn("The channel {} has no connection pending ({})", theSocketChannel, e.getMessage());
                        error = true;
                    } catch (ClosedChannelException e) {
                        logger.warn("The channel {} is closed ({})", theSocketChannel, e.getMessage());
                        error = true;
                    } catch (IOException e) {
                        logger.warn("The channel {} has encountered an unknown IO Exception: {}", theSocketChannel, e.getMessage());
                        error = true;
                    }
                    if (error) {
                        Scheduler scheduler = null;
                        try {
                            scheduler = StdSchedulerFactory.getDefaultScheduler();
                        } catch (SchedulerException e1) {
                            logger.error("An exception occurred while getting the Quartz scheduler: {}", e1.getMessage());
                        }
                        JobDataMap map = new JobDataMap();
                        map.put("Channel", theChannel);
                        map.put("Binding", this);
                        JobDetail job = newJob(ReconnectJob.class).withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-" + Long.toString(System.currentTimeMillis()), this.toString()).usingJobData(map).build();
                        Trigger trigger = newTrigger().withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-" + Long.toString(System.currentTimeMillis()), this.toString()).startAt(futureDate(reconnectInterval, IntervalUnit.SECOND)).build();
                        try {
                            if (job != null && trigger != null && selKey != listenerKey) {
                                if (!theChannel.isReconnecting) {
                                    channels.setAllReconnecting(theSocketChannel, true);
                                    scheduler.scheduleJob(job, trigger);
                                }
                            }
                        } catch (SchedulerException e) {
                            logger.error("An exception occurred while scheduling a job with the Quartz Scheduler {}", e.getMessage());
                        }
                    } else {
                        if (result) {
                            InetSocketAddress remote = null;
                            try {
                                remote = (InetSocketAddress) theSocketChannel.getRemoteAddress();
                            } catch (IOException e) {
                                logger.error("An exception occurred while getting the remote address of channel {} ({})", theSocketChannel, e.getMessage());
                            }
                            logger.info("The channel for {} is now connected", remote);
                            if (itemShareChannels) {
                                channels.replace(theChannel.item, theChannel.direction, remote, theChannel.channel);
                            }
                            if (bindingShareChannels) {
                                channels.replace(theChannel.direction, remote, theChannel.channel);
                            }
                            if (directionsShareChannels) {
                                channels.replace(remote, theChannel.channel);
                            }
                            Scheduler scheduler = null;
                            try {
                                scheduler = StdSchedulerFactory.getDefaultScheduler();
                            } catch (SchedulerException e1) {
                                logger.error("An exception occurred while getting the Quartz scheduler: {}", e1.getMessage());
                            }
                            JobDataMap map = new JobDataMap();
                            map.put("Channel", theChannel);
                            map.put("Binding", this);
                            JobDetail job = newJob(ConfigureJob.class).withIdentity(Integer.toHexString(hashCode()) + "-Configure-" + Long.toString(System.currentTimeMillis()), this.toString()).usingJobData(map).build();
                            Trigger trigger = newTrigger().withIdentity(Integer.toHexString(hashCode()) + "-Configure-" + Long.toString(System.currentTimeMillis()), this.toString()).startNow().build();
                            try {
                                if (job != null && trigger != null && selKey != listenerKey) {
                                    scheduler.scheduleJob(job, trigger);
                                }
                            } catch (SchedulerException e) {
                                logger.error("An exception occurred while scheduling a job with the Quartz Scheduler {}", e.getMessage());
                            }
                            job = newJob(ReconnectJob.class).withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-" + Long.toString(System.currentTimeMillis()), this.toString()).usingJobData(map).build();
                            trigger = newTrigger().withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-" + Long.toString(System.currentTimeMillis()), this.toString()).withSchedule(cronSchedule(reconnectCron)).build();
                            try {
                                if (job != null && trigger != null && selKey != listenerKey) {
                                    scheduler.scheduleJob(job, trigger);
                                }
                            } catch (SchedulerException e) {
                                logger.error("An exception occurred while scheduling a job with the Quartz Scheduler {}", e.getMessage());
                            }
                        }
                    }
                } else if (selKey.isReadable()) {
                    ByteBuffer readBuffer = ByteBuffer.allocate(maximumBufferSize);
                    int numberBytesRead = 0;
                    boolean error = false;
                    try {
                        // TODO: Additional code to split readBuffer in multiple parts, in case the data send by the
                        // remote end is not correctly fragemented. Could be handed of to implementation class if
                        // for example, the buffer needs to be split based on a special character like line feed or
                        // carriage return
                        numberBytesRead = theSocketChannel.read(readBuffer);
                    } catch (NotYetConnectedException e) {
                        logger.warn("The channel for {} has no connection pending ({})", theChannel.remote, e.getMessage());
                        if (!theSocketChannel.isConnectionPending()) {
                            error = true;
                        }
                    } catch (IOException e) {
                        logger.warn("The channel for {} has encountered an unknown IO Exception: {}", theChannel.remote, e.getMessage());
                        error = true;
                    }
                    if (numberBytesRead == -1) {
                        try {
                            theSocketChannel.close();
                        } catch (IOException e) {
                            logger.warn("The channel for {} is closed ({})", theChannel.remote, e.getMessage());
                        }
                        error = true;
                    }
                    if (error) {
                        if (theChannel.direction == Direction.OUT) {
                            Scheduler scheduler = null;
                            try {
                                scheduler = StdSchedulerFactory.getDefaultScheduler();
                            } catch (SchedulerException e1) {
                                logger.error("An exception occurred while getting the Quartz scheduler: {}", e1.getMessage());
                            }
                            JobDataMap map = new JobDataMap();
                            map.put("Channel", theChannel);
                            map.put("Binding", this);
                            JobDetail job = newJob(ReconnectJob.class).withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-" + Long.toString(System.currentTimeMillis()), "AbstractSocketChannelBinding").usingJobData(map).build();
                            Trigger trigger = newTrigger().withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-" + Long.toString(System.currentTimeMillis()), "AbstractSocketChannelBinding").startAt(futureDate(reconnectInterval, IntervalUnit.SECOND)).build();
                            try {
                                if (job != null && trigger != null && selKey != listenerKey) {
                                    if (!theChannel.isReconnecting) {
                                        channels.setAllReconnecting(theSocketChannel, true);
                                        scheduler.scheduleJob(job, trigger);
                                    }
                                }
                            } catch (SchedulerException e) {
                                logger.error("An exception occurred while scheduling a job with the Quartz Scheduler {}", e.getMessage());
                            }
                        } else {
                            theChannel.channel = null;
                        }
                    } else {
                        ArrayList<Channel> channelsToServe = new ArrayList<Channel>();
                        channelsToServe = channels.getAll(theSocketChannel);
                        if (channelsToServe.size() > 0) {
                            readBuffer.flip();
                            boolean isBlocking = channels.isBlocking(theSocketChannel);
                            if (isBlocking) {
                                // if we are in a blocking operation, we get are now finished and we have to reset
                                // the flag. The read buffer will be returned to the instance
                                // that initiated the write opreation - it has to parse the buffer itself
                                theChannel = channels.getBlocking(theSocketChannel);
                                theChannel.buffer = readBuffer;
                                theChannel.isBlocking = false;
                            } else {
                                for (Channel aChannel : channelsToServe) {
                                    // if not, then we parse the buffer as ususal
                                    parseChanneledBuffer(aChannel, readBuffer);
                                }
                            }
                        } else {
                            try {
                                logger.warn("No channel is active or defined for the data we received from {}. It will be discarded.", theSocketChannel.getRemoteAddress());
                            } catch (IOException e) {
                                logger.error("An exception occurred while getting the remote address of the channel {} ({})", theSocketChannel, e.getMessage());
                            }
                        }
                    }
                } else if (selKey.isWritable()) {
                    boolean isBlocking = channels.isBlocking(theSocketChannel);
                    if (isBlocking) {
                    // if this channel is already flagged as being in a blocked write/read operation, we skip
                    // this selKey
                    } else {
                        // pick up a QueueElement for this channel, if any
                        WriteBufferElement theElement = null;
                        Iterator<WriteBufferElement> iterator = writeQueue.iterator();
                        while (iterator.hasNext()) {
                            WriteBufferElement anElement = iterator.next();
                            if (anElement.channel.channel.equals(theSocketChannel)) {
                                theElement = anElement;
                                break;
                            }
                        }
                        if (theElement != null && theElement.buffer != null) {
                            logger.debug("Picked {} from the queue", theElement);
                            if (theElement.isBlocking) {
                                theElement.channel.isBlocking = true;
                            }
                            boolean error = false;
                            theElement.buffer.rewind();
                            try {
                                logger.debug("Sending {} for the outbound channel {}->{}", new Object[] { new String(theElement.buffer.array()), theElement.channel.channel.getLocalAddress(), theElement.channel.channel.getRemoteAddress() });
                                theSocketChannel.write(theElement.buffer);
                            } catch (NotYetConnectedException e) {
                                logger.warn("The channel for {} has no connection pending ({})", theChannel.remote, e.getMessage());
                                if (!theSocketChannel.isConnectionPending()) {
                                    error = true;
                                }
                            } catch (ClosedChannelException e) {
                                logger.warn("The channel for {} is closed ({})", theChannel.remote, e.getMessage());
                                error = true;
                            } catch (IOException e) {
                                logger.warn("The channel for {} has encountered an unknown IO Exception: {}", theChannel.remote, e.getMessage());
                                error = true;
                            }
                            if (error) {
                                if (theElement.channel.direction == Direction.OUT) {
                                    Scheduler scheduler = null;
                                    try {
                                        scheduler = StdSchedulerFactory.getDefaultScheduler();
                                    } catch (SchedulerException e1) {
                                        logger.error("An exception occurred while getting the Quartz scheduler: {}", e1.getMessage());
                                    }
                                    JobDataMap map = new JobDataMap();
                                    map.put("Channel", theElement.channel);
                                    map.put("Binding", this);
                                    JobDetail job = newJob(ReconnectJob.class).withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-" + Long.toString(System.currentTimeMillis()), "AbstractSocketChannelBinding").usingJobData(map).build();
                                    Trigger trigger = newTrigger().withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-" + Long.toString(System.currentTimeMillis()), "AbstractSocketChannelBinding").startAt(futureDate(reconnectInterval, IntervalUnit.SECOND)).build();
                                    try {
                                        if (job != null && trigger != null && selKey != listenerKey) {
                                            if (!theElement.channel.isReconnecting) {
                                                channels.setAllReconnecting(theSocketChannel, true);
                                                scheduler.scheduleJob(job, trigger);
                                            }
                                        }
                                    } catch (SchedulerException e) {
                                        logger.error("An exception occurred while scheduling a job with the Quartz Scheduler {}", e.getMessage());
                                    }
                                } else {
                                    theElement.channel.channel = null;
                                }
                            } else {
                                if (theElement != null) {
                                    writeQueue.remove(theElement);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
Example 62
Project: UNH_NDN-master  File: CCNNetworkManager.java View source code
// TODO Interest refresh time is supposed to "decay" over time but there are currently
// unresolved problems with this.
public void run() {
    //this method needs to do a few things
    // - reopen connection to ccnd if down
    // - refresh interests
    // - refresh prefix registrations
    // - heartbeats
    boolean refreshError = false;
    if (_protocol == NetworkProtocol.UDP) {
        if (!_channel.isConnected()) {
            //we are not connected.  reconnect attempt is in the heartbeat function...
            _channel.heartbeat();
        }
    }
    if (!_channel.isConnected()) {
        //we tried to reconnect and failed, try again next loop
        Log.fine(Log.FAC_NETMANAGER, "Not Connected to ccnd, try again in {0}ms", CCNNetworkChannel.SOCKET_TIMEOUT);
        _lastHeartbeat = 0;
        if (_run)
            _periodicTimer.schedule(new PeriodicWriter(), CCNNetworkChannel.SOCKET_TIMEOUT);
        return;
    }
    long ourTime = System.currentTimeMillis();
    long minInterestRefreshTime = PERIOD + ourTime;
    // Re-express interests that need to be re-expressed
    try {
        synchronized (_myInterests) {
            for (Entry<InterestRegistration> entry : _myInterests.values()) {
                InterestRegistration reg = entry.value();
                // allow some slop for scheduling
                if (ourTime + 20 > reg.nextRefresh) {
                    if (Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER))
                        Log.finer(Log.FAC_NETMANAGER, "Refresh interest: {0}", reg.interest);
                    _lastHeartbeat = ourTime;
                    reg.nextRefresh = ourTime + reg.nextRefreshPeriod;
                    try {
                        write(reg.interest);
                    } catch (NotYetConnectedException nyce) {
                        refreshError = true;
                    }
                }
                if (minInterestRefreshTime > reg.nextRefresh)
                    minInterestRefreshTime = reg.nextRefresh;
            }
        }
    } catch (ContentEncodingException xmlex) {
        Log.severe(Log.FAC_NETMANAGER, "PeriodicWriter interest refresh thread failure (Malformed datagram): {0}", xmlex.getMessage());
        Log.warningStackTrace(xmlex);
        refreshError = true;
    }
    // Re-express prefix registrations that need to be re-expressed
    // FIXME: The lifetime of a prefix is returned in seconds, not milliseconds.  The refresh code needs
    // to understand this.  This isn't a problem for now because the lifetime we request when we register a
    // prefix we use Integer.MAX_VALUE as the requested lifetime.
    // FIXME: so lets not go around the loop doing nothing... for now.
    long minFilterRefreshTime = PERIOD + ourTime;
    if (false && _usePrefixReg) {
        synchronized (_registeredPrefixes) {
            for (ContentName prefix : _registeredPrefixes.keySet()) {
                RegisteredPrefix rp = _registeredPrefixes.get(prefix);
                if (null != rp._forwarding && rp._lifetime != -1 && rp._nextRefresh != -1) {
                    if (ourTime > rp._nextRefresh) {
                        if (Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER))
                            Log.finer(Log.FAC_NETMANAGER, "Refresh registration: {0}", prefix);
                        rp._nextRefresh = -1;
                        try {
                            ForwardingEntry forwarding = _prefixMgr.selfRegisterPrefix(prefix);
                            if (null != forwarding) {
                                rp._lifetime = forwarding.getLifetime();
                                //										filter.nextRefresh = new Date().getTime() + (filter.lifetime / 2);
                                _lastHeartbeat = System.currentTimeMillis();
                                rp._nextRefresh = _lastHeartbeat + (rp._lifetime / 2);
                            }
                            rp._forwarding = forwarding;
                        } catch (CCNDaemonException e) {
                            Log.warning(e.getMessage());
                            rp._forwarding = null;
                            rp._lifetime = -1;
                            rp._nextRefresh = -1;
                            refreshError = true;
                        }
                    }
                    if (minFilterRefreshTime > rp._nextRefresh)
                        minFilterRefreshTime = rp._nextRefresh;
                }
            }
        // for (Entry<Filter> entry: _myFilters.values())
        }
    // synchronized (_myFilters)
    }
    if (refreshError) {
        Log.warning(Log.FAC_NETMANAGER, "we have had an error when refreshing an interest or prefix registration...  do we need to reconnect to ccnd?");
    }
    long currentTime = System.currentTimeMillis();
    long checkInterestDelay = minInterestRefreshTime - currentTime;
    if (checkInterestDelay < 0)
        checkInterestDelay = 0;
    if (checkInterestDelay > PERIOD)
        checkInterestDelay = PERIOD;
    long checkPrefixDelay = minFilterRefreshTime - currentTime;
    if (checkPrefixDelay < 0)
        checkPrefixDelay = 0;
    if (checkPrefixDelay > PERIOD)
        checkPrefixDelay = PERIOD;
    long useMe;
    if (checkInterestDelay < checkPrefixDelay) {
        useMe = checkInterestDelay;
    } else {
        useMe = checkPrefixDelay;
    }
    if (_protocol == NetworkProtocol.UDP) {
        //we haven't sent anything...  maybe need to send a heartbeat
        if ((currentTime - _lastHeartbeat) >= CCNNetworkChannel.HEARTBEAT_PERIOD) {
            _lastHeartbeat = currentTime;
            _channel.heartbeat();
        }
        //now factor in heartbeat time
        long timeToHeartbeat = CCNNetworkChannel.HEARTBEAT_PERIOD - (currentTime - _lastHeartbeat);
        if (useMe > timeToHeartbeat)
            useMe = timeToHeartbeat;
    }
    if (useMe < 20) {
        useMe = 20;
    }
    if (_run)
        _periodicTimer.schedule(new PeriodicWriter(), useMe);
}
Example 63
Project: android_libcore-master  File: SocketChannelTest.java View source code
/*
     * Test method for 'java.nio.channels.SocketChannel.open()'
     */
@TestTargets({ @TestTargetNew(level = TestLevel.PARTIAL_COMPLETE, notes = "", method = "open", args = {}), @TestTargetNew(level = TestLevel.PARTIAL_COMPLETE, notes = "", method = "SocketChannel", args = { SelectorProvider.class }) })
public void testOpen() throws IOException {
    java.nio.ByteBuffer[] buf = new java.nio.ByteBuffer[1];
    buf[0] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL);
    MockSocketChannel testMSChannel = new MockSocketChannel(null);
    MockSocketChannel testMSChannelnotnull = new MockSocketChannel(SelectorProvider.provider());
    SocketChannel testSChannel = MockSocketChannel.open();
    assertTrue(testSChannel.isOpen());
    assertNull(testMSChannel.provider());
    assertNotNull(testSChannel.provider());
    assertEquals(SelectorProvider.provider(), testSChannel.provider());
    assertNotNull(testMSChannelnotnull.provider());
    assertEquals(this.channel1.provider(), testMSChannelnotnull.provider());
    try {
        this.channel1.write(buf);
        fail("Should throw NotYetConnectedException");
    } catch (NotYetConnectedException e) {
    }
}
Example 64
Project: jpcsp-master  File: sceNetInet.java View source code
protected void setSocketError(Exception e) {
    if (e instanceof NotYetConnectedException) {
        setSocketError(ENOTCONN);
    } else if (e instanceof ClosedChannelException) {
        setSocketError(ECLOSED);
    } else if (e instanceof AsynchronousCloseException) {
        setSocketError(ECLOSED);
    } else if (e instanceof ClosedByInterruptException) {
        setSocketError(ECLOSED);
    } else if (e instanceof BindException) {
        setSocketError(EADDRNOTAVAIL);
    } else if (e instanceof IOException) {
        setSocketError(EIO);
    } else {
        // Unknown error
        setSocketError(-1);
    }
}
Example 65
Project: open-mika-master  File: SocketChannelTest.java View source code
/*
     * Test method for 'java.nio.channels.SocketChannel.open()'
    @TestTargets({
        @TestTargetNew(
            level = TestLevel.PARTIAL_COMPLETE,
            notes = "",
            method = "open",
            args = {}
        ),
        @TestTargetNew(
            level = TestLevel.PARTIAL_COMPLETE,
            notes = "",
            method = "SocketChannel",
            args = {SelectorProvider.class}
        )
    })
     */
public void testOpen() throws IOException {
    java.nio.ByteBuffer[] buf = new java.nio.ByteBuffer[1];
    buf[0] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL);
    MockSocketChannel testMSChannel = new MockSocketChannel(null);
    MockSocketChannel testMSChannelnotnull = new MockSocketChannel(SelectorProvider.provider());
    SocketChannel testSChannel = MockSocketChannel.open();
    assertTrue(testSChannel.isOpen());
    assertNull(testMSChannel.provider());
    assertNotNull(testSChannel.provider());
    assertEquals(SelectorProvider.provider(), testSChannel.provider());
    assertNotNull(testMSChannelnotnull.provider());
    assertEquals(this.channel1.provider(), testMSChannelnotnull.provider());
    try {
        this.channel1.write(buf);
        fail("Should throw NotYetConnectedException");
    } catch (NotYetConnectedException e) {
    }
}
Example 66
Project: redPandaj-master  File: ConnectionHandler.java View source code
private int parseCommands(byte command, final Peer peer, int parsedBytes, final ByteBuffer writeBuffer, final ByteBuffer readBuffer) {
    Log.put("Command byte: " + command + " ip:" + peer.ip, 150);
    if (peer.getPeerTrustData() == null || !peer.authed) {
        if (command == (byte) 1 || command == (byte) 2 || command == (byte) 10 || command == (byte) 51 || command == (byte) 52 || command == (byte) 53 || command == (byte) 55 || command == (byte) 100 || command == (byte) 101) {
        // erlaubte befehle welche ohne verschluesselung ausgefuehrt werden duerfen
        } else {
            System.out.println("PEER wanted to send a command (" + command + ") which is only allowed after auth. : " + peer.ip);
            peer.disconnect(" command but must be crypted");
            return 0;
        }
    }
    //System.out.println(peer.ip + " incoming command: " + command);
    if (command == (byte) 1) {
        Log.put("Command: get PeerList", 8);
        ByteBuffer tempWriteBuffer = ByteBuffer.allocate(1024 * 10);
        tempWriteBuffer.put((byte) 2);
        ArrayList<Peer> clonedPeerList = Test.getClonedPeerList();
        ArrayList<Peer> validPeers = new ArrayList<Peer>();
        ArrayList<Peer> validPeersIPv6 = new ArrayList<Peer>();
        for (Peer p1 : clonedPeerList) {
            if (p1.equals(peer)) {
                continue;
            }
            if (!p1.isConnected() || p1.writeBufferCrypted == null || !p1.authed) {
                continue;
            }
            if (p1.connectAble == 1 && p1.ip.split("\\.").length == 4) {
                if (validPeers.size() < 254) {
                    //currently only 254 peers possible since the counter for it is just a byte. probably just send two seperated lists
                    validPeers.add(p1);
                }
            }
            if (p1.connectAble == 1 && p1.ip.split("\\.").length != 4) {
                validPeersIPv6.add(p1);
            }
        }
        tempWriteBuffer.put((byte) validPeers.size());
        // no ipv6 addresses yet
        tempWriteBuffer.put((byte) 0);
        for (Peer p1 : validPeers) {
            String[] split = p1.ip.split("\\.");
            if (split.length == 4) {
                for (String a : split) {
                    int asdd = Integer.parseInt(a);
                    //System.out.println("Int: " + (int) ((byte) asdd & 0xFF));
                    tempWriteBuffer.put((byte) asdd);
                }
                putUnsignedShot(tempWriteBuffer, p1.port);
            }
        }
        for (Peer p1 : validPeersIPv6) {
            if (p1.ip.length() > 250) {
                System.out.println("konnte IPv6 nicht sharen, zu lang: " + p1.ip);
                continue;
            }
            tempWriteBuffer.put((byte) 10);
            tempWriteBuffer.put((byte) p1.ip.length());
            tempWriteBuffer.put(p1.ip.getBytes());
            putUnsignedShot(tempWriteBuffer, p1.port);
        }
        tempWriteBuffer.flip();
        peer.writeBufferLock.lock();
        writeBuffer.put(tempWriteBuffer);
        peer.writeBufferLock.unlock();
        return 1;
    } else if (command == (byte) 2) {
        Log.put("Command: peerList", 8);
        if (2 > readBuffer.remaining()) {
            return 0;
        }
        int ipv4addresses = (int) readBuffer.get() & 0xFF;
        int ipv6addresses = (int) readBuffer.get() & 0xFF;
        int needBytes = ipv4addresses * 6 + ipv6addresses * 18;
        if (needBytes > readBuffer.remaining()) {
            //                System.out.println("Bytesremaining: " + readBuffer.remaining() + " ipv4 addresses: " + ipv4addresses);
            return 0;
        }
        //            System.out.println("parse " + ipv4addresses + " ipv4 addresses....");
        for (int i = 0; i < ipv4addresses; i++) {
            int ipblock1 = (int) readBuffer.get() & 0xFF;
            int ipblock2 = (int) readBuffer.get() & 0xFF;
            int ipblock3 = (int) readBuffer.get() & 0xFF;
            int ipblock4 = (int) readBuffer.get() & 0xFF;
            int port = readUnsignedShort(readBuffer);
            String ip = ipblock1 + "." + ipblock2 + "." + ipblock3 + "." + ipblock4;
            Peer peerToAdd = new Peer(ip, port);
            boolean alreadyInList = false;
            ArrayList<Peer> clonedPeerList = getClonedPeerList();
            for (Peer tpeer : clonedPeerList) {
                if (tpeer.equalsIpAndPort(peerToAdd)) {
                    alreadyInList = true;
                }
            }
            //System.out.println("asdasdasd " + alreadyInList + " " + ip);
            if (!alreadyInList) {
                Test.messageStore.insertPeerConnectionInformation(ip, port, 0, System.currentTimeMillis());
            }
        }
        return 1 + 2 + needBytes;
    } else if (command == (byte) 3) {
        Log.put("Command: sync!", 8);
        if (2 > readBuffer.remaining()) {
            return 0;
        }
        final long timestamp = readBuffer.getLong();
        if (timestamp == -1) {
            peer.syncMessagesSince = System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 7;
            //full sync
            syncAllMessagesSince(peer.syncMessagesSince, peer);
            return 1 + 8;
        }
        int howMuchAddresses = readBuffer.get();
        if (howMuchAddresses == 0) {
            peer.syncMessagesSince = timestamp;
            long myTime = System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 7;
            if (Settings.SUPERNODE) {
                myTime = 0;
            }
            syncAllMessagesSince(Math.max(timestamp, myTime), peer);
        }
        //obsolet??
        if (howMuchAddresses * 33 > readBuffer.remaining()) {
            //need more bytes in readBuffer...
            return 0;
        }
        //obsolet??
        byte[] address = new byte[33];
        for (int i = 0; i < howMuchAddresses; i++) {
            readBuffer.get(address);
            //ECKey eCKey = new ECKey(null, address);
            ECKey eCKey = new ECKey(null, address, true);
            System.out.println("Address to filter: " + eCKey);
        }
        return 1 + 8 + 1 + howMuchAddresses * 33;
    } else if (command == (byte) 4) {
        Log.put("Command: address to id", 8);
        if (37 > readBuffer.remaining()) {
            return 0;
        }
        byte[] address = new byte[33];
        readBuffer.get(address);
        //ECKey eCKey = new ECKey(null, address);
        ECKey eCKey = new ECKey(null, address, true);
        int id = readBuffer.getInt();
        //System.out.println("address to id: " + Channel.byte2String(eCKey.getPubKey()) + " id: " + id);
        //eCKey.database_id = Test.messageStore.getPubkeyId(eCKey);
        //            if (peer.keyToIdHis.get(id) == null) {
        //                System.out.println("Warning, index not found... closing connection...");
        //                peer.disconnect();
        //                return 1 + 37;
        //            }
        //peer.keyToIdHis.put(id, eCKey);
        peer.getKeyToIdHis().put(id, eCKey);
        return 1 + 37;
    } else if (command == (byte) 5) {
        Log.put("Command: have message", 10);
        if (21 > readBuffer.remaining()) {
            return 0;
        }
        int pubkey_id_local = readBuffer.getInt();
        byte public_type = readBuffer.get();
        long timestamp = readBuffer.getLong();
        int nonce = readBuffer.getInt();
        int messageId = readBuffer.getInt();
        //peer.peerTrustData.introducedMessages++;
        ECKey id2KeyHis = peer.getId2KeyHis(pubkey_id_local);
        //System.out.println("Key for message: " + Channel.byte2String(id2KeyHis.getPubKey()));
        if (id2KeyHis == null) {
            System.out.println("WARNING: key not found -.- " + pubkey_id_local + " " + peer.getKeyToIdHis().size() + " --- disconnect");
            //                for (Entry<Integer, ECKey> entry :peer.keyToIdHis.entrySet()) {
            //                    
            //                    System.out.println("");
            //                    
            //                }
            peer.disconnect("key not found 32323.");
            return 1 + 21;
        }
        RawMsg rawMsg = new RawMsg(id2KeyHis, timestamp, nonce);
        rawMsg.public_type = public_type;
        //boolean contains = MessageHolder.contains(rawMsg);
        //System.out.println("Peer got following msg: " + timestamp + " " + channelId + " " + nonce + " " + messageId);
        //if (!contains) {
        //                System.out.println("found msg i want to have...");
        boolean dontAddMessage = false;
        // or i just wrote to a channel i'm not listening to, like the main channel!!!
        if (Settings.lightClient) {
            if (!peer.myInterestedChannelsCodedInHisIDs.contains(pubkey_id_local)) {
                //int my_pubkeyId = Test.messageStore.getPubkeyId(id2KeyHis);
                if (Test.channels.contains(new Channel(id2KeyHis, null))) {
                    peer.myInterestedChannelsCodedInHisIDs.add(pubkey_id_local);
                    Log.put("added !! " + pubkey_id_local + " node: " + peer.nonce, 100);
                } else {
                    int pubkeyId = Test.messageStore.getPubkeyId(id2KeyHis);
                    peer.writeBufferLock.lock();
                    ECKey k = id2KeyHis;
                    if (!peer.peerTrustData.keyToIdMine.contains(pubkeyId)) {
                        peer.peerTrustData.keyToIdMine.add(pubkeyId);
                        //int indexOf = keyToIdMine.indexOf(k);
                        int indexOf = pubkeyId;
                        peer.writeBuffer.put((byte) 4);
                        peer.writeBuffer.put(k.getPubKey());
                        peer.writeBuffer.putInt(indexOf);
                        Log.put("key introduced", 0);
                    }
                    peer.writeBuffer.put((byte) 62);
                    peer.writeBuffer.putInt(pubkeyId);
                    peer.writeBufferLock.unlock();
                    dontAddMessage = true;
                    Log.put("channel was removed, sending to node.... " + pubkeyId + " node: " + peer.nonce, 0);
                    //There may be still messages to sync to other nodes, we have to remove them!!
                    //ToDo: replace this hack!
                    Test.messageStore.removeMessageToSend(peer.getPeerTrustData().internalId);
                }
            }
            Log.put("contains!!! " + pubkey_id_local + " node: " + peer.nonce, 100);
        }
        if (!dontAddMessage) {
            HashMap<PeerTrustData, Long> perKey = ratingData.get(id2KeyHis);
            if (perKey == null) {
                perKey = new HashMap<PeerTrustData, Long>();
                ratingData.put(id2KeyHis, perKey);
            }
            ////                Long time = perKey.get(peer.peerTrustData);
            ////                if (time != null && time != 0L) {
            ////                    //there is already a time, we have to evaluate last round...
            ////                    System.out.println("there is already a time, we have to evaluate last round...");
            ////
            ////                    ArrayList<PeerTrustData> keySet = new ArrayList<PeerTrustData>(perKey.keySet());
            ////
            ////                    final HashMap<PeerTrustData, Long> perKeyFinal = perKey;
            ////                    Collections.sort(keySet, new Comparator<PeerTrustData>() {
            ////
            ////                        @Override
            ////                        public int compare(PeerTrustData t, PeerTrustData t1) {
            ////                            return (int) (perKeyFinal.get(t) - perKeyFinal.get(t1));
            ////                        }
            ////                    });
            ////
            ////                    int valueToAdd = 0;
            ////
            ////                    for (PeerTrustData ptd : keySet) {
            ////
            ////                        if (ptd == peer.peerTrustData) {
            ////                            continue;
            ////                        }
            ////
            ////                        long diff = peer.peerTrustData.rating - ptd.rating;
            ////                        double value1 = 10 / (1 + Math.pow(10, (float) diff / 8)) * 20;
            ////
            ////                        int value = (int) Math.floor(value1);
            ////
            ////                        if (value == 0) {
            ////                            value = 1;
            ////                        }
            ////
            ////                        ptd.rating += -value;
            ////                        valueToAdd += value;
            ////
            ////                        System.out.println(perKey.get(ptd) + " - value: " + (-value) + " -  " + ptd.rating + "    - " + ptd.ips);
            ////                        //reset round!
            ////                        perKey.put(ptd, 0L);
            ////                    }
            ////
            ////                    peer.peerTrustData.rating += valueToAdd;
            ////                    System.out.println(perKey.get(peer.peerTrustData) + " - Winner: " + (valueToAdd) + " -  " + peer.peerTrustData.rating + "    - " + peer.peerTrustData.ips);
            ////
            ////                }
            ////
            ////                perKey.put(peer.peerTrustData, System.currentTimeMillis());
            peer.addPendingMessage(messageId, rawMsg);
            //Test.messageStore.addMsgIntroducedToMe(peer.getPeerTrustData().internalId, messageId);
            peer.getPeerTrustData().synchronizedMessages++;
            Log.put("added pending msg... + " + peer.ip + " - " + messageId, 60);
        //                synchronized (writeBuffer) {
        //                    writeBuffer.put((byte) 6);
        //                    writeBuffer.putInt(messageId);
        //                }
        //}
        }
        return 1 + 21;
    } else if (command == (byte) 6) {
        Log.put("Command: get message content " + peer.ip + ":" + peer.port, -2);
        if (4 > readBuffer.remaining()) {
            return 0;
        }
        final int id = readBuffer.getInt();
        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                final String orgName = Thread.currentThread().getName();
                if (!orgName.contains(" ")) {
                    Thread.currentThread().setName(orgName + " - send Message Thread");
                }
                RawMsg rawMsg = null;
                rawMsg = MessageHolder.getRawMsg(id);
                Log.put("message to fetch by id: " + id, -2);
                if (rawMsg == null) {
                    System.out.println("HM diese Nachricht habe ich nicht, id: " + id + " ip: " + peer.getIp());
                    return;
                }
                if (rawMsg.getContent() == null || rawMsg.getContent().length > 1024 * 201) {
                    Main.sendBroadCastMsg("ohoh, rawMsg.getContent() is null or too long...");
                    return;
                }
                int cnt = 0;
                peer.writeBufferLock.lock();
                while (peer.writeBuffer != null && peer.writeBuffer.remaining() < rawMsg.getContent().length + 1 + 4 + 72) {
                    if (!peer.isConnected()) {
                        peer.writeBufferLock.unlock();
                        return;
                    }
                    cnt++;
                    try {
                        peer.writeBufferLock.unlock();
                        sleep(1000);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(ConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    System.out.println("Buffer full, cnt: " + cnt + " contentlen: " + rawMsg.getContent().length + " remaining: " + ((peer.writeBuffer != null) ? peer.writeBuffer.remaining() : "null"));
                    if (cnt == 100) {
                        Main.sendBroadCastMsg("CODE 2kcvh5: buffer to small..." + cnt);
                        peer.writeBufferLock.unlock();
                        return;
                    }
                    peer.writeBufferLock.lock();
                }
                if (peer.writeBuffer == null) {
                    System.out.println("writebuffer was null while, wanted to write msg to node");
                    return;
                }
                writeBuffer.put((byte) 7);
                writeBuffer.putInt(id);
                if (rawMsg.getSignature().length != 72) {
                    throw new RuntimeException("hreuhrwuirhew signature got wrong length!!!");
                }
                writeBuffer.put(rawMsg.getSignature());
                writeBuffer.putInt(rawMsg.getContent().length);
                //NullPointer thrown in HeapByteBuffer, dont know why, so hack!
                try {
                    //todo: catch via another way?
                    peer.writeBuffer.put(rawMsg.getContent());
                } catch (Throwable e) {
                    Main.sendBroadCastMsg("prevented exception 73632.");
                    peer.disconnect("prevented exception 73632");
                }
                peer.writeBufferLock.unlock();
                peer.setWriteBufferFilled();
                Log.put("wrote msg to peer " + peer.ip + " with byte length: " + rawMsg.getContent().length + " msgid: " + rawMsg.database_Id, -2);
            }
        };
        threadPool2.execute(runnable);
        return 1 + 4;
    } else if (command == (byte) 7) {
        //message content
        if (4 + RawMsg.SIGNATURE_LENGRTH + 4 > readBuffer.remaining()) {
            return 0;
        }
        final int msgId = readBuffer.getInt();
        byte[] signature = new byte[RawMsg.SIGNATURE_LENGRTH];
        readBuffer.get(signature);
        //System.out.println("SIGNATURE  : " + Utils.bytesToHexString(signature));
        int contentLength = readBuffer.getInt();
        //            System.out.println("###### content len: " + contentLength);
        if (contentLength > readBuffer.remaining()) {
            Log.put("not enough bytes yet... missing: " + (contentLength - readBuffer.remaining()) + " got: " + readBuffer.remaining() + " needed: " + contentLength, 20);
            return 0;
        }
        //            Log.put("Command: msg content incoming...", 8);
        byte[] content = new byte[contentLength];
        readBuffer.get(content);
        RawMsg get = peer.getPendingMessages().get(msgId);
        if (get == null) {
            get = peer.getPendingMessagesTimedOut().get(msgId);
            if (get == null) {
                System.out.println("WARNING: got message content for a message I cant find... " + msgId + " " + peer.getPendingMessages().size() + " ip: " + peer.ip);
                return 1 + 4 + RawMsg.SIGNATURE_LENGRTH + 4 + contentLength;
            }
            System.out.println("WARNING: get message content for a timed out message... trying to add content to database...." + msgId + " " + peer.getPendingMessages().size() + " ip: " + peer.ip);
        }
        get.signature = signature;
        get.content = content;
        MessageDownloader.publicMsgsLoadedLock.lock();
        MessageDownloader.publicMsgsLoaded++;
        MessageDownloader.publicMsgsLoadedLock.unlock();
        final RawMsg getFinal = get;
        Log.put("execute new msg thread", 70);
        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                final String orgName = Thread.currentThread().getName();
                if (!orgName.contains(" ")) {
                    Thread.currentThread().setName(orgName + " - addMessage + pr. broadcast");
                }
                RawMsg addMessage = MessageHolder.addMessage(getFinal);
                peer.requestedMsgs--;
                MessageDownloader.removeRequestedMessage(getFinal);
                //System.out.println("DWGDYWGDYW " + addMessage.key.database_id);
                //                            synchronized (peer.getPendingMessages()) {
                //                                peer.getPendingMessages().remove(msgId);
                //                            }
                Log.put("msg: " + getFinal.timestamp + " " + getFinal.nonce, 100);
                if (addMessage.getChannel() == null) {
                    //isPublic...
                    MessageDownloader.publicMsgsLoaded++;
                }
                //                    System.out.println("signature hash: " + Sha256Hash.create(addMessage.signature));
                synchronized (peer.getLoadedMsgs()) {
                    peer.addLoadedMsg(addMessage.database_Id);
                }
                if (addMessage.key.database_id == -1) {
                    addMessage = MessageHolder.addMessage(addMessage);
                    System.out.println("woooot " + Utils.bytesToHexString(getFinal.key.getPubKey()) + " " + getFinal.timestamp);
                }
                if (addMessage.key.database_id == -1) {
                    System.out.println("#####CODE: 19564 - NICHT GUT!!!! - try again to get PUBKEY ID");
                    RawMsg again = MessageHolder.addMessage(addMessage);
                    System.out.println("#####Key id is now: " + again.key.database_id);
                    System.out.println("#####Message not broadcasted...");
                    return;
                }
                if (!Settings.BROADCAST_MSGS_AFTER_VERIFICATION) {
                    Test.broadcastMsg(addMessage);
                }
                MessageDownloader.trigger();
                MessageVerifierHsqlDb.trigger();
                if (peer.maxSimultaneousRequests <= MessageDownloader.MAX_REQUEST_PER_PEER) {
                    peer.maxSimultaneousRequests++;
                    Log.put("increased max req to: " + peer.maxSimultaneousRequests, -1);
                }
            }
        };
        threadPool.execute(runnable);
        //runnable.run();
        //            new Thread() {
        //
        //                @Override
        //                public void run() {
        //                    try {
        //                        sleep(10000);
        //                    } catch (InterruptedException ex) {
        //                        Logger.getLogger(ConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
        //                    }
        //                    peer.requestedMsgs--;
        //                    MessageDownloader.trigger();
        //                }
        //            }.start();
        Log.put("parsed bytes: " + (1 + 4 + RawMsg.SIGNATURE_LENGRTH + 4 + contentLength) + " remainig: " + readBuffer.remaining(), 200);
        return 1 + 4 + RawMsg.SIGNATURE_LENGRTH + 4 + contentLength;
    } else if (command == (byte) 8) {
        Log.put("Command: control data request...", 8);
        PeerTrustData peerTrustData = peer.getPeerTrustData();
        //ToDo: remove 0.s
        peer.writeBufferLock.lock();
        writeBuffer.put((byte) 9);
        writeBuffer.putInt(0);
        writeBuffer.putInt(peerTrustData.keyToIdHis.size());
        writeBuffer.putInt(peerTrustData.keyToIdMine.size());
        writeBuffer.putInt(0);
        ArrayList<Integer> keySet = new ArrayList<Integer>(peerTrustData.keyToIdHis.keySet());
        Collections.sort(keySet);
        //            String toHashkeyToIdHis = "";
        //            for (Entry<Integer, ECKey> entry : peerTrustData.keyToIdHis.entrySet()) {
        //                int key = entry.getKey();
        //                toHashkeyToIdHis += "" + key;
        //            }
        String toHashkeyToIdHis = "";
        for (Integer key : keySet) {
            toHashkeyToIdHis += "" + key;
        }
        Collections.sort(peerTrustData.keyToIdMine);
        String toHashkeyToIdMine = "";
        for (int key : peerTrustData.keyToIdMine) {
            toHashkeyToIdMine += "" + key;
        }
        try {
            writeBuffer.putInt(Sha256Hash.create(toHashkeyToIdMine.getBytes("UTF-8")).hashCode());
            writeBuffer.putInt(Sha256Hash.create(toHashkeyToIdHis.getBytes("UTF-8")).hashCode());
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(ConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
        peer.writeBufferLock.unlock();
        return 1;
    } else if (command == (byte) 9) {
        if (4 + 4 + 4 + 4 + 4 + 4 > readBuffer.remaining()) {
            return 0;
        }
        PeerTrustData peerTrustData = peer.getPeerTrustData();
        int introducedMessages = readBuffer.getInt();
        int keyToIdHis = readBuffer.getInt();
        int keyToIdMine = readBuffer.getInt();
        int sendMessages = readBuffer.getInt();
        int hashkeyToIdMine = readBuffer.getInt();
        int hashkeyToIdHis = readBuffer.getInt();
        //mine = his
        //System.out.println("keyToIdHis: " + peerTrustData.keyToIdHis.size() + " - " + keyToIdMine);
        //System.out.println("keyToIdMine: " + peerTrustData.keyToIdMine.size() + " - " + keyToIdHis);
        Set<Integer> keySet = peerTrustData.keyToIdHis.keySet();
        ArrayList<Integer> arrayList = new ArrayList<Integer>(keySet);
        //            Comparator<Integer> comparator = new Comparator<Integer>() {
        //                public int compare(Integer o1, Integer o2) {
        //                    return 0;
        //                }
        //            };
        Collections.sort(arrayList);
        String toHashkeyToIdHis = "";
        for (int key : arrayList) {
            toHashkeyToIdHis += "" + key;
        }
        Collections.sort(peerTrustData.keyToIdMine);
        String toHashkeyToIdMine = "";
        for (int key : peerTrustData.keyToIdMine) {
            toHashkeyToIdMine += "" + key;
        }
        try {
            int myHashkeyToIdMine = Sha256Hash.create(toHashkeyToIdMine.getBytes("UTF-8")).hashCode();
            int myHashkeyToIdHis = Sha256Hash.create(toHashkeyToIdHis.getBytes("UTF-8")).hashCode();
            Log.put("Hash keyToIdMine: " + myHashkeyToIdHis + " - " + hashkeyToIdMine, 30);
            if (peerTrustData.keyToIdHis.size() != keyToIdMine || myHashkeyToIdHis != hashkeyToIdMine) {
                System.out.println("keyToIdHis wrong, clearing....");
                System.out.println("list: " + toHashkeyToIdHis);
                peerTrustData.keyToIdHis.clear();
            }
            Log.put("Hash keyToIdMine: " + myHashkeyToIdMine + " - " + hashkeyToIdHis, 30);
            if (peerTrustData.keyToIdMine.size() != keyToIdHis || myHashkeyToIdMine != hashkeyToIdHis) {
                System.out.println("keyToIdMine wrong, clearing....");
                System.out.println("list: " + toHashkeyToIdMine);
                peerTrustData.keyToIdMine.clear();
            }
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(ConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
        //            }
        if (Settings.lightClient) {
            //remove -1 for migration from super node to light node.
            peer.writeBuffer.put((byte) 62);
            peer.writeBuffer.putInt(-1);
            for (Channel channel : Test.channels) {
                if (!peer.getPeerTrustData().sendChannelsToFilter.contains(peer)) {
                    peer.sendChannelToFilter(channel.key);
                }
            }
        //TODO: code remove routine....
        } else {
            peer.writeBufferLock.lock();
            //ToDo: remove later
            if (!peerTrustData.keyToIdMine.contains(-1)) {
                peerTrustData.keyToIdMine.add(-1);
                writeBuffer.put((byte) 4);
                writeBuffer.put(new byte[33]);
                writeBuffer.putInt(-1);
            //System.out.println("Msg index: " + indexOf);
            }
            peer.writeBuffer.put((byte) 60);
            peer.writeBuffer.putInt(-1);
            peer.writeBufferLock.unlock();
        }
        peer.writeBufferLock.lock();
        //init sync
        writeBuffer.put((byte) 3);
        //sync last two days
        //writeBuffer.putLong(-1);// full sync!
        //writeBuffer.putLong(0);
        //writeBuffer.putLong(Math.max(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 2, Settings.till));
        //writeBuffer.putLong(Math.max(System.currentTimeMillis() - 1000 * 60, Settings.till));
        //writeBuffer.putLong(System.currentTimeMillis() - 1000 * 60 * 60);
        long myTime = System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 7;
        if (Settings.SUPERNODE) {
            myTime = 0;
        }
        writeBuffer.putLong(myTime);
        writeBuffer.put((byte) 0);
        //get PeerList
        writeBuffer.put((byte) 1);
        //                    peer.setWriteBufferFilled();
        peer.writeBufferLock.unlock();
        return 1 + 4 + 4 + 4 + 4 + 4 + 4;
    } else if (command == (byte) 10) {
        if (1 + +1 + 2 > readBuffer.remaining()) {
            return 0;
        }
        byte get = readBuffer.get();
        if (get < 1) {
            System.out.println("omg, wrong IP address length....");
            peer.disconnect("ip address len < 0");
            return 0;
        }
        if (1 + 1 + ((int) get) + 2 > readBuffer.remaining()) {
            return 0;
        }
        byte[] ipBytes = new byte[get];
        readBuffer.get(ipBytes);
        String ip = new String(ipBytes);
        int port = readUnsignedShort(readBuffer);
        Peer newPeer = new Peer(ip, port);
        //System.out.println("Peerexchange: new peer " + ip + ":" + port);
        Test.findPeer(newPeer);
        return 1 + 1 + get + 2;
    } else if (command == (byte) 51) {
        if (1 + 16 > readBuffer.remaining()) {
            return 0;
        }
        byte[] otherAuthKeyBytes = new byte[16];
        readBuffer.get(otherAuthKeyBytes);
        if (!peer.requestedNewAuth) {
            //dafuq, thought I had an authkey for node. Generating new AuthKey
            System.out.println("dafuq, thought I had an authkey for node. Generating new AuthKey: " + peer.nonce);
            //peer.peerTrustData = new PeerTrustData();
            sendNewAuthKey(peer);
        }
        if (peer.peerIsHigher()) {
            System.arraycopy(otherAuthKeyBytes, 0, peer.peerTrustData.authKey, 16, 16);
        } else {
            System.arraycopy(otherAuthKeyBytes, 0, peer.peerTrustData.authKey, 0, 16);
        }
        peer.peerTrustData.nonce = peer.nonce;
        Test.peerTrusts.add(peer.peerTrustData);
        peer.peerTrustData.initInternalId();
        saveTrustData();
        System.out.println("added key from other side... " + peer.nonce);
        System.out.println("requesting auth ...: " + peer.nonce);
        Random r = new SecureRandom();
        byte[] toEncrypt = new byte[32];
        r.nextBytes(toEncrypt);
        peer.writeBufferLock.lock();
        writeBuffer.put((byte) 52);
        writeBuffer.put(toEncrypt);
        peer.writeBufferLock.unlock();
        peer.toEncodeForAuthFromMe = toEncrypt;
        //            System.out.println("request authentication...");
        return 1 + 16;
    } else if (command == (byte) 52) {
        if (32 > readBuffer.remaining()) {
            return 0;
        }
        byte[] toEnc = new byte[32];
        readBuffer.get(toEnc);
        boolean send = false;
        for (PeerTrustData pt : Test.peerTrusts) {
            if (pt.nonce != peer.nonce) {
                continue;
            }
            byte[] encode = AESCrypt.encode(pt.authKey, toEnc);
            peer.toEncodeForAuthFromHim = toEnc;
            peer.writeBufferLock.lock();
            writeBuffer.put((byte) 53);
            writeBuffer.put(encode);
            peer.writeBufferLock.unlock();
            send = true;
        }
        peer.setWriteBufferFilled();
        if (!send) {
            System.out.println("ERROR 77877");
        }
        //System.out.println("encoded data with authKey... " + Utils.bytesToHexString(encode) + " len: " + encode.length);
        return 1 + 32;
    } else if (command == (byte) 53) {
        if (48 > readBuffer.remaining()) {
            System.out.println("zu wenig bytes.... " + readBuffer.remaining());
            return 0;
        }
        byte[] thereEnc = new byte[48];
        readBuffer.get(thereEnc);
        if (peer.toEncodeForAuthFromHim == null || peer.toEncodeForAuthFromMe == null) {
            System.out.println("FATAL ERROR: 48727 - auth failed");
            return 1 + 48;
        }
        boolean found = false;
        for (PeerTrustData pt : Test.peerTrusts) {
            if (pt.nonce != peer.nonce) {
                continue;
            }
            found = true;
            byte[] myEnc = AESCrypt.encode(pt.authKey, peer.toEncodeForAuthFromMe);
            if (Arrays.equals(thereEnc, myEnc)) {
                peer.peerTrustData = pt;
                //System.out.println("Auth successfull with nonce: " + peer.nonce);
                peer.authed = true;
                //Schluessel ist peer.peer.peerTrustData.authKey + thereEnc + myEnc, falls die Verbindung von aussem kommt.
                //ansonsten vertausche thereEnc mit myEnc.
                byte[] rc4CrpytKeySeedWrite = new byte[32 + 32 + 32];
                byte[] rc4CrpytKeySeedRead = new byte[32 + 32 + 32];
                System.arraycopy(peer.peerTrustData.authKey, 0, rc4CrpytKeySeedWrite, 0, 32);
                System.arraycopy(peer.peerTrustData.authKey, 0, rc4CrpytKeySeedRead, 0, 32);
                if (peer.peerIsHigher()) {
                    //System.out.println("Im higher");
                    System.arraycopy(peer.toEncodeForAuthFromMe, 0, rc4CrpytKeySeedWrite, 32, 32);
                    System.arraycopy(peer.toEncodeForAuthFromHim, 0, rc4CrpytKeySeedWrite, 64, 32);
                    System.arraycopy(peer.toEncodeForAuthFromHim, 0, rc4CrpytKeySeedRead, 32, 32);
                    System.arraycopy(peer.toEncodeForAuthFromMe, 0, rc4CrpytKeySeedRead, 64, 32);
                } else {
                    //System.out.println("Im lower");
                    System.arraycopy(peer.toEncodeForAuthFromMe, 0, rc4CrpytKeySeedRead, 32, 32);
                    System.arraycopy(peer.toEncodeForAuthFromHim, 0, rc4CrpytKeySeedRead, 64, 32);
                    System.arraycopy(peer.toEncodeForAuthFromHim, 0, rc4CrpytKeySeedWrite, 32, 32);
                    System.arraycopy(peer.toEncodeForAuthFromMe, 0, rc4CrpytKeySeedWrite, 64, 32);
                }
                //                    System.out.println("My NONCE: " + Test.NONCE);
                //                    System.out.println("There NONCE: " + peer.nonce);
                //                    System.out.println("KABUM, initialisiere Verschluesselung, key fuer ARC4  " + Utils.bytesToHexString(rc4CrpytKeySeed));
                //
                //                    System.out.println("my: " + Utils.bytesToHexString(myEnc));
                //                    System.out.println("te: " + Utils.bytesToHexString(thereEnc));
                byte[] rc4CryptKeyFalseWrite = Sha256Hash.create(rc4CrpytKeySeedWrite).getBytes();
                byte[] rc4CryptKeyFalseRead = Sha256Hash.create(rc4CrpytKeySeedRead).getBytes();
                //                    System.out.println("Hashed key is: " + Utils.bytesToHexString(rc4CryptKey));
                //System.out.println("KABUM, initialisiere Verschluesselung, key fuer ARC4  " + Utils.bytesToHexString(rc4CryptKeyFalseWrite) + " -- " + Utils.bytesToHexString(rc4CryptKeyFalseRead));
                //System.out.println("ARC4 active. IP: " + peer.ip);
                //Beide bruachen einen eigenen rc4 verschluesseler da sich der Key aendert mit jedem byte welches verschluesselt wird...
                //System.out.println("Key length: " + rc4CryptKeyFalse.length);
                //Key fuer RC4 darf nur max 31 bytes haben, loesche letztes byte...
                byte[] rc4CryptKeyWrite = new byte[31];
                byte[] rc4CryptKeyRead = new byte[31];
                System.arraycopy(rc4CryptKeyFalseWrite, 0, rc4CryptKeyWrite, 0, 31);
                System.arraycopy(rc4CryptKeyFalseRead, 0, rc4CryptKeyRead, 0, 31);
                if (peer.peerIsHigher()) {
                    peer.writeKey = new RC4(rc4CryptKeyWrite);
                    peer.readKey = new RC4(rc4CryptKeyRead);
                } else {
                    peer.writeKey = new RC4(rc4CryptKeyRead);
                    peer.readKey = new RC4(rc4CryptKeyWrite);
                }
                peer.peerTrustData.lastSeen = System.currentTimeMillis();
                Log.put("PEER is now trusted...", 300);
                if (peer.peerTrustData.ips.contains(peer.ip)) {
                    Log.put("IP schon in den trusted Data...", 200);
                } else {
                    if (peer.peerTrustData.ips.size() > 10) {
                        peer.peerTrustData.ips.clear();
                    }
                    peer.peerTrustData.ips.add(peer.ip);
                    peer.peerTrustData.port = peer.port;
                    Log.put("IP added and port set!", 300);
                }
                peer.removeRequestedMsgs();
                pt.pendingMessages = new HashMap<Integer, RawMsg>();
                pt.pendingMessagesTimedOut = new HashMap<Integer, RawMsg>();
                pt.pendingMessagesPublic = new HashMap<Integer, RawMsg>();
                peer.writeBufferLock.lock();
                //ab nun werden alle bytes verschluesselt, dies wird mit dem folgenden Befehl gestarted
                writeBuffer.put((byte) 55);
                //schicke dieses byte noch unverschluesselt...
                //peer.setWriteBufferFilled();
                peer.writeBufferLock.lock();
                int writtenBytes = 0;
                //switch buffer for reading
                peer.writeBuffer.flip();
                try {
                    writtenBytes = peer.writeBytesToPeer(peer.writeBuffer);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                Test.outBytes += writtenBytes;
                peer.sendBytes += writtenBytes;
                peer.writeBuffer.compact();
                if (peer.writeBuffer.position() != 0) {
                    System.out.println("ACHTUNG konnte nun verschluessel byte nicht direkt schicken...");
                }
                peer.writeBufferLock.unlock();
                //peer.readBufferCrypted = ByteBuffer.allocate(peer.readBuffer.capacity());
                try {
                    peer.writeBufferCrypted = ByteBuffer.allocate(1024 * 1024);
                } catch (Throwable e) {
                    e.printStackTrace();
                    System.out.println("Speicher konnte nicht reserviert werden2. Disconnect peer...");
                    peer.disconnect("speicher voll 34642");
                    return 0;
                }
                //FULL CONNECTED TO NODE!
                //NUN darf die Verbindung genutzt werden zum syncen usw...
                writeBuffer.put((byte) 8);
                peer.writeBufferLock.unlock();
                //peer.getPeerTrustData().removeNotSuccesfulSendMessages();
                peer.retries = 0;
                //System.out.println("send byte 8 to node");
                break;
            } else {
            //System.out.println("WARNING: auth failed with nonce: " + peer.nonce + " key: " + Utils.bytesToHexString(pt.authKey));
            //System.out.println("DATA: " + Utils.bytesToHexString(myEnc));
            //System.out.println("DATA: " + Utils.bytesToHexString(thereEnc));
            }
        }
        if (!found) {
            System.out.println("erm, nicht gefunden?!?");
        }
        return 1 + 48;
    } else if (command == (byte) 55) {
        if (peer.readKey == null) {
            System.out.println("ERROR 14275, peer wants to crypt connection, but i got no key?!?");
            peer.disconnect("ERROR 14275");
            return 0;
        }
        try {
            peer.readBufferCrypted = ByteBuffer.allocate(READ_BUFFER_SIZE);
        } catch (Throwable e) {
            System.out.println("Speicher konnte nicht reserviert werden3. Disconnect peer...");
            peer.disconnect("Speicher konnte nicht reserviert werden3.");
        }
        //Verschluessel die schon gelesenen bytes...
        if (readBuffer.hasRemaining()) {
            synchronized (peer.readBuffer) {
                byte[] buffer = new byte[peer.readBuffer.remaining()];
                peer.readBuffer.get(buffer);
                peer.readBuffer.compact();
                byte[] decrypt = peer.readKey.decrypt(buffer);
                //                peer.readBuffer.clear();
                peer.readBuffer.put(decrypt);
                peer.readBuffer.flip();
                //readbuffer darf nicht mehr verschoben werden!
                return -1;
            }
        }
        //ja das muss so!!
        return 1;
    } else if (command == (byte) 60) {
        //addFilterMessage
        if (4 > readBuffer.remaining()) {
            System.out.println("zu wenig bytes.... " + readBuffer.remaining());
            return 0;
        }
        final int hisKeyId = readBuffer.getInt();
        if (hisKeyId == -1) {
            //all channels...
            Test.messageStore.addFilterChannel(peer.getPeerTrustData().internalId, -1);
            Log.put("added all channels to get messages from: " + peer.ip, 20);
        } else {
            ECKey id2KeyHis = peer.getId2KeyHis(hisKeyId);
            if (id2KeyHis == null) {
                //id2keys wrong!
                peer.disconnect("id2KeyHis null");
            } else {
                int pubkeyIdMine = Test.messageStore.getPubkeyId(id2KeyHis);
                //System.out.println("FILTERMSG ID: " + pubkeyIdMine);
                Test.messageStore.addFilterChannel(peer.getPeerTrustData().internalId, pubkeyIdMine);
            }
        }
        return 1 + 4;
    } else if (command == (byte) 61) {
        //set Client Type
        System.out.println("command not supported, yet");
        return 1 + 4;
    } else if (command == (byte) 62) {
        //remove channel - delFilterMessage
        if (4 > readBuffer.remaining()) {
            System.out.println("zu wenig bytes.... " + readBuffer.remaining());
            return 0;
        }
        final int hisKeyId = readBuffer.getInt();
        if (hisKeyId == -1) {
            Test.messageStore.delFilterChannel(peer.getPeerTrustData().internalId, -1);
        } else {
            ECKey id2KeyHis = peer.getId2KeyHis(hisKeyId);
            if (id2KeyHis == null) {
                //id2keys wrong!
                peer.disconnect("id2KeyHis null");
            } else {
                int pubkeyIdMine = Test.messageStore.getPubkeyId(id2KeyHis);
                Test.messageStore.delFilterChannel(peer.getPeerTrustData().internalId, pubkeyIdMine);
            }
        }
        return 1 + 4;
    } else if (command == (byte) 70) {
        if (8 > readBuffer.remaining()) {
            System.out.println("zu wenig bytes.... " + readBuffer.remaining());
            return 0;
        }
        long timestamp = readBuffer.getLong();
        System.out.println("syncing back in time...");
        syncMessagesBack(timestamp, peer, 100);
        return 1 + 8;
    } else if (command == (byte) 71) {
        if (8 > readBuffer.remaining()) {
            System.out.println("zu wenig bytes.... " + readBuffer.remaining());
            return 0;
        }
        long timestamp = readBuffer.getLong();
        peer.getPeerTrustData().backSyncedTill = timestamp;
        System.out.println("setted back sync time to: " + timestamp);
        return 1 + 8;
    } else if (command == (byte) 101) {
        double a = ((System.currentTimeMillis() - peer.lastPinged) / 10.);
        double b = peer.ping * 9 / 10.;
        double c = a + b;
        peer.ping = c;
        return 1;
    } else if (command == (byte) 100) {
        //            System.out.println("Antworte auf ping...");
        //            ByteBuffer allocate = ByteBuffer.allocate(1);
        //            allocate.put((byte) 101);
        //            allocate.flip();
        //            try {
        //                peer.getSocketChannel().write(allocate);
        //            } catch (IOException ex) {
        //                Logger.getLogger(ConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
        //            }
        peer.writeBufferLock.lock();
        writeBuffer.put((byte) 101);
        peer.writeBufferLock.unlock();
        peer.setWriteBufferFilled();
        return 1;
    } else if (command == (byte) 254) {
        System.out.println("closing, other side init it...");
        peer.disconnect("closing, other side init it...");
        return 1;
    }
    byte nextByte = 0;
    if (readBuffer.hasRemaining()) {
        nextByte = readBuffer.get();
    }
    System.out.println("Wrong protocol, disconnecting + removing peer, nonce: " + peer.nonce + " Command was: " + command + " next byte: " + nextByte + " remaining: " + readBuffer.remaining() + " crypt-Stauts: out: " + (peer.writeBufferCrypted != null) + ", in: " + (peer.readBufferCrypted != null));
    ByteBuffer a = ByteBuffer.allocate(1);
    a.put((byte) 255);
    a.flip();
    try {
        int write = peer.getSocketChannel().write(a);
        System.out.println("QUIT bytes: " + write);
    } catch (IOException ex) {
    } catch (java.nio.channels.NotYetConnectedException e) {
    }
    //System.out.println("closing, got panic command...");
    peer.disconnect("WRONG BYTE!");
    //TODO add again
    Test.removePeer(peer);
    return 0;
}
Example 67
Project: jHaushalt-master  File: BuchungFactory.java View source code
public void saveData(DataOutputFacade dataOutputFacade, Buchung booking) {
    throw new NotYetConnectedException();
}
Example 68
Project: RaspiDroid-master  File: WSClient.java View source code
public void send(RDMessage msg) throws NotYetConnectedException {
    super.send(msg.toMessageString());
}
Example 69
Project: reactive-audit-master  File: DatagramChannelTest.java View source code
@Test(expected = java.nio.channels.NotYetConnectedException.class)
public void read_nb() throws IOException {
    Assume.assumeTrue(IOTestTools.isNetworkConnected());
    ByteBuffer buf = ByteBuffer.allocate(10);
    try (DatagramChannel w = channel.get()) {
        w.configureBlocking(false);
        TestTools.strict.commit();
        w.read(buf);
    }
}
Example 70
Project: roborace-master  File: ServerController.java View source code
public void sendMsg(String msg) throws NotYetConnectedException {
    System.out.println("Sending message: " + msg);
    wsc.send(msg);
}
Example 71
Project: minha-master  File: DatagramChannelImpl.java View source code
@Override
public int read(ByteBuffer dst) throws IOException {
    if (socket.isClosed())
        throw new SocketException("socket closed");
    if (!isConnected())
        throw new NotYetConnectedException();
    int res = dst.remaining();
    receive(dst);
    return res - dst.remaining();
}
Example 72
Project: Statik-Report-master  File: BeanstalkConnection.java View source code
private void throwException(Exception x) throws BeanstalkException {
    if (x instanceof NotYetConnectedException)
        throw new BeanstalkDisconnectedException(x);
    if (x instanceof IOException)
        throw new BeanstalkDisconnectedException(x);
    throw new BeanstalkException(x);
}
Example 73
Project: tcpmd5-master  File: MD5SocketChannelTest.java View source code
@Test(expected = NotYetConnectedException.class)
public void testShutdownInput() throws IOException {
    try (MD5SocketChannel sc = MD5SocketChannel.open()) {
        sc.shutdownOutput();
    }
}
Example 74
Project: TrendrrBeanstalk-master  File: BeanstalkConnection.java View source code
private void throwException(Exception x) throws BeanstalkDisconnectedException, BeanstalkException {
    if (x instanceof NotYetConnectedException) {
        throw new BeanstalkDisconnectedException(x);
    }
    if (x instanceof IOException) {
        throw new BeanstalkDisconnectedException(x);
    }
    throw new BeanstalkException(x);
}
Example 75
Project: kevoree-library-master  File: WebSocketClient.java View source code
/**
	 * Sends <var>text</var> to the connected WebSocket server.
	 * 
	 * @param text
	 *            The String to send to the WebSocket server.
	 */
public void send(String text) throws NotYetConnectedException, InterruptedException {
    if (conn != null) {
        conn.send(text);
    }
}
Example 76
Project: speech-android-sdk-master  File: WebSocketUploader.java View source code
/**
     * Write string into socket
     *
     * @param message
     */
public void upload(String message) {
    try {
        this.send(message);
    } catch (NotYetConnectedException ex) {
        Log.e(TAG, ex.getLocalizedMessage());
    }
}
Example 77
Project: Doris-master  File: DorisClientEncodeAndDecodeHandler.java View source code
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
    Throwable t = e.getCause();
    if (t instanceof IOException) {
        processChannelClosed(ctx);
    } else if (t instanceof NotYetConnectedException) {
        processChannelClosed(ctx);
    }
    super.exceptionCaught(ctx, e);
}
Example 78
Project: encore-master  File: WebSocketClient.java View source code
/**
	 * Sends <var>text</var> to the connected websocket server.
	 * 
	 * @param text
	 *            The string which will be transmitted.
	 */
public void send(String text) throws NotYetConnectedException {
    engine.send(text);
}
Example 79
Project: jx-master  File: WebSocketClient.java View source code
/**
     * Sends <var>text</var> to the connected websocket server.
     *
     * @param text The string which will be transmitted.
     */
public void send(String text) throws NotYetConnectedException {
    engine.send(text);
}
Example 80
Project: jxm-master  File: WebSocketClient.java View source code
/**
     * Sends <var>text</var> to the connected websocket server.
     *
     * @param text The string which will be transmitted.
     */
public void send(String text) throws NotYetConnectedException {
    engine.send(text);
}
Example 81
Project: keypad.io-master  File: WebSocketClient.java View source code
/**
	 * Sends <var>text</var> to the connected websocket server.
	 * 
	 * @param text
	 *            The string which will be transmitted.
	 */
public void send(String text) throws NotYetConnectedException {
    engine.send(text);
}
Example 82
Project: matlab-websockets-master  File: WebSocketClient.java View source code
/**
	 * Sends <var>text</var> to the connected WebSocket server.
	 * 
	 * @param text
	 *            The String to send to the WebSocket server.
	 */
public void send(String text) throws NotYetConnectedException {
    conn.send(text);
}
Example 83
Project: MinecraftSecondScreenMod-master  File: WebSocketClient.java View source code
/**
	 * Sends binary <var> data</var> to the connected webSocket server.
	 * 
	 * @param data
	 *            The byte-Array of data to send to the WebSocket server.
	 */
@Override
public void send(byte[] data) throws NotYetConnectedException {
    engine.send(data);
}
Example 84
Project: mixpanel-android-master  File: WebSocketClient.java View source code
/**
	 * Sends <var>text</var> to the connected websocket server.
	 * 
	 * @param text
	 *            The string which will be transmitted.
	 */
public void send(String text) throws NotYetConnectedException {
    engine.send(text);
}
Example 85
Project: mtgox-java-master  File: WebSocketClient.java View source code
/**
	 * Sends <var>text</var> to the connected WebSocket server.
	 * 
	 * @param text
	 *            The String to send to the WebSocket server.
	 */
public void send(String text) throws NotYetConnectedException {
    conn.send(text);
}
Example 86
Project: RipplePower-master  File: WebSocketClient.java View source code
/**
	 * Sends <var>text</var> to the connected websocket server.
	 * 
	 * @param text
	 *            The string which will be transmitted.
	 */
public void send(String text) throws NotYetConnectedException {
    engine.send(text);
}
Example 87
Project: tracking-master  File: WebSocketClient.java View source code
/**
	 * Sends <var>text</var> to the connected websocket server.
	 * 
	 * @param text
	 *            The string which will be transmitted.
	 */
public void send(String text) throws NotYetConnectedException {
    engine.send(text);
}
Example 88
Project: web-matlab-bridge-master  File: WebSocketClient.java View source code
/**
	 * Sends <var>text</var> to the connected WebSocket server.
	 * 
	 * @param text
	 *            The String to send to the WebSocket server.
	 */
public void send(String text) throws NotYetConnectedException {
    conn.send(text);
}
Example 89
Project: android-15-master  File: DatagramChannelImpl.java View source code
/*
     * Status check, must be open and connected, for read and write.
     */
private void checkOpenConnected() throws IOException {
    checkOpen();
    if (!isConnected()) {
        throw new NotYetConnectedException();
    }
}
Example 90
Project: bugvm-master  File: DatagramChannelImpl.java View source code
/*
     * Status check, must be open and connected, for read and write.
     */
private void checkOpenConnected() throws IOException {
    checkOpen();
    if (!isConnected()) {
        throw new NotYetConnectedException();
    }
}
Example 91
Project: pi4jmultimeter-master  File: WebSocketClient.java View source code
/**
	 * Sends <var>text</var> to the connected WebSocket server.
	 * 
	 * @param text
	 *            The String to send to the WebSocket server.
	 */
public void send(String text) throws NotYetConnectedException {
    conn.send(text);
}
Example 92
Project: property-db-master  File: DatagramChannelImpl.java View source code
/*
     * Status check, must be open and connected, for read and write.
     */
private void checkOpenConnected() throws IOException {
    checkOpen();
    if (!isConnected()) {
        throw new NotYetConnectedException();
    }
}
Example 93
Project: XobotOS-master  File: DatagramChannelImpl.java View source code
/*
     * Status check, must be open and connected, for read and write.
     */
private void checkOpenConnected() throws IOException {
    checkOpen();
    if (!isConnected()) {
        throw new NotYetConnectedException();
    }
}
Example 94
Project: j2objc-master  File: DatagramChannelImpl.java View source code
/*
     * Status check, must be open and connected, for read and write.
     */
private void checkOpenConnected() throws IOException {
    checkOpen();
    if (!isConnected()) {
        throw new NotYetConnectedException();
    }
}
Example 95
Project: algo-improv-orch-master  File: OSCServer.java View source code
public void setCodec(OSCPacketCodec c, SocketAddress target) throws IOException {
    final OSCTransmitter trns;
    synchronized (connSync) {
        trns = (OSCTransmitter) mapTrns.get(target);
    }
    if (trns == null)
        throw new NotYetConnectedException();
}
Example 96
Project: ardroid-export-master  File: OSCServer.java View source code
public void setCodec(OSCPacketCodec c, SocketAddress target) throws IOException {
    final OSCTransmitter trns;
    synchronized (connSync) {
        trns = (OSCTransmitter) mapTrns.get(target);
    }
    if (trns == null)
        throw new NotYetConnectedException();
}
Example 97
Project: NetUtil-master  File: OSCServer.java View source code
public void setCodec(OSCPacketCodec c, SocketAddress target) throws IOException {
    final OSCTransmitter trns;
    synchronized (connSync) {
        trns = (OSCTransmitter) mapTrns.get(target);
    }
    if (trns == null)
        throw new NotYetConnectedException();
}
Example 98
Project: roboband-master  File: OSCServer.java View source code
public void setCodec(OSCPacketCodec c, SocketAddress target) throws IOException {
    final OSCTransmitter trns;
    synchronized (connSync) {
        trns = (OSCTransmitter) mapTrns.get(target);
    }
    if (trns == null)
        throw new NotYetConnectedException();
}