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:gov.nist.appvet.toolmgr.ToolServiceAdapter.java

public static String getHtmlReportString(String reportPath, AppInfo appInfo) {
    byte[] encoded = null;
    try {//from  ww w.j  a v a2s .c  om
        encoded = Files.readAllBytes(Paths.get(reportPath));
        return Charset.defaultCharset().decode(ByteBuffer.wrap(encoded)).toString();
    } catch (final IOException e) {
        appInfo.log.error(e.getMessage());
        return null;
    } finally {
        encoded = null;
    }
}

From source file:edu.umn.cs.spatialHadoop.core.OGCShape.java

@Override
public void readFields(DataInput in) throws IOException {
    int size = in.readInt();
    byte[] bytes = new byte[size];
    in.readFully(bytes);/*from w ww  . j av a  2s  . c  o  m*/
    geom = OGCGeometry.fromBinary(ByteBuffer.wrap(bytes));
    size = in.readInt();
    if (size == -1) {
        extra = null;
    } else {
        bytes = new byte[size];
        in.readFully(bytes);
        extra = new String(bytes);
    }
}

From source file:com.ebay.jetstream.application.dataflows.VisualDataFlow.java

public ByteBuffer getAsByteArray(URL url) throws IOException {
    URLConnection connection = url.openConnection();
    InputStream in = connection.getInputStream();
    int contentLength = connection.getContentLength();
    ByteArrayOutputStream tmpOut;

    if (contentLength != -1) {
        tmpOut = new ByteArrayOutputStream(contentLength);
    } else {/*w  ww.  ja v  a 2 s .c  om*/
        tmpOut = new ByteArrayOutputStream(16384);
    }

    byte[] buf = new byte[BUF];
    while (true) {
        int len = in.read(buf);
        if (len == -1) {
            break;
        }
        tmpOut.write(buf, 0, len);
    }
    in.close();
    tmpOut.close();
    byte[] array = tmpOut.toByteArray();
    return ByteBuffer.wrap(array);
}

From source file:com.almende.eve.transport.ws.WsServerTransport.java

@Override
public void send(final URI receiverUri, final byte[] message, final String tag) throws IOException {
    if (remotes.containsKey(receiverUri)) {
        final Async remote = remotes.get(receiverUri);
        remote.sendBinary(ByteBuffer.wrap(message));
        remote.flushBatch();/*  ww  w  .j a  v a 2 s . co  m*/
    } else {
        throw new IOException("Remote: " + receiverUri.toASCIIString() + " is currently not connected.");
    }
}

From source file:ffx.xray.CCP4MapFilter.java

/**
 * {@inheritDoc}//from   w w  w.  j a  v  a  2s. c o  m
 */
@Override
public Crystal getCrystal(String filename, CompositeConfiguration properties) {
    int imapdata;
    int sg = -1;
    double cella = -1.0;
    double cellb = -1.0;
    double cellc = -1.0;
    double cellalpha = -1.0;
    double cellbeta = -1.0;
    double cellgamma = -1.0;

    ByteOrder b = ByteOrder.nativeOrder();

    FileInputStream fis;
    DataInputStream dis;

    // first determine byte order of file versus system
    try {
        fis = new FileInputStream(filename);
        dis = new DataInputStream(fis);

        dis.skipBytes(212);
        byte bytes[] = new byte[4];
        dis.read(bytes, 0, 4);
        ByteBuffer bb = ByteBuffer.wrap(bytes);

        imapdata = bb.order(ByteOrder.BIG_ENDIAN).getInt();
        String stampstr = Integer.toHexString(imapdata);
        // System.out.println("stamp: " + stampstr);
        switch (stampstr.charAt(0)) {
        case '1':
        case '3':
            if (b.equals(ByteOrder.LITTLE_ENDIAN)) {
                b = ByteOrder.BIG_ENDIAN;
            }
            break;
        case '4':
            if (b.equals(ByteOrder.BIG_ENDIAN)) {
                b = ByteOrder.LITTLE_ENDIAN;
            }
            break;
        }
        fis.close();
    } catch (Exception e) {
        String message = "Fatal exception reading CCP4 map.\n";
        logger.log(Level.SEVERE, message, e);
        System.exit(-1);
    }

    try {
        fis = new FileInputStream(filename);
        dis = new DataInputStream(fis);

        dis.skipBytes(40);
        byte bytes[] = new byte[80];
        dis.read(bytes, 0, 80);
        ByteBuffer bb = ByteBuffer.wrap(bytes);

        cella = bb.order(b).getFloat();
        cellb = bb.order(b).getFloat();
        cellc = bb.order(b).getFloat();
        cellalpha = bb.order(b).getFloat();
        cellbeta = bb.order(b).getFloat();
        cellgamma = bb.order(b).getFloat();

        for (int i = 0; i < 3; i++) {
            bb.order(b).getInt();
        }
        for (int i = 0; i < 3; i++) {
            bb.order(b).getFloat();
        }

        sg = bb.order(b).getInt();
        fis.close();
    } catch (Exception e) {
        String message = "Fatal exception reading CCP4 map.\n";
        logger.log(Level.SEVERE, message, e);
        System.exit(-1);
    }

    return new Crystal(cella, cellb, cellc, cellalpha, cellbeta, cellgamma, SpaceGroup.spaceGroupNames[sg - 1]);
}

From source file:de.nx42.maps4cim.map.texture.osm.OsmHash.java

protected static Area parseLocationHash(String locationHash) throws IOException {
    byte[] base64decode = Base64.decodeBase64(locationHash);
    ByteBuffer byteBuf = ByteBuffer.wrap(base64decode);
    final BitInput bitIn = BitInput.newInstance(byteBuf);

    double minLat = restoreCoordinate(bitIn);
    double maxLat = restoreCoordinate(bitIn);
    double minLon = restoreCoordinate(bitIn);
    double maxLon = restoreCoordinate(bitIn);

    return new Area(minLat, minLon, maxLat, maxLon);
}

From source file:edu.umass.cs.gigapaxos.paxospackets.AcceptPacket.java

@Override
public synchronized byte[] toBytes() {
    long t = System.nanoTime();
    if (!(PaxosPacket.BYTEIFICATION && IntegerMap.allInt()))
        return super.toBytes();

    if (this.getByteifiedSelf() != null)
        return this.getByteifiedSelf();

    // else construct
    byte[] buf = super.toBytes(false);
    byte[] bytes = new byte[buf.length
            // ProposalPacket.slot
            + SIZEOF_PROPOSAL//from   www .  ja va  2  s . c  o m
            // PValuePacket:ballot, recovery, medianCheckpointedSlot,
            // noCoalesce
            + SIZEOF_PVALUE
            // AcceptPacket.sender
            + SIZEOF_ACCEPT];
    ByteBuffer bbuf = ByteBuffer.wrap(bytes);

    // request
    bbuf.put(buf);
    // proposal
    bbuf.putInt(this.slot)
            // pvalue
            .putInt(this.ballot.ballotNumber).putInt(this.ballot.coordinatorID)
            .put(this.isRecovery() ? (byte) 1 : 0).putInt(this.getMedianCheckpointedSlot()).put((byte) 0)
            // accept
            .putInt(this.sender);

    assert (bbuf.remaining() == 0); // exact alignment

    this.setByteifiedSelf(bytes);

    if (PaxosMessenger.INSTRUMENT_SERIALIZATION && Util.oneIn(100))
        DelayProfiler.updateDelayNano("accept->", t, this.batchSize() + 1);

    return bytes;
}

From source file:com.amazonaws.services.dynamodbv2.streamsadapter.model.RecordAdapter.java

/**
 * This method returns JSON serialized {@link Record} object. However, This is not the best to use the object
 * It is recommended to get an object using {@link #getInternalObject()} and cast appropriately.
 *
 * @return JSON serialization of {@link Record} object. JSON contains only non-null
 * fields of {@link com.amazonaws.services.dynamodbv2.model.Record}. It returns null if serialization fails.
 *//*from  w  ww .  ja  v a2  s  .  c  o m*/
@Override
public ByteBuffer getData() {
    if (data == null) {
        if (generateDataBytes) {
            try {
                data = ByteBuffer.wrap(MAPPER.writeValueAsString(internalRecord).getBytes(defaultCharset));
            } catch (JsonProcessingException e) {
                final String errorMessage = "Failed to serialize stream record to JSON";
                LOG.error(errorMessage, e);
                throw new RuntimeException(errorMessage, e);
            }
        } else {
            data = ByteBuffer.wrap(new byte[0]);
        }
    }
    return data;
}

From source file:net.iponweb.hadoop.streaming.avro.IOWJsonDecoder.java

@Override
public ByteBuffer readBytes(ByteBuffer old) throws IOException {
    advance(Symbol.BYTES);//from   w w w  .  j  a v  a 2 s.  c  o m
    if (in.getCurrentToken() == JsonToken.VALUE_STRING) {
        byte[] result = readByteArray();
        in.nextToken();
        return ByteBuffer.wrap(result);
    } else {
        throw error("bytes");
    }
}

From source file:com.spectralogic.ds3client.helpers.FileObjectGetter_Test.java

@Test
public void testThatSymbolicLinksAreResolved() {
    Assume.assumeFalse(Platform.isWindows());
    final String message = "Hello World";
    final String file = "file.txt";
    try {//  www  . j a v  a 2  s .  c o m
        final Path tempDirectory = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")),
                "ds3");
        final Path realDirectory = Files.createDirectory(Paths.get(tempDirectory.toString(), "dir"));
        final Path symbolicDirectory = Paths.get(tempDirectory.toString(), "symbolic");
        Files.createSymbolicLink(symbolicDirectory, realDirectory);
        Files.createFile(Paths.get(realDirectory.toString(), file));
        final ByteBuffer bb = ByteBuffer.wrap(message.getBytes());

        final SeekableByteChannel getterChannel = new FileObjectGetter(symbolicDirectory).buildChannel(file);
        getterChannel.write(bb);
        getterChannel.close();
        final String content = new String(Files.readAllBytes(Paths.get(realDirectory.toString(), file)));
        assertTrue(message.equals(content));
    } catch (final IOException e) {
        fail("Symbolic links are not handled correctly");
    }
}