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.dreamworks.dsp.server.EmbeddedSftpServer.java

private BigInteger decodeBigInt(ByteBuffer bb) {
    int len = bb.getInt();
    byte[] bytes = new byte[len];
    bb.get(bytes);
    return new BigInteger(bytes);
}

From source file:com.offbynull.portmapper.pcp.ThirdPartyPcpOption.java

/**
 * Constructs a {@link ThirdPartyPcpOption} by parsing a buffer.
 * @param buffer buffer containing PCP option data
 * @throws NullPointerException if any argument is {@code null}
 * @throws BufferUnderflowException if not enough data is available in {@code buffer}
 * @throws IllegalArgumentException if option code is not {@code 1}
 *//* w  w  w.  j av a2s .  c  o m*/
public ThirdPartyPcpOption(ByteBuffer buffer) {
    super(buffer);
    Validate.isTrue(super.getCode() == 1);
    byte[] addrArr = new byte[16];
    buffer.get(addrArr);
    try {
        internalIpAddress = InetAddress.getByAddress(addrArr);
    } catch (UnknownHostException uhe) {
        throw new IllegalStateException(uhe); // should never happen
    }
}

From source file:com.acciente.oacc.sql.internal.StrongCleanablePasswordEncryptor.java

private byte[] getCleanedBytes(char[] password) {
    final ByteBuffer byteBuffer = StandardCharsets.UTF_8
            .encode(CharBuffer.wrap(Normalizer.normalizeToNfc(password)));
    final byte[] byteArray = new byte[byteBuffer.remaining()];
    byteBuffer.get(byteArray);
    Arrays.fill(byteBuffer.array(), (byte) 0);
    return byteArray;
}

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

public TxAck(byte[] _randoms, ByteBuffer _raw) throws MalformedPacketException {
    super(_randoms, PacketType.TX_ACK);

    byte[] txt = new byte[_raw.remaining()];
    _raw.get(txt);

    JSONObject jo;/*from   w w w  .jav a 2  s  .  c  o  m*/

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

    if (!jo.has("txpk_ack") || !jo.get("txpk_ack").getClass().equals(JSONObject.class)) {
        throw new MalformedPacketException("malformed json");
    }

    if (!jo.getJSONObject("txpk_ack").has("error")) {
        throw new MalformedPacketException("malformed json");
    }

    error = Error.parse(jo.getJSONObject("txpk_ack").getString("error"));
}

From source file:com.dreamworks.dsp.server.EmbeddedSftpServer.java

private PublicKey decodePublicKey() throws Exception {
    InputStream stream = new ClassPathResource("keys/sftp_rsa.pub").getInputStream();
    byte[] decodeBuffer = Base64.decodeBase64(StreamUtils.copyToByteArray(stream));
    ByteBuffer bb = ByteBuffer.wrap(decodeBuffer);
    int len = bb.getInt();
    byte[] type = new byte[len];
    bb.get(type);
    if ("ssh-rsa".equals(new String(type))) {
        BigInteger e = decodeBigInt(bb);
        BigInteger m = decodeBigInt(bb);
        RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e);
        return KeyFactory.getInstance("RSA").generatePublic(spec);

    } else {//from  w  w  w  .j av  a2  s. c o m
        throw new IllegalArgumentException("Only supports RSA");
    }
}

From source file:net.jradius.packet.PacketFactory.java

public static RadiusPacket parseUDP(int code, int identifier, int length, ByteBuffer buffer, boolean pool)
        throws RadiusException, IOException {
    RadiusPacket rp = null;/*from   w  w w  .j av a2s  . co  m*/
    Integer key = new Integer(code);

    if (pktObjectPool != null && pool) {
        try {
            rp = (RadiusPacket) pktObjectPool.borrowObject(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    if (rp == null) {
        Class<?> c = (Class<?>) codeMap.get(key);

        if (c == null) {
            throw new RadiusException("bad radius code - " + key);
        }

        try {
            rp = (RadiusPacket) c.newInstance();
        } catch (Exception e) {
            RadiusLog.error(e.getMessage(), e);
            return null;
        }
    }

    byte[] bAuthenticator = new byte[16];
    buffer.get(bAuthenticator);

    rp.setIdentifier(identifier);
    rp.setAuthenticator(bAuthenticator);

    length -= RadiusPacket.RADIUS_HEADER_LENGTH;
    if (length > 0) {
        RadiusFormat.setAttributeBytes(rp, buffer, length);
    }

    return rp;
}

From source file:name.martingeisse.stackd.server.section.storage.CassandraSectionStorage.java

@Override
public byte[] loadSectionRelatedObject(final SectionDataId id) {
    try {/*from ww w . ja  va 2 s.com*/
        for (final Row row : fetch(QueryBuilder.eq("id", id.getIdentifierText()))) {
            final ByteBuffer dataBuffer = row.getBytes("data");
            final byte[] data = new byte[dataBuffer.remaining()];
            dataBuffer.get(data);
            return data;
        }
        return null;
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.umn.cs.spatialHadoop.nasa.HDFRecordReader.java

/**
 * Converts a water mask from the byte_array format to the bit_array format.
 * In the byte array format, 0 means land, anything else means water.
 * In the bit array format, false means land and true means water.
 * Each square with side length of <code>size</code> will be converted to
 * one value in the output bit array depending on average value in this
 * square box. If at least half of the values are land (i.e., 0), the
 * corresponding value in the bit array is set to false. Otherwise, the
 * corresponding value in the bit array is set to true. 
 * @param waterMaskBytes/*from ww  w .j  a  v a 2 s  .c o  m*/
 * @param size
 * @return
 */
static BitArray convertWaterMaskToBits(ByteBuffer waterMaskBytes, int size) {
    int wmRes = (int) Math.sqrt(waterMaskBytes.limit());
    int dataRes = wmRes / size;
    BitArray waterMaskBits = new BitArray(dataRes * dataRes);
    // Size of each pixel of the data when mapped to the water mask
    for (int row = 0; row < dataRes; row++)
        for (int col = 0; col < dataRes; col++) {
            int r1 = row * size;
            int r2 = (row + 1) * size;
            int c1 = col * size;
            int c2 = (col + 1) * size;

            byte wm_sum = 0;
            for (int r = r1; r < r2; r++)
                for (int c = c1; c < c2; c++) {
                    byte wm_value = waterMaskBytes.get(r * wmRes + c);
                    if (wm_value == 0)
                        wm_sum++;
                }
            waterMaskBits.set(row * dataRes + col, wm_sum < (size * size) / 2);
        }
    return waterMaskBits;
}

From source file:com.stratio.ingestion.sink.kafka.KafkaSinkTest.java

@Test
public void test() throws EventDeliveryException, UnsupportedEncodingException {
    Transaction tx = channel.getTransaction();
    tx.begin();//from w ww.j  a va 2s  .  c o  m

    ObjectNode jsonBody = new ObjectNode(JsonNodeFactory.instance);
    jsonBody.put("myString", "foo");
    jsonBody.put("myInt32", 32);

    Map<String, String> headers = new HashMap<String, String>();
    headers.put("myString", "bar");
    headers.put("myInt64", "64");
    headers.put("myBoolean", "true");
    headers.put("myDouble", "1.0");
    headers.put("myNull", "foobar");

    Event event = EventBuilder.withBody(jsonBody.toString().getBytes(Charsets.UTF_8), headers);
    channel.put(event);

    tx.commit();
    tx.close();

    kafkaSink.process();

    kafka.api.FetchRequest req = new FetchRequestBuilder().clientId(CLIENT_ID).addFetch("test", 0, 0L, 100)
            .build();
    FetchResponse fetchResponse = simpleConsumer.fetch(req);
    ByteBufferMessageSet messageSet = fetchResponse.messageSet("test", 0);

    Assert.assertTrue(messageSet.sizeInBytes() > 0);
    for (MessageAndOffset messageAndOffset : messageSet) {
        ByteBuffer payload = messageAndOffset.message().payload();
        byte[] bytes = new byte[payload.limit()];
        payload.get(bytes);
        String message = new String(bytes, "UTF-8");
        Assert.assertNotNull(message);
        Assert.assertEquals(message, "{\"myString\":\"foo\",\"myInt32\":32}");
    }
}

From source file:com.stratio.ingestion.sink.kafka.KafkaSinkTestIT.java

@Test
public void test() throws EventDeliveryException, UnsupportedEncodingException {
    Transaction tx = channel.getTransaction();
    tx.begin();//from  www.ja  va 2  s  . c om

    ObjectNode jsonBody = new ObjectNode(JsonNodeFactory.instance);
    jsonBody.put("myString", "foo");
    jsonBody.put("myInt32", 32);

    Map<String, String> headers = new HashMap<String, String>();
    headers.put("myString", "bar");
    headers.put("myInt64", "64");
    headers.put("myBoolean", "true");
    headers.put("myDouble", "1.0");
    headers.put("myNull", "foobar");

    Event event = EventBuilder.withBody(jsonBody.toString().getBytes(Charsets.UTF_8), headers);
    channel.put(event);

    tx.commit();
    tx.close();

    kafkaSink.process();

    kafka.api.FetchRequest req = new FetchRequestBuilder().clientId(CLIENT_ID).addFetch("test", 0, 0L, 100)
            .build();
    FetchResponse fetchResponse = simpleConsumer.fetch(req);
    ByteBufferMessageSet messageSet = fetchResponse.messageSet("test", 0);

    for (MessageAndOffset messageAndOffset : messageSet) {
        ByteBuffer payload = messageAndOffset.message().payload();
        byte[] bytes = new byte[payload.limit()];
        payload.get(bytes);
        String message = new String(bytes, "UTF-8");
        Assert.assertNotNull(message);
        Assert.assertEquals(message, "{\"myString\":\"foo\",\"myInt32\":32}");
    }
}