List of usage examples for java.nio ByteBuffer allocateDirect
public static ByteBuffer allocateDirect(int capacity)
From source file:org.neo4j.io.pagecache.impl.SingleFilePageSwapperTest.java
@Test public void mustZeroFillPageBeyondEndOfFile() throws IOException { byte[] bytes = new byte[] { // --- page 0: 1, 2, 3, 4,// w w w. j a v a 2s . c o m // --- page 1: 5, 6 }; StoreChannel channel = getFs().create(getFile()); channel.writeAll(wrap(bytes)); channel.close(); PageSwapperFactory factory = swapperFactory(); PageSwapper swapper = createSwapper(factory, getFile(), 4, null, false); ByteBuffer target = ByteBuffer.allocateDirect(4); ByteBufferPage page = new ByteBufferPage(target); swapper.read(1, page); assertThat(array(target), byteArray(new byte[] { 5, 6, 0, 0 })); }
From source file:com.alvermont.terraj.fracplanet.geom.TriangleBufferArray.java
/** * Create a TriangleBufferArray with a specified capacity * * @param capacity The number of elements this buffer should be capable of holding */// w w w .j av a 2 s.c om public TriangleBufferArray(int capacity) { this.buffer = ByteBuffer.allocateDirect(capacity * INTS_PER_ENTRY * SIZEOF_INT) .order(ByteOrder.nativeOrder()).asIntBuffer(); this.buffer.limit(0); }
From source file:edu.hawaii.soest.pacioos.text.SocketTextSource.java
@Override protected boolean execute() { log.debug("SocketTextSource.execute() called."); // do not execute the stream if there is no connection if (!isConnected()) return false; boolean failed = false; /* Get a connection to the instrument */ SocketChannel socket = getSocketConnection(); if (socket == null) return false; // while data are being sent, read them into the buffer try {//from ww w . ja va2s .c o m // create four byte placeholders used to evaluate up to a four-byte // window. The FIFO layout looks like: // ------------------------- // in ---> | One | Two |Three|Four | ---> out // ------------------------- byte byteOne = 0x00, // set initial placeholder values byteTwo = 0x00, byteThree = 0x00, byteFour = 0x00; // Create a buffer that will store the sample bytes as they are read ByteBuffer sampleBuffer = ByteBuffer.allocate(getBufferSize()); // create a byte buffer to store bytes from the TCP stream ByteBuffer buffer = ByteBuffer.allocateDirect(getBufferSize()); // while there are bytes to read from the socket ... while (socket.read(buffer) != -1 || buffer.position() > 0) { // prepare the buffer for reading buffer.flip(); // while there are unread bytes in the ByteBuffer while (buffer.hasRemaining()) { byteOne = buffer.get(); // log the byte stream String character = new String(new byte[] { byteOne }); if (log.isDebugEnabled()) { List<Byte> whitespaceBytes = new ArrayList<Byte>(); whitespaceBytes.add(new Byte((byte) 0x0A)); whitespaceBytes.add(new Byte((byte) 0x0D)); if (whitespaceBytes.contains(new Byte(byteOne))) { character = new String(Hex.encodeHex((new byte[] { byteOne }))); } } log.debug("char: " + character + "\t" + "b1: " + new String(Hex.encodeHex((new byte[] { byteOne }))) + "\t" + "b2: " + new String(Hex.encodeHex((new byte[] { byteTwo }))) + "\t" + "b3: " + new String(Hex.encodeHex((new byte[] { byteThree }))) + "\t" + "b4: " + new String(Hex.encodeHex((new byte[] { byteFour }))) + "\t" + "sample pos: " + sampleBuffer.position() + "\t" + "sample rem: " + sampleBuffer.remaining() + "\t" + "sample cnt: " + sampleByteCount + "\t" + "buffer pos: " + buffer.position() + "\t" + "buffer rem: " + buffer.remaining() + "\t" + "state: " + state); // evaluate each byte to find the record delimiter(s), and when found, validate and // send the sample to the DataTurbine. int numberOfChannelsFlushed = 0; if (getRecordDelimiters().length == 2) { // have we hit the delimiters in the stream yet? if (byteTwo == getFirstDelimiterByte() && byteOne == getSecondDelimiterByte()) { sampleBuffer.put(byteOne); sampleByteCount++; // extract just the length of the sample bytes out of the // sample buffer, and place it in the channel map as a // byte array. Then, send it to the DataTurbine. log.debug("Sample byte count: " + sampleByteCount); byte[] sampleArray = new byte[sampleByteCount]; sampleBuffer.flip(); sampleBuffer.get(sampleArray); String sampleString = new String(sampleArray, "US-ASCII"); if (validateSample(sampleString)) { numberOfChannelsFlushed = sendSample(sampleString); } sampleBuffer.clear(); sampleByteCount = 0; byteOne = 0x00; byteTwo = 0x00; byteThree = 0x00; byteFour = 0x00; log.debug("Cleared b1,b2,b3,b4. Cleared sampleBuffer. Cleared rbnbChannelMap."); } else { // still in the middle of the sample, keep adding bytes sampleByteCount++; // add each byte found if (sampleBuffer.remaining() > 0) { sampleBuffer.put(byteOne); } else { sampleBuffer.compact(); log.debug("Compacting sampleBuffer ..."); sampleBuffer.put(byteOne); } } } else if (getRecordDelimiters().length == 1) { // have we hit the delimiter in the stream yet? if (byteOne == getFirstDelimiterByte()) { sampleBuffer.put(byteOne); sampleByteCount++; // extract just the length of the sample bytes out of the // sample buffer, and place it in the channel map as a // byte array. Then, send it to the DataTurbine. byte[] sampleArray = new byte[sampleByteCount]; sampleBuffer.flip(); sampleBuffer.get(sampleArray); String sampleString = new String(sampleArray, "US-ASCII"); if (validateSample(sampleString)) { numberOfChannelsFlushed = sendSample(sampleString); } sampleBuffer.clear(); sampleByteCount = 0; byteOne = 0x00; byteTwo = 0x00; byteThree = 0x00; byteFour = 0x00; log.debug("Cleared b1,b2,b3,b4. Cleared sampleBuffer. Cleared rbnbChannelMap."); } else { // still in the middle of the sample, keep adding bytes sampleByteCount++; // add each byte found if (sampleBuffer.remaining() > 0) { sampleBuffer.put(byteOne); } else { sampleBuffer.compact(); log.debug("Compacting sampleBuffer ..."); sampleBuffer.put(byteOne); } } } // end getRecordDelimiters().length // shift the bytes in the FIFO window byteFour = byteThree; byteThree = byteTwo; byteTwo = byteOne; } //end while (more unread bytes) // prepare the buffer to read in more bytes from the stream buffer.compact(); } // end while (more socket bytes to read) socket.close(); } catch (IOException e) { // handle exceptions // In the event of an i/o exception, log the exception, and allow execute() // to return false, which will prompt a retry. failed = true; log.error("There was a communication error in sending the data sample. The message was: " + e.getMessage()); if (log.isDebugEnabled()) { e.printStackTrace(); } return !failed; } catch (SAPIException sapie) { // In the event of an RBNB communication exception, log the exception, // and allow execute() to return false, which will prompt a retry. failed = true; log.error("There was an RBNB error while sending the data sample. The message was: " + sapie.getMessage()); if (log.isDebugEnabled()) { sapie.printStackTrace(); } return !failed; } return !failed; }
From source file:com.chicm.cmraft.rpc.PacketUtils.java
public static RpcCall parseRpcRequestFromChannel(AsynchronousSocketChannel channel, BlockingService service) throws InterruptedException, ExecutionException, IOException { RpcCall call = null;//from w w w .ja va2s .co m long t = System.currentTimeMillis(); InputStream in = Channels.newInputStream(channel); byte[] datasize = new byte[MESSAGE_LENGHT_FIELD_SIZE]; in.read(datasize); int nDataSize = bytes2Int(datasize); int len = 0; ByteBuffer buf = ByteBuffer.allocateDirect(nDataSize); for (; len < nDataSize;) { len += channel.read(buf).get(); } if (len < nDataSize) { LOG.error("SOCKET READ FAILED, len:" + len); return call; } byte[] data = new byte[nDataSize]; buf.flip(); buf.get(data); int offset = 0; CodedInputStream cis = CodedInputStream.newInstance(data, offset, nDataSize - offset); int headerSize = cis.readRawVarint32(); offset += cis.getTotalBytesRead(); RequestHeader header = RequestHeader.newBuilder().mergeFrom(data, offset, headerSize).build(); offset += headerSize; cis.skipRawBytes(headerSize); cis.resetSizeCounter(); int bodySize = cis.readRawVarint32(); offset += cis.getTotalBytesRead(); //LOG.debug("header parsed:" + header.toString()); MethodDescriptor md = service.getDescriptorForType().findMethodByName(header.getRequestName()); Builder builder = service.getRequestPrototype(md).newBuilderForType(); Message body = null; if (builder != null) { body = builder.mergeFrom(data, offset, bodySize).build(); //LOG.debug("server : request parsed:" + body.toString()); } call = new RpcCall(header.getId(), header, body, md); if (LOG.isTraceEnabled()) { LOG.trace("Parse Rpc request from socket: " + call.getCallId() + ", takes" + (System.currentTimeMillis() - t) + " ms"); } return call; }
From source file:io.horizondb.io.buffers.DirectBuffer.java
/** * Creates a new <code>DirectBuffer</code> with the specified capacity. * //from www .jav a 2 s . c om * @param capacity the buffer capacity. */ DirectBuffer(int capacity) { isTrue(capacity >= 0, "the capacity must be positive"); this.buffer = ByteBuffer.allocateDirect(capacity); subRegion(0, capacity); writerIndex(0); }
From source file:org.solmix.commons.util.Files.java
/** * ?/*from ww w . j a v a 2 s. c o m*/ * * @param f1 * ? * @param f2 * * @throws Exception */ public static void copyFile(File f1, File f2) throws Exception { int length = 2097152; FileInputStream in = new FileInputStream(f1); FileOutputStream out = new FileOutputStream(f2); FileChannel inC = in.getChannel(); FileChannel outC = out.getChannel(); ByteBuffer b = null; while (true) { if (inC.position() == inC.size()) { inC.close(); outC.close(); } if ((inC.size() - inC.position()) < length) { length = (int) (inC.size() - inC.position()); } else length = 2097152; b = ByteBuffer.allocateDirect(length); inC.read(b); b.flip(); outC.write(b); outC.force(false); } }
From source file:Main.java
public static IntBuffer createIntBuffer(final int size) { final IntBuffer buf = ByteBuffer.allocateDirect(4 * size).order(ByteOrder.nativeOrder()).asIntBuffer(); buf.clear();//from w w w.ja v a 2 s. c om return buf; }
From source file:org.carlspring.strongbox.storage.metadata.nuget.TempNupkgFile.java
/** * Copies data from one channel to another * * @param src// w ww . j a v a 2 s . c om * channel source * @param dest * destination channel * @throws IOException * input / output error */ private static void fastChannelCopy(final ReadableByteChannel src, final WritableByteChannel dest) throws IOException { final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024); while (src.read(buffer) != -1) { buffer.flip(); dest.write(buffer); buffer.compact(); } buffer.flip(); while (buffer.hasRemaining()) { dest.write(buffer); } }
From source file:com.digium.respokesdk.RespokeDirectConnection.java
/** * Send a message to the remote client through the direct connection. * * @param message The message to send * @param completionListener A listener to receive a notification on the success of the asynchronous operation *//* w w w .j ava 2 s . c om*/ public void sendMessage(String message, final Respoke.TaskCompletionListener completionListener) { if (isActive()) { JSONObject jsonMessage = new JSONObject(); try { jsonMessage.put("message", message); byte[] rawMessage = jsonMessage.toString().getBytes(Charset.forName("UTF-8")); ByteBuffer directData = ByteBuffer.allocateDirect(rawMessage.length); directData.put(rawMessage); directData.flip(); DataChannel.Buffer data = new DataChannel.Buffer(directData, false); if (dataChannel.send(data)) { Respoke.postTaskSuccess(completionListener); } else { Respoke.postTaskError(completionListener, "Error sending message"); } } catch (JSONException e) { Respoke.postTaskError(completionListener, "Unable to encode message to JSON"); } } else { Respoke.postTaskError(completionListener, "DataChannel not in an open state"); } }
From source file:nextflow.fs.dx.DxUploadOutputStream.java
/** * Create a new byte buffer to hold parallel chunks uploads. Override to use custom * buffer capacity or strategy e.g. {@code DirectBuffer} * * @return The {@code ByteBuffer} instance *///w w w. j a v a2 s . c o m protected ByteBuffer allocate() { return ByteBuffer.allocateDirect(defaultCapacity); }