List of usage examples for java.nio ByteBuffer flip
public final Buffer flip()
From source file:com.taobao.tair.comm.TairClient.java
public void invokeAsync(final BasePacket packet, final long timeout, ResponseListener listener) { if (isDebugEnabled) { LOGGER.debug("send request [" + packet.getChid() + "] async,time is:" + System.currentTimeMillis()); }//from w w w .j a v a 2 s .c o m if (minTimeout > timeout) { minTimeout = timeout; } final ResponseCallbackTask callbackTask = new ResponseCallbackTask(packet.getChid(), listener, this.session, timeout); callbackTasks.put(packet.getChid(), callbackTask); ByteBuffer bb = packet.getByteBuffer(); bb.flip(); byte[] data = new byte[bb.remaining()]; bb.get(data); WriteFuture writeFuture = session.write(data); writeFuture.addListener(new IoFutureListener() { public void operationComplete(IoFuture future) { WriteFuture wfuture = (WriteFuture) future; if (wfuture.isWritten()) { return; } String error = "send message to tair server error [" + packet.getChid() + "], tair server: " + session.getRemoteAddress() + ", maybe because this connection closed :" + !session.isConnected(); LOGGER.warn(error); callbackTask.setResponse(new TairClientException(error)); // close this session if (session.isConnected()) session.close(); else clientFactory.removeClient(key); } }); }
From source file:com.streamsets.pipeline.lib.generator.wholefile.WholeFileDataGenerator.java
@Override public void write(Record record) throws IOException, DataGeneratorException { validateRecord(record);/* w w w .ja v a 2 s. c om*/ FileRef fileRef = record.get(FileRefUtil.FILE_REF_FIELD_PATH).getValueAsFileRef(); int bufferSize = fileRef.getBufferSize(); boolean canUseDirectByteBuffer = fileRef.getSupportedStreamClasses().contains(ReadableByteChannel.class); if (canUseDirectByteBuffer) { //Don't have to close this here, because generate.close will call output stream close WritableByteChannel writableByteChannel = Channels.newChannel(outputStream); //NOSONAR try (ReadableByteChannel readableByteChannel = getReadableStream(fileRef, ReadableByteChannel.class)) { ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize); while ((readableByteChannel.read(buffer)) > 0) { //Flip to use the buffer from 0 to position. buffer.flip(); while (buffer.hasRemaining()) { writableByteChannel.write(buffer); } //Compact the buffer for reuse. buffer.clear(); } } } else { byte[] b = new byte[bufferSize]; try (InputStream stream = getReadableStream(fileRef, InputStream.class)) { IOUtils.copyLarge(stream, outputStream, b); } } }
From source file:com.openteach.diamond.network.waverider.command.Command.java
/** * ByteBuffer//from ww w.j a v a 2s .c o m * @return */ public ByteBuffer marshall() { int length = getSize(); ByteBuffer buffer = ByteBuffer.allocate(length); buffer.putLong(type); buffer.putInt(length); buffer.put(payLoad); buffer.flip(); payLoad.clear(); return buffer; }
From source file:net.socket.nio.TimeClientHandle.java
private void handleInput(SelectionKey key) throws IOException { if (key.isValid()) { // ??/* w w w .jav a2 s . co m*/ SocketChannel sc = (SocketChannel) key.channel(); if (key.isConnectable()) { if (sc.finishConnect()) { sc.register(selector, SelectionKey.OP_READ); doWrite(sc); } else { System.exit(1);// } } if (key.isReadable()) { ByteBuffer readBuffer = ByteBuffer.allocate(1024); int readBytes = sc.read(readBuffer); if (readBytes > 0) { readBuffer.flip(); byte[] bytes = new byte[readBuffer.remaining()]; readBuffer.get(bytes); String body = new String(bytes, "UTF-8"); System.out.println("Now is : " + body); this.stop = true; } else if (readBytes < 0) { // key.cancel(); sc.close(); } else { ; // 0 } } } }
From source file:com.unister.semweb.drums.file.SpecificEnlargmentTest.java
/** Converts the given {@link List} of {@link TestStorable} to a {@link ByteBuffer}. */ private ByteBuffer toByteBuffer(List<TestStorable> toConvert) { ByteBuffer buffer = ByteBuffer.allocate(toConvert.size() * globalParameters.getElementSize()); for (TestStorable oneElement : toConvert) { buffer.put(oneElement.toByteBuffer()); }//w w w . ja v a2 s.c o m buffer.flip(); return buffer; }
From source file:com.koda.integ.hbase.test.BlockCacheSimpleTest.java
/** * Test byte cacheable./*from ww w . j ava 2s. co m*/ * * @throws IOException Signals that an I/O exception has occurred. */ public void testByteCacheable() throws IOException { LOG.info("Test byte cacheable started"); byte[] array = new byte[30000]; Random r = new Random(); r.nextBytes(array); ByteArrayCacheable bac = new ByteArrayCacheable(array); ByteBuffer buf = ByteBuffer.allocate(100000); bac.serialize(buf); buf.flip(); ByteArrayCacheable bb = (ByteArrayCacheable) ByteArrayCacheable.deserializer.deserialize(buf); assertTrue(bb.equals(bac)); LOG.info("Test byte cacheable finished"); }
From source file:com.taobao.common.tfs.comm.TfsClient.java
public Object invoke(final BasePacket packet, final long timeout) throws TfsException { if (isDebugEnabled) { log.debug("send request [" + packet.getChid() + "],time is:" + System.currentTimeMillis()); }/*from ww w . j a va2s. c o m*/ ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(1); responses.put(packet.getChid(), queue); ByteBuffer bb = packet.getByteBuffer(); bb.flip(); byte[] data = new byte[bb.remaining()]; bb.get(data); WriteFuture writeFuture = session.write(data); writeFuture.addListener(new IoFutureListener() { public void operationComplete(IoFuture future) { WriteFuture wfuture = (WriteFuture) future; if (wfuture.isWritten()) { return; } String error = "send message to tfs server error [" + packet.getChid() + "], tfs server: " + session.getRemoteAddress() + ", maybe because this connection closed: " + !session.isConnected(); try { putResponse(packet.getChid(), new TfsException(error)); } catch (TfsException e) { // should never happen log.error("put response fail", e); } // close this session if (session.isConnected()) { session.close(); } else { TfsClientFactory.getInstance().removeClient(key); } } }); Object response = null; try { response = queue.poll(timeout, TimeUnit.MILLISECONDS); if (response == null) { // timeout return null; } else if (response instanceof TfsException) { throw (TfsException) response; } } catch (InterruptedException e) { throw new TfsException("tfs client invoke error", e); } finally { responses.remove(packet.getChid()); // For GC queue = null; } if (isDebugEnabled) { log.debug("return response [" + packet.getChid() + "],time is:" + System.currentTimeMillis()); } // do decode here if (response instanceof BasePacket) { ((BasePacket) response).decode(); } return response; }
From source file:com.sm.store.utils.FileStore.java
private boolean checkSignature(FileChannel channel) throws IOException { ByteBuffer intBytes = ByteBuffer.allocate(OFFSET); if (channel.size() == 0) { intBytes.putInt(MAGIC);/* w w w . j a v a 2s . c o m*/ intBytes.flip(); channel.write(intBytes); return true; } else { channel.read(intBytes); intBytes.rewind(); if (intBytes.getInt() != MAGIC) throw new StoreException("Header mismatch expect " + MAGIC + " read " + intBytes.getInt()); } return true; }
From source file:com.taobao.tair.comm.TairClient.java
public Object invoke(final BasePacket packet, final long timeout) throws TairClientException { if (isDebugEnabled) { LOGGER.debug("send request [" + packet.getChid() + "],time is:" + System.currentTimeMillis()); }/*from w w w . j a v a2 s .c om*/ ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(1); responses.put(packet.getChid(), queue); ByteBuffer bb = packet.getByteBuffer(); bb.flip(); byte[] data = new byte[bb.remaining()]; bb.get(data); WriteFuture writeFuture = session.write(data); writeFuture.addListener(new IoFutureListener() { public void operationComplete(IoFuture future) { WriteFuture wfuture = (WriteFuture) future; if (wfuture.isWritten()) { return; } String error = "send message to tair server error [" + packet.getChid() + "], tair server: " + session.getRemoteAddress() + ", maybe because this connection closed :" + !session.isConnected(); LOGGER.warn(error); TairResponse response = new TairResponse(); response.setRequestId(packet.getChid()); response.setResponse(new TairClientException(error)); try { putResponse(packet.getChid(), response.getResponse()); } catch (TairClientException e) { // IGNORE,should not happen } // close this session if (session.isConnected()) session.close(); else clientFactory.removeClient(key); } }); Object response = null; try { response = queue.poll(timeout, TimeUnit.MILLISECONDS); if (response == null) { throw new TairClientException("tair client invoke timeout,timeout is: " + timeout + ",requestId is: " + packet.getChid() + "request type:" + packet.getClass().getName()); } else if (response instanceof TairClientException) { throw (TairClientException) response; } } catch (InterruptedException e) { throw new TairClientException("tair client invoke error", e); } finally { responses.remove(packet.getChid()); // For GC queue = null; } if (isDebugEnabled) { LOGGER.debug("return response [" + packet.getChid() + "],time is:" + System.currentTimeMillis()); LOGGER.debug("current responses size: " + responses.size()); } // do decode here if (response instanceof BasePacket) { ((BasePacket) response).decode(); } return response; }
From source file:com.buaa.cfs.common.oncrpc.XDR.java
public XDR asReadOnlyWrap() { ByteBuffer b = buf.asReadOnlyBuffer(); if (state == State.WRITING) { b.flip(); }//from ww w. j ava 2s .c o m XDR n = new XDR(b, State.READING); return n; }