Example usage for java.nio ByteBuffer flip

List of usage examples for java.nio ByteBuffer flip

Introduction

In this page you can find the example usage for java.nio ByteBuffer flip.

Prototype

public final Buffer flip() 

Source Link

Document

Flips this buffer.

Usage

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

/**
 * ByteBuffer//  w  w  w  . ja  v  a 2s . com
 * @return
 */
public ByteBuffer marshall() {
    int size = getSize();
    ByteBuffer buffer = ByteBuffer.allocate(size);
    buffer.put(magic.getBytes());
    buffer.putLong(sequence);
    buffer.putLong(type);
    buffer.putInt(size);
    buffer.put(payLoad);
    buffer.flip();
    return buffer;
}

From source file:net.kungfoo.grizzly.proxy.impl.ConnectingHandler.java

public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) {
    System.out.println(conn + " [proxy<-origin] input ready");

    HttpContext context = conn.getContext();
    ProxyProcessingInfo proxyTask = (ProxyProcessingInfo) context.getAttribute(ProxyProcessingInfo.ATTRIB);

    synchronized (proxyTask) {
        ConnState connState = proxyTask.getOriginState();
        if (connState != ConnState.RESPONSE_RECEIVED && connState != ConnState.RESPONSE_BODY_STREAM) {
            throw new IllegalStateException("Illegal target connection state: " + connState);
        }/* w w w  .  ja  va  2 s.c  o m*/

        final Response response = proxyTask.getResponse();
        try {

            ByteBuffer dst = proxyTask.getOutBuffer();
            int bytesRead = decoder.read(dst);
            if (bytesRead > 0) {
                dst.flip();
                final ByteChunk chunk = new ByteChunk(bytesRead);
                final byte[] buf = new byte[bytesRead];
                dst.get(buf);
                chunk.setBytes(buf, 0, bytesRead);
                dst.compact();
                try {
                    response.doWrite(chunk);
                } catch (ClassCastException e) {
                    System.err.println("gone bad: " + e.getMessage());
                    e.printStackTrace(System.err);
                }
                response.flush();
                System.out.println(conn + " [proxy<-origin] " + bytesRead + " bytes read");
                System.out.println(conn + " [proxy<-origin] " + decoder);
            }
            if (!dst.hasRemaining()) {
                // Output buffer is full. Suspend origin input until
                // the client handler frees up some space in the buffer
                conn.suspendInput();
            }
            /*
                    // If there is some content in the buffer make sure client output
                    // is active
                    if (dst.position() > 0) {
                      proxyTask.getClientIOControl().requestOutput();
                    }
            */

            if (decoder.isCompleted()) {
                System.out.println(conn + " [proxy<-origin] response body received");
                proxyTask.setOriginState(ConnState.RESPONSE_BODY_DONE);
                if (!this.connStrategy.keepAlive(conn.getHttpResponse(), context)) {
                    System.out.println(conn + " [proxy<-origin] close connection");
                    proxyTask.setOriginState(ConnState.CLOSING);
                    conn.close();
                }
                proxyTask.getCompletion().run();
            } else {
                proxyTask.setOriginState(ConnState.RESPONSE_BODY_STREAM);
            }

        } catch (IOException ex) {
            shutdownConnection(conn);
        }
    }
}

From source file:com.l2jfree.loginserver.L2LoginIdentifier.java

private synchronized void load() {
    if (isLoaded())
        return;//from  w  ww .  j  a  v a 2s.  co m

    File f = new File(System.getProperty("user.home", null), FILENAME);
    ByteBuffer bb = ByteBuffer.allocateDirect(8);

    if (!f.exists() || f.length() != 8) {
        _uid = getRandomUID();
        _loaded = true;
        _log.info("A new UID has been generated for this login server.");

        FileOutputStream fos = null;
        try {
            f.createNewFile();
            fos = new FileOutputStream(f);
            FileChannel fc = fos.getChannel();
            bb.putLong(getUID());
            bb.flip();
            fc.write(bb);
            fos.flush();
        } catch (IOException e) {
            _log.warn("Could not store login server's UID!", e);
        } finally {
            IOUtils.closeQuietly(fos);
            f.setReadOnly();
        }
    } else {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(f);
            FileChannel fc = fis.getChannel();
            fc.read(bb);
        } catch (IOException e) {
            _log.warn("Could not read stored login server's UID!", e);
        } finally {
            IOUtils.closeQuietly(fis);
        }

        if (bb.position() > 0) {
            bb.flip();
            _uid = bb.getLong();
        } else
            _uid = getRandomUID();
        _loaded = true;
    }
}

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

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

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

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

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

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

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

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

From source file:com.unister.semweb.drums.file.EnlargeFileTest.java

/**
 * Writes the given test data to the test file. The <code>globalParameters</code> are used to control the increment
 * and the initial file size.//from ww  w . j av  a  2 s  . c  o  m
 */
private List<Long> writeData(List<TestStorable> toWrite, DRUMSParameterSet<TestStorable> globalParameters)
        throws Exception {
    HeaderIndexFile<TestStorable> file = new HeaderIndexFile<TestStorable>(testFilename, AccessMode.READ_WRITE,
            1, globalParameters);
    List<Long> filePositions = new ArrayList<Long>();
    ByteBuffer overallBuffer = ByteBuffer.allocate(globalParameters.getPrototype().getSize() * toWrite.size());
    long currentFilePosition = file.getFilledUpFromContentStart();
    for (TestStorable currentTestObject : toWrite) {
        ByteBuffer buffer = currentTestObject.toByteBuffer();
        overallBuffer.put(buffer);
        filePositions.add(currentFilePosition);
        currentFilePosition += globalParameters.getPrototype().getSize();
    }
    overallBuffer.flip();
    file.append(overallBuffer);
    file.close();
    return filePositions;
}

From source file:de.tum.in.socket.client.SocketClient.java

/**
 * Process the receiving of data from server
 *//*  w  w  w  .jav a2  s.  c o  m*/
private void doProcess(final KuraResponsePayload respPayload) throws KuraException {
    this.m_activityLogService.saveLog("Socket Communication Started");

    String message = null;
    try {
        if (isNull(this.channel)) {
            this.channel = SocketChannel.open();
        }

        // we open this channel in non blocking mode
        if (!isNull(this.channel) && this.channel.isOpen() && !this.channel.isConnected()) {
            this.channel.configureBlocking(false);
            this.channel.connect(new InetSocketAddress(this.m_socketIPAddress, this.m_socketPort));
        }

        while (!this.channel.finishConnect()) {
            // No need to log. Still connecting to server.
        }
        while (!Thread.currentThread().isInterrupted()) {
            final ByteBuffer bufferA = ByteBuffer.allocate(500);
            message = "";
            while ((this.channel.read(bufferA)) > 0) {
                bufferA.flip();
                message += Charset.defaultCharset().decode(bufferA);
            }
            if (message.length() > 0) {
                LOGGER.info("Message Received: " + message);
            }
            if (!Strings.isNullOrEmpty(message)) {
                this.doPublish(respPayload, message);
            }
        }
    } catch (final Exception e) {
        LOGGER.error(Throwables.getStackTraceAsString(e));
    }
}

From source file:com.rs.worldserver.io.IOClient.java

private void directFlushOutStream() throws java.io.IOException {
    ByteBuffer buf = ByteBuffer.allocate(outStream.currentOffset);
    buf.put(outStream.buffer, 0, outStream.currentOffset);
    buf.flip();
    Server.getIoThread().writeReq(Server.getIoThread().socketFor(this), buf);
    try {/*from  w ww. j  a va2  s .  com*/
    } catch (Exception e) {
        e.printStackTrace();
    }
    outStream.currentOffset = 0; // reset
}

From source file:com.healthmarketscience.jackcess.PageChannel.java

/**
 * @param buffer Buffer to read the page into
 * @param pageNumber Number of the page to read in (starting at 0)
 *//* w  w  w  .  j a v a2  s  .c  o  m*/
public void readPage(ByteBuffer buffer, int pageNumber) throws IOException {
    validatePageNumber(pageNumber);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Reading in page " + Integer.toHexString(pageNumber));
    }
    buffer.clear();
    int bytesRead = _channel.read(buffer, (long) pageNumber * (long) getFormat().PAGE_SIZE);
    buffer.flip();
    if (bytesRead != getFormat().PAGE_SIZE) {
        throw new IOException("Failed attempting to read " + getFormat().PAGE_SIZE + " bytes from page "
                + pageNumber + ", only read " + bytesRead);
    }

    if (pageNumber == 0) {
        // de-mask header (note, page 0 never has additional encoding)
        applyHeaderMask(buffer);
    } else {
        _codecHandler.decodePage(buffer, pageNumber);
    }
}

From source file:gridool.memcached.gateway.MemcachedProxyHandler.java

@Override
public short handleSet(byte[] key, byte[] value, int flags, int expiry) {
    final ByteBuffer reqPacket = ByteBuffer
            .allocate(HEADER_LENGTH + SET_EXTRA_LENGTH + key.length + value.length);
    // request header
    Header header = new Header(MAGIC_BYTE_REQUEST, OPCODE_SET);
    header.setBodyLength(SET_EXTRA_LENGTH, key.length, value.length);
    header.encode(reqPacket);/*from  w  w w. ja  v  a 2 s .  c o m*/
    // request body (flags, expiration, key, value)
    reqPacket.putInt(flags);
    reqPacket.putInt(expiry);
    reqPacket.put(key);
    reqPacket.put(value);
    reqPacket.flip();

    final ByteBuffer resPacket = ByteBuffer.allocate(HEADER_LENGTH);
    final SocketAddress sockAddr = getSocket(key);
    final ByteChannel channel = sockPool.borrowObject(sockAddr);
    try {
        NIOUtils.writeFully(channel, reqPacket);
        NIOUtils.readFully(channel, resPacket);
    } catch (IOException e) {
        LOG.error(e);
        return ResponseStatus.UNKNOWN.status;
    } finally {
        sockPool.returnObject(sockAddr, channel);
    }
    resPacket.flip();
    short status = resPacket.getShort(6);
    return status;
}

From source file:org.alfresco.contentstore.ContentStoreTest.java

private void assertFileEquals(byte[] bytes, String contentPath) throws IOException {
    File file = new File(contentPath);
    if (!file.exists()) {
        fail();//from  w w w .j  av  a2  s .c  o  m
    }

    try (FileInputStream fis = new FileInputStream(file); FileChannel channel = fis.getChannel()) {
        ByteBuffer bb = ByteBuffer.allocate(1024);
        channel.read(bb);
        bb.flip();
        assertEquals(0, bb.compareTo(ByteBuffer.wrap(bytes)));
    }
}