Example usage for java.nio ByteBuffer get

List of usage examples for java.nio ByteBuffer get

Introduction

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

Prototype

public abstract byte get(int index);

Source Link

Document

Returns the byte at the specified index and does not change the position.

Usage

From source file:edu.uci.ics.hyracks.dataflow.std.sort.util.DeletableFrameTupleAppenderTest.java

@Test
public void testReOrganizeBuffer() throws Exception {
    int count = 10;
    testDelete();/*from   w  w  w  .  j  a va2  s.com*/
    appender.reOrganizeBuffer();
    ByteBuffer bufferRead = makeAFrame(cap, count, 0);
    DeletableFrameTupleAppender accessor = new DeletableFrameTupleAppender(recordDescriptor);
    accessor.reset(bufferRead);
    for (int i = 0; i < accessor.getTupleCount(); i++) {
        appender.append(accessor, i);
    }
    for (int i = 0; i < bufferRead.capacity(); i++) {
        assertEquals(bufferRead.get(i), appender.getBuffer().get(i));
    }
}

From source file:pl.allegro.tech.hermes.consumers.consumer.sender.http.ByteBufferEntityTest.java

@Test
public void testWriteTo() throws Exception {
    final ByteBuffer bytes = ByteBuffer.wrap("Message content".getBytes(Consts.ASCII));
    final ByteBufferEntity httpentity = new ByteBufferEntity(bytes);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    httpentity.writeTo(out);//from   ww  w  .j a  va  2 s  .  c o m
    byte[] bytes2 = out.toByteArray();
    Assert.assertNotNull(bytes2);
    Assert.assertEquals(bytes.capacity(), bytes2.length);
    bytes.position(0);
    for (int i = 0; i < bytes2.length; i++) {
        Assert.assertEquals(bytes.get(i), bytes2[i]);
    }

    out = new ByteArrayOutputStream();
    httpentity.writeTo(out);
    bytes2 = out.toByteArray();
    Assert.assertNotNull(bytes2);
    Assert.assertEquals(bytes.capacity(), bytes2.length);
    bytes.position(0);
    for (int i = 0; i < bytes.capacity(); i++) {
        Assert.assertEquals(bytes.get(i), bytes2[i]);
    }

    try {
        httpentity.writeTo(null);
        Assert.fail("IllegalArgumentException should have been thrown");
    } catch (final IllegalArgumentException ex) {
        // expected
    }
}

From source file:com.yobidrive.diskmap.needles.Needle.java

public boolean getNeedleDataFromBuffer(ByteBuffer input) throws Exception {
    try {//from w  w w.  j  a v a2s  .  c om
        // input.reset() ; // Back to end of header
        // int startPosition = readBytes * -1 ;

        if (size > 0) {
            data = new byte[size];
            input.get(data);
        } else
            data = null;
        int magic = input.getInt();
        if (magic != MAGICEND) {
            logger.error("No MAGICEND within needle " + this.needleNumber);
            return false;
        }
        byte[] md5 = new byte[16];
        input.get(md5);
        byte[] currentMD5 = hashMD5();
        if (!Arrays.equals(md5, currentMD5)) {
            logger.error("Needle MD5 failed for " + new String(keyBytes, "UTF-8"));
            return false;
        }
    } catch (BufferUnderflowException bue) {
        return false;
    }
    return true;
}

From source file:com.alexkli.jhb.Worker.java

@Override
public void run() {
    try {//from  w  ww  .  ja  v a2  s .  com
        while (true) {
            long start = System.nanoTime();

            QueueItem<HttpRequestBase> item = queue.take();

            idleAvg.add(System.nanoTime() - start);

            if (item.isPoisonPill()) {
                return;
            }

            HttpRequestBase request = item.getRequest();

            if ("java".equals(config.client)) {
                System.setProperty("http.keepAlive", "false");

                item.sent();

                try {
                    HttpURLConnection http = (HttpURLConnection) new URL(request.getURI().toString())
                            .openConnection();
                    http.setConnectTimeout(5000);
                    http.setReadTimeout(5000);
                    int statusCode = http.getResponseCode();

                    consumeAndCloseStream(http.getInputStream());

                    if (statusCode == 200) {
                        item.done();
                    } else {
                        item.failed();
                    }
                } catch (IOException e) {
                    System.err.println("Failed request: " + e.getMessage());
                    e.printStackTrace();
                    //                        System.exit(2);
                    item.failed();
                }
            } else if ("ahc".equals(config.client)) {
                try {
                    item.sent();

                    try (CloseableHttpResponse response = httpClient.execute(request, context)) {
                        int statusCode = response.getStatusLine().getStatusCode();
                        if (statusCode == 200) {
                            item.done();
                        } else {
                            item.failed();
                        }
                    }
                } catch (IOException e) {
                    System.err.println("Failed request: " + e.getMessage());
                    item.failed();
                }
            } else if ("fast".equals(config.client)) {
                try {
                    URI uri = request.getURI();

                    item.sent();

                    InetAddress addr = InetAddress.getByName(uri.getHost());
                    Socket socket = new Socket(addr, uri.getPort());
                    PrintWriter out = new PrintWriter(socket.getOutputStream());
                    //                        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    // send an HTTP request to the web server
                    out.println("GET / HTTP/1.1");
                    out.append("Host: ").append(uri.getHost()).append(":").println(uri.getPort());
                    out.println("Connection: Close");
                    out.println();
                    out.flush();

                    // read the response
                    consumeAndCloseStream(socket.getInputStream());
                    //                        boolean loop = true;
                    //                        StringBuilder sb = new StringBuilder(8096);
                    //                        while (loop) {
                    //                            if (in.ready()) {
                    //                                int i = 0;
                    //                                while (i != -1) {
                    //                                    i = in.read();
                    //                                    sb.append((char) i);
                    //                                }
                    //                                loop = false;
                    //                            }
                    //                        }
                    item.done();
                    socket.close();

                } catch (IOException e) {
                    e.printStackTrace();
                    item.failed();
                }
            } else if ("nio".equals(config.client)) {
                URI uri = request.getURI();

                item.sent();

                String requestBody = "GET / HTTP/1.1\n" + "Host: " + uri.getHost() + ":" + uri.getPort() + "\n"
                        + "Connection: Close\n\n";

                try {
                    InetSocketAddress addr = new InetSocketAddress(uri.getHost(), uri.getPort());
                    SocketChannel channel = SocketChannel.open();
                    channel.socket().setSoTimeout(5000);
                    channel.connect(addr);

                    ByteBuffer msg = ByteBuffer.wrap(requestBody.getBytes());
                    channel.write(msg);
                    msg.clear();

                    ByteBuffer buf = ByteBuffer.allocate(1024);

                    int count;
                    while ((count = channel.read(buf)) != -1) {
                        buf.flip();

                        byte[] bytes = new byte[count];
                        buf.get(bytes);

                        buf.clear();
                    }
                    channel.close();

                    item.done();

                } catch (IOException e) {
                    e.printStackTrace();
                    item.failed();
                }
            }
        }
    } catch (InterruptedException e) {
        System.err.println("Worker thread [" + this.toString() + "] was interrupted: " + e.getMessage());
    }
}

From source file:org.red5.stream.http.servlet.TransportSegmentFeeder.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)// w ww.j  av  a2s.c  om
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.debug("Segment feed requested");
    // get red5 context and segmenter
    if (service == null) {
        ApplicationContext appCtx = (ApplicationContext) getServletContext()
                .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        service = (SegmenterService) appCtx.getBean("segmenter.service");
    }
    // get the requested stream / segment
    String servletPath = request.getServletPath();
    String streamName = servletPath.split("\\.")[0];
    log.debug("Stream name: {}", streamName);
    if (service.isAvailable(streamName)) {
        response.setContentType("video/MP2T");
        // data segment
        Segment segment = null;
        // setup buffers and output stream
        byte[] buf = new byte[188];
        ByteBuffer buffer = ByteBuffer.allocate(188);
        ServletOutputStream sos = response.getOutputStream();
        // loop segments
        while ((segment = service.getSegment(streamName)) != null) {
            do {
                buffer = segment.read(buffer);
                // log.trace("Limit - position: {}", (buffer.limit() - buffer.position()));
                if ((buffer.limit() - buffer.position()) == 188) {
                    buffer.get(buf);
                    // write down the output stream
                    sos.write(buf);
                } else {
                    log.info("Segment result has indicated a problem");
                    // verifies the currently requested stream segment
                    // number against the currently active segment
                    if (service.getSegment(streamName) == null) {
                        log.debug("Requested segment is no longer available");
                        break;
                    }
                }
                buffer.clear();
            } while (segment.hasMoreData());
            log.trace("Segment {} had no more data", segment.getIndex());
            // flush
            sos.flush();
            // segment had no more data
            segment.cleanupThreadLocal();
        }
        buffer.clear();
        buffer = null;
    } else {
        // let requester know that stream segment is not available
        response.sendError(404, "Requested segmented stream not found");
    }
}

From source file:com.kactech.otj.Utils.java

public static String open(byte[] encryptedEnvelope, PrivateKey privateKey)
        throws InvalidKeyException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        IllegalBlockSizeException, BadPaddingException {
    String str;/*from w  w w  . j  a  v  a 2 s . co  m*/
    byte[] by;
    ByteBuffer buff = ByteBuffer.wrap(encryptedEnvelope);
    buff.order(ByteOrder.BIG_ENDIAN);
    int envType = buff.getShort();// expected 1(asymmetric)
    if (envType != 1)
        throw new UnsupportedOperationException("unexpected envelope type " + envType);
    int arraySize = buff.getInt();// can result in negative integer but not expecting it here
    if (arraySize != 1)//TODO
        throw new UnsupportedOperationException("current code doesn't support multi-nym response");
    byte[] encKeyBytes = null;
    byte[] vectorBytes = null;
    for (int i = 0; i < arraySize; i++) {
        int nymIDLen = buff.getInt();
        by = new byte[nymIDLen];
        buff.get(by);
        String nymID;
        try {
            nymID = new String(by, 0, by.length - 1, Utils.US_ASCII);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } // take nymID W/O trailing \0
          //TODO nymID matching!
        int keyLength = buff.getInt();
        encKeyBytes = new byte[keyLength];
        buff.get(encKeyBytes);
        int vectorLength = buff.getInt();
        vectorBytes = new byte[vectorLength];
        buff.get(vectorBytes);

    }
    byte[] encryptedMsg = new byte[buff.remaining()];
    buff.get(encryptedMsg);

    Cipher cipher;
    try {
        cipher = Cipher.getInstance(WRAP_ALGO);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    cipher.init(Cipher.UNWRAP_MODE, privateKey);
    SecretKeySpec aesKey = (SecretKeySpec) cipher.unwrap(encKeyBytes, "AES", Cipher.SECRET_KEY);
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(vectorBytes));
    by = cipher.doFinal(encryptedMsg);
    try {
        str = new String(by, 0, by.length - 1, Utils.UTF8);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } // w/o trailing \0
    return str;
}

From source file:com.l2jfree.gameserver.geodata.pathfinding.geonodes.GeoPathFinding.java

/**
 * @see net.sf.l2j.gameserver.pathfinding.PathFinding#ReadNeighbors(short, short)
 *//*from   ww  w .j a  v a 2 s  . co m*/
@Override
public Node[] readNeighbors(Node n, int idx, int instanceId) {
    int node_x = n.getNodeX();
    int node_y = n.getNodeY();
    //short node_z = n.getZ();

    short regoffset = getRegionOffset(getRegionX(node_x), getRegionY(node_y));
    ByteBuffer pn = _pathNodes.get(regoffset);

    Node[] Neighbors = new Node[8];
    int index = 0;
    Node newNode;
    short new_node_x, new_node_y;

    //Region for sure will change, we must read from correct file
    byte neighbor = pn.get(idx++); //N
    if (neighbor > 0) {
        neighbor--;
        new_node_x = (short) node_x;
        new_node_y = (short) (node_y - 1);
        newNode = readNode(new_node_x, new_node_y, neighbor);
        if (newNode != null)
            Neighbors[index++] = newNode;
    }
    neighbor = pn.get(idx++); //NE
    if (neighbor > 0) {
        neighbor--;
        new_node_x = (short) (node_x + 1);
        new_node_y = (short) (node_y - 1);
        newNode = readNode(new_node_x, new_node_y, neighbor);
        if (newNode != null)
            Neighbors[index++] = newNode;
    }
    neighbor = pn.get(idx++); //E
    if (neighbor > 0) {
        neighbor--;
        new_node_x = (short) (node_x + 1);
        new_node_y = (short) node_y;
        newNode = readNode(new_node_x, new_node_y, neighbor);
        if (newNode != null)
            Neighbors[index++] = newNode;
    }
    neighbor = pn.get(idx++); //SE
    if (neighbor > 0) {
        neighbor--;
        new_node_x = (short) (node_x + 1);
        new_node_y = (short) (node_y + 1);
        newNode = readNode(new_node_x, new_node_y, neighbor);
        if (newNode != null)
            Neighbors[index++] = newNode;
    }
    neighbor = pn.get(idx++); //S
    if (neighbor > 0) {
        neighbor--;
        new_node_x = (short) node_x;
        new_node_y = (short) (node_y + 1);
        newNode = readNode(new_node_x, new_node_y, neighbor);
        if (newNode != null)
            Neighbors[index++] = newNode;
    }
    neighbor = pn.get(idx++); //SW
    if (neighbor > 0) {
        neighbor--;
        new_node_x = (short) (node_x - 1);
        new_node_y = (short) (node_y + 1);
        newNode = readNode(new_node_x, new_node_y, neighbor);
        if (newNode != null)
            Neighbors[index++] = newNode;
    }
    neighbor = pn.get(idx++); //W
    if (neighbor > 0) {
        neighbor--;
        new_node_x = (short) (node_x - 1);
        new_node_y = (short) node_y;
        newNode = readNode(new_node_x, new_node_y, neighbor);
        if (newNode != null)
            Neighbors[index++] = newNode;
    }
    neighbor = pn.get(idx++); //NW
    if (neighbor > 0) {
        neighbor--;
        new_node_x = (short) (node_x - 1);
        new_node_y = (short) (node_y - 1);
        newNode = readNode(new_node_x, new_node_y, neighbor);
        if (newNode != null)
            Neighbors[index++] = newNode;
    }

    return L2Arrays.compact(Neighbors);
}

From source file:edu.hawaii.soest.kilonalu.adcp.EnsembleHeader.java

/**
 *  Constructor.  This method populates the Header fields from the given
 *  ByteBuffer of data passed in as an argument.
 *
 * @param ensembleBuffer the ByteBuffer that contains the binary ensemble data
 *//*from   ww  w.j  a  va  2  s .  com*/
public EnsembleHeader(ByteBuffer ensembleBuffer, Ensemble ensemble) {

    // prepare the ensemble buffer for reading
    ensembleBuffer.flip();

    // define the temporary arrays for passing bytes
    byte[] oneByte = new byte[1];
    byte[] twoBytes = new byte[2];

    // set each of the Ensemble Header fields n the order that they are 
    // read from the byte stream
    ensembleBuffer.get(twoBytes);
    setHeaderID(twoBytes);
    headerID.flip();
    ensemble.addToByteSum(twoBytes);

    ensembleBuffer.get(twoBytes);
    setNumberOfBytesInEnsemble(twoBytes);
    numberOfBytesInEnsemble.flip();
    ensemble.addToByteSum(twoBytes);

    ensembleBuffer.get(oneByte);
    setHeaderSpare(oneByte);
    headerSpare.flip();
    ensemble.addToByteSum(oneByte);

    ensembleBuffer.get(oneByte);
    setNumberOfDataTypes(oneByte);
    numberOfDataTypes.flip();
    ensemble.addToByteSum(oneByte);

    // set the dataTypeOffsets ByteBuffer size
    dataTypeOffsets = ByteBuffer.allocate(((int) getNumberOfDataTypes().get()) * 2);
    numberOfDataTypes.flip();
    byte[] offsetBytes = new byte[(getNumberOfDataTypes().get() * 2)];
    numberOfDataTypes.flip();
    ensembleBuffer.get(offsetBytes);
    setDataTypeOffsets(offsetBytes);
    dataTypeOffsets.flip();
    ensemble.addToByteSum(offsetBytes);

}

From source file:edu.umass.cs.nio.MessageExtractor.java

private void processMessageInternal(SocketChannel socket, ByteBuffer incoming) throws IOException {
    /* The emulated delay value is in the message, so we need to read all
     * bytes off incoming and stringify right away. */
    long delay = -1;
    if (JSONDelayEmulator.isDelayEmulated()) {
        byte[] msg = new byte[incoming.remaining()];
        incoming.get(msg);
        String message = new String(msg, MessageNIOTransport.NIO_CHARSET_ENCODING);
        // always true because of max(0,delay)
        if ((delay = Math.max(0, JSONDelayEmulator.getEmulatedDelay(message))) >= 0)
            // run in a separate thread after scheduled delay
            executor.schedule(new MessageWorker(socket, msg, packetDemuxes), delay, TimeUnit.MILLISECONDS);
    } else//from   ww w  .  j  av  a 2  s. c  o m
        // run it immediately
        this.demultiplexMessage(new NIOHeader((InetSocketAddress) socket.getRemoteAddress(),
                (InetSocketAddress) socket.getLocalAddress()), incoming);
}

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

/**
 * Applies the XOR mask to the database header in the given buffer.
 *//*  ww  w  .  ja  v  a2s.c  o  m*/
private void applyHeaderMask(ByteBuffer buffer) {
    // de/re-obfuscate the header
    byte[] headerMask = _format.HEADER_MASK;
    for (int idx = 0; idx < headerMask.length; ++idx) {
        int pos = idx + _format.OFFSET_MASKED_HEADER;
        byte b = (byte) (buffer.get(pos) ^ headerMask[idx]);
        buffer.put(pos, b);
    }
}