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.saasovation.common.port.adapter.messaging.slothmq.SlothWorker.java

protected String receive() {
    SocketChannel socketChannel = null;

    try {/*from   w w w  .ja  va  2 s.co  m*/
        socketChannel = this.socket.accept();

        if (socketChannel == null) {
            return null; // if non-blocking
        }

        ReadableByteChannel readByteChannel = Channels.newChannel(socketChannel.socket().getInputStream());

        ByteArrayOutputStream byteArray = new ByteArrayOutputStream();

        ByteBuffer readBuffer = ByteBuffer.allocate(8);

        while (readByteChannel.read(readBuffer) != -1) {
            readBuffer.flip();

            while (readBuffer.hasRemaining()) {
                byteArray.write(readBuffer.get());
            }

            readBuffer.clear();
        }

        return new String(byteArray.toByteArray());

    } catch (IOException e) {
        logger.error("Failed to receive because: {}: Continuing...", e.getMessage(), e);
        return null;

    } finally {
        if (socketChannel != null) {
            try {
                socketChannel.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

From source file:ch.cyberduck.core.cryptomator.CryptoInputStream.java

private int readNextChunk() throws IOException {
    final ByteBuffer ciphertextBuf = ByteBuffer.allocate(chunkSize);
    final int read = IOUtils.read(proxy, ciphertextBuf.array());
    if (read == 0) {
        return IOUtils.EOF;
    }//from  ww w. j  a  v a  2 s .  c o  m
    ciphertextBuf.position(read);
    ciphertextBuf.flip();
    try {
        buffer = cryptor.fileContentCryptor().decryptChunk(ciphertextBuf, chunkIndexOffset++, header, true);
    } catch (CryptoException e) {
        throw new IOException(e.getMessage(), new CryptoAuthenticationException(e.getMessage(), e));
    }
    return read;
}

From source file:org.apache.jackrabbit.oak.plugins.document.persistentCache.BroadcastTest.java

private static void listen() throws InterruptedException {
    String config = "key 123";

    ConsoleAppender<ILoggingEvent> ca = new ConsoleAppender<ILoggingEvent>();
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    ca.setContext(lc);/* www.  j  a v a  2  s.co m*/
    PatternLayout pl = new PatternLayout();
    pl.setPattern("%msg%n");
    pl.setContext(lc);
    pl.start();
    ca.setLayout(pl);
    ca.start();

    ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory
            .getLogger(TCPBroadcaster.class);
    logger.addAppender(ca);
    logger.setLevel(Level.DEBUG);

    TCPBroadcaster receiver = new TCPBroadcaster(config);
    receiver.addListener(new Broadcaster.Listener() {

        @Override
        public void receive(ByteBuffer buff) {
            int end = buff.position();
            StringBuilder sb = new StringBuilder();
            while (buff.remaining() > 0) {
                char c = (char) buff.get();
                if (c >= ' ' && c < 128) {
                    sb.append(c);
                } else if (c <= 9) {
                    sb.append((char) ('0' + c));
                } else {
                    sb.append('.');
                }
            }
            String dateTime = new Timestamp(System.currentTimeMillis()).toString().substring(0, 19);
            System.out.println(dateTime + " Received " + sb);
            buff.position(end);
        }

    });
    Random r = new Random();
    int x = r.nextInt();
    System.out.println("Sending " + x);
    for (int i = 0; i < 10; i++) {
        Thread.sleep(10);
        ByteBuffer buff = ByteBuffer.allocate(1024);
        buff.putInt(0);
        buff.putInt(x);
        buff.put(new byte[100]);
        buff.flip();
        receiver.send(buff);
        if (!receiver.isRunning()) {
            System.out.println("Did not start or already stopped");
            break;
        }
    }
    Thread.sleep(Integer.MAX_VALUE);
}

From source file:net.fenyo.mail4hotspot.service.HttpProxy.java

public void sendData(final byte data[]) throws IOException {
    // log.debug("sendData on id " + local_port);

    last_use = System.currentTimeMillis();

    //      log.debug("sendData(): " + data.length + " bytes");

    if (closed)/*  ww  w.  java 2 s.com*/
        return;

    try {
        final ByteBuffer bb = ByteBuffer.allocate(to_socket_array.length + data.length);
        bb.put(to_socket_array);
        bb.put(data);
        bb.flip();
        final int nbytes = socket_channel.write(bb);
        to_socket_array = ArrayUtils.subarray(bb.array(), nbytes, bb.array().length);

    } catch (final IOException ex) {
        log.warn(ex);
        ex.printStackTrace();

        socket_channel.close();
        closed = true;

        throw ex;
    }
}

From source file:org.apache.cassandra.io.compress.CompressedSequentialWriterTest.java

private void testWrite(File f, int bytesToTest) throws IOException {
    final String filename = f.getAbsolutePath();
    final ChannelProxy channel = new ChannelProxy(f);

    try {//from   w w  w.jav  a2 s  .  c  om
        MetadataCollector sstableMetadataCollector = new MetadataCollector(
                new SimpleDenseCellNameType(BytesType.instance)).replayPosition(null);
        byte[] dataPre = new byte[bytesToTest];
        byte[] rawPost = new byte[bytesToTest];
        try (CompressedSequentialWriter writer = new CompressedSequentialWriter(f, filename + ".metadata",
                new CompressionParameters(compressor), sstableMetadataCollector);) {
            Random r = new Random();

            // Test both write with byte[] and ByteBuffer
            r.nextBytes(dataPre);
            r.nextBytes(rawPost);
            ByteBuffer dataPost = makeBB(bytesToTest);
            dataPost.put(rawPost);
            dataPost.flip();

            writer.write(dataPre);
            FileMark mark = writer.mark();

            // Write enough garbage to transition chunk
            for (int i = 0; i < CompressionParameters.DEFAULT_CHUNK_LENGTH; i++) {
                writer.write((byte) i);
            }
            writer.resetAndTruncate(mark);
            writer.write(dataPost);
            writer.finish();
        }

        assert f.exists();
        RandomAccessReader reader = CompressedRandomAccessReader.open(channel,
                new CompressionMetadata(filename + ".metadata", f.length()));
        assertEquals(dataPre.length + rawPost.length, reader.length());
        byte[] result = new byte[(int) reader.length()];

        reader.readFully(result);

        assert (reader.isEOF());
        reader.close();

        byte[] fullInput = new byte[bytesToTest * 2];
        System.arraycopy(dataPre, 0, fullInput, 0, dataPre.length);
        System.arraycopy(rawPost, 0, fullInput, bytesToTest, rawPost.length);
        assert Arrays.equals(result, fullInput);
    } finally {
        // cleanup
        channel.close();

        if (f.exists())
            f.delete();
        File metadata = new File(f + ".metadata");
        if (metadata.exists())
            metadata.delete();
    }
}

From source file:gridool.communication.transport.tcp.GridNioServer.java

private static void handleRead(final SocketChannel channel, final SelectionKey key,
        final ByteBuffer sharedReadBuf, final GridTransportListener notifier, final ExecutorService exec) {
    sharedReadBuf.clear();/*from  w w  w  .  j av a  2 s. c  o  m*/
    final SocketAddress remoteAddr = channel.socket().getRemoteSocketAddress();
    final int bytesRead;
    try {
        bytesRead = channel.read(sharedReadBuf);
    } catch (IOException e) {
        LOG.warn("Failed to read data from client: " + remoteAddr, e);
        NIOUtils.close(key);
        return;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Read " + bytesRead + " bytes from a client socket: " + remoteAddr);
    }
    if (bytesRead == -1) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Remote client closed connection: " + remoteAddr);
        }
        NIOUtils.close(key);
        return;
    } else if (bytesRead == 0) {
        return;
    }

    final GridMessageBuffer msgBuf = (GridMessageBuffer) key.attachment();
    sharedReadBuf.flip();
    while (sharedReadBuf.remaining() > 0) {
        msgBuf.read(sharedReadBuf);
        if (msgBuf.isFilled()) {
            exec.execute(new Runnable() {
                public void run() {
                    final GridCommunicationMessage msg = msgBuf.toMessage();
                    msgBuf.reset();
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Recieved a GridCommunicationMessage [" + msg.getMessageId() + "]");
                    }
                    notifier.notifyListener(msg);
                }
            });
            break;
        }
    }
}

From source file:com.esri.geoevent.solutions.adapter.geomessage.DefenseOutboundAdapter.java

@SuppressWarnings("incomplete-switch")
@Override/*w  w  w  . j a  v a  2 s .  co  m*/
public synchronized void receive(GeoEvent geoEvent) {

    ByteBuffer byteBuffer = ByteBuffer.allocate(10 * 1024);
    Integer wkid = -1;
    String message = "";

    message += "<geomessage v=\"1.0\">\n\r";
    message += "<_type>";
    message += messageType;
    message += "</_type>\n\r";
    message += "<_action>";
    message += "update";
    message += "</_action>\n\r";
    String messageid = UUID.randomUUID().toString();
    message += "<_id>";
    message += "{" + messageid + "}";
    message += "</_id>\n\r";
    MapGeometry geom = geoEvent.getGeometry();
    if (geom.getGeometry().getType() == com.esri.core.geometry.Geometry.Type.Point) {
        Point p = (Point) geom.getGeometry();
        message += "<_control_points>";
        message += ((Double) p.getX()).toString();
        message += ",";
        message += ((Double) p.getY()).toString();
        message += "</_control_points>\n\r";
        wkid = ((Integer) geom.getSpatialReference().getID());
    }

    if (wkid > 0) {
        String wkidValue = wkid.toString();
        message += "<_wkid>";
        message += wkidValue.toString();
        message += "</_wkid>\n\r";
    }
    GeoEventDefinition definition = geoEvent.getGeoEventDefinition();
    for (FieldDefinition fieldDefinition : definition.getFieldDefinitions()) {

        String attributeName = fieldDefinition.getName();
        Object value = geoEvent.getField(attributeName);

        if (value == null || value.equals("null")) {
            continue;
        }
        FieldType t = fieldDefinition.getType();
        if (t != FieldType.Geometry) {
            message += "<" + attributeName + ">";

            switch (t) {
            case String:
                // if(((String)value).isEmpty())
                // continue;
                message += value;
                break;
            case Date:
                Date date = (Date) value;
                message += (formatter.format(date));
                break;
            case Double:
                Double doubleValue = (Double) value;
                message += doubleValue.toString();
                break;
            case Float:
                Float floatValue = (Float) value;
                message += floatValue.toString();
                break;

            case Integer:
                Integer intValue = (Integer) value;
                message += intValue.toString();
                break;
            case Long:
                Long longValue = (Long) value;
                message += longValue.toString();
                break;
            case Short:
                Short shortValue = (Short) value;
                message += shortValue.toString();
                break;
            case Boolean:
                Boolean booleanValue = (Boolean) value;
                message += booleanValue.toString();
                break;

            }
            message += "</" + attributeName + ">\n\r";
        } else {
            if (definition.getIndexOf(attributeName) == definition.getIndexOf("GEOMETRY")) {
                continue;
            } else {
                String json = GeometryEngine.geometryToJson(wkid, (Geometry) value);
                message += "<" + attributeName + ">";
                message += json;
                message += "</" + attributeName + ">\n\r";
            }
            break;
        }

    }
    message += "</geomessage>";
    // stringBuffer.append("</geomessages>");
    message += "\r\n";

    ByteBuffer buf = charset.encode(message);
    if (buf.position() > 0)
        buf.flip();

    try {
        byteBuffer.put(buf);
    } catch (BufferOverflowException ex) {
        LOG.error(
                "Csv Outbound Adapter does not have enough room in the buffer to hold the outgoing data.  Either the receiving transport object is too slow to process the data, or the data message is too big.");
    }
    byteBuffer.flip();
    super.receive(byteBuffer, geoEvent.getTrackId(), geoEvent);
    byteBuffer.clear();
}

From source file:cn.ac.ncic.mastiff.io.coding.RLEDecoder.java

@Override
public byte[] ensureDecompressed() throws IOException {
    FlexibleEncoding.ORC.DynamicByteArray dynamicBuffer = new FlexibleEncoding.ORC.DynamicByteArray();
    dynamicBuffer.add(inBuf.getData(), 12, inBuf.getLength() - 12);
    ByteBuffer byteBuf = ByteBuffer.allocate(dynamicBuffer.size());
    dynamicBuffer.setByteBuffer(byteBuf, 0, dynamicBuffer.size());
    byteBuf.flip();
    FlexibleEncoding.ORC.InStream instream = FlexibleEncoding.ORC.InStream.create("test", byteBuf, null,
            dynamicBuffer.size());// w  w w.  j  a va 2 s.co m
    RunLengthIntegerReader rlein = new RunLengthIntegerReader(instream, true);
    DataOutputBuffer decoding = new DataOutputBuffer();
    decoding.writeInt(decompressedSize);
    decoding.writeInt(numPairs);
    decoding.writeInt(startPos);
    for (int i = 1; i < numPairs; i++) {
        int tmp = (int) rlein.next();
        decoding.writeInt(tmp);
    }
    byteBuf.clear();
    inBuf.close();
    return decoding.getData();
}

From source file:org.alfresco.cacheserver.PatchServiceTest.java

private void assertFileEquals(String contentPath1, String contentPath2) throws IOException {
    File file1 = new File(contentPath1);
    if (!file1.exists()) {
        fail();//w w  w . ja v a  2 s. c o m
    }

    File file2 = new File(contentPath2);
    if (!file2.exists()) {
        fail();
    }

    try (FileInputStream fis1 = new FileInputStream(file1); FileChannel channel1 = fis1.getChannel();) {
        try (FileInputStream fis2 = new FileInputStream(file2); FileChannel channel2 = fis2.getChannel()) {
            ByteBuffer bb1 = ByteBuffer.allocate(1024);
            channel1.read(bb1);
            ByteBuffer bb2 = ByteBuffer.allocate(1024);
            channel2.read(bb2);
            bb1.flip();
            bb2.flip();
            assertEquals(0, bb1.compareTo(bb2));
        }
    }
}

From source file:com.github.srgg.yads.impl.context.communication.AbstractTransport.java

private ByteBuffer encode(final byte msgCode, final byte[] payload) throws Exception {
    final int length = payload.length + 1;
    final ByteBuffer b = ByteBuffer.allocateDirect(length + 4 /* sizeof(length header) */).putInt(length)
            .put(msgCode).put(payload);//  w  ww . j  a v a 2 s .  c  om

    assert b.remaining() == 0;
    b.flip();
    return b;
}