java.nio.ByteBuffer Java Examples
The following examples show how to use
java.nio.ByteBuffer.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FileWrite.java From coroutines with Apache License 2.0 | 6 votes |
/*************************************** * {@inheritDoc} */ @Override protected void performBlockingOperation( AsynchronousFileChannel aChannel, ByteBuffer rData) throws InterruptedException, ExecutionException { long nPosition = 0; while (rData.hasRemaining()) { nPosition += aChannel.write(rData, nPosition).get(); } rData.clear(); }
Example #2
Source File: JimfsAsynchronousFileChannelTest.java From jimfs with Apache License 2.0 | 6 votes |
@Test public void testClosedChannel() throws Throwable { RegularFile file = regularFile(15); ExecutorService executor = Executors.newSingleThreadExecutor(); try { JimfsAsynchronousFileChannel channel = channel(file, executor, READ, WRITE); channel.close(); assertClosed(channel.read(ByteBuffer.allocate(10), 0)); assertClosed(channel.write(ByteBuffer.allocate(10), 15)); assertClosed(channel.lock()); assertClosed(channel.lock(0, 10, true)); } finally { executor.shutdown(); } }
Example #3
Source File: RemotingCommandTest.java From rocketmq-4.3.0 with Apache License 2.0 | 6 votes |
@Test public void testEncodeAndDecode_EmptyBody() { System.setProperty(RemotingCommand.REMOTING_VERSION_KEY, "2333"); int code = 103; //org.apache.rocketmq.common.protocol.RequestCode.REGISTER_BROKER CommandCustomHeader header = new SampleCommandCustomHeader(); RemotingCommand cmd = RemotingCommand.createRequestCommand(code, header); ByteBuffer buffer = cmd.encode(); //Simulate buffer being read in NettyDecoder buffer.getInt(); byte[] bytes = new byte[buffer.limit() - 4]; buffer.get(bytes, 0, buffer.limit() - 4); buffer = ByteBuffer.wrap(bytes); RemotingCommand decodedCommand = RemotingCommand.decode(buffer); assertThat(decodedCommand.getSerializeTypeCurrentRPC()).isEqualTo(SerializeType.JSON); assertThat(decodedCommand.getBody()).isNull(); }
Example #4
Source File: FastIOUtils.java From webanno with Apache License 2.0 | 6 votes |
public static void copy(InputStream aIS, File aTargetFile) throws IOException { aTargetFile.getParentFile().mkdirs(); try ( ReadableByteChannel in = newChannel(aIS); WritableByteChannel out = newChannel(new FileOutputStream(aTargetFile)) ) { final ByteBuffer buffer = allocateDirect(8192); while (in.read(buffer) != -1) { buffer.flip(); out.write(buffer); buffer.compact(); } buffer.flip(); while (buffer.hasRemaining()) { out.write(buffer); } } }
Example #5
Source File: Channels.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
public int write(ByteBuffer src) throws IOException { int len = src.remaining(); int totalWritten = 0; synchronized (writeLock) { while (totalWritten < len) { int bytesToWrite = Math.min((len - totalWritten), TRANSFER_SIZE); if (buf.length < bytesToWrite) buf = new byte[bytesToWrite]; src.get(buf, 0, bytesToWrite); try { begin(); out.write(buf, 0, bytesToWrite); } finally { end(bytesToWrite > 0); } totalWritten += bytesToWrite; } return totalWritten; } }
Example #6
Source File: GeneralColumnDataReader.java From kylin-on-parquet-v2 with Apache License 2.0 | 6 votes |
public ByteBuffer get(int index) { int offset; if (index == 0) { offset = 0; } else { dataBuffer.position(indexStartOffset + ((index - 1) << 2)); offset = dataBuffer.getInt(); } ByteBuffer resultBuffer = dataBuffer.asReadOnlyBuffer(); int startOffset = dataStartOffset + offset; resultBuffer.position(startOffset); int length = resultBuffer.getInt(); resultBuffer.limit(startOffset + 4 + length); return resultBuffer; }
Example #7
Source File: Texture.java From lwjglbook with Apache License 2.0 | 6 votes |
private int createTexture(ByteBuffer buf) { // Create a new OpenGL texture int textureId = glGenTextures(); // Bind the texture glBindTexture(GL_TEXTURE_2D, textureId); // Tell OpenGL how to unpack the RGBA bytes. Each component is 1 byte size glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // Upload the texture data glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buf); // Generate Mip Map glGenerateMipmap(GL_TEXTURE_2D); return textureId; }
Example #8
Source File: CycleTransactionSignScript.java From nyzoVerifier with The Unlicense | 6 votes |
private static List<ByteBuffer> fetchCycleOrder(List<ManagedVerifier> managedVerifiers) { List<ByteBuffer> cycleOrder = new CopyOnWriteArrayList<>(); for (int i = 0; i < managedVerifiers.size() && cycleOrder.isEmpty(); i++) { Message meshRequest = new Message(MessageType.BootstrapRequestV2_35, new BootstrapRequest()); ManagedVerifier verifier = managedVerifiers.get(i); AtomicBoolean processedResponse = new AtomicBoolean(false); Message.fetchTcp(verifier.getHost(), verifier.getPort(), meshRequest, new MessageCallback() { @Override public void responseReceived(Message message) { if (message != null && (message.getContent() instanceof BootstrapResponseV2)) { BootstrapResponseV2 response = (BootstrapResponseV2) message.getContent(); cycleOrder.addAll(response.getCycleVerifiers()); } processedResponse.set(true); } }); // Wait up to 2 seconds for the response to be processed. for (int j = 0; j < 10 && !processedResponse.get(); j++) { ThreadUtil.sleep(200L); } } return cycleOrder; }
Example #9
Source File: ErrorHandler.java From bboxdb with Apache License 2.0 | 6 votes |
/** * Handle error with body result * @return */ @Override public boolean handleServerResult(final BBoxDBConnection bBoxDBConnection, final ByteBuffer encodedPackage, final NetworkOperationFuture future) throws PackageEncodeException { final AbstractBodyResponse result = ErrorResponse.decodePackage(encodedPackage); if(logger.isDebugEnabled()) { logger.debug("Handle error package (seq={}, message={})", result.getSequenceNumber(), result.getBody()); } if(future != null) { future.setMessage(result.getBody()); future.setFailedState(); future.fireCompleteEvent(); } return true; }
Example #10
Source File: ReadByte.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws IOException { ReadableByteChannel channel = new ReadableByteChannel() { public int read(ByteBuffer dst) { dst.put((byte) 129); return 1; } public boolean isOpen() { return true; } public void close() { } }; InputStream in = Channels.newInputStream(channel); int data = in.read(); if (data < 0) throw new RuntimeException( "InputStream.read() spec'd to return 0-255"); }
Example #11
Source File: AnnotationParser.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 6 votes |
private static Object parseAnnotationArray(int length, Class<? extends Annotation> annotationType, ByteBuffer buf, ConstantPool constPool, Class<?> container) { Object[] result = (Object[]) Array.newInstance(annotationType, length); boolean typeMismatch = false; int tag = 0; for (int i = 0; i < length; i++) { tag = buf.get(); if (tag == '@') { result[i] = parseAnnotation(buf, constPool, container, true); } else { skipMemberValue(tag, buf); typeMismatch = true; } } return typeMismatch ? exceptionProxy(tag) : result; }
Example #12
Source File: BytesField.java From paradoxdriver with GNU Lesser General Public License v3.0 | 6 votes |
/** * {@inheritDoc}. */ @Override public FieldValue parse(final ParadoxTable table, final ByteBuffer buffer, final ParadoxField field) { final ByteBuffer bytes = ByteBuffer.allocate(field.getSize()); // Track for NULL values. boolean allZeroes = true; for (int chars = 0; chars < field.getSize(); chars++) { byte value = buffer.get(); bytes.put(value); if (value != 0) { allZeroes = false; } } if (allZeroes) { return NULL; } return new FieldValue(bytes.array(), ParadoxFieldType.BYTES.getSQLType()); }
Example #13
Source File: HadoopRecoverableSerializer.java From flink with Apache License 2.0 | 6 votes |
private static HadoopFsRecoverable deserializeV1(byte[] serialized) throws IOException { final ByteBuffer bb = ByteBuffer.wrap(serialized).order(ByteOrder.LITTLE_ENDIAN); if (bb.getInt() != MAGIC_NUMBER) { throw new IOException("Corrupt data: Unexpected magic number."); } final long offset = bb.getLong(); final byte[] targetFileBytes = new byte[bb.getInt()]; final byte[] tempFileBytes = new byte[bb.getInt()]; bb.get(targetFileBytes); bb.get(tempFileBytes); final String targetPath = new String(targetFileBytes, CHARSET); final String tempPath = new String(tempFileBytes, CHARSET); return new HadoopFsRecoverable(new Path(targetPath), new Path(tempPath), offset); }
Example #14
Source File: ByteBuffAllocator.java From hbase with Apache License 2.0 | 6 votes |
/** * Free all direct buffers if allocated, mainly used for testing. */ @VisibleForTesting public void clean() { while (!buffers.isEmpty()) { ByteBuffer b = buffers.poll(); if (b instanceof DirectBuffer) { DirectBuffer db = (DirectBuffer) b; if (db.cleaner() != null) { db.cleaner().clean(); } } } this.usedBufCount.set(0); this.maxPoolSizeInfoLevelLogged = false; this.poolAllocationBytes.reset(); this.heapAllocationBytes.reset(); this.lastPoolAllocationBytes = 0; this.lastHeapAllocationBytes = 0; }
Example #15
Source File: FileChannelImpl.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
public int write(ByteBuffer src, long position) throws IOException { if (src == null) throw new NullPointerException(); if (position < 0) throw new IllegalArgumentException("Negative position"); if (!writable) throw new NonWritableChannelException(); ensureOpen(); if (nd.needsPositionLock()) { synchronized (positionLock) { return writeInternal(src, position); } } else { return writeInternal(src, position); } }
Example #16
Source File: OpenSslNativeJna.java From commons-crypto with Apache License 2.0 | 5 votes |
public static int EVP_CipherFinal_ex(final PointerByReference context, final ByteBuffer outBuffer, final int[] outlen) { if (VERSION == VERSION_1_1_X) { return OpenSsl11XNativeJna.EVP_CipherFinal_ex(context, outBuffer, outlen); } return OpenSsl10XNativeJna.EVP_CipherFinal_ex(context, outBuffer, outlen); }
Example #17
Source File: GridNioCodecFilter.java From ignite with Apache License 2.0 | 5 votes |
/** {@inheritDoc} */ @Override public void onMessageReceived(GridNioSession ses, Object msg) throws IgniteCheckedException { if (!(msg instanceof ByteBuffer)) throw new GridNioException("Failed to decode incoming message (incoming message is not a byte buffer, " + "is filter properly placed?): " + msg.getClass()); try { ByteBuffer input = (ByteBuffer)msg; while (input.hasRemaining()) { Object res = parser.decode(ses, input); if (res != null) proceedMessageReceived(ses, res); else { if (input.hasRemaining()) { if (directMode) return; LT.warn(log, "Parser returned null but there are still unread data in input buffer (bug in " + "parser code?) [parser=" + parser + ", ses=" + ses + ']'); input.position(input.limit()); } } } } catch (IOException e) { throw new GridNioException(e); } }
Example #18
Source File: NIOMmapFileCopy.java From yuzhouwan with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { final String cont = RandomStringUtils.randomAlphanumeric(8 * 1024 * 1024); try (final FileChannel src = new RandomAccessFile(SOURCE, "rw").getChannel(); final FileChannel dest = new RandomAccessFile(DEST, "rw").getChannel()) { src.write(ByteBuffer.wrap(cont.getBytes())); long start = System.currentTimeMillis(); final MappedByteBuffer mmap = dest.map(FileChannel.MapMode.READ_WRITE, 0, src.size()); src.write(mmap); mmap.flip(); System.out.println("Cost: " + (System.currentTimeMillis() - start) + " ms"); } finally { Files.deleteIfExists(Paths.get(SOURCE)); Files.deleteIfExists(Paths.get(DEST)); } }
Example #19
Source File: WindowsAsynchronousSocketChannelImpl.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 5 votes |
/** * Invoked prior to write to prepare the WSABUF array. Where necessary, * it substitutes non-direct buffers with direct buffers. */ void prepareBuffers() { shadow = new ByteBuffer[numBufs]; long address = writeBufferArray; for (int i=0; i<numBufs; i++) { ByteBuffer src = bufs[i]; int pos = src.position(); int lim = src.limit(); assert (pos <= lim); int rem = (pos <= lim ? lim - pos : 0); long a; if (!(src instanceof DirectBuffer)) { // substitute with direct buffer ByteBuffer bb = Util.getTemporaryDirectBuffer(rem); bb.put(src); bb.flip(); src.position(pos); // leave heap buffer untouched for now shadow[i] = bb; a = ((DirectBuffer)bb).address(); } else { shadow[i] = src; a = ((DirectBuffer)src).address() + pos; } unsafe.putAddress(address + OFFSETOF_BUF, a); unsafe.putInt(address + OFFSETOF_LEN, rem); address += SIZEOF_WSABUF; } }
Example #20
Source File: Position.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws Exception { Path blah = Files.createTempFile("blah", null); blah.toFile().deleteOnExit(); initTestFile(blah); for (int i=0; i<10; i++) { try (FileChannel fc = (generator.nextBoolean()) ? FileChannel.open(blah, READ) : new FileInputStream(blah.toFile()).getChannel()) { for (int j=0; j<100; j++) { long newPos = generator.nextInt(1000); fc.position(newPos); if (fc.position() != newPos) throw new RuntimeException("Position failed"); } } } for (int i=0; i<10; i++) { try (FileChannel fc = (generator.nextBoolean()) ? FileChannel.open(blah, APPEND) : new FileOutputStream(blah.toFile(), true).getChannel()) { for (int j=0; j<10; j++) { if (fc.position() != fc.size()) throw new RuntimeException("Position expected to be size"); byte[] buf = new byte[generator.nextInt(100)]; fc.write(ByteBuffer.wrap(buf)); } } } Files.delete(blah); }
Example #21
Source File: Util.java From hottub with GNU General Public License v2.0 | 5 votes |
static boolean compare(ByteBuffer bb, String str) { try{ return Util.compare(bb, str.getBytes("ISO-8859-1")); } catch (UnsupportedEncodingException unsupported) { throw new AssertionError(unsupported); } }
Example #22
Source File: AkServerUtilTest.java From sql-layer with GNU Affero General Public License v3.0 | 5 votes |
@Test(expected=IllegalArgumentException.class) public void decodeNullCharset() { final byte[] someBytes; someBytes = "some bytes".getBytes(); assertTrue("someBytes was empty!", someBytes.length > 0); AkServerUtil.decodeString(ByteBuffer.wrap(someBytes), null); }
Example #23
Source File: DataInOutputUtils.java From mynlp with Apache License 2.0 | 5 votes |
static int[] readIntArray(ByteBuffer buffer) { int size = buffer.getInt() / 4; int[] ints = new int[size]; buffer.asIntBuffer().get(ints); buffer.position(buffer.position() + size * 4); if (ints.length == 3 && ints[0] == 1123992342 && ints[1] == 832718121 && ints[2] == 957462342) { return null; } return ints; }
Example #24
Source File: PublishServiceImplTest.java From hivemq-community-edition with Apache License 2.0 | 5 votes |
@Test(expected = RateLimitExceededException.class) public void test_publish_rate_limit_exceeded() throws Throwable { when(rateLimitService.rateLimitExceeded()).thenReturn(true); final Publish publish = new PublishBuilderImpl(fullConfigurationService).topic("topic").payload(ByteBuffer.wrap("message".getBytes())).build(); try { publishService.publish(publish).get(); } catch (final ExecutionException e) { throw e.getCause(); } }
Example #25
Source File: Util.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
static boolean compare(ByteBuffer bb, String str) { try{ return Util.compare(bb, str.getBytes("ISO-8859-1")); } catch (UnsupportedEncodingException unsupported) { throw new AssertionError(unsupported); } }
Example #26
Source File: AvroMessageDeserializer.java From Kafdrop with Apache License 2.0 | 5 votes |
@Override public String deserializeMessage(ByteBuffer buffer) { KafkaAvroDeserializer deserializer = getDeserializer(); // Convert byte buffer to byte array byte[] bytes = ByteUtils.convertToByteArray(buffer); return formatJsonMessage(deserializer.deserialize(topicName, bytes).toString()); }
Example #27
Source File: PlayerTransferService.java From aion-germany with GNU General Public License v3.0 | 5 votes |
/** * sent from login to target server with character information from source server */ public void cloneCharacter(int taskId, int targetAccountId, String name, String account, byte[] db) { if (!PlayerService.isFreeName(name)) { if (PlayerTransferConfig.BLOCK_SAMENAME) { LoginServer.getInstance().sendPacket(new SM_PTRANSFER_CONTROL(SM_PTRANSFER_CONTROL.ERROR, taskId, "Name is already in use")); return; } log.info("Name is already in use `" + name + "`"); textLog.info("taskId:" + taskId + "; [CloneCharacter:!isFreeName]"); String newName = name + PlayerTransferConfig.NAME_PREFIX; int i = 0; while (!PlayerService.isFreeName(newName)) { newName = name + PlayerTransferConfig.NAME_PREFIX + i; } name = newName; } if (AccountService.loadAccount(targetAccountId).size() >= GSConfig.CHARACTER_LIMIT_COUNT) { LoginServer.getInstance().sendPacket(new SM_PTRANSFER_CONTROL(SM_PTRANSFER_CONTROL.ERROR, taskId, "No free character slots")); return; } CMT_CHARACTER_INFORMATION acp = new CMT_CHARACTER_INFORMATION(0, State.CONNECTED); acp.setBuffer(ByteBuffer.wrap(db).order(ByteOrder.LITTLE_ENDIAN)); Player cha = acp.readInfo(name, targetAccountId, account, rsList, textLog); if (cha == null) { // something went wrong! log.error("clone failed #" + taskId + " `" + name + "`"); LoginServer.getInstance().sendPacket(new SM_PTRANSFER_CONTROL(SM_PTRANSFER_CONTROL.ERROR, taskId, "unexpected sql error while creating a clone")); } else { DAOManager.getDAO(PlayerDAO.class).setPlayerLastTransferTime(cha.getObjectId(), System.currentTimeMillis()); LoginServer.getInstance().sendPacket(new SM_PTRANSFER_CONTROL(SM_PTRANSFER_CONTROL.OK, taskId)); log.info("clone successful #" + taskId + " `" + name + "`"); textLog.info("taskId:" + taskId + "; [CloneCharacter:Done]"); } }
Example #28
Source File: CIDRUtils.java From XRTB with Apache License 2.0 | 5 votes |
public long getEndAddress() { ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE); buffer.put(endAddress.getAddress()); buffer.position(0); Long longValue = buffer.getLong(); return longValue; }
Example #29
Source File: DefaultAudioSink.java From TelePlus-Android with GNU General Public License v2.0 | 5 votes |
/** * Creates a new default audio sink, optionally using float output for high resolution PCM and * with the specified {@code audioProcessorChain}. * * @param audioCapabilities The audio capabilities for playback on this device. May be null if the * default capabilities (no encoded audio passthrough support) should be assumed. * @param audioProcessorChain An {@link AudioProcessorChain} which is used to apply playback * parameters adjustments. The instance passed in must not be reused in other sinks. * @param enableConvertHighResIntPcmToFloat Whether to enable conversion of high resolution * integer PCM to 32-bit float for output, if possible. Functionality that uses 16-bit integer * audio processing (for example, speed and pitch adjustment) will not be available when float * output is in use. */ public DefaultAudioSink( @Nullable AudioCapabilities audioCapabilities, AudioProcessorChain audioProcessorChain, boolean enableConvertHighResIntPcmToFloat) { this.audioCapabilities = audioCapabilities; this.audioProcessorChain = Assertions.checkNotNull(audioProcessorChain); this.enableConvertHighResIntPcmToFloat = enableConvertHighResIntPcmToFloat; releasingConditionVariable = new ConditionVariable(true); audioTrackPositionTracker = new AudioTrackPositionTracker(new PositionTrackerListener()); channelMappingAudioProcessor = new ChannelMappingAudioProcessor(); trimmingAudioProcessor = new TrimmingAudioProcessor(); ArrayList<AudioProcessor> toIntPcmAudioProcessors = new ArrayList<>(); Collections.addAll( toIntPcmAudioProcessors, new ResamplingAudioProcessor(), channelMappingAudioProcessor, trimmingAudioProcessor); Collections.addAll(toIntPcmAudioProcessors, audioProcessorChain.getAudioProcessors()); toIntPcmAvailableAudioProcessors = toIntPcmAudioProcessors.toArray(new AudioProcessor[toIntPcmAudioProcessors.size()]); toFloatPcmAvailableAudioProcessors = new AudioProcessor[] {new FloatResamplingAudioProcessor()}; volume = 1.0f; startMediaTimeState = START_NOT_SET; audioAttributes = AudioAttributes.DEFAULT; audioSessionId = C.AUDIO_SESSION_ID_UNSET; playbackParameters = PlaybackParameters.DEFAULT; drainingAudioProcessorIndex = C.INDEX_UNSET; activeAudioProcessors = new AudioProcessor[0]; outputBuffers = new ByteBuffer[0]; playbackParametersCheckpoints = new ArrayDeque<>(); }
Example #30
Source File: UnsafeOptimizeStringColumnBinaryMaker.java From multiple-dimension-spread with Apache License 2.0 | 5 votes |
@Override public IColumn toColumn( final ColumnBinary columnBinary ) throws IOException{ ByteBuffer wrapBuffer = ByteBuffer.wrap( columnBinary.binary , columnBinary.binaryStart , columnBinary.binaryLength ); int minLength = wrapBuffer.getInt(); char[] minCharArray = new char[minLength / Character.BYTES]; wrapBuffer.asCharBuffer().get( minCharArray ); wrapBuffer.position( wrapBuffer.position() + minLength ); int maxLength = wrapBuffer.getInt(); char[] maxCharArray = new char[maxLength / Character.BYTES]; wrapBuffer.asCharBuffer().get( maxCharArray ); wrapBuffer.position( wrapBuffer.position() + maxLength ); String min = new String( minCharArray ); String max = new String( maxCharArray ); int headerSize = Integer.BYTES + minLength + Integer.BYTES + maxLength; return new HeaderIndexLazyColumn( columnBinary.columnName , columnBinary.columnType , new StringColumnManager( columnBinary , columnBinary.binaryStart + headerSize , columnBinary.binaryLength - headerSize ) , new RangeStringIndex( min , max ) ); }