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:zipkin.server.brave.BraveConfiguration.java

/** This gets the lanIP without trying to lookup its name. */
// http://stackoverflow.com/questions/8765578/get-local-ip-address-without-connecting-to-the-internet
@Bean//from  w  w  w .  j a  va 2 s  .  co m
@Scope
Endpoint local(@Value("${server.port:9411}") int port) {
    Endpoint.Builder builder = Endpoint.builder().serviceName("zipkin-server").port(port == -1 ? 0 : port);
    try {
        byte[] address = Collections.list(NetworkInterface.getNetworkInterfaces()).stream()
                .flatMap(i -> Collections.list(i.getInetAddresses()).stream())
                .filter(ip -> ip.isSiteLocalAddress()).findAny().get().getAddress();
        if (address.length == 4) {
            builder.ipv4(ByteBuffer.wrap(address).getInt());
        } else if (address.length == 16) {
            builder.ipv6(address);
        }
    } catch (Exception ignored) {
        builder.ipv4(127 << 24 | 1);
    }
    return builder.build();
}

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

@Test
public void testSerializerDeserializerV1() throws Exception {
    BluefloodGaugeRollup gauge1 = BluefloodGaugeRollup.buildFromRawSamples(
            Rollups.asPoints(SimpleNumber.class, System.currentTimeMillis(), 300, new SimpleNumber(10L)));
    BluefloodGaugeRollup gauge2 = BluefloodGaugeRollup.buildFromRawSamples(Rollups.asPoints(SimpleNumber.class,
            System.currentTimeMillis() - 100, 300, new SimpleNumber(1234567L)));
    BluefloodGaugeRollup gauge3 = BluefloodGaugeRollup.buildFromRawSamples(Rollups.asPoints(SimpleNumber.class,
            System.currentTimeMillis() - 200, 300, new SimpleNumber(10.4D)));
    BluefloodGaugeRollup gaugesRollup = BluefloodGaugeRollup.buildFromGaugeRollups(Rollups
            .asPoints(BluefloodGaugeRollup.class, System.currentTimeMillis(), 300, gauge1, gauge2, gauge3));
    Assert.assertEquals(3, gaugesRollup.getCount());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos.write(Base64.encodeBase64(new NumericSerializer.GaugeRollupSerializer().toByteBuffer(gauge1).array()));
    baos.write("\n".getBytes());
    baos.write(Base64.encodeBase64(new NumericSerializer.GaugeRollupSerializer().toByteBuffer(gauge2).array()));
    baos.write("\n".getBytes());
    baos.write(Base64.encodeBase64(new NumericSerializer.GaugeRollupSerializer().toByteBuffer(gauge3).array()));
    baos.write("\n".getBytes());
    baos.write(Base64//w w w. ja v  a 2  s . c  om
            .encodeBase64(new NumericSerializer.GaugeRollupSerializer().toByteBuffer(gaugesRollup).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()));
    BluefloodGaugeRollup deserializedGauge1 = NumericSerializer.serializerFor(BluefloodGaugeRollup.class)
            .fromByteBuffer(bb);
    Assert.assertEquals(gauge1, deserializedGauge1);

    bb = ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes()));
    BluefloodGaugeRollup deserializedGauge2 = NumericSerializer.serializerFor(BluefloodGaugeRollup.class)
            .fromByteBuffer(bb);
    Assert.assertEquals(gauge2, deserializedGauge2);

    bb = ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes()));
    BluefloodGaugeRollup deserializedGauge3 = NumericSerializer.serializerFor(BluefloodGaugeRollup.class)
            .fromByteBuffer(bb);
    Assert.assertEquals(gauge3, deserializedGauge3);

    bb = ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes()));
    BluefloodGaugeRollup deserializedGauge4 = NumericSerializer.serializerFor(BluefloodGaugeRollup.class)
            .fromByteBuffer(bb);
    Assert.assertEquals(gaugesRollup, deserializedGauge4);

    Assert.assertFalse(deserializedGauge1.equals(deserializedGauge2));
}

From source file:edu.smu.tspell.wordnet.impl.RandomAccessReader.java

/**
 * Constructs an instance of this class, specifying the file that is to
 * be read.//from  ww w.ja va2 s .c  o m
 * 
 * @param  file File that is to be read.
 * @throws FileNotFoundException The specified file does not exist.
 */
protected RandomAccessReader(String name) throws IOException {
    super();
    InputStream stream = getClass().getResourceAsStream(name);
    if (stream == null) {
        throw new IOException("Cannot open resource: " + name);
    }
    fileSize = stream.available();
    byte[] buffer = IOUtils.toByteArray(stream);
    int read = buffer.length;
    if (read != fileSize) {
        throw new IOException("Unsuccessful read from: " + name + " " + read + " instead of " + fileSize);
    }
    accessor = ByteBuffer.wrap(buffer);
    filePointer = accessor.position();
    stream.close();
}

From source file:mastermind.RandomGenerator.java

public long getLongSeed() {
    if (isValid) {
        byte[] seed = secureRandom.generateSeed(NUM_SEED_BYTES);
        ByteBuffer byteBuffer = ByteBuffer.wrap(seed);
        return byteBuffer.getLong();
    } else {/* w  w  w . j  av a2s .com*/
        return -1;
    }
}

From source file:org.apache.asterix.experiment.action.derived.RunSQLPPFileAction.java

@Override
public void doPerform() throws Exception {
    FileOutputStream csvFileOut = new FileOutputStream(csvFilePath.toFile());
    PrintWriter printer = new PrintWriter(csvFileOut, true);
    try {//from   w  w  w. j  a  v a2  s .  c o m
        if (aqlFilePath.toFile().isDirectory()) {
            for (File f : aqlFilePath.toFile().listFiles()) {
                queriesToRun.add(f.toPath());
            }
        } else {
            queriesToRun.add(aqlFilePath);
        }

        for (Path p : queriesToRun) {
            String sqlpp = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(Files.readAllBytes(p))).toString();
            String uri = MessageFormat.format(REST_URI_TEMPLATE, restHost, String.valueOf(restPort));
            HttpPost post = new HttpPost(uri);
            post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
            post.setEntity(new StringEntity(sqlpp, StandardCharsets.UTF_8));
            long start = System.currentTimeMillis();
            HttpResponse resp = httpClient.execute(post);
            HttpEntity entity = resp.getEntity();
            if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                throw new HttpException("Query returned error" + EntityUtils.toString(entity));
            }
            EntityUtils.consume(entity);
            long end = System.currentTimeMillis();
            long wallClock = end - start;
            String currLine = p.getFileName().toString() + ',' + wallClock;
            System.out.println(currLine);
            printer.print(currLine + '\n');
        }
    } finally {
        printer.close();
    }
}

From source file:com.ah.be.ls.processor2.TxProcessor.java

public void run() throws Exception {
    byte[] sendData = buildPacket();

    Header sendHeader = new Header();
    sendHeader.setPacketType(getPacketType());
    sendHeader.setProtocolVersion(CommConst.Protocol_Version);
    sendHeader.setLength(sendData.length);
    sendHeader.setSecretFlag(true);/*  w  w w  .  ja v  a  2 s.c  o m*/

    byte[] sendBytes = PacketUtil.join(sendHeader, sendData);

    HttpCommunication hc = new HttpCommunication(getLsMessageServerURL());
    initHttpProxySetting(hc);

    byte[] recvBytes = hc.sendAndReceive(sendBytes);

    if (recvBytes.length > 0) {
        if (recvBytes.length == 1) {
            byte a = recvBytes[0];
            log.warn("TxProcessor,result=" + a + ", no this packet type:" + this.packetType);
            throw new Exception("TxProcessor,no this transaction");
        } else {
            Header recvHeader = new Header();
            byte[] recvData = PacketUtil.split(ByteBuffer.wrap(recvBytes), recvHeader);
            if ((recvHeader.getType() != sendHeader.getType() + 1)
                    && (recvHeader.getType() != CommConst.PacketType_Error_Response)) {
                log.error("TxProcessor,response header type mismatch! require " + (sendHeader.getType() + 1)
                        + " but " + recvHeader.getType() + "!");
                throw new Exception("TxProcessor,response error");
            }
            parsePacket(recvHeader.getType(), recvData);
        }
    } else {
        throw new Exception("TxProcessor,no response");
    }
}

From source file:com.amazonaws.services.kinesis.connectors.s3.S3ManifestEmitter.java

@Override
public List<byte[]> emit(final UnmodifiableBuffer<byte[]> buffer) throws IOException {
    // Store the contents of buffer.getRecords because superclass will
    // clear the buffer on success
    List<byte[]> failed = super.emit(buffer);
    // calls S3Emitter to write objects to Amazon S3
    if (!failed.isEmpty()) {
        return buffer.getRecords();
    }//from  ww  w.  ja  v  a2 s  .c  o m
    String s3File = getS3FileName(buffer.getFirstSequenceNumber(), buffer.getLastSequenceNumber());
    // wrap the name of the Amazon S3 file as the record data
    ByteBuffer data = ByteBuffer.wrap(s3File.getBytes());
    // Put the list of file names to the manifest Amazon Kinesis stream
    PutRecordRequest putRecordRequest = new PutRecordRequest();
    putRecordRequest.setData(data);
    putRecordRequest.setStreamName(manifestStream);
    // Use constant partition key to ensure file order
    putRecordRequest.setPartitionKey(manifestStream);
    try {
        kinesisClient.putRecord(putRecordRequest);
        LOG.info("S3ManifestEmitter emitted record downstream: " + s3File);
        return Collections.emptyList();
    } catch (Exception e) {
        LOG.error(e);
        return buffer.getRecords();
    }
}

From source file:com.streamsets.pipeline.stage.it.AvroToParquetHiveIT.java

@Parameterized.Parameters(name = "type({0})")
public static Collection<Object[]> data() throws Exception {
    return Arrays.asList(new Object[][] {
            // Primitive types
            { "\"boolean\"", true, true, "BOOLEAN", Types.BOOLEAN, "0" },
            { "\"int\"", Integer.MIN_VALUE, Integer.MIN_VALUE, "INT", Types.INTEGER, "0" },
            { "\"long\"", Long.MAX_VALUE, Long.MAX_VALUE, "BIGINT", Types.BIGINT, "0" },
            // From some reason type is FLOAT, but returned object is double
            { "\"float\"", Float.NaN, Double.NaN, "FLOAT", Types.FLOAT, "0" },
            { "\"double\"", Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, "DOUBLE", Types.DOUBLE, "0" },
            { "\"bytes\"", ByteBuffer.wrap(new byte[] { (byte) 0x00, (byte) 0xFF }),
                    new byte[] { (byte) 0x00, (byte) 0xFF }, "BINARY", Types.BINARY, "1.0" },
            { "\"string\"", new Utf8("StreamSets"), "StreamSets", "STRING", Types.VARCHAR, "1.0" },

            // Complex types are skipped for now

            // Logical types
            { DECIMAL.toString(), ByteBuffer.wrap(new byte[] { (byte) 0x0F }), new BigDecimal("2"), "DECIMAL",
                    Types.DECIMAL, "0" },
            { DATE.toString(), 17039, new java.sql.Date(116, 7, 26), "DATE", Types.DATE, "1.2" }, });
}

From source file:com.sm.store.Utils.java

public static void addOneLong(Value value) {
    ByteBuffer buf = ByteBuffer.wrap((byte[]) value.getData());
    long k = buf.getLong() + 1;
    byte[] data = putLong(k);
    value.setData(data);/*from w w w.  ja v  a2  s . c o  m*/
    value.setVersion(value.getVersion() + 1);
}

From source file:zipkin.autoconfigure.storage.mysql.brave.TraceZipkinMySQLStorageAutoConfiguration.java

/** Attach the IP of the remote datasource, knowing that DNS may invalidate this */
@Bean/*  ww  w. j  a va 2  s .  c  o  m*/
@Qualifier("mysql")
Endpoint mysql() throws UnknownHostException {
    int ipv4 = ByteBuffer.wrap(InetAddress.getByName(mysql.getHost()).getAddress()).getInt();
    return Endpoint.builder().serviceName("mysql").ipv4(ipv4).port(mysql.getPort()).build();
}