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:reactor.ipc.netty.http.client.PostAndGetTests.java

private void get(String path, SocketAddress address) {
    try {//from ww w.ja v a2s . c  om
        StringBuilder request = new StringBuilder().append(String.format("GET %s HTTP/1.1\r\n", path))
                .append("Connection: Keep-Alive\r\n").append("\r\n");
        java.nio.channels.SocketChannel channel = java.nio.channels.SocketChannel.open(address);
        System.out.println(String.format("get: request >> [%s]", request.toString()));
        channel.write(ByteBuffer.wrap(request.toString().getBytes()));
        ByteBuffer buf = ByteBuffer.allocate(4 * 1024);
        while (channel.read(buf) > -1) {
        }
        String response = new String(buf.array());
        System.out.println(String.format("get: << Response: %s", response));
        channel.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.tinspx.util.io.ChannelSourceTest.java

@Test
public void testWrap() throws IOException {
    ByteSourceTests.testByteSource(ChannelSource.of(ByteSource.wrap(INPUT)), INPUT);
    ByteSourceTests.testByteSource(ChannelSource.of(Forced.byteSource(ChannelSource.of(INPUT))), INPUT);
    ByteSourceTests.testByteSource(// www.j a  v  a 2  s.c  om
            ChannelSource.of(Forced.byteSource(new ByteSourceTests.ForcedByteArray(INPUT))), INPUT);
    ByteSourceTests.testByteSource(
            ChannelSource.of(Forced.byteSource(ChannelSource.of(ByteBuffer.wrap(INPUT)))), INPUT);
    ByteSourceTests.testByteSource(
            ChannelSource.of(Forced.byteSource(ChannelSource.of(ByteBuffer.wrap(INPUT).asReadOnlyBuffer()))),
            INPUT);
}

From source file:c5db.tablet.tabletCreationBehaviors.RootTabletLeaderBehavior.java

private void createLeaderLessMetaEntryInRoot(Region region, List<Long> pickedPeers) throws IOException {
    org.apache.hadoop.hbase.TableName hbaseDatabaseName = SystemTableNames.metaTableName();
    ByteBuffer hbaseNameSpace = ByteBuffer.wrap(hbaseDatabaseName.getNamespace());
    ByteBuffer hbaseTableName = ByteBuffer.wrap(hbaseDatabaseName.getQualifier());
    TableName tableName = new TableName(hbaseNameSpace, hbaseTableName);

    byte[] initialMetaRockeyInRoot = Bytes.add(TabletNameHelpers.toBytes(tableName), SystemTableNames.sep,
            new byte[0]);
    Put put = new Put(initialMetaRockeyInRoot);

    RegionInfo regionInfo = new RegionInfo(1, tableName, pickedPeers, 0l, // This signifies that we haven't picked the leader
            ByteBuffer.wrap(new byte[0]), ByteBuffer.wrap(new byte[0]), true, false);

    put.add(HConstants.CATALOG_FAMILY, HConstants.REGIONINFO_QUALIFIER,
            ProtobufIOUtil.toByteArray(regionInfo, RegionInfo.getSchema(), LinkedBuffer.allocate(512)));

    boolean processed = region.mutate(ProtobufUtil.toMutation(MutationProto.MutationType.PUT, put),
            new Condition());
    if (!processed) {
        throw new IOException(
                "Unable to mutate root and thus we can't properly run root tablet leader behavior");
    }//  ww  w .j a  v  a  2  s  .co  m
}

From source file:com.sm.message.Header.java

public static Header toHeader(byte[] data) {
    ByteBuffer buf = ByteBuffer.wrap(data);
    byte release = buf.get();
    long version = buf.getLong();
    long node = buf.getLong();
    byte[] n = new byte[data.length - FIRST];
    buf.get(n);/*  w  w  w.j  a v  a 2  s.  c  o m*/
    try {
        String name = new String(n, "UTF-8");
        return new Header(name, version, release, node);
    } catch (UnsupportedEncodingException ex) {
        throw new RuntimeException(ex.getMessage());
    }

}

From source file:com.yahoo.yqlplus.engine.tools.YQLPlusRun.java

@SuppressWarnings("unchecked")
public int run(CommandLine command) throws Exception {
    String script = null;//from   ww  w  .  jav  a2s . co m
    String filename = null;
    if (command.hasOption("command")) {
        script = command.getOptionValue("command");
        filename = "<command line>";
    }
    List<String> scriptAndArgs = (List<String>) command.getArgList();
    if (filename == null && scriptAndArgs.size() < 1) {
        System.err.println("No script specified.");
        return -1;
    } else if (script == null) {
        filename = scriptAndArgs.get(0);
        Path scriptPath = Paths.get(filename);
        if (!Files.isRegularFile(scriptPath)) {
            System.err.println(scriptPath + " is not a file.");
            return -1;
        }
        script = Charsets.UTF_8.decode(ByteBuffer.wrap(Files.readAllBytes(scriptPath))).toString();
    }
    List<String> paths = Lists.newArrayList();
    if (command.hasOption("path")) {
        paths.addAll(Arrays.asList(command.getOptionValues("path")));
    }
    // TODO: this isn't going to be very interesting without some sources
    Injector injector = Guice.createInjector(new JavaEngineModule());
    YQLPlusCompiler compiler = injector.getInstance(YQLPlusCompiler.class);
    CompiledProgram program = compiler.compile(script);
    if (command.hasOption("source")) {
        program.dump(System.out);
        return 0;
    }
    // TODO: read command line arguments to pass to program
    ExecutorService outputThreads = Executors.newSingleThreadExecutor();
    ProgramResult result = program.run(Maps.<String, Object>newHashMap(), true);
    for (String name : result.getResultNames()) {
        final ListenableFuture<YQLResultSet> future = result.getResult(name);
        future.addListener(new Runnable() {
            @Override
            public void run() {
                try {
                    YQLResultSet resultSet = future.get();
                    System.out.println(new String((byte[]) resultSet.getResult()));
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }

            }
        }, outputThreads);
    }
    Future<TraceRequest> done = result.getEnd();
    try {
        done.get(10000L, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (ExecutionException | TimeoutException e) {
        e.printStackTrace();
    }
    outputThreads.awaitTermination(1L, TimeUnit.SECONDS);
    return 0;
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.por.PORFileReaderSpi.java

@Override
public boolean canDecodeInput(Object source) throws IOException {
    if (!(source instanceof BufferedInputStream)) {
        return false;
    }/*from   w  w  w.  java2 s .  c  o m*/
    if (source == null) {
        throw new IllegalArgumentException("source == null!");
    }
    BufferedInputStream stream = (BufferedInputStream) source;
    dbgLog.fine("applying the por test\n");

    byte[] b = new byte[POR_HEADER_SIZE];

    if (stream.markSupported()) {
        stream.mark(0);
    }

    int nbytes = stream.read(b, 0, POR_HEADER_SIZE);

    //printHexDump(b, "hex dump of the byte-array");

    if (nbytes == 0) {
        throw new IOException();
    } else if (nbytes < 491) {
        // size test
        dbgLog.fine("this file is NOT spss-por type");
        return false;
    }

    if (stream.markSupported()) {
        stream.reset();
    }

    boolean DEBUG = false;

    //windows [0D0A]=>   [1310] = [CR/LF]
    //unix    [0A]  =>   [10]
    //mac     [0D]  =>   [13]
    // 3char  [0D0D0A]=> [131310] spss for windows rel 15
    // expected results
    // unix    case: [0A]   : [80], [161], [242], [323], [404], [485]
    // windows case: [0D0A] : [81], [163], [245], [327], [409], [491]
    //  : [0D0D0A] : [82], [165], [248], [331], [414], [495]

    // convert b into a ByteBuffer

    ByteBuffer buff = ByteBuffer.wrap(b);
    byte[] nlch = new byte[36];
    int pos1;
    int pos2;
    int pos3;
    int ucase = 0;
    int wcase = 0;
    int mcase = 0;
    int three = 0;
    int nolines = 6;
    int nocols = 80;
    for (int i = 0; i < nolines; ++i) {
        int baseBias = nocols * (i + 1);
        // 1-char case
        pos1 = baseBias + i;
        buff.position(pos1);
        dbgLog.finer("\tposition(1)=" + buff.position());
        int j = 6 * i;
        nlch[j] = buff.get();

        if (nlch[j] == 10) {
            ucase++;
        } else if (nlch[j] == 13) {
            mcase++;
        }

        // 2-char case
        pos2 = baseBias + 2 * i;
        buff.position(pos2);
        dbgLog.finer("\tposition(2)=" + buff.position());

        nlch[j + 1] = buff.get();
        nlch[j + 2] = buff.get();

        // 3-char case
        pos3 = baseBias + 3 * i;
        buff.position(pos3);
        dbgLog.finer("\tposition(3)=" + buff.position());

        nlch[j + 3] = buff.get();
        nlch[j + 4] = buff.get();
        nlch[j + 5] = buff.get();

        dbgLog.finer(i + "-th iteration position =" + nlch[j] + "\t" + nlch[j + 1] + "\t" + nlch[j + 2]);
        dbgLog.finer(i + "-th iteration position =" + nlch[j + 3] + "\t" + nlch[j + 4] + "\t" + nlch[j + 5]);

        if ((nlch[j + 3] == 13) && (nlch[j + 4] == 13) && (nlch[j + 5] == 10)) {
            three++;
        } else if ((nlch[j + 1] == 13) && (nlch[j + 2] == 10)) {
            wcase++;
        }

        buff.rewind();
    }
    if (three == nolines) {
        dbgLog.fine("0D0D0A case");
        windowsNewLine = false;
    } else if ((ucase == nolines) && (wcase < nolines)) {
        dbgLog.fine("0A case");
        windowsNewLine = false;
    } else if ((ucase < nolines) && (wcase == nolines)) {
        dbgLog.fine("0D0A case");
    } else if ((mcase == nolines) && (wcase < nolines)) {
        dbgLog.fine("0D case");
        windowsNewLine = false;
    }

    buff.rewind();
    int PORmarkPosition = POR_MARK_POSITION_DEFAULT;
    if (windowsNewLine) {
        PORmarkPosition = PORmarkPosition + 5;
    } else if (three == nolines) {
        PORmarkPosition = PORmarkPosition + 10;
    }

    byte[] pormark = new byte[8];
    buff.position(PORmarkPosition);
    buff.get(pormark, 0, 8);
    String pormarks = new String(pormark);

    dbgLog.fine(
            "pormark[hex: 53 50 53 53 50 4F 52 54 == SPSSPORT] =>" + new String(Hex.encodeHex(pormark)) + "<-");

    if (pormarks.equals(POR_MARK)) {
        dbgLog.fine("this file is spss-por type");
        return true;
    } else {
        dbgLog.fine("this file is NOT spss-por type");
    }
    return false;
}

From source file:com.lhings.java.utils.ByteMan.java

public static byte[] toByteArray(double value) {
    byte[] bytes = new byte[8];
    ByteBuffer.wrap(bytes).putDouble(value);
    return bytes;
}

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

@Override
public void close() {
    if (this.cos.getByteCount() != 0 && this.dataRecords.size() < MAX_RECORDS) {
        logger.trace("flushing remainder of buffer");
        ByteBuffer data = ByteBuffer.wrap(baos.toByteArray());
        this.dataRecords.add(new Record().withData(data));
    }/*from   www  . jav  a  2 s . co m*/

    try {
        this.baos.close();
    } catch (IOException e) {
    }
}

From source file:com.liveramp.commons.util.BytesUtils.java

public static ByteBuffer hexStringToBytes(String hexString) {
    hexString = hexString.replaceAll("\\W+", "");
    if (hexString.length() % 2 != 0) {
        throw new RuntimeException("Input string's size must be even.");
    }/*  ww  w. j a v a 2s . c  o m*/
    byte[] result = new byte[hexString.length() / 2];
    for (int i = 0; i < hexString.length(); i += 2) {
        result[i / 2] = (byte) Integer.valueOf(hexString.substring(i, i + 2), 16).intValue();
    }
    return ByteBuffer.wrap(result);
}