Example usage for java.nio ByteBuffer wrap

List of usage examples for java.nio ByteBuffer wrap

Introduction

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

Prototype

public static ByteBuffer wrap(byte[] array) 

Source Link

Document

Creates a new byte buffer by wrapping the given byte array.

Usage

From source file:info.archinnov.achilles.test.integration.tests.SupportedTypesIT.java

@Test
public void should_persist_and_find_all_types() throws Exception {
    // Given// w ww  .  j a  v a2  s .  c om
    Long id = RandomUtils.nextLong();
    byte[] bytes = "toto".getBytes(Charsets.UTF_8);
    Date now = new Date();
    InetAddress inetAddress = InetAddresses.forString("192.168.0.1");

    EntityWithAllTypes entity = new EntityWithAllTypes();
    entity.setId(id);

    entity.setPrimitiveByte((byte) 7);
    entity.setObjectByte((byte) 7);
    entity.setByteArray(bytes);
    entity.setByteBuffer(ByteBuffer.wrap(bytes));

    entity.setPrimitiveBool(true);
    entity.setObjectBool(true);

    entity.setDate(now);

    entity.setPrimitiveDouble(1.0d);
    entity.setObjectDouble(1.0d);
    entity.setBigDecimal(new BigDecimal(1.11));

    entity.setPrimitiveFloat(1.0f);
    entity.setObjectFloat(1.0f);

    entity.setInetAddress(inetAddress);

    entity.setBigInt(new BigInteger("10"));
    entity.setPrimitiveInt(10);
    entity.setObjectInt(10);

    entity.setPrimitiveLong(10L);

    // When
    manager.persist(entity);
    EntityWithAllTypes found = manager.find(EntityWithAllTypes.class, id);

    // Then
    assertThat(found.getPrimitiveByte()).isEqualTo((byte) 7);
    assertThat(found.getObjectByte()).isEqualTo((byte) 7);
    assertThat(found.getByteArray()).isEqualTo(bytes);
    assertThat(found.getByteBuffer()).isEqualTo(ByteBuffer.wrap(bytes));

    assertThat(found.isPrimitiveBool()).isTrue();
    assertThat(found.getObjectBool()).isTrue();

    assertThat(found.getDate()).isEqualTo(now);

    assertThat(found.getPrimitiveDouble()).isEqualTo(1.0d);
    assertThat(found.getObjectDouble()).isEqualTo(1.0d);
    assertThat(found.getBigDecimal()).isEqualTo(new BigDecimal(1.11));

    assertThat(found.getPrimitiveFloat()).isEqualTo(1.0f);
    assertThat(found.getObjectFloat()).isEqualTo(1.0f);

    assertThat(found.getInetAddress()).isEqualTo(inetAddress);

    assertThat(found.getBigInt()).isEqualTo(new BigInteger("10"));
    assertThat(found.getPrimitiveInt()).isEqualTo(10);
    assertThat(found.getObjectInt()).isEqualTo(10);

    assertThat(found.getPrimitiveLong()).isEqualTo(10L);
}

From source file:com.calamp.services.kinesis.events.writer.CalAmpEventWriter.java

/**
 * Uses the Kinesis client to send the event to the given stream.
 *
 * @param trade instance representing the stock trade
 * @param kinesisClient Amazon Kinesis client
 * @param streamName Name of stream /*from ww w . j  ava 2s.  c om*/
 */
public static void sendEvent(CalAmpEvent event, AmazonKinesis kinesisClient, String streamName) {
    byte[] bytes = event.toJsonAsBytes();
    // The bytes could be null if there is an issue with the JSON serialization by the Jackson JSON library.
    if (bytes == null) {
        LOG.warn("Could not get JSON bytes for stock trade");
        return;
    }

    LOG.info("Putting trade: " + event.toString());
    PutRecordRequest putRecord = new PutRecordRequest();
    putRecord.setStreamName(CalAmpParameters.unorderdStreamName);
    putRecord.setPartitionKey(String.valueOf(event.getMachineId()));
    putRecord.setData(ByteBuffer.wrap(bytes));

    //This is needed to guaranteed FIFO ordering per partitionKey
    if (prevSeqNum != null) {
        putRecord.setSequenceNumberForOrdering(prevSeqNum);
    }
    try {
        PutRecordResult res = kinesisClient.putRecord(putRecord);
        prevSeqNum = res.getSequenceNumber();
        Utils.lazyLog(putRecord, CalAmpParameters.writeLogName);
    } catch (AmazonClientException ex) {
        LOG.warn("Error sending record to Amazon Kinesis.", ex);
    }
}

From source file:io.druid.query.aggregation.hyperloglog.PreComputedHyperUniquesSerde.java

@Override
public ComplexMetricExtractor getExtractor() {
    return new ComplexMetricExtractor() {
        @Override/*w w w.  j a  v  a  2  s .co m*/
        public Class<HyperLogLogCollector> extractedClass() {
            return HyperLogLogCollector.class;
        }

        @Override
        public HyperLogLogCollector extractValue(InputRow inputRow, String metricName) {
            Object rawValue = inputRow.getRaw(metricName);

            if (rawValue == null) {
                return HyperLogLogCollector.makeLatestCollector();
            } else if (rawValue instanceof HyperLogLogCollector) {
                return (HyperLogLogCollector) rawValue;
            } else if (rawValue instanceof byte[]) {
                return HyperLogLogCollector.makeLatestCollector().fold(ByteBuffer.wrap((byte[]) rawValue));
            } else if (rawValue instanceof String) {
                return HyperLogLogCollector.makeLatestCollector()
                        .fold(ByteBuffer.wrap(Base64.decodeBase64((String) rawValue)));
            }

            throw new ISE("Object is not of a type[%s] that can be deserialized to HyperLogLog.",
                    rawValue.getClass());
        }
    };
}

From source file:io.undertow.server.handlers.encoding.RequestContentEncodingTestCase.java

@BeforeClass
public static void setup() {
    final EncodingHandler handler = new EncodingHandler(
            new ContentEncodingRepository().addEncodingHandler("deflate", new DeflateEncodingProvider(), 50)
                    .addEncodingHandler("gzip", new GzipEncodingProvider(), 60)).setNext(new HttpHandler() {
                        @Override
                        public void handleRequest(final HttpServerExchange exchange) throws Exception {
                            exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, message.length() + "");
                            exchange.getResponseSender().send(message, IoCallback.END_EXCHANGE);
                        }//from w  w  w.jav  a2 s  .c  om
                    });

    final HttpHandler decode = new RequestEncodingHandler(new HttpHandler() {
        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            exchange.getRequestReceiver().receiveFullBytes(new Receiver.FullBytesCallback() {
                @Override
                public void handle(HttpServerExchange exchange, byte[] message) {
                    exchange.getResponseSender().send(ByteBuffer.wrap(message));
                }
            });
        }
    }).addEncoding("deflate", InflatingStreamSourceConduit.WRAPPER).addEncoding("gzip",
            GzipStreamSourceConduit.WRAPPER);
    PathHandler pathHandler = new PathHandler();
    pathHandler.addPrefixPath("/encode", handler);
    pathHandler.addPrefixPath("/decode", decode);

    DefaultServer.setRootHandler(pathHandler);
}

From source file:com.pnf.plugin.pdf.XFAParser.java

public void parse(byte[] xmlContent) throws ParserConfigurationException, SAXException, IOException {
    CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
    decoder.onMalformedInput(CodingErrorAction.REPLACE);
    decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
    CharBuffer parsed = decoder.decode(ByteBuffer.wrap(xmlContent));

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();

    try (@SuppressWarnings("deprecation")
    InputStream is = new ReaderInputStream(new CharArrayReader(parsed.array()))) {
        parser.parse(is, xfa);//from w  w w.jav a2  s. c  om
    } catch (Exception e) {
        logger.catching(e);
        logger.error("Error while parsing XFA content");
    }
}

From source file:foss.filemanager.core.Utils.java

static byte[] encode(byte[] arr, Charset srcCharset, Charset dstCharset) {
    ByteBuffer inputBuffer = ByteBuffer.wrap(arr);
    CharBuffer data = srcCharset.decode(inputBuffer);
    ByteBuffer outputBuffer = dstCharset.encode(data);
    byte[] outputData = outputBuffer.array();

    return outputData;
}

From source file:com.guardtime.ksi.service.client.http.apache.ApacheHttpGetRequestFuture.java

public ByteBuffer getResult() throws KSIClientException, KSIProtocolException {
    InputStream inputStream = null;
    try {//from   www.  j  a va2s  .  c  o m
        HttpResponse response = future.get();
        int statusCode = response.getStatusLine().getStatusCode();
        String responseMessage = response.getStatusLine().getReasonPhrase();
        validateHttpResponse(statusCode, responseMessage);
        inputStream = response.getEntity().getContent();
        return ByteBuffer.wrap(Util.toByteArray(inputStream));
    } catch (InterruptedException e) {
        throw new KSIClientException("Getting KSI response failed", e);
    } catch (ExecutionException e) {
        throw new KSIClientException("Getting KSI response failed", e);
    } catch (IOException e) {
        throw new KSIClientException("Getting KSI response failed", e);
    } finally {
        Util.closeQuietly(inputStream);
    }
}

From source file:edu.umass.cs.gigapaxos.paxosutil.PaxosPacketDemultiplexerFast.java

private static PaxosPacket toPaxosPacket(byte[] bytes)
        throws UnsupportedEncodingException, UnknownHostException {
    assert (bytes != null);
    ByteBuffer bbuf = ByteBuffer.wrap(bytes);

    PaxosPacket.PaxosPacketType type = bbuf.getInt() == PaxosPacketType.PAXOS_PACKET.getInt()
            ? PaxosPacketType.getPaxosPacketType(bbuf.getInt())
            : null;//www  .ja v a2 s  .c  o m

    if (type == null)
        fatal(bytes);

    // bbuf = ByteBuffer.wrap(bytes);
    bbuf.rewind();

    PaxosPacket paxosPacket = null;
    switch (type) {
    case REQUEST:
        // log.info("before new RequestPacket(ByteBuffer)");
        paxosPacket = new RequestPacket(bbuf);
        // log.info("after new RequestPacket(ByteBuffer)");
        break;
    case ACCEPT:
        paxosPacket = new AcceptPacket(bbuf);
        break;
    case BATCHED_COMMIT:
        paxosPacket = new BatchedCommit(bbuf);
        break;
    case BATCHED_ACCEPT_REPLY:
        paxosPacket = new BatchedAcceptReply(bbuf);
        break;

    default:
        assert (false);
    }
    return paxosPacket;
}

From source file:CharsetDetector.java

private boolean identify(byte[] bytes, CharsetDecoder decoder) {
    try {/*from   ww  w .  j  a v  a  2 s .  c om*/
        decoder.decode(ByteBuffer.wrap(bytes));
    } catch (CharacterCodingException e) {
        return false;
    }
    return true;
}

From source file:com.nestedbird.util.UUIDConverter.java

/**
 * Converts a Base64 encoded string to a string represented UUID
 *
 * @param base64String Base64 Representation of the UUID
 * @return String represented UUID//from   w w w .  j  ava 2  s .  co m
 * @throws NullPointerException     String must not be null
 * @throws IllegalArgumentException String should be 22 characters long
 */
public static String fromBase64(final String base64String) {
    if (base64String == null)
        throw new NullPointerException("String cannot be null");
    if (base64String.length() != 22)
        throw new IllegalArgumentException("String should be 22 characters long");

    final byte[] bytes = Base64.decodeBase64(base64String);
    final ByteBuffer bb = ByteBuffer.wrap(bytes);
    final UUID uuid = new UUID(bb.getLong(), bb.getLong());
    return uuid.toString();
}