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:ru.jts_dev.common.tcp.ProtocolByteArrayLengthHeaderSerializer.java

@Override
protected int readHeader(InputStream inputStream) throws IOException {
    byte[] lengthPart = new byte[this.headerSize];
    try {//from  w ww  .  j a v a2 s .  c o m
        int status = read(inputStream, lengthPart, true);
        if (status < 0) {
            throw new SoftEndOfStreamException("Stream closed between payloads");
        }
        int messageLength;
        switch (this.headerSize) {
        case HEADER_SIZE_INT:
            messageLength = ByteBuffer.wrap(lengthPart).order(LITTLE_ENDIAN).getInt();
            if (messageLength < 0) {
                throw new IllegalArgumentException("Length header:" + messageLength + " is negative");
            }
            break;
        case HEADER_SIZE_UNSIGNED_BYTE:
            messageLength = ByteBuffer.wrap(lengthPart).order(LITTLE_ENDIAN).get() & 0xff;
            break;
        case HEADER_SIZE_UNSIGNED_SHORT:
            messageLength = ByteBuffer.wrap(lengthPart).order(LITTLE_ENDIAN).getShort() & 0xffff;
            break;
        default:
            throw new IllegalArgumentException("Bad header size:" + headerSize);
        }

        messageLength -= headerSize; // substract header size from data
        return messageLength;
    } catch (SoftEndOfStreamException e) {
        throw e;
    } catch (IOException | RuntimeException e) {
        publishEvent(e, lengthPart, -1);
        throw e;
    }
}

From source file:com.jim.im.broker.config.ImBrokerMessageListener.java

private PublishMessage createPublishMessage(ImMessage imMessage) throws UnsupportedEncodingException {
    PublishMessage publishMessage = new PublishMessage();
    publishMessage.setTopicName(imMessage.getTopicName());
    publishMessage.setQos(AbstractMessage.QOSType.MOST_ONE);
    ByteBuffer messageId = ByteBuffer.wrap(imMessage.getId().toString().getBytes());
    messageId.flip();//  w  w w.  j a v  a 2s.c  om
    publishMessage.setPayload(messageId);
    return publishMessage;
}

From source file:io.undertow.server.handlers.ReceiverTestCase.java

@BeforeClass
public static void setup() {
    HttpHandler testFullString = new HttpHandler() {
        @Override// w  ww. jav a 2s .  c  o  m
        public void handleRequest(final HttpServerExchange exchange) throws Exception {

            exchange.getRequestReceiver().receiveFullString(new Receiver.FullStringCallback() {
                @Override
                public void handle(HttpServerExchange exchange, String message) {
                    exchange.getResponseSender().send(message);
                }
            }, ERROR_CALLBACK);
        }
    };

    HttpHandler testPartialString = new HttpHandler() {
        @Override
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            final StringBuilder sb = new StringBuilder();
            exchange.getRequestReceiver().receivePartialString(new Receiver.PartialStringCallback() {
                @Override
                public void handle(HttpServerExchange exchange, String message, boolean last) {
                    sb.append(message);
                    if (last) {
                        exchange.getResponseSender().send(sb.toString());
                    }
                }
            }, ERROR_CALLBACK);
        }
    };

    HttpHandler testFullBytes = new HttpHandler() {
        @Override
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            exchange.getRequestReceiver().receiveFullBytes(new Receiver.FullBytesCallback() {
                @Override
                public void handle(HttpServerExchange exchange, byte[] message) {
                    exchange.getResponseSender().send(ByteBuffer.wrap(message));
                }
            }, ERROR_CALLBACK);
        }
    };

    HttpHandler testPartialBytes = new HttpHandler() {
        @Override
        public void handleRequest(final HttpServerExchange exchange) throws Exception {

            class CB implements Receiver.PartialBytesCallback, IoCallback {

                final Receiver receiver;
                final Sender sender;

                CB(Receiver receiver, Sender sender) {
                    this.receiver = receiver;
                    this.sender = sender;
                }

                @Override
                public void onComplete(HttpServerExchange exchange, Sender sender) {
                    receiver.resume();
                }

                @Override
                public void onException(HttpServerExchange exchange, Sender sender, IOException exception) {
                    exception.printStackTrace();
                    exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
                    exchange.endExchange();
                }

                @Override
                public void handle(HttpServerExchange exchange, byte[] message, boolean last) {
                    receiver.pause();
                    sender.send(ByteBuffer.wrap(message), last ? IoCallback.END_EXCHANGE : this);
                }
            }
            CB callback = new CB(exchange.getRequestReceiver(), exchange.getResponseSender());
            exchange.getRequestReceiver().receivePartialBytes(callback);
        }
    };
    final PathHandler handler = new PathHandler().addPrefixPath("/fullstring", testFullString)
            .addPrefixPath("/partialstring", testPartialString).addPrefixPath("/fullbytes", testFullBytes)
            .addPrefixPath("/partialbytes", testPartialBytes);
    DefaultServer.setRootHandler(new HttpHandler() {
        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            Deque<String> block = exchange.getQueryParameters().get("blocking");
            if (block != null) {
                exchange.startBlocking();
                exchange.dispatch(handler);
                return;
            }
            handler.handleRequest(exchange);
        }
    });
}

From source file:de.onyxbits.raccoon.appmgr.ExtractWorker.java

@Override
protected File doInBackground() throws Exception {
    ZipFile zip = new ZipFile(source);
    parseResourceTable();//from   ww w . ja  v  a2  s  .  co m
    if (filenames == null) {
        Enumeration<? extends ZipEntry> e = zip.entries();
        Vector<String> tmp = new Vector<String>();
        while (e.hasMoreElements()) {
            tmp.add(e.nextElement().getName());
        }
        filenames = tmp;
    }

    for (String filename : filenames) {
        ZipEntry entry = zip.getEntry(filename);
        InputStream in = zip.getInputStream(entry);
        OutputStream out = openDestination(filename);

        if (isBinaryXml(filename)) {
            XmlTranslator xmlTranslator = new XmlTranslator();
            ByteBuffer buffer = ByteBuffer.wrap(Utils.toByteArray(in));
            BinaryXmlParser binaryXmlParser = new BinaryXmlParser(buffer, resourceTable);
            binaryXmlParser.setLocale(Locale.getDefault());
            binaryXmlParser.setXmlStreamer(xmlTranslator);
            binaryXmlParser.parse();
            IOUtils.write(xmlTranslator.getXml(), out);
        } else {
            // Simply extract
            IOUtils.copy(in, out);
        }
        in.close();
        out.close();
    }

    zip.close();
    return dest;
}

From source file:com.google.identitytoolkit.GitkitClient.java

/**
 * Constructs a Gitkit client from a JSON config file
 *
 * @param configPath Path to JSON configuration file
 * @return Gitkit client//w  ww  .j a  v a2 s .c om
 */
public static GitkitClient createFromJson(String configPath) throws JSONException, IOException {
    JSONObject configData = new JSONObject(StandardCharsets.UTF_8
            .decode(ByteBuffer.wrap(Files.readAllBytes(Paths.get(configPath)))).toString());

    return new GitkitClient.Builder().setGoogleClientId(configData.getString("clientId"))
            .setServiceAccountEmail(configData.getString("serviceAccountEmail"))
            .setKeyStream(new FileInputStream(configData.getString("serviceAccountPrivateKeyFile")))
            .setWidgetUrl(configData.getString("widgetUrl")).setCookieName(configData.getString("cookieName"))
            .setServerApiKey(configData.optString("serverApiKey", null)).build();
}

From source file:com.nextdoor.bender.ipc.firehose.FirehoseTransportBufferBatch.java

@Override
public boolean add(InternalEvent ievent) throws IllegalStateException, IOException {
    byte[] record = serializer.serialize(ievent);

    /*//from w  w  w. j av  a2  s  .co  m
     * Restrict size of individual record
     */
    if (record.length > MAX_RECORD_SIZE) {
        throw new IOException(
                "serialized event is " + record.length + " larger than max of " + MAX_RECORD_SIZE);
    }

    /*
     * Write record if there's room in buffer
     */
    if (dataRecords.size() >= MAX_RECORDS) {
        logger.trace("hit record index max");
        throw new IllegalStateException("reached max payload size");
    } else {
        if (cos.getByteCount() + record.length < MAX_RECORD_SIZE) {
            cos.write(record);
            return true;
        }

        /*
         * If current record is full then flush buffer to a Firehose Record and create a new buffer
         */
        logger.trace("creating new datarecord");
        ByteBuffer data = ByteBuffer.wrap(baos.toByteArray());
        this.dataRecords.add(new Record().withData(data));
        baos.reset();
        cos.resetByteCount();
        cos.resetCount();

        /*
         * If we hit the max number of Firehose Records (4) then notify IPC service that this buffer
         * needs to be sent.
         */
        if (dataRecords.size() >= MAX_RECORDS) {
            logger.trace("hit record index max");
            throw new IllegalStateException("reached max payload size");
        }

        /*
         * Otherwise write the record to the empty internal buffer
         */
        cos.write(record);
    }

    return true;
}

From source file:oz.hadoop.yarn.api.core.LocalApplicationLaunchTests.java

@Test //(timeout=10000)
public void validateWithReplyListener() throws Exception {
    final AtomicInteger repliesCounter = new AtomicInteger();
    YarnApplication<DataProcessor> yarnApplication = YarnAssembly
            .forApplicationContainer(SimpleEchoContainer.class).containerCount(2).memory(512)
            .withApplicationMaster().maxAttempts(2).priority(2).build("sample-yarn-application");
    yarnApplication.registerReplyListener(new ContainerReplyListener() {
        @Override/*from  www.j a  va 2s  .c  o  m*/
        public void onReply(ByteBuffer replyData) {
            repliesCounter.incrementAndGet();
        }
    });

    DataProcessor dataProcessor = yarnApplication.launch();

    assertEquals(2, dataProcessor.containers());

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < dataProcessor.containers(); j++) {
            dataProcessor.process(ByteBuffer.wrap(("Hello Yarn!-" + i).getBytes()));
        }
    }
    assertTrue(yarnApplication.isRunning());
    yarnApplication.shutDown();
    assertEquals(repliesCounter.get(), dataProcessor.completedSinceStart());
    assertFalse(yarnApplication.isRunning());
}

From source file:com.rackspacecloud.blueflood.io.serializers.astyanax.EnumRollupSerializationTest.java

@Test
public void testEnumV1RoundTrip() throws IOException {
    BluefloodEnumRollup e0 = new BluefloodEnumRollup().withEnumValue("enumValue1", 1L)
            .withEnumValue("enumValue2", 5L);
    BluefloodEnumRollup e1 = new BluefloodEnumRollup().withEnumValue(
            "t4.enum.abcdefg.hijklmnop.qrstuvw.xyz.ABCDEFG.HIJKLMNOP.QRSTUVW.XYZ.abcdefg.hijklmnop.qrstuvw.xyz.met",
            34454722343L)// w w w. j av  a 2  s  . c o  m
            .withEnumValue(
                    "t5.enum.abcdefg.hijklmnop.qrstuvw.xyz.ABCDEFG.HIJKLMNOP.QRSTUVW.XYZ.abcdefg.hijklmnop.qrstuvw.xyz.met",
                    34454722343L)
            .withEnumValue("enumValue2", 10L);
    BluefloodEnumRollup e2 = new BluefloodEnumRollup().withEnumValue("enumValue1", 1L)
            .withEnumValue("enumValue1", 1L);
    BluefloodEnumRollup er = BluefloodEnumRollup
            .buildRollupFromEnumRollups(Rollups.asPoints(BluefloodEnumRollup.class, 0, 300, e0, e1, e2));
    Assert.assertEquals(4, er.getCount());
    Map<Long, Long> map = er.getHashedEnumValuesWithCounts();
    Assert.assertTrue(map.get((long) "enumValue1".hashCode()) == 3L);
    Assert.assertTrue(map.get((long) "enumValue2".hashCode()) == 15L);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos.write(Base64.encodeBase64(Serializers.enumRollupInstance.toByteBuffer(e0).array()));
    baos.write("\n".getBytes());
    baos.write(Base64.encodeBase64(Serializers.enumRollupInstance.toByteBuffer(e1).array()));
    baos.write("\n".getBytes());
    baos.write(Base64.encodeBase64(Serializers.enumRollupInstance.toByteBuffer(e2).array()));
    baos.write("\n".getBytes());
    baos.write(Base64.encodeBase64(Serializers.enumRollupInstance.toByteBuffer(er).array()));
    baos.write("\n".getBytes());
    baos.close();

    BufferedReader reader = new BufferedReader(
            new InputStreamReader(new ByteArrayInputStream(baos.toByteArray())));

    ByteBuffer bb = ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes()));
    BluefloodEnumRollup ee0 = Serializers.serializerFor(BluefloodEnumRollup.class).fromByteBuffer(bb);
    Assert.assertEquals(e0, ee0);

    bb = ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes()));
    BluefloodEnumRollup ee1 = Serializers.serializerFor(BluefloodEnumRollup.class).fromByteBuffer(bb);
    Assert.assertEquals(e1, ee1);

    bb = ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes()));
    BluefloodEnumRollup ee2 = Serializers.serializerFor(BluefloodEnumRollup.class).fromByteBuffer(bb);
    Assert.assertEquals(e2, ee2);

    bb = ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes()));
    BluefloodEnumRollup ee3 = Serializers.serializerFor(BluefloodEnumRollup.class).fromByteBuffer(bb);
    Assert.assertEquals(er, ee3);

    Assert.assertFalse(ee0.equals(ee1));
}

From source file:com.rackspacecloud.blueflood.io.serializers.HistogramSerializationTest.java

@Test
public void testBadSerializationVersion() {
    byte[] buf = new byte[] { 99, 99 }; // hopefully we won't have 99 different serialization versions.
    try {/*from  w  w w.  j  av  a 2  s  .c  om*/
        HistogramSerializer.get().fromByteBuffer(ByteBuffer.wrap(buf));
        Assert.fail(String.format("Should have errored out. Such a version doesn't exist for histogram."));
    } catch (RuntimeException ex) {
        Assert.assertTrue(ex.getCause().getMessage().startsWith("Unexpected serialization version"));
    }
}

From source file:org.bubblecloud.vr4java.rpc.RpcEndpoint.java

public void start() throws IOException, InterruptedException {
    synchronized (session) {
        final byte[] requestBytes = sealer.getHandshake(true);
        LOGGER.trace(sealer.getIdentity() + " sent request: " + (byte) requestBytes[1]);
        session.getBasicRemote().sendBinary(ByteBuffer.wrap(requestBytes));
        session.wait(RPC_TIMEOUT_MILLIS);
        if (responseBytes == null) {
            throw new IOException("RPC handshake timeout.");
        }//from ww  w  . j a  v  a2s .c om
        sealer.verifyHandshake(responseBytes);
    }
}