下面列出了java.nio.ByteBuffer#allocateDirect ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Alternate constructor.
*/
public InternalAprInputBuffer(Request request, int headerBufferSize) {
this.request = request;
headers = request.getMimeHeaders();
buf = new byte[headerBufferSize];
if (headerBufferSize < (8 * 1024)) {
bbuf = ByteBuffer.allocateDirect(6 * 1500);
} else {
bbuf = ByteBuffer.allocateDirect((headerBufferSize / 1500 + 1) * 1500);
}
inputStreamInputBuffer = new SocketInputBuffer();
filterLibrary = new InputFilter[0];
activeFilters = new InputFilter[0];
lastActiveFilter = -1;
parsingHeader = true;
swallowInput = true;
}
Quad(float[] vertices, float scale, float[] colors, float posX, float posY) {
mVertices = vertices;
mColors = colors;
mScale = scale;
setPosX(posX);
setPosY(posY);
ByteBuffer vbb = ByteBuffer.allocateDirect(mVertices.length * FLOAT_SIZE_BYTES);
vbb.order(ByteOrder.nativeOrder());
mVertexBuffer = vbb.asFloatBuffer();
mVertexBuffer.put(mVertices);
mVertexBuffer.position(0);
ByteBuffer cbb = ByteBuffer.allocateDirect(mColors.length * FLOAT_SIZE_BYTES);
cbb.order(ByteOrder.nativeOrder());
mColorBuffer = cbb.asFloatBuffer();
mColorBuffer.put(mColors);
mColorBuffer.position(0);
}
private static void TestByteBuffer(byte[] chars) {
// 1st: serialization
ByteBuffer serialized = ByteBuffer.allocateDirect(1024);
ChromiumBase64DecodeByteBuffer(serialized, chars, chars.length);
System.out.println();
byte[] tmp = new byte[]{0x6a, (byte) 0xf7, 0x1d, 0x7b, 0x4d, 0x40, 0x73, 0x6d, (byte) 0xf8};
System.out.println("ground truth of serialized: " + tmp.length);
for (byte ch : tmp) {
System.out.print(Integer.toString(ch & 0xff, 16) + ",");
}
System.out.println();
// 2nd: deserialization
byte[] deserialized = new byte[chars.length];
serialized.flip(); // for later reading
ChromiumBase64EncodeByteBuffer(deserialized, serialized, serialized.limit());
System.out.println(new String(chars));
System.out.println(new String(deserialized));
}
public static final ByteBuffer getImageDataFromImage(BufferedImage bufferedImage) {
WritableRaster wr;
DataBuffer db;
BufferedImage bi = new BufferedImage(128, 64, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
g.drawImage(bufferedImage, null, null);
bufferedImage = bi;
wr = bi.getRaster();
db = wr.getDataBuffer();
DataBufferInt dbi = (DataBufferInt) db;
int[] data = dbi.getData();
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(data.length * 4);
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
byteBuffer.asIntBuffer().put(data);
byteBuffer.flip();
return byteBuffer;
}
private static ByteBuffer alloc0(int size) {
ByteBuffer result = null;
ThreadData local = getThreadData();
int index = 32 - Integer.numberOfLeadingZeros(size-1);
// allocate aligned memory if it is less than MAX_CACHE_SIZE
if (size <= MAX_CACHE_BLOCK_SIZE) {
Deque<ByteBuffer> q = local.buffers[index];
result = q.pollLast();
if (result != null) {
local.pooled -= result.capacity();
}
}
// allocate whatever it is if it is too big
if (result == null) {
int roundedSize = 1 << index;
_log.trace("ByteBuffer.allocateDirect {}", roundedSize);
result = ByteBuffer.allocateDirect(roundedSize);
result.order(ByteOrder.nativeOrder());
}
// track the allocation
if (_isDebugEnabled) {
local.allocated += result.capacity();
}
if (_isTraceEnabled) {
if (local.traces == null) {
local.traces = new HashMap<>();
}
local.traces.put(UberUtil.getAddress(result), new Exception());
}
// done
return result;
}
/**
* Sending any byte array to USB device
* @return 'false' if no issues
* 'true' if errors happened
* */
private boolean writeUsb(byte[] message){
ByteBuffer writeBuffer = ByteBuffer.allocateDirect(message.length); //writeBuffer.order() equals BIG_ENDIAN;
writeBuffer.put(message); // Don't do writeBuffer.rewind();
IntBuffer writeBufTransferred = IntBuffer.allocate(1);
int result;
while (! task.isCancelled()) {
result = LibUsb.bulkTransfer(handlerNS, (byte) 0x01, writeBuffer, writeBufTransferred, 1000); // last one is TIMEOUT. 0 stands for unlimited. Endpoint OUT = 0x01
switch (result){
case LibUsb.SUCCESS:
if (writeBufTransferred.get() == message.length)
return false;
else {
logPrinter.print("GL Data transfer issue [write]\n Requested: "+message.length+"\n Transferred: "+writeBufTransferred.get(), EMsgType.FAIL);
return true;
}
case LibUsb.ERROR_TIMEOUT:
continue;
default:
logPrinter.print("GL Data transfer issue [write]\n Returned: "+ UsbErrorCodes.getErrCode(result), EMsgType.FAIL);
logPrinter.print("GL Execution stopped", EMsgType.FAIL);
return true;
}
}
logPrinter.print("GL Execution interrupted", EMsgType.INFO);
return true;
}
@Override
protected void processInput(String input) throws SteamException {
if (input.equals("encrypt")) {
byte[] ident = "Hello World!".getBytes(Charset.defaultCharset());
ByteBuffer dataToInclude = ByteBuffer.allocateDirect(ident.length);
dataToInclude.put(ident);
dataToInclude.flip();
user.requestEncryptedAppTicket(dataToInclude);
}
}
/**
* It's a heavy init method.
*/
public void init() {
for (int i = 0; i < poolSize; i++) {
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(fileSize);
final long address = ((DirectBuffer) byteBuffer).address();
Pointer pointer = new Pointer(address);
LibC.INSTANCE.mlock(pointer, new NativeLong(fileSize));
availableBuffers.offer(byteBuffer);
}
}
protected static ByteBuffer _getByteBuffer() {
ByteBuffer byteBuff = _nativeECDSABuffer.get();
if ((byteBuff == null) || (byteBuff.capacity() < 520)) {
byteBuff = ByteBuffer.allocateDirect(520);
byteBuff.order(ByteOrder.nativeOrder());
_nativeECDSABuffer.set(byteBuff);
}
return byteBuff;
}
static void sendImage(int width, int height) {
ByteBuffer rgbaBuf = ByteBuffer.allocateDirect(width * height * 4);
rgbaBuf.position(0);
long start = System.nanoTime();
GLES20.glReadPixels(0, 0, width, height, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE,
rgbaBuf);
long end = System.nanoTime();
Log.d("TryOpenGL", "glReadPixels: " + (end - start));
saveRgb2Bitmap(rgbaBuf, Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/gl_dump_" + width + "_" + height + ".png", width, height);
}
@Override
public synchronized ByteBuffer getBuffer(boolean direct, int length) {
TreeMap<Key, ByteBuffer> tree = getBufferTree(direct);
Map.Entry<Key, ByteBuffer> entry =
tree.ceilingEntry(new Key(length, 0));
if (entry == null) {
return direct ? ByteBuffer.allocateDirect(length) :
ByteBuffer.allocate(length);
}
tree.remove(entry.getKey());
return entry.getValue();
}
/**
*
* @param url
* printer-uri
* @param map
* attributes
* i.e.job-name,ipp-attribute-fidelity,document-name,compression,
* document -format,document-natural-language,job-impressions
* ,job-media-sheets, job-template-attributes
* @return IPP header
* @throws UnsupportedEncodingException
*/
public ByteBuffer getIppHeader(URL uri, Map<String, String> map) throws UnsupportedEncodingException {
if (uri == null) {
LOG.error("IppCancelJobOperation.getIppHeader(): uri is null");
return null;
}
ByteBuffer ippBuf = ByteBuffer.allocateDirect(bufferSize);
ippBuf = IppTag.getOperation(ippBuf, operationID);
if (map == null) {
ippBuf = IppTag.getEnd(ippBuf);
ippBuf.flip();
return ippBuf;
}
if (map.get("job-id") == null) {
ippBuf = IppTag.getUri(ippBuf, "job-uri", stripPortNumber(uri));
} else {
ippBuf = IppTag.getUri(ippBuf, "printer-uri", stripPortNumber(uri));
int jobId = Integer.parseInt(map.get("job-id"));
ippBuf = IppTag.getInteger(ippBuf, "job-id", jobId);
}
ippBuf = IppTag.getNameWithoutLanguage(ippBuf, "requesting-user-name", map.get("requesting-user-name"));
if (map.get("message") != null) {
ippBuf = IppTag.getTextWithoutLanguage(ippBuf, "message", map.get("message"));
}
ippBuf = IppTag.getEnd(ippBuf);
ippBuf.flip();
return ippBuf;
}
BTChipTransportHID(DeviceHandle handle, int timeout, byte inEndpoint, byte outEndpoint, boolean ledger) {
this.handle = handle;
this.timeout = timeout;
this.inEndpoint = inEndpoint;
this.outEndpoint = outEndpoint;
responseBuffer = ByteBuffer.allocateDirect(HID_BUFFER_SIZE);
sizeBuffer = BufferUtils.allocateIntBuffer();
}
/**
* Set the ColorMap of node n to the supplied colorTable
* @param n
* @param colorTable
*/
public void setColormap( Node n, ColorTable colorTable ) {
final int copies = 16;
final ByteBuffer byteBuffer = ByteBuffer.allocateDirect(
4 * colorTable.getLength() * copies );// Num bytes * num components * color map length * height of color map texture
final byte[] tmp = new byte[4 * colorTable.getLength()];
for( int k = 0; k < colorTable.getLength(); k++ ) {
for( int c = 0; c < colorTable.getComponentCount(); c++ ) {
// TODO this assumes numBits is 8, could be 16
tmp[4 * k + c] = ( byte ) colorTable.get( c, k );
}
if( colorTable.getComponentCount() == 3 ) {
tmp[4 * k + 3] = (byte)255;
}
}
for( int i = 0; i < copies; i++ ) {
byteBuffer.put(tmp);
}
byteBuffer.flip();
n.getMetadata().put("sciviewColormap", colorTable);
if(n instanceof Volume) {
((Volume) n).setColormap(Colormap.fromColorTable(colorTable));
n.setDirty(true);
n.setNeedsUpdate(true);
}
}
private boolean initPlayout(int sampleRate, int channels) {
threadChecker.checkIsOnValidThread();
Logging.d(TAG, "initPlayout(sampleRate=" + sampleRate + ", channels=" + channels + ")");
final int bytesPerFrame = channels * (BITS_PER_SAMPLE / 8);
byteBuffer = ByteBuffer.allocateDirect(bytesPerFrame * (sampleRate / BUFFERS_PER_SECOND));
Logging.d(TAG, "byteBuffer.capacity: " + byteBuffer.capacity());
emptyBytes = new byte[byteBuffer.capacity()];
// Rather than passing the ByteBuffer with every callback (requiring
// the potentially expensive GetDirectBufferAddress) we simply have the
// the native class cache the address to the memory once.
nativeCacheDirectBufferAddress(byteBuffer, nativeAudioTrack);
// Get the minimum buffer size required for the successful creation of an
// AudioTrack object to be created in the MODE_STREAM mode.
// Note that this size doesn't guarantee a smooth playback under load.
// TODO(henrika): should we extend the buffer size to avoid glitches?
final int channelConfig = channelCountToConfiguration(channels);
final int minBufferSizeInBytes =
AudioTrack.getMinBufferSize(sampleRate, channelConfig, AudioFormat.ENCODING_PCM_16BIT);
Logging.d(TAG, "AudioTrack.getMinBufferSize: " + minBufferSizeInBytes);
// For the streaming mode, data must be written to the audio sink in
// chunks of size (given by byteBuffer.capacity()) less than or equal
// to the total buffer size |minBufferSizeInBytes|. But, we have seen
// reports of "getMinBufferSize(): error querying hardware". Hence, it
// can happen that |minBufferSizeInBytes| contains an invalid value.
if (minBufferSizeInBytes < byteBuffer.capacity()) {
reportWebRtcAudioTrackInitError("AudioTrack.getMinBufferSize returns an invalid value.");
return false;
}
// Ensure that prevision audio session was stopped correctly before trying
// to create a new AudioTrack.
if (audioTrack != null) {
reportWebRtcAudioTrackInitError("Conflict with existing AudioTrack.");
return false;
}
try {
// Create an AudioTrack object and initialize its associated audio buffer.
// The size of this buffer determines how long an AudioTrack can play
// before running out of data.
if (Build.VERSION.SDK_INT >= 21) {
// If we are on API level 21 or higher, it is possible to use a special AudioTrack
// constructor that uses AudioAttributes and AudioFormat as input. It allows us to
// supersede the notion of stream types for defining the behavior of audio playback,
// and to allow certain platforms or routing policies to use this information for more
// refined volume or routing decisions.
audioTrack = createAudioTrackOnLollipopOrHigher(
sampleRate, channelConfig, minBufferSizeInBytes);
} else {
// Use default constructor for API levels below 21.
audioTrack =
createAudioTrackOnLowerThanLollipop(sampleRate, channelConfig, minBufferSizeInBytes);
}
} catch (IllegalArgumentException e) {
reportWebRtcAudioTrackInitError(e.getMessage());
releaseAudioResources();
return false;
}
// It can happen that an AudioTrack is created but it was not successfully
// initialized upon creation. Seems to be the case e.g. when the maximum
// number of globally available audio tracks is exceeded.
if (audioTrack == null || audioTrack.getState() != AudioTrack.STATE_INITIALIZED) {
reportWebRtcAudioTrackInitError("Initialization of audio track failed.");
releaseAudioResources();
return false;
}
logMainParameters();
logMainParametersExtended();
return true;
}
public static void main(String args[]) throws Exception {
String msg = "HELLO";
// Launch the service with arguments to tell it to close
// the connection after reading 5 bytes ("HELLO"). After
// closing the connection the service should hang around
// for 15 seconds.
String service_args[] = new String[2];
service_args[0] = String.valueOf(msg.length());
service_args[1] = String.valueOf( 15*1000 );
SocketChannel sc = Launcher.launchWithSocketChannel("EchoService", service_args);
// send message - service will echo the message and close the connection.
sc.write(ByteBuffer.wrap(msg.getBytes("UTF-8")));
// read the reply (with timeout)
ByteBuffer bb = ByteBuffer.allocateDirect(50);
sc.configureBlocking(false);
Selector sel = sc.provider().openSelector();
SelectionKey sk = sc.register(sel, SelectionKey.OP_READ);
long to = 12 * 1000;
for (;;) {
long st = System.currentTimeMillis();
sel.select(to);
if (sk.isReadable()) {
int n = sc.read(bb);
// EOF
if (n < 0) {
break;
}
}
sel.selectedKeys().remove(sk);
to -= System.currentTimeMillis() - st;
if (to <= 0) {
throw new RuntimeException("Timed out waiting for connection to close");
}
}
sel.close();
sc.close();
// finally check that the reply length is okay
bb.flip();
if (bb.remaining() < msg.length()) {
throw new RuntimeException("Premature EOF from echo service");
}
System.out.println("Test passed - service closed connection.");
}
private Path writeWAL(final WALFactory wals, final String tblName, boolean offheap)
throws IOException {
Configuration conf = TEST_UTIL.getConfiguration();
String clsName = conf.get(WALCellCodec.WAL_CELL_CODEC_CLASS_KEY, WALCellCodec.class.getName());
conf.setClass(WALCellCodec.WAL_CELL_CODEC_CLASS_KEY, SecureWALCellCodec.class,
WALCellCodec.class);
try {
TableName tableName = TableName.valueOf(tblName);
NavigableMap<byte[], Integer> scopes = new TreeMap<>(Bytes.BYTES_COMPARATOR);
scopes.put(tableName.getName(), 0);
RegionInfo regionInfo = RegionInfoBuilder.newBuilder(tableName).build();
final int total = 10;
final byte[] row = Bytes.toBytes("row");
final byte[] family = Bytes.toBytes("family");
final MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl(1);
// Write the WAL
WAL wal = wals.getWAL(regionInfo);
for (int i = 0; i < total; i++) {
WALEdit kvs = new WALEdit();
KeyValue kv = new KeyValue(row, family, Bytes.toBytes(i), value);
if (offheap) {
ByteBuffer bb = ByteBuffer.allocateDirect(kv.getBuffer().length);
bb.put(kv.getBuffer());
ByteBufferKeyValue offheapKV = new ByteBufferKeyValue(bb, 0, kv.getLength());
kvs.add(offheapKV);
} else {
kvs.add(kv);
}
wal.appendData(regionInfo, new WALKeyImpl(regionInfo.getEncodedNameAsBytes(), tableName,
System.currentTimeMillis(), mvcc, scopes), kvs);
}
wal.sync();
final Path walPath = AbstractFSWALProvider.getCurrentFileName(wal);
wal.shutdown();
return walPath;
} finally {
// restore the cell codec class
conf.set(WALCellCodec.WAL_CELL_CODEC_CLASS_KEY, clsName);
}
}
static void test(Path file, LinkOption... options) throws IOException {
final UserDefinedFileAttributeView view =
Files.getFileAttributeView(file, UserDefinedFileAttributeView.class, options);
ByteBuffer buf = rand.nextBoolean() ?
ByteBuffer.allocate(100) : ByteBuffer.allocateDirect(100);
// Test: write
buf.put(ATTR_VALUE.getBytes()).flip();
int size = buf.remaining();
int nwrote = view.write(ATTR_NAME, buf);
if (nwrote != size)
throw new RuntimeException("Unexpected number of bytes written");
// Test: size
if (view.size(ATTR_NAME) != size)
throw new RuntimeException("Unexpected size");
// Test: read
buf.clear();
int nread = view.read(ATTR_NAME, buf);
if (nread != size)
throw new RuntimeException("Unexpected number of bytes read");
buf.flip();
String value = Charset.defaultCharset().decode(buf).toString();
if (!value.equals(ATTR_VALUE))
throw new RuntimeException("Unexpected attribute value");
// Test: read with insufficient space
tryCatch(IOException.class, new Task() {
public void run() throws IOException {
view.read(ATTR_NAME, ByteBuffer.allocateDirect(1));
}});
// Test: replace value
buf.clear();
buf.put(ATTR_VALUE2.getBytes()).flip();
size = buf.remaining();
view.write(ATTR_NAME, buf);
if (view.size(ATTR_NAME) != size)
throw new RuntimeException("Unexpected size");
// Test: list
if (!hasAttribute(view, ATTR_NAME))
throw new RuntimeException("Attribute name not in list");
// Test: delete
view.delete(ATTR_NAME);
if (hasAttribute(view, ATTR_NAME))
throw new RuntimeException("Attribute name in list");
// Test: dynamic access
String name = "user:" + ATTR_NAME;
byte[] valueAsBytes = ATTR_VALUE.getBytes();
Files.setAttribute(file, name, valueAsBytes);
byte[] actualAsBytes = (byte[])Files.getAttribute(file, name);
if (!Arrays.equals(valueAsBytes, actualAsBytes))
throw new RuntimeException("Unexpected attribute value");
Map<String,?> map = Files.readAttributes(file, name);
if (!Arrays.equals(valueAsBytes, (byte[])map.get(ATTR_NAME)))
throw new RuntimeException("Unexpected attribute value");
map = Files.readAttributes(file, "user:*");
if (!Arrays.equals(valueAsBytes, (byte[])map.get(ATTR_NAME)))
throw new RuntimeException("Unexpected attribute value");
}
public SocketOutputStream(SocketChannel socket) throws IOException {
this.socket = socket;
selector = Selector.open();
socket.register(selector, SelectionKey.OP_WRITE);
buffer = ByteBuffer.allocateDirect(4096);
}
public DynamicByteBuffer(int cap, boolean useDirectBuffer) {
buffer = useDirectBuffer ? ByteBuffer.allocateDirect(cap) : ByteBuffer.allocate(cap);
}