List of usage examples for java.nio ByteBuffer remaining
public final int remaining()
From source file:gda.device.scannable.keyence.Keyence.java
/** * Send command to the server./*from www. j av a 2 s .c o m*/ * * @param msg * an unterminated command * @param expectedReplyItems * @return the reply string. * @throws DeviceException */ public Object[] processImageRequest(String msg, int expectedReplyItems) throws DeviceException { if (expectedReplyItems < 2) throw new IllegalArgumentException("need at least two values for images (length definition and data)"); String command = msg + '\r'; Object reply[] = new Object[expectedReplyItems + 1]; logger.debug(getName() + ": sent command: " + msg); synchronized (socketAccessLock) { try { if (!isConnected()) { throw new DeviceException("not connected"); } cleanPipe(); socketChannel.write(encoder.encode(CharBuffer.wrap(command))); ByteBuffer singleByte = ByteBuffer.allocate(1); StringBuilder sb = new StringBuilder(); int argCounter = 0; while (argCounter < expectedReplyItems) { singleByte.clear(); socketChannel.socket().setSoTimeout(socketTimeOut); socketChannel.configureBlocking(true); while (singleByte.position() == 0) socketChannel.read(singleByte); singleByte.flip(); String c = decoder.decode(singleByte).toString(); logger.debug(c.toString()); if (c.equals(",")) { reply[argCounter] = sb.toString(); sb = new StringBuilder(); argCounter++; } else if (c.equals("\r")) { throw new DeviceException( "sendCommand: not enough data for image received - suspect an error"); } else { sb.append(c); } } int imageLength = Integer.parseInt(reply[expectedReplyItems - 1].toString()); byte[] imageData = new byte[imageLength]; ByteBuffer bybu = ByteBuffer.wrap(imageData); while (bybu.remaining() != 0) { socketChannel.read(bybu); } reply[expectedReplyItems] = imageData; } catch (SocketTimeoutException ex) { throw new DeviceException("sendCommand read timeout " + ex.getMessage(), ex); } catch (IOException ex) { // treat as fatal connected = false; throw new DeviceException("sendCommand: " + ex.getMessage(), ex); } } return reply; }
From source file:com.github.cambierr.lorawanpacket.semtech.Rxpk.java
public JSONObject toJson() throws MalformedPacketException { JSONObject output = new JSONObject(); output.put("time", time); output.put("tmst", tmst); output.put("freq", freq); output.put("chan", chan); output.put("rfch", rfch); output.put("stat", stat); output.put("modu", modu.name()); if (modu.equals(Modulation.LORA)) { output.put("codr", codr); output.put("lsnr", lsnr); }/*from w ww. jav a2 s . c o m*/ output.put("datr", datr); output.put("rssi", rssi); output.put("size", size); ByteBuffer bb = ByteBuffer.allocate(384); data.toRaw(bb); output.put("data", Base64.getEncoder() .encodeToString(Arrays.copyOfRange(bb.array(), 0, bb.capacity() - bb.remaining()))); return output; }
From source file:com.googlecode.mp4parser.boxes.microsoft.XtraBox.java
@Override public void _parseDetails(ByteBuffer content) { int boxSize = content.remaining(); data = content.slice(); //Keep this in case we fail to parse successfulParse = false;/*from ww w . j a va 2 s.c om*/ try { tags.clear(); while (content.remaining() > 0) { XtraTag tag = new XtraTag(); tag.parse(content); tags.addElement(tag); } int calcSize = detailSize(); if (boxSize != calcSize) { throw new RuntimeException("Improperly handled Xtra tag: Calculated sizes don't match ( " + boxSize + "/" + calcSize + ")"); } successfulParse = true; } catch (Exception e) { successfulParse = false; System.err.println("Malformed Xtra Tag detected: " + e.toString()); e.printStackTrace(); content.position(content.position() + content.remaining()); } finally { content.order(ByteOrder.BIG_ENDIAN); //Just in case we bailed out mid-parse we don't want to leave the byte order in MS land } }
From source file:com.openteach.diamond.network.waverider.session.DefaultSession.java
@Override public void onWrite() throws IOException { logger.debug("onWrite"); int count = 0; Command command = null;/*from ww w.j ava 2 s. com*/ Packet packet = null; ByteBuffer data = null; while ((command = outputBuffer.poll()) != null) { packet = Packet.newDataPacket(command); data = packet.marshall(); count += data.remaining(); while (data.hasRemaining()) { channel.write(data); } // flush channel.socket().getOutputStream().flush(); } //logger.info("Session is onWrite, write " + count + " bytes"); }
From source file:com.bittorrent.mpetazzoni.common.Torrent.java
private static String hashFiles(List<File> files) throws InterruptedException, IOException { int threads = getHashingThreadsCount(); ExecutorService executor = Executors.newFixedThreadPool(threads); ByteBuffer buffer = ByteBuffer.allocate(Torrent.PIECE_LENGTH); List<Future<String>> results = new LinkedList<Future<String>>(); StringBuilder hashes = new StringBuilder(); long length = 0L; int pieces = 0; long start = System.nanoTime(); for (File file : files) { logger.info("Hashing data from {} with {} threads ({} pieces)...", new Object[] { file.getName(), threads, (int) (Math.ceil((double) file.length() / Torrent.PIECE_LENGTH)) }); length += file.length();// ww w.j a v a 2 s . co m FileInputStream fis = new FileInputStream(file); FileChannel channel = fis.getChannel(); int step = 10; try { while (channel.read(buffer) > 0) { if (buffer.remaining() == 0) { buffer.clear(); results.add(executor.submit(new CallableChunkHasher(buffer))); } if (results.size() >= threads) { pieces += accumulateHashes(hashes, results); } if (channel.position() / (double) channel.size() * 100f > step) { logger.info(" ... {}% complete", step); step += 10; } } } finally { channel.close(); fis.close(); } } // Hash the last bit, if any if (buffer.position() > 0) { buffer.limit(buffer.position()); buffer.position(0); results.add(executor.submit(new CallableChunkHasher(buffer))); } pieces += accumulateHashes(hashes, results); // Request orderly executor shutdown and wait for hashing tasks to // complete. executor.shutdown(); while (!executor.isTerminated()) { Thread.sleep(10); } long elapsed = System.nanoTime() - start; int expectedPieces = (int) (Math.ceil((double) length / Torrent.PIECE_LENGTH)); logger.info("Hashed {} file(s) ({} bytes) in {} pieces ({} expected) in {}ms.", new Object[] { files.size(), length, pieces, expectedPieces, String.format("%.1f", elapsed / 1e6), }); return hashes.toString(); }
From source file:edu.umass.cs.nio.MessageExtractor.java
private void processMessageInternal(SocketChannel socket, ByteBuffer incoming) throws IOException { /* The emulated delay value is in the message, so we need to read all * bytes off incoming and stringify right away. */ long delay = -1; if (JSONDelayEmulator.isDelayEmulated()) { byte[] msg = new byte[incoming.remaining()]; incoming.get(msg);/*www .j av a2 s. com*/ String message = new String(msg, MessageNIOTransport.NIO_CHARSET_ENCODING); // always true because of max(0,delay) if ((delay = Math.max(0, JSONDelayEmulator.getEmulatedDelay(message))) >= 0) // run in a separate thread after scheduled delay executor.schedule(new MessageWorker(socket, msg, packetDemuxes), delay, TimeUnit.MILLISECONDS); } else // run it immediately this.demultiplexMessage(new NIOHeader((InetSocketAddress) socket.getRemoteAddress(), (InetSocketAddress) socket.getLocalAddress()), incoming); }
From source file:hivemall.mf.OnlineMatrixFactorizationUDTF.java
protected void beforeTrain(final long rowNum, final int user, final int item, final double rating) throws HiveException { if (inputBuf != null) { assert (fileIO != null); final ByteBuffer buf = inputBuf; int remain = buf.remaining(); if (remain < RECORD_BYTES) { writeBuffer(buf, fileIO, lastWritePos); this.lastWritePos = rowNum; }/*from w w w. j av a 2s . c o m*/ buf.putInt(user); buf.putInt(item); buf.putDouble(rating); } }
From source file:org.commoncrawl.hadoop.mergeutils.MergeSortSpillWriter.java
public static InputStream newInputStream(final ByteBuffer buf) { return new InputStream() { public synchronized int read() throws IOException { if (!buf.hasRemaining()) { return -1; }/*ww w. j a v a 2 s .c o m*/ return buf.get() & 0xff; } public synchronized int read(byte[] bytes, int off, int len) throws IOException { // Read only what's left len = Math.min(len, buf.remaining()); buf.get(bytes, off, len); return len; } }; }
From source file:eu.stratosphere.runtime.io.network.netty.InboundEnvelopeDecoder.java
/** * Copies min(from.readableBytes(), to.remaining() bytes from Nettys ByteBuf to the Java NIO ByteBuffer. *///from w ww .jav a2 s .c om private void copy(ByteBuf src, ByteBuffer dst) { // This branch is necessary, because an Exception is thrown if the // destination buffer has more remaining (writable) bytes than // currently readable from the Netty ByteBuf source. if (src.isReadable()) { if (src.readableBytes() < dst.remaining()) { int oldLimit = dst.limit(); dst.limit(dst.position() + src.readableBytes()); src.readBytes(dst); dst.limit(oldLimit); } else { src.readBytes(dst); } } }
From source file:android.syncml.pim.vcard.VCardDataBuilder.java
private String encodeString(String originalString, String targetCharset) { if (mSourceCharset.equalsIgnoreCase(targetCharset)) { return originalString; }//from w w w.j a v a 2s. c o m Charset charset = Charset.forName(mSourceCharset); ByteBuffer byteBuffer = charset.encode(originalString); // byteBuffer.array() "may" return byte array which is larger than // byteBuffer.remaining(). Here, we keep on the safe side. byte[] bytes = new byte[byteBuffer.remaining()]; byteBuffer.get(bytes); try { return new String(bytes, targetCharset); } catch (UnsupportedEncodingException e) { Log.e(LOG_TAG, "Failed to encode: charset=" + targetCharset); return new String(bytes); } }