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:com.intel.chimera.stream.AbstractCryptoStreamTest.java

private void byteBufferReadCheck(InputStream in, ByteBuffer buf, int bufPos) throws Exception {
    buf.position(bufPos);//  ww w .  j  a va2s  .com
    int n = ((ReadableByteChannel) in).read(buf);
    Assert.assertEquals(bufPos + n, buf.position());
    byte[] readData = new byte[n];
    buf.rewind();
    buf.position(bufPos);
    buf.get(readData);
    byte[] expectedData = new byte[n];
    System.arraycopy(data, 0, expectedData, 0, n);
    Assert.assertArrayEquals(readData, expectedData);
}

From source file:dotaSoundEditor.Controls.EditorPanel.java

protected void revertButtonActionPerformed(ActionEvent evt, Path vpkToRevert) {
    //TODO: See if we can abstract away some of this functionality
    if (currentTree.getSelectionRows().length != 0
            && ((TreeNode) currentTree.getSelectionPath().getLastPathComponent()).isLeaf()) {
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) currentTree.getSelectionPath()
                .getLastPathComponent();
        String selectedWaveString = ((DefaultMutableTreeNode) selectedNode).getUserObject().toString();
        String selectedWaveParentString = ((DefaultMutableTreeNode) ((DefaultMutableTreeNode) selectedNode)
                .getParent()).getUserObject().toString();
        selectedNode = (DefaultMutableTreeNode) this.getTreeNodeFromWavePath(selectedWaveString);
        //First go in and delete the sound in customSounds
        deleteSoundFileByWaveString(selectedWaveString);
        //Get the relevant wavestring from the internal scriptfile
        VPKArchive vpk = new VPKArchive();
        try {/*from w w  w .jav a2s  . c  o  m*/
            vpk.load(new File(vpkToRevert.toString()));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        String scriptDir = getCurrentScriptString();
        scriptDir = scriptDir.replace(Paths.get(installDir, "/dota/").toString(), "");
        scriptDir = scriptDir.replace("\\", "/"); //Match internal forward slashes
        scriptDir = scriptDir.substring(1); //Cut off leading slash
        byte[] bytes = null;
        VPKEntry entry = vpk.getEntry(scriptDir);
        try {
            ByteBuffer scriptBuffer = entry.getData();
            bytes = new byte[scriptBuffer.remaining()];
            scriptBuffer.get(bytes);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        String scriptFileString = new String(bytes, Charset.forName("UTF-8"));
        ArrayList<String> wavePathList = this.getWavePathsAsList(selectedNode.getParent());
        int waveStringIndex = wavePathList.indexOf(selectedWaveString);
        //Cut off every part of the scriptFileString before we get to the entry describing the relevant hero action, so we don't accidentally get the wrong wavepaths
        StringBuilder scriptFileStringShortened = new StringBuilder();
        Scanner scan = new Scanner(scriptFileString);
        boolean found = false;
        while (scan.hasNextLine()) {
            String curLine = scan.nextLine();
            if (curLine.equals(selectedWaveParentString)) {
                found = true;
            }
            if (found == true) {
                scriptFileStringShortened.append(curLine).append(System.lineSeparator());
            }
        }
        scriptFileString = scriptFileStringShortened.toString();
        ArrayList<String> internalWavePathsList = getWavePathListFromString(scriptFileString);
        String replacementString = internalWavePathsList.get(waveStringIndex);
        selectedNode.setUserObject(replacementString);
        ScriptParser parser = new ScriptParser(this.currentTreeModel);
        parser.writeModelToFile(getCurrentScriptString());
        //Modify the UI treeNode in addition to the backing TreeNode
        ((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent()).setUserObject(replacementString);
        ((DefaultTreeModel) currentTree.getModel())
                .nodeChanged((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent());
    }
}

From source file:com.codestation.henkakuserver.HenkakuServer.java

/**
 * Finalize the exploit with the addesses from the device
 *
 * @param exploit payload compiled code//from  w  ww  .jav a 2s  .  co  m
 * @param params  list of addresses from the device
 * @return patched shellcode
 * @throws Exception
 */
private byte[] patchExploit(byte[] exploit, Map<String, String> params) throws Exception {

    if (params.size() != 7) {
        throw new Exception("invalid argument count");
    }

    ArrayList<Long> args = new ArrayList<>();
    args.add(0L);

    for (int i = 1; i <= 7; ++i) {
        String arg = String.format("a%s", i);
        if (params.containsKey(arg)) {
            args.add(Long.parseLong(params.get(arg), 16));
        } else {
            throw new Exception(String.format("argument %s is missing", arg));
        }
    }

    byte[] copy = new byte[exploit.length];
    System.arraycopy(exploit, 0, copy, 0, exploit.length);

    ByteBuffer buf = ByteBuffer.wrap(copy).order(ByteOrder.LITTLE_ENDIAN);
    int size_words = buf.getInt(0);

    int dsize = buf.getInt(4 + 0x10);
    int csize = buf.getInt(4 + 0x20);

    long data_base = args.get(1) + csize;

    for (int i = 1; i < size_words; ++i) {
        long add = 0;
        byte x = buf.get(size_words * 4 + 4 + i - 1);

        if (x == 1) {
            add = data_base;
        } else if (x != 0) {
            add = args.get(x);
        }

        buf.putInt(i * 4, buf.getInt(i * 4) + (int) add);
    }

    byte[] out = new byte[dsize + csize];

    System.arraycopy(copy, 4 + 0x40, out, csize, dsize);
    System.arraycopy(copy, 4 + 0x40 + dsize, out, 0, csize);

    return out;
}

From source file:com.l2jfree.gameserver.network.L2ClientSelectorThread.java

public void printDebug(ByteBuffer buf, L2Client client, int... opcodes) {
    report(ErrorMode.INVALID_OPCODE, client, null, null);

    if (!Config.PACKET_HANDLER_DEBUG)
        return;/*  w  w  w  .j  ava2 s.  com*/

    L2TextBuilder sb = L2TextBuilder.newInstance();
    sb.append("Unknown Packet: ");

    for (int i = 0; i < opcodes.length; i++) {
        if (i != 0)
            sb.append(" : ");

        sb.append("0x").append(Integer.toHexString(opcodes[i]));
    }
    sb.append(", Client: ").append(client);
    _log.info(sb.moveToString());

    byte[] array = new byte[buf.remaining()];
    buf.get(array);
    for (String line : StringUtils.split(HexUtil.printData(array), "\n"))
        _log.info(line);
}

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);
        }//from w  w  w  .j av a  2 s . com

        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:io.github.dsheirer.source.tuner.hackrf.HackRFTunerController.java

/**
 * HackRF firmware version string//ww w  .java2s.com
 */
public String getFirmwareVersion() throws UsbException {
    ByteBuffer buffer = readArray(Request.VERSION_STRING_READ, 0, 0, 255);

    byte[] data = new byte[255];

    buffer.get(data);

    return new String(data);
}

From source file:io.github.dsheirer.source.tuner.hackrf.HackRFTunerController.java

public int read(Request request, int value, int index, int length) throws UsbException {
    if (!(length == 1 || length == 2 || length == 4)) {
        throw new IllegalArgumentException(
                "invalid length [" + length + "] must be: byte=1, short=2, int=4 to read a primitive");
    }/*w  w w.ja  va2s.c om*/

    ByteBuffer buffer = readArray(request, value, index, length);

    byte[] data = new byte[buffer.capacity()];

    buffer.get(data);

    switch (data.length) {
    case 1:
        return data[0];
    case 2:
        return EndianUtils.readSwappedShort(data, 0);
    case 4:
        return EndianUtils.readSwappedInteger(data, 0);
    default:
        throw new UsbException(
                "read() primitive returned an " + "unrecognized byte array " + Arrays.toString(data));
    }
}

From source file:com.xuggle.xuggler.UtilsTest.java

@Test
public void testGetBlankFrame() {
    IVideoPicture frame = null;//  www .  ja  v a2 s.  c  o  m
    byte y = 62;
    byte u = 15;
    byte v = 33;
    int w = 100;
    int h = 200;
    long pts = 102832;

    frame = Utils.getBlankFrame(w, h, y, u, v, pts);
    assertTrue("got a frame", frame != null);
    assertTrue("is complete", frame.isComplete());
    assertTrue("correct pts", frame.getPts() == pts);

    // now, loop through the array and ensure it is set
    // correctly.
    IBuffer data = frame.getData();
    java.nio.ByteBuffer buffer = data.getByteBuffer(0, data.getBufferSize());
    assertNotNull(buffer);
    // we have the raw data; now we set it to the specified YUV value.
    int lineLength = 0;
    int offset = 0;

    // first let's check the L
    offset = 0;
    lineLength = frame.getDataLineSize(0);
    assertTrue("incorrect format", lineLength == w);
    for (int i = offset; i < offset + lineLength * h; i++) {
        byte val = buffer.get(i);
        assertTrue("color not set correctly: " + i, val == y);
    }

    // now, check the U value
    offset = (frame.getDataLineSize(0) * h);
    lineLength = frame.getDataLineSize(1);
    assertTrue("incorrect format", lineLength == w / 2);
    for (int i = offset; i < offset + lineLength * h / 2; i++) {
        byte val = buffer.get(i);
        assertTrue("color not set correctly: " + i, val == u);
    }

    // and finally the V
    offset = (frame.getDataLineSize(0) * h) + (frame.getDataLineSize(1) * h / 2);
    lineLength = frame.getDataLineSize(2);
    assertTrue("incorrect format", lineLength == w / 2);
    for (int i = offset; i < offset + lineLength * h / 2; i++) {
        byte val = buffer.get(i);
        assertTrue("color not set correctly: " + i, val == v);
    }

    // And check another way
    for (int i = 0; i < w; i++) {
        for (int j = 0; j < h; j++) {
            assertEquals(y, IPixelFormat.getYUV420PPixel(frame, i, j, IPixelFormat.YUVColorComponent.YUV_Y));
            assertEquals(u, IPixelFormat.getYUV420PPixel(frame, i, j, IPixelFormat.YUVColorComponent.YUV_U));
            assertEquals(v, IPixelFormat.getYUV420PPixel(frame, i, j, IPixelFormat.YUVColorComponent.YUV_V));
        }
    }
}

From source file:TrackerPanel.java

private void convertToPixels(ByteBuffer pixelsRGB, int[] cameraPixels) {
    int rowStart = 0;

    int bbIdx; // index into ByteBuffer
    int i = 0; // index into pixels int[]
    int rowLen = imWidth * 3; // number of bytes in each row
    for (int row = 0; row < imHeight; row++) {
        bbIdx = rowStart;/* www .  jav  a  2  s. com*/
        // System.out.println("bbIdx: " + bbIdx);
        for (int col = 0; col < imWidth; col++) {
            int pixR = pixelsRGB.get(bbIdx++);
            int pixG = pixelsRGB.get(bbIdx++);
            int pixB = pixelsRGB.get(bbIdx++);

            cameraPixels[i++] = 0xFF000000 | ((pixR & 0xFF) << 16) | ((pixG & 0xFF) << 8) | (pixB & 0xFF);
        }
        rowStart += rowLen; // move to next row
    }
}