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

public static void main(String[] args) {
    /*System.out.println("[DEBUG] Packet Header size = " + getHeaderSize());
            //ww w.  jav  a2 s .  c o  m
    SlaveState slaveState = new SlaveState();
    slaveState.setId(1L);
    slaveState.setIsMasterCandidate(false);
    Command command = CommandFactory.createHeartbeatCommand(slaveState.toByteBuffer());
    Packet packet = Packet.newDataPacket(command);
    ByteBuffer buffer = packet.marshall();
    Packet p = Packet.unmarshall(buffer);
    Command cmd = Command.unmarshall(p.getPayLoad());
    SlaveState ss = SlaveState.fromByteBuffer(cmd.getPayLoad());
    System.out.println(cmd.toString());
            
            
    // Test 2
    MasterState masterState = new MasterState();
    masterState.setId(1L);
    masterState.setIp("127.0.0.1");
    masterState.setPort(8206);
    List<SessionState> sessionStateList = new LinkedList<SessionState>();
    masterState.setSessionStateList(sessionStateList);
    SessionState sessionState = null;
    for(int i = 0; i < 10; i++) {
       sessionState = new SessionState();
       sessionState.setIp("127.0.0.1");
       sessionState.setPriority(1L);
       sessionState.setIsMasterCandidate(false);
       sessionStateList.add(sessionState);
    }
    Command command2 = CommandFactory.createHeartbeatCommand(masterState.toByteBuffer());
    Packet packet2 = Packet.newDataPacket(command2);
    ByteBuffer buffer2 = packet2.marshall();
    Packet p2 = Packet.unmarshall(buffer2);
    Command cmd2 = Command.unmarshall(p2.getPayLoad());
    MasterState ms = MasterState.fromByteBuffer(cmd2.getPayLoad());
    System.out.println(cmd.toString());
    */

    System.out.println("[DEBUG] Packet Header size = " + getHeaderSize());

    BlockingQueue<ByteBuffer> queue = new LinkedBlockingQueue<ByteBuffer>();
    Random rand = new Random();
    int count = 0;
    int size = 0;
    for (int i = 0; i < 100000; i++) {
        SlaveState state = new SlaveState();
        state.setId(Long.valueOf(i));
        state.setIsMasterCandidate(true);
        Packet packet = Packet.newDataPacket(
                CommandFactory.createCommand(Command.AVAILABLE_COMMAND_START, state.toByteBuffer()));
        ByteBuffer buffer = packet.marshall();
        rand.setSeed(System.currentTimeMillis());
        count = rand.nextInt(100) + 1;
        size = buffer.remaining() / count;
        for (int j = 0; j < count; j++) {
            ByteBuffer buf = null;
            if (j == count - 1) {
                buf = ByteBuffer.allocate(buffer.remaining() - j * size);
                buf.put(buffer.array(), j * size, buffer.remaining() - j * size);
            } else {
                buf = ByteBuffer.allocate(size);
                buf.put(buffer.array(), j * size, size);
            }
            buf.flip();
            queue.add(buf);
        }
    }

    for (int i = 0; i < 100000; i++) {
        //Packet packet = Packet.parse(queue);
        //Command commad = Command.unmarshall(packet.getPayLoad());
        //SlaveState state = SlaveState.fromByteBuffer(commad.getPayLoad());
        //System.out.println(state.toString());
    }
}

From source file:Test.java

public static void main(String[] args) throws IOException {
    Path path = Paths.get("/users.txt");

    try (SeekableByteChannel sbc = Files.newByteChannel(path)) {
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        sbc.position(4);//ww w.j a v a 2  s  . co m
        sbc.read(buffer);
        for (int i = 0; i < 5; i++) {
            System.out.print((char) buffer.get(i));
        }

        buffer.clear();
        sbc.position(0);
        sbc.read(buffer);
        for (int i = 0; i < 4; i++) {
            System.out.print((char) buffer.get(i));
        }
        sbc.position(0);
        buffer = ByteBuffer.allocate(1024);
        String encoding = System.getProperty("file.encoding");
        int numberOfBytesRead = sbc.read(buffer);
        System.out.println("Number of bytes read: " + numberOfBytesRead);
        while (numberOfBytesRead > 0) {
            buffer.rewind();
            System.out.print("[" + Charset.forName(encoding).decode(buffer) + "]");
            buffer.flip();
            numberOfBytesRead = sbc.read(buffer);
            System.out.println("\nNumber of bytes read: " + numberOfBytesRead);
        }

    }

}

From source file:org.apache.hadoop.hdfs.hoss.db.FileStreamStore.java

public static void main(String[] args) {
    final int BUFFER_LEN = 4096;//65536
    final int TOTAL = 10000000;
    FileStreamStore fss = new FileStreamStore("./data/stream", BUFFER_LEN);
    final ByteBuffer buf = ByteBuffer.allocate(BUFFER_LEN);
    final long[] offset = new long[TOTAL];

    fss.delete();// w  w w  .  j  a va  2  s.  c om
    fss.open();
    // Parameters
    fss.setFlushOnWrite(false);
    fss.setSyncOnFlush(false);
    fss.setAlignBlocks(true);
    long start = System.currentTimeMillis();
    for (int i = 0; i < TOTAL; i++) {
        buf.clear();
        StringSerializer.fromStringToBuffer(buf, "hehe" + i);
        buf.flip();
        offset[i] = fss.write(buf);
    }
    fss.sync();
    //System.out.println(ArrayUtils.toString(offset));
    System.out.println("write time: " + (System.currentTimeMillis() - start) / 1000);
    start = System.currentTimeMillis();
    long newOffset = 0;
    for (int i = 0; i < TOTAL; i++) {
        buf.clear();
        newOffset = fss.read(newOffset, buf);
        if (newOffset < 0) {
            System.out.println("Error trying read offset " + i + " size=" + fss.size());
            break;
        }
        StringSerializer.fromBufferToString(buf);
        //System.out.print(hehe + "\t");
    }
    System.out.println("read time: " + (System.currentTimeMillis() - start) / 1000);
}

From source file:Lock.java

public static void main(String args[]) throws IOException, InterruptedException {
    RandomAccessFile file = null; // The file we'll lock
    FileChannel f = null; // The channel to the file
    FileLock lock = null; // The lock object we hold

    try { // The finally clause closes the channel and releases the lock
        // We use a temporary file as the lock file.
        String tmpdir = System.getProperty("java.io.tmpdir");
        String filename = Lock.class.getName() + ".lock";
        File lockfile = new File(tmpdir, filename);

        // Create a FileChannel that can read and write that file.
        // Note that we rely on the java.io package to open the file,
        // in read/write mode, and then just get a channel from it.
        // This will create the file if it doesn't exit. We'll arrange
        // for it to be deleted below, if we succeed in locking it.
        file = new RandomAccessFile(lockfile, "rw");
        f = file.getChannel();//from  w w  w . j a va2  s. co  m

        // Try to get an exclusive lock on the file.
        // This method will return a lock or null, but will not block.
        // See also FileChannel.lock() for a blocking variant.
        lock = f.tryLock();

        if (lock != null) {
            // We obtained the lock, so arrange to delete the file when
            // we're done, and then write the approximate time at which
            // we'll relinquish the lock into the file.
            lockfile.deleteOnExit(); // Just a temporary file

            // First, we need a buffer to hold the timestamp
            ByteBuffer bytes = ByteBuffer.allocate(8); // a long is 8 bytes

            // Put the time in the buffer and flip to prepare for writing
            // Note that many Buffer methods can be "chained" like this.
            bytes.putLong(System.currentTimeMillis() + 10000).flip();

            f.write(bytes); // Write the buffer contents to the channel
            f.force(false); // Force them out to the disk
        } else {
            // We didn't get the lock, which means another instance is
            // running. First, let the user know this.
            System.out.println("Another instance is already running");

            // Next, we attempt to read the file to figure out how much
            // longer the other instance will be running. Since we don't
            // have a lock, the read may fail or return inconsistent data.
            try {
                ByteBuffer bytes = ByteBuffer.allocate(8);
                f.read(bytes); // Read 8 bytes from the file
                bytes.flip(); // Flip buffer before extracting bytes
                long exittime = bytes.getLong(); // Read bytes as a long
                // Figure out how long that time is from now and round
                // it to the nearest second.
                long secs = (exittime - System.currentTimeMillis() + 500) / 1000;
                // And tell the user about it.
                System.out.println("Try again in about " + secs + " seconds");
            } catch (IOException e) {
                // This probably means that locking is enforced by the OS
                // and we were prevented from reading the file.
            }

            // This is an abnormal exit, so set an exit code.
            System.exit(1);
        }

        // Simulate a real application by sleeping for 10 seconds.
        System.out.println("Starting...");
        Thread.sleep(10000);
        System.out.println("Exiting.");
    } finally {
        // Always release the lock and close the file
        // Closing the RandomAccessFile also closes its FileChannel.
        if (lock != null && lock.isValid())
            lock.release();
        if (file != null)
            file.close();
    }
}

From source file:MainClass.java

public static void main(String[] args) throws IOException {
    Charset charset = Charset.forName("ISO-8859-1");
    CharsetEncoder encoder = charset.newEncoder();
    CharsetDecoder decoder = charset.newDecoder();

    ByteBuffer buffer = ByteBuffer.allocate(512);

    Selector selector = Selector.open();

    ServerSocketChannel server = ServerSocketChannel.open();
    server.socket().bind(new java.net.InetSocketAddress(8000));
    server.configureBlocking(false);//from w  w  w.  j  a v a  2 s  .com
    SelectionKey serverkey = server.register(selector, SelectionKey.OP_ACCEPT);

    for (;;) {
        selector.select();
        Set keys = selector.selectedKeys();

        for (Iterator i = keys.iterator(); i.hasNext();) {
            SelectionKey key = (SelectionKey) i.next();
            i.remove();

            if (key == serverkey) {
                if (key.isAcceptable()) {
                    SocketChannel client = server.accept();
                    client.configureBlocking(false);
                    SelectionKey clientkey = client.register(selector, SelectionKey.OP_READ);
                    clientkey.attach(new Integer(0));
                }
            } else {
                SocketChannel client = (SocketChannel) key.channel();
                if (!key.isReadable())
                    continue;
                int bytesread = client.read(buffer);
                if (bytesread == -1) {
                    key.cancel();
                    client.close();
                    continue;
                }
                buffer.flip();
                String request = decoder.decode(buffer).toString();
                buffer.clear();
                if (request.trim().equals("quit")) {
                    client.write(encoder.encode(CharBuffer.wrap("Bye.")));
                    key.cancel();
                    client.close();
                } else {
                    int num = ((Integer) key.attachment()).intValue();
                    String response = num + ": " + request.toUpperCase();
                    client.write(encoder.encode(CharBuffer.wrap(response)));
                    key.attach(new Integer(num + 1));
                }
            }
        }
    }
}

From source file:GetWebPageApp.java

public static void main(String args[]) throws Exception {
    String resource, host, file;/*  w  ww .j  a  va2s. c o m*/
    int slashPos;

    resource = "www.java2s.com/index.htm"; // skip HTTP://
    slashPos = resource.indexOf('/'); // find host/file separator
    if (slashPos < 0) {
        resource = resource + "/";
        slashPos = resource.indexOf('/');
    }
    file = resource.substring(slashPos); // isolate host and file parts
    host = resource.substring(0, slashPos);
    System.out.println("Host to contact: '" + host + "'");
    System.out.println("File to fetch : '" + file + "'");

    SocketChannel channel = null;

    try {
        Charset charset = Charset.forName("ISO-8859-1");
        CharsetDecoder decoder = charset.newDecoder();
        CharsetEncoder encoder = charset.newEncoder();

        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        CharBuffer charBuffer = CharBuffer.allocate(1024);

        InetSocketAddress socketAddress = new InetSocketAddress(host, 80);
        channel = SocketChannel.open();
        channel.configureBlocking(false);
        channel.connect(socketAddress);

        selector = Selector.open();

        channel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ);

        while (selector.select(500) > 0) {
            Set readyKeys = selector.selectedKeys();
            try {
                Iterator readyItor = readyKeys.iterator();

                while (readyItor.hasNext()) {

                    SelectionKey key = (SelectionKey) readyItor.next();
                    readyItor.remove();
                    SocketChannel keyChannel = (SocketChannel) key.channel();

                    if (key.isConnectable()) {
                        if (keyChannel.isConnectionPending()) {
                            keyChannel.finishConnect();
                        }
                        String request = "GET " + file + " \r\n\r\n";
                        keyChannel.write(encoder.encode(CharBuffer.wrap(request)));
                    } else if (key.isReadable()) {
                        keyChannel.read(buffer);
                        buffer.flip();

                        decoder.decode(buffer, charBuffer, false);
                        charBuffer.flip();
                        System.out.print(charBuffer);

                        buffer.clear();
                        charBuffer.clear();

                    } else {
                        System.err.println("Unknown key");
                    }
                }
            } catch (ConcurrentModificationException e) {
            }
        }
    } catch (UnknownHostException e) {
        System.err.println(e);
    } catch (IOException e) {
        System.err.println(e);
    } finally {
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException ignored) {
            }
        }
    }
    System.out.println("\nDone.");
}

From source file:edu.hawaii.soest.kilonalu.dvp2.DavisWxParser.java

public static void main(String[] args) {

    // Ensure we have a path to the binary file
    if (args.length != 1) {
        logger.info("Please provide the path to a file containing a binary LOOP packet.");
        System.exit(1);/*from w  w w  . j av a2 s .  co m*/
    } else {
        try {
            // open and read the file
            File packetFile = new File(args[0]);
            FileInputStream fis = new FileInputStream(packetFile);
            FileChannel fileChannel = fis.getChannel();
            ByteBuffer inBuffer = ByteBuffer.allocateDirect(8192);
            ByteBuffer packetBuffer = ByteBuffer.allocateDirect(8192);

            while (fileChannel.read(inBuffer) != -1 || inBuffer.position() > 0) {
                inBuffer.flip();
                packetBuffer.put(inBuffer.get());
                inBuffer.compact();
            }
            fileChannel.close();
            fis.close();
            packetBuffer.put(inBuffer.get());

            // create an instance of the parser, and report the field contents after parsing
            DavisWxParser davisWxParser = new DavisWxParser(packetBuffer);

            // Set up a simple logger that logs to the console
            PropertyConfigurator.configure(davisWxParser.getLogConfigurationFile());

            logger.info("loopID:                         " + davisWxParser.getLoopID());
            logger.info("barTrend:                       " + davisWxParser.getBarTrend());
            logger.info("barTrendAsString:               " + davisWxParser.getBarTrendAsString());
            logger.info("packetType:                     " + davisWxParser.getPacketType());
            logger.info("nextRecord:                     " + davisWxParser.getNextRecord());
            logger.info("barometer:                      " + davisWxParser.getBarometer());
            logger.info("insideTemperature:              " + davisWxParser.getInsideTemperature());
            logger.info("insideHumidity:                 " + davisWxParser.getInsideHumidity());
            logger.info("outsideTemperature:             " + davisWxParser.getOutsideTemperature());
            logger.info("windSpeed:                      " + davisWxParser.getWindSpeed());
            logger.info("tenMinuteAverageWindSpeed:      " + davisWxParser.getTenMinuteAverageWindSpeed());
            logger.info("windDirection:                  " + davisWxParser.getWindDirection());
            logger.info(
                    "extraTemperatures:              " + Arrays.toString(davisWxParser.getExtraTemperatures()));
            logger.info(
                    "soilTemperatures:               " + Arrays.toString(davisWxParser.getSoilTemperatures()));
            logger.info(
                    "leafTemperatures:               " + Arrays.toString(davisWxParser.getLeafTemperatures()));
            logger.info("outsideHumidity:                " + davisWxParser.getOutsideHumidity());
            logger.info(
                    "extraHumidities:                " + Arrays.toString(davisWxParser.getExtraHumidities()));
            logger.info("rainRate:                       " + davisWxParser.getRainRate());
            logger.info("uvRadiation:                    " + davisWxParser.getUvRadiation());
            logger.info("solarRadiation:                 " + davisWxParser.getSolarRadiation());
            logger.info("stormRain:                      " + davisWxParser.getStormRain());
            logger.info("currentStormStartDate:          " + davisWxParser.getCurrentStormStartDate());
            logger.info("dailyRain:                      " + davisWxParser.getDailyRain());
            logger.info("monthlyRain:                    " + davisWxParser.getMonthlyRain());
            logger.info("yearlyRain:                     " + davisWxParser.getYearlyRain());
            logger.info("dailyEvapoTranspiration:        " + davisWxParser.getDailyEvapoTranspiration());
            logger.info("monthlyEvapoTranspiration:      " + davisWxParser.getMonthlyEvapoTranspiration());
            logger.info("yearlyEvapoTranspiration:       " + davisWxParser.getYearlyEvapoTranspiration());
            logger.info("soilMoistures:                  " + Arrays.toString(davisWxParser.getSoilMoistures()));
            logger.info("leafWetnesses:                  " + Arrays.toString(davisWxParser.getLeafWetnesses()));
            logger.info("insideAlarm:                    " + davisWxParser.getInsideAlarm());
            logger.info("rainAlarm:                      " + davisWxParser.getRainAlarm());
            logger.info("outsideAlarms:                  " + davisWxParser.getOutsideAlarms());
            logger.info("extraTemperatureHumidityAlarms: " + davisWxParser.getExtraTemperatureHumidityAlarms());
            logger.info("soilLeafAlarms:                 " + davisWxParser.getSoilLeafAlarms());
            logger.info("transmitterBatteryStatus:       " + davisWxParser.getTransmitterBatteryStatus());
            logger.info("consoleBatteryVoltage:          " + davisWxParser.getConsoleBatteryVoltage());
            logger.info("forecastIconValues:             " + davisWxParser.getForecastAsString());
            logger.info("forecastRuleNumber:             " + davisWxParser.getForecastRuleNumberAsString());
            logger.info("timeOfSunrise:                  " + davisWxParser.getTimeOfSunrise());
            logger.info("timeOfSunset:                   " + davisWxParser.getTimeOfSunset());
            logger.info("recordDelimiter:                " + davisWxParser.getRecordDelimiterAsHexString());
            logger.info("crcChecksum:                    " + davisWxParser.getCrcChecksum());

        } catch (java.io.FileNotFoundException fnfe) {
            fnfe.printStackTrace();

        } catch (java.io.IOException ioe) {
            ioe.printStackTrace();

        }

    }
}

From source file:PrintServiceWebInterface.java

public static void main(String[] args) throws IOException {
    // Get the character encoders and decoders we'll need
    Charset charset = Charset.forName("ISO-8859-1");
    CharsetEncoder encoder = charset.newEncoder();

    // The HTTP headers we send back to the client are fixed
    String headers = "HTTP/1.1 200 OK\r\n" + "Content-type: text/html\r\n" + "Connection: close\r\n" + "\r\n";

    // We'll use two buffers in our response. One holds the fixed
    // headers, and the other holds the variable body of the response.
    ByteBuffer[] buffers = new ByteBuffer[2];
    buffers[0] = encoder.encode(CharBuffer.wrap(headers));
    ByteBuffer body = ByteBuffer.allocateDirect(16 * 1024);
    buffers[1] = body;//from ww  w.j  ava2s  .  c o m

    // Find all available PrintService objects to describe
    PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);

    // All of the channels we use in this code will be in non-blocking
    // mode. So we create a Selector object that will block while
    // monitoring all of the channels and will only stop blocking when
    // one or more of the channels is ready for I/O of some sort.
    Selector selector = Selector.open();

    // Create a new ServerSocketChannel, and bind it to port 8000.
    // Note that we have to do this using the underlying ServerSocket.
    ServerSocketChannel server = ServerSocketChannel.open();
    server.socket().bind(new java.net.InetSocketAddress(8000));

    // Put the ServerSocketChannel into non-blocking mode
    server.configureBlocking(false);

    // Now register the channel with the Selector. The SelectionKey
    // represents the registration of this channel with this Selector.
    SelectionKey serverkey = server.register(selector, SelectionKey.OP_ACCEPT);

    for (;;) { // The main server loop. The server runs forever.
        // This call blocks until there is activity on one of the
        // registered channels. This is the key method in non-blocking I/O.
        selector.select();

        // Get a java.util.Set containing the SelectionKey objects for
        // all channels that are ready for I/O.
        Set keys = selector.selectedKeys();

        // Use a java.util.Iterator to loop through the selected keys
        for (Iterator i = keys.iterator(); i.hasNext();) {
            // Get the next SelectionKey in the set, and then remove it
            // from the set. It must be removed explicitly, or it will
            // be returned again by the next call to select().
            SelectionKey key = (SelectionKey) i.next();
            i.remove();

            // Check whether this key is the SelectionKey we got when
            // we registered the ServerSocketChannel.
            if (key == serverkey) {
                // Activity on the ServerSocketChannel means a client
                // is trying to connect to the server.
                if (key.isAcceptable()) {
                    // Accept the client connection, and obtain a
                    // SocketChannel to communicate with the client.
                    SocketChannel client = server.accept();

                    // Make sure we actually got a connection
                    if (client == null)
                        continue;

                    // Put the client channel in non-blocking mode.
                    client.configureBlocking(false);

                    // Now register the client channel with the Selector,
                    // specifying that we'd like to know when there is
                    // data ready to read on the channel.
                    SelectionKey clientkey = client.register(selector, SelectionKey.OP_READ);
                }
            } else {
                // If the key we got from the Set of keys is not the
                // ServerSocketChannel key, then it must be a key
                // representing one of the client connections.
                // Get the channel from the key.
                SocketChannel client = (SocketChannel) key.channel();

                // If we got here, it should mean that there is data to
                // be read from the channel, but we double-check here.
                if (!key.isReadable())
                    continue;

                // Now read bytes from the client. We assume that
                // we get all the client's bytes in one read operation
                client.read(body);

                // The data we read should be some kind of HTTP GET
                // request. We don't bother checking it however since
                // there is only one page of data we know how to return.
                body.clear();

                // Build an HTML document as our reponse.
                // The body of the document contains PrintService details
                StringBuffer response = new StringBuffer();
                response.append(
                        "<html><head><title>Printer Status</title></head>" + "<body><h1>Printer Status</h1>");
                for (int s = 0; s < services.length; s++) {
                    PrintService service = services[s];
                    response.append("<h2>").append(service.getName()).append("</h2><table>");
                    Attribute[] attrs = service.getAttributes().toArray();
                    for (int a = 0; a < attrs.length; a++) {
                        Attribute attr = attrs[a];
                        response.append("<tr><td>").append(attr.getName()).append("</td><td>").append(attr)
                                .append("</tr>");
                    }
                    response.append("</table>");
                }
                response.append("</body></html>\r\n");

                // Encode the response into the body ByteBuffer
                encoder.reset();
                encoder.encode(CharBuffer.wrap(response), body, true);
                encoder.flush(body);

                body.flip(); // Prepare the body buffer to be drained
                // While there are bytes left to write
                while (body.hasRemaining()) {
                    // Write both header and body buffers
                    client.write(buffers);
                }
                buffers[0].flip(); // Prepare header buffer for next write
                body.clear(); // Prepare body buffer for next read

                // Once we've sent our response, we have no more interest
                // in the client channel or its SelectionKey
                client.close(); // Close the channel.
                key.cancel(); // Tell Selector to stop monitoring it.
            }
        }
    }
}

From source file:Main.java

public static String convert(final ByteBuffer src) {
    src.flip();
    final StringBuilder buffer = new StringBuilder(src.remaining());
    while (src.hasRemaining()) {
        buffer.append((char) (src.get() & 0xff));
    }//w ww. j  av a2  s  . com
    return buffer.toString();
}

From source file:Main.java

private static byte[] getByteArrayFromBuffer(ByteBuffer byteBuf) {
    byteBuf.flip();
    byte[] row = new byte[byteBuf.limit()];
    byteBuf.get(row);//from  w  w  w  . java2s.  c o  m
    byteBuf.clear();
    return row;
}