Java Code Examples for java.nio.ByteBuffer.asReadOnlyBuffer()

The following are Jave code examples for showing how to use asReadOnlyBuffer() of the java.nio.ByteBuffer class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: openjdk-jdk10   File: DataProviders.java   View Source Code Vote up 7 votes
@DataProvider(name = "outgoingData", parallel = true)
public static Iterator<Object[]> outgoingData() {
    List<Integer> leading  = of(0, 1, 17, 125);
    List<Integer> trailing = of(0, 1, 19, 123);
    List<Integer> sizes    = of(0, 1, 2, 17, 32, 64, 122, 123, 124, 125, 126, 127, 128, 256);
    List<Boolean> direct   = of(true, false);
    List<Boolean> readonly = of(false); // TODO: return readonly (true)
    F5<Integer, Integer, Integer, Boolean, Boolean, Object[]> f =
            (l, t, s, d, r) -> {
                ByteBuffer b;
                if (d) {
                    b = ByteBuffer.allocateDirect(l + t + s);
                } else {
                    b = ByteBuffer.allocate(l + t + s);
                }
                fill(b);
                if (r) {
                    b = b.asReadOnlyBuffer();
                }
                b.position(l).limit(l + s);
                return new ByteBuffer[]{b};
            };
    Iterator<Object[]> product = cartesianIterator(leading, trailing, sizes, direct, readonly, f);
    Iterator<Object[]> i = iteratorOf1(new Object[]{null});
    return concat(iteratorOf(i, product));
}
 
Example 2
Project: ibm-cos-sdk-java   File: BinaryUtils.java   View Source Code Vote up 6 votes
/**
 * Returns a copy of all the bytes from the given <code>ByteBuffer</code>,
 * from the beginning to the buffer's limit; or null if the input is null.
 * <p>
 * The internal states of the given byte buffer will be restored when this
 * method completes execution.
 * <p>
 * When handling <code>ByteBuffer</code> from user's input, it's typical to
 * call the {@link #copyBytesFrom(ByteBuffer)} instead of
 * {@link #copyAllBytesFrom(ByteBuffer)} so as to account for the position
 * of the input <code>ByteBuffer</code>. The opposite is typically true,
 * however, when handling <code>ByteBuffer</code> from withint the
 * unmarshallers of the low-level clients.
 */
public static byte[] copyAllBytesFrom(ByteBuffer bb) {
    if (bb == null) {
        return null;
    }

    if (bb.hasArray()) {
        return Arrays.copyOfRange(
                bb.array(),
                bb.arrayOffset(),
                bb.arrayOffset() + bb.limit());
    }

    ByteBuffer copy = bb.asReadOnlyBuffer();
    copy.rewind();

    byte[] dst = new byte[copy.remaining()];
    copy.get(dst);
    return dst;
}
 
Example 3
Project: memory   File: WritableMemoryImplTest.java   View Source Code Vote up 6 votes
@Test
public void checkWrapWithDirectBBReadonly() {
  int memCapacity = 64;
  ByteBuffer byteBuf = ByteBuffer.allocateDirect(memCapacity);
  byteBuf.order(ByteOrder.nativeOrder());

  for (int i = 0; i < memCapacity; i++) {
    byteBuf.put(i, (byte) i);
  }
  ByteBuffer byteBufRO = byteBuf.asReadOnlyBuffer();
  byteBufRO.order(ByteOrder.nativeOrder());

  Memory mem = Memory.wrap(byteBufRO);

  for (int i = 0; i < memCapacity; i++) {
    assertEquals(mem.getByte(i), byteBuf.get(i));
  }

  //println(mem.toHexString("HeapBB", 0, memCapacity));
}
 
Example 4
Project: aws-sdk-java-v2   File: BinaryUtils.java   View Source Code Vote up 6 votes
/**
 * Returns a copy of all the bytes from the given <code>ByteBuffer</code>,
 * from the beginning to the buffer's limit; or null if the input is null.
 * <p>
 * The internal states of the given byte buffer will be restored when this
 * method completes execution.
 * <p>
 * When handling <code>ByteBuffer</code> from user's input, it's typical to
 * call the {@link #copyBytesFrom(ByteBuffer)} instead of
 * {@link #copyAllBytesFrom(ByteBuffer)} so as to account for the position
 * of the input <code>ByteBuffer</code>. The opposite is typically true,
 * however, when handling <code>ByteBuffer</code> from withint the
 * unmarshallers of the low-level clients.
 */
public static byte[] copyAllBytesFrom(ByteBuffer bb) {
    if (bb == null) {
        return null;
    }

    if (bb.hasArray()) {
        return Arrays.copyOfRange(
                bb.array(),
                bb.arrayOffset(),
                bb.arrayOffset() + bb.limit());
    }

    ByteBuffer copy = bb.asReadOnlyBuffer();
    copy.rewind();

    byte[] dst = new byte[copy.remaining()];
    copy.get(dst);
    return dst;
}
 
Example 5
Project: memory   File: WritableBufferImplTest.java   View Source Code Vote up 6 votes
@Test
public void checkWrapWithDirectBBReadonly() {
  int memCapacity = 64;
  ByteBuffer byteBuf = ByteBuffer.allocateDirect(memCapacity);
  byteBuf.order(ByteOrder.nativeOrder());

  for (int i = 0; i < memCapacity; i++) {
    byteBuf.put(i, (byte) i);
  }
  ByteBuffer byteBufRO = byteBuf.asReadOnlyBuffer();
  byteBufRO.order(ByteOrder.nativeOrder());

  Buffer buf = Buffer.wrap(byteBufRO);

  for (int i = 0; i < memCapacity; i++) {
    assertEquals(buf.getByte(), byteBuf.get(i));
  }

  //println(mem.toHexString("HeapBB", 0, memCapacity));
}
 
Example 6
Project: memory   File: WritableMemoryImplTest.java   View Source Code Vote up 5 votes
@Test(expectedExceptions = ReadOnlyException.class)
public void checkWrapWithDirectBBReadonlyPut() {
  int memCapacity = 64;
  ByteBuffer byteBuf = ByteBuffer.allocateDirect(memCapacity);
  ByteBuffer byteBufRO = byteBuf.asReadOnlyBuffer();
  byteBufRO.order(ByteOrder.nativeOrder());

  WritableMemory.wrap(byteBufRO);
}
 
Example 7
Project: GitHub   File: GifHeaderParser.java   View Source Code Vote up 5 votes
public GifHeaderParser setData(ByteBuffer data) {
  reset();
  rawData = data.asReadOnlyBuffer();
  rawData.position(0);
  rawData.order(ByteOrder.LITTLE_ENDIAN);
  return this;
}
 
Example 8
Project: GitHub   File: ByteBufferUtil.java   View Source Code Vote up 5 votes
public static byte[] toBytes(ByteBuffer byteBuffer) {
  final byte[] result;
  SafeArray safeArray = getSafeArray(byteBuffer);
  if (safeArray != null && safeArray.offset == 0 && safeArray.limit == safeArray.data.length) {
    result = byteBuffer.array();
  } else {
    ByteBuffer toCopy = byteBuffer.asReadOnlyBuffer();
    result = new byte[toCopy.limit()];
    toCopy.position(0);
    toCopy.get(result);
  }
  return result;
}
 
Example 9
Project: openjdk-jdk10   File: MessageBase.java   View Source Code Vote up 5 votes
public static Message readGIOPBody(ORB orb,
                                   CorbaConnection connection,
                                   Message msg)
{
    ReadTimeouts readTimeouts =
                       orb.getORBData().getTransportTCPReadTimeouts();
    ByteBuffer buf = msg.getByteBuffer();

    buf.position(MessageBase.GIOPMessageHeaderLength);
    int msgSizeMinusHeader =
        msg.getSize() - MessageBase.GIOPMessageHeaderLength;
    try {
        buf = connection.read(buf,
                      GIOPMessageHeaderLength, msgSizeMinusHeader,
                      readTimeouts.get_max_time_to_wait());
    } catch (IOException e) {
        throw wrapper.ioexceptionWhenReadingConnection(e);
    }

    msg.setByteBuffer(buf);

    if (orb.giopDebugFlag) {
        dprint(".readGIOPBody: received message:");
        ByteBuffer viewBuffer = buf.asReadOnlyBuffer();
        viewBuffer.position(0).limit(msg.getSize());
        ByteBufferWithInfo bbwi = new ByteBufferWithInfo(orb, viewBuffer);
        CDRInputStream_1_0.printBuffer(bbwi);
    }

    return msg;
}
 
Example 10
Project: fitnotifications   File: ICUResourceBundleReader.java   View Source Code Vote up 5 votes
ByteBuffer getBinary(int res) {
    int offset=RES_GET_OFFSET(res);
    int length;
    if(RES_GET_TYPE(res)==UResourceBundle.BINARY) {
        if(offset==0) {
            // Don't just
            //   return emptyByteBuffer;
            // in case it matters whether the buffer's mark is defined or undefined.
            return emptyByteBuffer.duplicate();
        } else {
            // Not cached: The returned buffer is small (shares its bytes with the bundle)
            // and usually quickly discarded after use.
            // Also, even a cached buffer would have to be cloned because it is mutable
            // (position & mark).
            offset=getResourceByteOffset(offset);
            length=getInt(offset);
            if(length == 0) {
                return emptyByteBuffer.duplicate();
            }
            offset += 4;
            ByteBuffer result = bytes.duplicate();
            result.position(offset).limit(offset + length);
            result = ICUBinary.sliceWithOrder(result);
            if(!result.isReadOnly()) {
                result = result.asReadOnlyBuffer();
            }
            return result;
        }
    } else {
        return null;
    }
}
 
Example 11
Project: BBSSDK-for-Android   File: GifHeaderParser.java   View Source Code Vote up 5 votes
public GifHeaderParser setData(ByteBuffer data) {
	reset();
	rawData = data.asReadOnlyBuffer();
	rawData.position(0);
	rawData.order(ByteOrder.LITTLE_ENDIAN);
	return this;
}
 
Example 12
Project: rtmp-rtsp-stream-client-java   File: GifDecoder.java   View Source Code Vote up 5 votes
public synchronized void setData(GifHeader header, ByteBuffer buffer, int sampleSize) {
  if (sampleSize <= 0) {
    throw new IllegalArgumentException("Sample size must be >=0, not: " + sampleSize);
  }
  // Make sure sample size is a power of 2.
  sampleSize = Integer.highestOneBit(sampleSize);
  this.status = STATUS_OK;
  this.header = header;
  isFirstFrameTransparent = false;
  framePointer = INITIAL_FRAME_POINTER;
  resetLoopIndex();
  // Initialize the raw data buffer.
  rawData = buffer.asReadOnlyBuffer();
  rawData.position(0);
  rawData.order(ByteOrder.LITTLE_ENDIAN);

  // No point in specially saving an old frame if we're never going to use it.
  savePrevious = false;
  for (GifFrame frame : header.frames) {
    if (frame.dispose == DISPOSAL_PREVIOUS) {
      savePrevious = true;
      break;
    }
  }

  this.sampleSize = sampleSize;
  downsampledWidth = header.width / sampleSize;
  downsampledHeight = header.height / sampleSize;
  // Now that we know the size, init scratch arrays.
  // TODO Find a way to avoid this entirely or at least downsample it (either should be possible).
  mainPixels = bitmapProvider.obtainByteArray(header.width * header.height);
  mainScratch = bitmapProvider.obtainIntArray(downsampledWidth * downsampledHeight);
}
 
Example 13
Project: rcom   File: AutoGrowBuffer.java   View Source Code Vote up 5 votes
private synchronized void ensureWriteCapacity(int i) {
	int size=readSize();
	int writeCapacity=data.capacity()-size-1;
	while(writeCapacity<i)
	{
		ByteBuffer doubled=ByteBuffer.allocate(data.capacity()*2).order(AbstractMultiplexer.order);
		copyTo(doubled, size);
		readView=doubled.asReadOnlyBuffer();
		readPtr=0;
		writePtr=size;
		data=doubled;
		size=readSize();
		writeCapacity=data.capacity()-size-1;
	}
}
 
Example 14
Project: bytes   File: ByteArrayBytes.java   View Source Code Vote up 4 votes
@Override
public ByteBuffer toReadOnlyByteBuffer() {
    final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes, offset, length);
    return byteBuffer.asReadOnlyBuffer();
}
 
Example 15
Project: sstore-soft   File: ByteString.java   View Source Code Vote up 4 votes
/**
 * Constructs a new read-only {@code java.nio.ByteBuffer} with the
 * same backing byte array.
 */
public ByteBuffer asReadOnlyByteBuffer() {
  final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
  return byteBuffer.asReadOnlyBuffer();
}
 
Example 16
Project: openjdk-jdk10   File: JISAutoDetect.java   View Source Code Vote up 4 votes
protected CoderResult decodeLoop(ByteBuffer src, CharBuffer dst) {
    if (detectedDecoder == null) {
        copyLeadingASCII(src, dst);

        // All ASCII?
        if (! src.hasRemaining())
            return CoderResult.UNDERFLOW;
        // Overflow only if there is still ascii but no out buffer.
        if (!dst.hasRemaining() &&
            isPlainASCII(src.get(src.position())))
            return CoderResult.OVERFLOW;

        // We need to perform double, not float, arithmetic; otherwise
        // we lose low order bits when src is larger than 2**24.
        int cbufsiz = (int)(src.limit() * (double)maxCharsPerByte());
        CharBuffer sandbox = CharBuffer.allocate(cbufsiz);

        // First try ISO-2022-JP, since there is no ambiguity
        Charset cs2022 = Charset.forName("ISO-2022-JP");
        DelegatableDecoder dd2022
            = (DelegatableDecoder) cs2022.newDecoder();
        ByteBuffer src2022 = src.asReadOnlyBuffer();
        CoderResult res2022 = dd2022.decodeLoop(src2022, sandbox);
        if (! res2022.isError())
            return decodeLoop(dd2022, src, dst);

        // We must choose between EUC and SJIS
        Charset csEUCJ = Charset.forName(EUCJPName);
        Charset csSJIS = Charset.forName(SJISName);

        DelegatableDecoder ddEUCJ
            = (DelegatableDecoder) csEUCJ.newDecoder();
        DelegatableDecoder ddSJIS
            = (DelegatableDecoder) csSJIS.newDecoder();

        ByteBuffer srcEUCJ = src.asReadOnlyBuffer();
        sandbox.clear();
        CoderResult resEUCJ = ddEUCJ.decodeLoop(srcEUCJ, sandbox);
        // If EUC decoding fails, must be SJIS
        if (resEUCJ.isError())
            return decodeLoop(ddSJIS, src, dst);
        ByteBuffer srcSJIS = src.asReadOnlyBuffer();
        CharBuffer sandboxSJIS = CharBuffer.allocate(cbufsiz);
        CoderResult resSJIS = ddSJIS.decodeLoop(srcSJIS, sandboxSJIS);
        // If SJIS decoding fails, must be EUC
        if (resSJIS.isError())
            return decodeLoop(ddEUCJ, src, dst);

        // From here on, we have some ambiguity, and must guess.

        // We prefer input that does not appear to end mid-character.
        if (srcEUCJ.position() > srcSJIS.position())
            return decodeLoop(ddEUCJ, src, dst);

        if (srcEUCJ.position() < srcSJIS.position())
            return decodeLoop(ddSJIS, src, dst);

        // end-of-input is after the first byte of the first char?
        if (src.position() == srcEUCJ.position())
            return CoderResult.UNDERFLOW;

        // Use heuristic knowledge of typical Japanese text
        sandbox.flip();
        return decodeLoop(looksLikeJapanese(sandbox) ? ddEUCJ : ddSJIS,
                          src, dst);
    }

    return detectedDecoder.decodeLoop(src, dst);
}
 
Example 17
Project: s-store   File: ByteString.java   View Source Code Vote up 4 votes
/**
 * Constructs a new read-only {@code java.nio.ByteBuffer} with the
 * same backing byte array.
 */
public ByteBuffer asReadOnlyByteBuffer() {
  final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
  return byteBuffer.asReadOnlyBuffer();
}
 
Example 18
Project: openjdk-jdk10   File: ByteBuffers.java   View Source Code Vote up 4 votes
@Override
public void main(Provider p) throws Exception {

    /*
     * Use Solaris SPARC 11.2 or later to avoid an intermittent failure
     * when running SunPKCS11-Solaris provider (8044554)
     */
    if (p.getName().equals("SunPKCS11-Solaris") &&
        props.getProperty("os.name").equals("SunOS") &&
        props.getProperty("os.arch").equals("sparcv9") &&
        props.getProperty("os.version").compareTo("5.11") <= 0 &&
        getDistro().compareTo("11.2") < 0) {

        System.out.println("SunPKCS11-Solaris provider requires " +
            "Solaris SPARC 11.2 or later, skipping");
        return;
    }

    Random random = new Random();
    int n = 10 * 1024;
    byte[] t = new byte[n];
    random.nextBytes(t);

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", p);
    kpg.initialize(512);
    KeyPair kp = kpg.generateKeyPair();

    Signature sig = Signature.getInstance("MD5withRSA", p);
    sig.initSign(kp.getPrivate());
    sig.update(t);
    byte[] signature = sig.sign();

    sig.initVerify(kp.getPublic());

    // test 1: ByteBuffer with an accessible backing array
    ByteBuffer b1 = ByteBuffer.allocate(n + 256);
    b1.position(random.nextInt(256));
    b1.limit(b1.position() + n);
    ByteBuffer b2 = b1.slice();
    b2.put(t);
    b2.clear();
    verify(sig, signature, b2, random);

    // test 2: direct ByteBuffer
    ByteBuffer b3 = ByteBuffer.allocateDirect(t.length);
    b3.put(t);
    b3.clear();
    verify(sig, signature, b3, random);

    // test 3: ByteBuffer without an accessible backing array
    b2.clear();
    ByteBuffer b4 = b2.asReadOnlyBuffer();
    verify(sig, signature, b4, random);

    System.out.println("All tests passed");
}
 
Example 19
Project: OpenJSharp   File: JISAutoDetect.java   View Source Code Vote up 4 votes
protected CoderResult decodeLoop(ByteBuffer src, CharBuffer dst) {
    if (detectedDecoder == null) {
        copyLeadingASCII(src, dst);

        // All ASCII?
        if (! src.hasRemaining())
            return CoderResult.UNDERFLOW;
        if (! dst.hasRemaining())
            return CoderResult.OVERFLOW;

        // We need to perform double, not float, arithmetic; otherwise
        // we lose low order bits when src is larger than 2**24.
        int cbufsiz = (int)(src.limit() * (double)maxCharsPerByte());
        CharBuffer sandbox = CharBuffer.allocate(cbufsiz);

        // First try ISO-2022-JP, since there is no ambiguity
        Charset cs2022 = Charset.forName("ISO-2022-JP");
        DelegatableDecoder dd2022
            = (DelegatableDecoder) cs2022.newDecoder();
        ByteBuffer src2022 = src.asReadOnlyBuffer();
        CoderResult res2022 = dd2022.decodeLoop(src2022, sandbox);
        if (! res2022.isError())
            return decodeLoop(cs2022, src, dst);

        // We must choose between EUC and SJIS
        Charset csEUCJ = Charset.forName(EUCJPName);
        Charset csSJIS = Charset.forName(SJISName);

        DelegatableDecoder ddEUCJ
            = (DelegatableDecoder) csEUCJ.newDecoder();
        ByteBuffer srcEUCJ = src.asReadOnlyBuffer();
        sandbox.clear();
        CoderResult resEUCJ = ddEUCJ.decodeLoop(srcEUCJ, sandbox);
        // If EUC decoding fails, must be SJIS
        if (resEUCJ.isError())
            return decodeLoop(csSJIS, src, dst);

        DelegatableDecoder ddSJIS
            = (DelegatableDecoder) csSJIS.newDecoder();
        ByteBuffer srcSJIS = src.asReadOnlyBuffer();
        CharBuffer sandboxSJIS = CharBuffer.allocate(cbufsiz);
        CoderResult resSJIS = ddSJIS.decodeLoop(srcSJIS, sandboxSJIS);
        // If SJIS decoding fails, must be EUC
        if (resSJIS.isError())
            return decodeLoop(csEUCJ, src, dst);

        // From here on, we have some ambiguity, and must guess.

        // We prefer input that does not appear to end mid-character.
        if (srcEUCJ.position() > srcSJIS.position())
            return decodeLoop(csEUCJ, src, dst);

        if (srcEUCJ.position() < srcSJIS.position())
            return decodeLoop(csSJIS, src, dst);

        // end-of-input is after the first byte of the first char?
        if (src.position() == srcEUCJ.position())
            return CoderResult.UNDERFLOW;

        // Use heuristic knowledge of typical Japanese text
        sandbox.flip();
        Charset guess = looksLikeJapanese(sandbox) ? csEUCJ : csSJIS;
        return decodeLoop(guess, src, dst);
    }

    return detectedDecoder.decodeLoop(src, dst);
}
 
Example 20
Project: openjdk-jdk10   File: ByteBuffers.java   View Source Code Vote up 4 votes
@Override
public void main(Provider p) throws Exception {
    if (p.getService("MessageDigest", "MD5") == null) {
        System.out.println("Provider does not support MD5, skipping");
        return;
    }

    Random random = new Random();
    int n = 10 * 1024;
    byte[] t = new byte[n];
    random.nextBytes(t);

    MessageDigest md = MessageDigest.getInstance("MD5", p);
    byte[] d1 = md.digest(t);

    // test 1: ByteBuffer with an accessible backing array
    ByteBuffer b1 = ByteBuffer.allocate(n + 256);
    b1.position(random.nextInt(256));
    b1.limit(b1.position() + n);
    ByteBuffer b2 = b1.slice();
    b2.put(t);
    b2.clear();
    byte[] d2 = digest(md, b2, random);
    if (Arrays.equals(d1, d2) == false) {
        throw new Exception("Test 1 failed");
    }

    // test 2: direct ByteBuffer
    ByteBuffer b3 = ByteBuffer.allocateDirect(t.length);
    b3.put(t);
    b3.clear();
    byte[] d3 = digest(md, b3, random);
    if (Arrays.equals(d1, d2) == false) {
        throw new Exception("Test 2 failed");
    }

    // test 3: ByteBuffer without an accessible backing array
    b2.clear();
    ByteBuffer b4 = b2.asReadOnlyBuffer();
    byte[] d4 = digest(md, b4, random);
    if (Arrays.equals(d1, d2) == false) {
        throw new Exception("Test 3 failed");
    }
    System.out.println("All tests passed");
}