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.cellngine.crypto.RSACipher.java

private BigInteger[] getKeyData(final byte[] fromBytes) {
    final ByteBuffer buffer = ByteBuffer.wrap(fromBytes);

    final int modulusLength = buffer.getInt();
    final byte[] modulusBuffer = new byte[modulusLength];
    buffer.get(modulusBuffer);
    final BigInteger modulus = new BigInteger(modulusBuffer);

    final int exponentLength = buffer.getInt();
    final byte[] exponentBuffer = new byte[exponentLength];
    buffer.get(exponentBuffer);//from www  . ja v a2s. c o  m
    final BigInteger exponent = new BigInteger(exponentBuffer);

    return new BigInteger[] { modulus, exponent };
}

From source file:com.cloudera.sqoop.TestParquetImport.java

private void runParquetImportTest(String codec) throws IOException {
    String[] types = { "BIT", "INTEGER", "BIGINT", "REAL", "DOUBLE", "VARCHAR(6)", "VARBINARY(2)", };
    String[] vals = { "true", "100", "200", "1.0", "2.0", "'s'", "'0102'", };
    createTableWithColTypes(types, vals);

    String[] extraArgs = { "--compression-codec", codec };
    runImport(getOutputArgv(true, extraArgs));

    assertEquals(CompressionType.forName(codec), getCompressionType());

    Schema schema = getSchema();//w  w  w . j  a v  a  2  s . c  om
    assertEquals(Type.RECORD, schema.getType());
    List<Field> fields = schema.getFields();
    assertEquals(types.length, fields.size());
    checkField(fields.get(0), "DATA_COL0", Type.BOOLEAN);
    checkField(fields.get(1), "DATA_COL1", Type.INT);
    checkField(fields.get(2), "DATA_COL2", Type.LONG);
    checkField(fields.get(3), "DATA_COL3", Type.FLOAT);
    checkField(fields.get(4), "DATA_COL4", Type.DOUBLE);
    checkField(fields.get(5), "DATA_COL5", Type.STRING);
    checkField(fields.get(6), "DATA_COL6", Type.BYTES);

    DatasetReader<GenericRecord> reader = getReader();
    try {
        GenericRecord record1 = reader.next();
        assertNotNull(record1);
        assertEquals("DATA_COL0", true, record1.get("DATA_COL0"));
        assertEquals("DATA_COL1", 100, record1.get("DATA_COL1"));
        assertEquals("DATA_COL2", 200L, record1.get("DATA_COL2"));
        assertEquals("DATA_COL3", 1.0f, record1.get("DATA_COL3"));
        assertEquals("DATA_COL4", 2.0, record1.get("DATA_COL4"));
        assertEquals("DATA_COL5", "s", record1.get("DATA_COL5"));
        Object object = record1.get("DATA_COL6");
        assertTrue(object instanceof ByteBuffer);
        ByteBuffer b = ((ByteBuffer) object);
        assertEquals((byte) 1, b.get(0));
        assertEquals((byte) 2, b.get(1));
        assertFalse(reader.hasNext());
    } finally {
        reader.close();
    }
}

From source file:net.socket.nio.TimeClientHandle.java

private void handleInput(SelectionKey key) throws IOException {

    if (key.isValid()) {
        // ??//from w ww .  j a  v a  2 s . co m
        SocketChannel sc = (SocketChannel) key.channel();
        if (key.isConnectable()) {
            if (sc.finishConnect()) {
                sc.register(selector, SelectionKey.OP_READ);
                doWrite(sc);
            } else {
                System.exit(1);// 
            }
        }
        if (key.isReadable()) {
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            int readBytes = sc.read(readBuffer);
            if (readBytes > 0) {
                readBuffer.flip();
                byte[] bytes = new byte[readBuffer.remaining()];
                readBuffer.get(bytes);
                String body = new String(bytes, "UTF-8");
                System.out.println("Now is : " + body);
                this.stop = true;
            } else if (readBytes < 0) {
                // 
                key.cancel();
                sc.close();
            } else {
                ; // 0
            }
        }
    }

}

From source file:com.github.cambierr.lorawanpacket.semtech.PullResp.java

public PullResp(byte[] _randoms, ByteBuffer _raw) throws MalformedPacketException {
    super(_randoms, PacketType.PULL_RESP);
    _raw.order(ByteOrder.LITTLE_ENDIAN);

    if (_raw.remaining() < 1) {
        throw new MalformedPacketException("too short");
    }/*from   w w  w  .  j av a2  s .co m*/

    byte[] json = new byte[_raw.remaining()];
    _raw.get(json);
    JSONObject jo;

    try {
        jo = new JSONObject(new String(json));
    } catch (JSONException ex) {
        throw new MalformedPacketException("malformed json");
    }

    txpks = new ArrayList<>();

    if (!jo.has("txpk")) {
        throw new MalformedPacketException("missing json (txpk)");
    }

    if (!jo.get("txpk").getClass().equals(JSONArray.class)) {
        throw new MalformedPacketException("malformed json (txpk)");
    }
    JSONArray rxpk = jo.getJSONArray("txpk");

    for (int i = 0; i < rxpk.length(); i++) {
        txpks.add(new Txpk(rxpk.getJSONObject(i)));
    }
}

From source file:MainActivity.java

protected void takePicture(View view) {
    if (null == mCameraDevice) {
        return;//from w  ww  .  ja v  a 2s  .  c o  m
    }
    CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    try {
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(mCameraDevice.getId());
        StreamConfigurationMap configurationMap = characteristics
                .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        if (configurationMap == null)
            return;
        Size largest = Collections.max(Arrays.asList(configurationMap.getOutputSizes(ImageFormat.JPEG)),
                new CompareSizesByArea());
        ImageReader reader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(), ImageFormat.JPEG,
                1);
        List<Surface> outputSurfaces = new ArrayList<Surface>(2);
        outputSurfaces.add(reader.getSurface());
        outputSurfaces.add(new Surface(mTextureView.getSurfaceTexture()));
        final CaptureRequest.Builder captureBuilder = mCameraDevice
                .createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
        captureBuilder.addTarget(reader.getSurface());
        captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
        ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
            @Override
            public void onImageAvailable(ImageReader reader) {
                Image image = null;
                try {
                    image = reader.acquireLatestImage();
                    ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                    byte[] bytes = new byte[buffer.capacity()];
                    buffer.get(bytes);
                    OutputStream output = new FileOutputStream(getPictureFile());
                    output.write(bytes);
                    output.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (image != null) {
                        image.close();
                    }
                }
            }
        };
        HandlerThread thread = new HandlerThread("CameraPicture");
        thread.start();
        final Handler backgroudHandler = new Handler(thread.getLooper());
        reader.setOnImageAvailableListener(readerListener, backgroudHandler);
        final CameraCaptureSession.CaptureCallback captureCallback = new CameraCaptureSession.CaptureCallback() {
            @Override
            public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request,
                    TotalCaptureResult result) {
                super.onCaptureCompleted(session, request, result);
                Toast.makeText(MainActivity.this, "Picture Saved", Toast.LENGTH_SHORT).show();
                startPreview(session);
            }
        };
        mCameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {
            @Override
            public void onConfigured(CameraCaptureSession session) {
                try {
                    session.capture(captureBuilder.build(), captureCallback, backgroudHandler);
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onConfigureFailed(CameraCaptureSession session) {
            }
        }, backgroudHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

From source file:io.gomint.server.network.packet.PacketLogin.java

@Override
public void deserialize(PacketBuffer buffer) {
    this.protocol = buffer.readInt();

    // Decompress inner data (i don't know why you compress inside of a Batched Packet but hey)
    byte[] compressed = new byte[buffer.readInt()];
    buffer.readBytes(compressed);/*from  w  w  w. ja v a  2 s .  co  m*/

    Inflater inflater = new Inflater();
    inflater.setInput(compressed);

    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    try {
        byte[] comBuffer = new byte[1024];
        while (!inflater.finished()) {
            int read = inflater.inflate(comBuffer);
            bout.write(comBuffer, 0, read);
        }
    } catch (DataFormatException e) {
        System.out.println("Failed to decompress batch packet" + e);
        return;
    }

    // More data please
    ByteBuffer byteBuffer = ByteBuffer.wrap(bout.toByteArray());
    byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
    byte[] stringBuffer = new byte[byteBuffer.getInt()];
    byteBuffer.get(stringBuffer);

    // Decode the json stuff
    try {
        JSONObject jsonObject = (JSONObject) new JSONParser().parse(new String(stringBuffer));
        JSONArray chainArray = (JSONArray) jsonObject.get("chain");
        if (chainArray != null) {
            this.validationKey = parseBae64JSON((String) chainArray.get(chainArray.size() - 1)); // First key in chain is last response in chain #brainfuck :D
            for (Object chainObj : chainArray) {
                decodeBase64JSON((String) chainObj);
            }
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }

    // Skin comes next
    this.skin = new byte[byteBuffer.getInt()];
    byteBuffer.get(this.skin);
}

From source file:com.github.cambierr.lorawanpacket.semtech.PushData.java

public PushData(byte[] _randoms, ByteBuffer _raw) throws MalformedPacketException {
    super(_randoms, PacketType.PUSH_DATA);
    _raw.order(ByteOrder.LITTLE_ENDIAN);

    if (_raw.remaining() < 8) {
        throw new MalformedPacketException("too short");
    }//from   w ww . j  a va 2s  .  c om

    gatewayEui = new byte[8];
    _raw.get(gatewayEui);

    byte[] json = new byte[_raw.remaining()];
    _raw.get(json);
    JSONObject jo;

    try {
        jo = new JSONObject(new String(json));
    } catch (JSONException ex) {
        throw new MalformedPacketException("malformed json");
    }

    stats = new ArrayList<>();
    rxpks = new ArrayList<>();

    if (jo.has("rxpk")) {
        if (!jo.get("rxpk").getClass().equals(JSONArray.class)) {
            throw new MalformedPacketException("malformed json (rxpk)");
        }
        JSONArray rxpk = jo.getJSONArray("rxpk");

        for (int i = 0; i < rxpk.length(); i++) {
            rxpks.add(new Rxpk(rxpk.getJSONObject(i)));
        }
    }

    if (jo.has("stat")) {
        if (!jo.get("stat").getClass().equals(JSONArray.class)) {
            throw new MalformedPacketException("malformed json (stat)");
        }
        JSONArray stat = jo.getJSONArray("stat");

        for (int i = 0; i < stat.length(); i++) {
            stats.add(new Stat(stat.getJSONObject(i)));
        }
    }

}

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

@Override
public void receive(ByteBuffer buffer, String channelId) {
    try {/*  w  w  w  . j av a  2  s . c o  m*/
        int remaining = buffer.remaining();
        if (remaining <= 0)
            return;
        if (bytes == null) {
            bytes = new byte[remaining];
            buffer.get(bytes);
        } else {
            byte[] temp = new byte[bytes.length + remaining];
            System.arraycopy(bytes, 0, temp, 0, bytes.length);
            buffer.get(temp, bytes.length, remaining);
            bytes = temp;
        }
        try {
            saxParser.parse(new ByteArrayInputStream(bytes), messageParser);
            bytes = null;
            commit();
        } catch (SAXException e) {
            LOG.error("SAXException while trying to parse the incoming xml.", e);

            // TODO : figure out a way to recover the lost bytes. for now, just
            // throwing them away.
            if (tryingToRecoverPartialMessages) {
                queue.clear();
            } else {
                bytes = null;
                commit();
            }
        }
    } catch (IOException e) {
        LOG.error("IOException while trying to route data from the byte buffer to the pipe.", e);
    }
}

From source file:com.linkedin.databus.core.DbusEventPart.java

@Override
public String toString() {
    StringBuilder sb = new StringBuilder(64);
    sb.append("Length=").append(getDataLength()).append(";SchemaVersion=").append(getSchemaVersion())
            .append(";SchemaId=").append("0x").append(Hex.encodeHexString(getSchemaDigest()));

    ByteBuffer dataBB = getData();
    if (dataBB.remaining() > MAX_DATA_BYTES_PRINTED) {
        dataBB.limit(MAX_DATA_BYTES_PRINTED);
    }//www.j a va 2  s.c  o  m
    byte[] data = new byte[dataBB.remaining()];
    dataBB.get(data);
    sb.append(";Value=").append("0x").append(Hex.encodeHexString(data));
    return sb.toString();
}

From source file:tanks10.SendAndReceive.java

/**
 * Umieszczenie bufora w kolejce do wysania
 *//*  w ww  .  ja  va  2s  .  c  om*/
public void addToSendBuffers(ByteBuffer in) {
    if (closed) {
        return;
    }
    if (kill) {
        closeSession();
    } else {

        // blokada tylko dotyczy operowania na wskanikach bufora
        synchronized (sendBuffers) {
            final TextMessage message;
            try {
                byte[] arrayContent = new byte[in.limit()];
                in.get(arrayContent);
                String content = new String(arrayContent, "UTF-8");
                message = new TextMessage(content);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }

            try {
                session.sendMessage(message);
            } catch (Exception e) {
                LOG.log(Level.WARNING, "send message failed to " + session.getRemoteAddress().toString(), e);
                closeSession();
            }
        }
    }

}