List of usage examples for java.nio ByteBuffer remaining
public final int remaining()
From source file:org.apache.james.protocols.smtp.core.esmtp.MailSizeEsmtpExtension.java
/** * @see org.apache.james.protocols.smtp.core.DataLineFilter#onLine(SMTPSession, byte[], LineHandler) *//* w w w. ja v a 2 s . c o m*/ public Response onLine(SMTPSession session, ByteBuffer line, LineHandler<SMTPSession> next) { Response response = null; Boolean failed = (Boolean) session.getAttachment(MESG_FAILED, State.Transaction); // If we already defined we failed and sent a reply we should simply // wait for a CRLF.CRLF to be sent by the client. if (failed != null && failed.booleanValue()) { // TODO } else { if (line.remaining() == 3 && line.get() == 46) { line.rewind(); response = next.onLine(session, line); } else { line.rewind(); Long currentSize = (Long) session.getAttachment("CURRENT_SIZE", State.Transaction); Long newSize; if (currentSize == null) { newSize = Long.valueOf(line.remaining()); } else { newSize = Long.valueOf(currentSize.intValue() + line.remaining()); } if (session.getConfiguration().getMaxMessageSize() > 0 && newSize.intValue() > session.getConfiguration().getMaxMessageSize()) { // Add an item to the state to suppress // logging of extra lines of data // that are sent after the size limit has // been hit. session.setAttachment(MESG_FAILED, Boolean.TRUE, State.Transaction); // then let the client know that the size // limit has been hit. response = next.onLine(session, ByteBuffer.wrap(".\r\n".getBytes())); } else { line.rewind(); response = next.onLine(session, line); } session.setAttachment("CURRENT_SIZE", newSize, State.Transaction); } } return response; }
From source file:com.github.cambierr.lorawanpacket.semtech.Txpk.java
public JSONObject toJson() throws MalformedPacketException { JSONObject output = new JSONObject(); output.put("imme", isImme()); output.put("tmst", getTmst()); output.put("time", getTime()); output.put("freq", getFreq()); output.put("rfch", getRfch()); output.put("powe", getPowe()); output.put("modu", getModu().name()); if (getModu().equals(Modulation.LORA)) { output.put("codr", getCodr()); output.put("ipol", isIpol()); } else {// ww w . j a v a 2 s. c o m output.put("fdev", getFdev()); } output.put("datr", getDatr()); output.put("prea", getPrea()); output.put("size", getSize()); output.put("ncrc", isNcrc()); ByteBuffer bb = ByteBuffer.allocate(384); getData().toRaw(bb); output.put("data", Base64.getEncoder() .encodeToString(Arrays.copyOfRange(bb.array(), 0, bb.capacity() - bb.remaining()))); return output; }
From source file:org.apache.usergrid.persistence.index.utils.ConversionUtils.java
public static Object object(Class<?> type, ByteBuffer bytes) { try {//from w w w . java2 s.c om if (Long.class.isAssignableFrom(type)) { return bytes.slice().getLong(); } else if (UUID.class.isAssignableFrom(type)) { return uuid(bytes); } else if (String.class.isAssignableFrom(type)) { return string(bytes); } else if (Boolean.class.isAssignableFrom(type)) { return bytes.slice().get() != 0; } else if (Integer.class.isAssignableFrom(type)) { return bytes.slice().getInt(); } else if (Double.class.isAssignableFrom(type)) { return bytes.slice().getDouble(); } else if (Float.class.isAssignableFrom(type)) { return bytes.slice().getFloat(); } else if (ByteBuffer.class.isAssignableFrom(type)) { return bytes.duplicate(); } else if (byte[].class.isAssignableFrom(type)) { byte[] b = new byte[bytes.remaining()]; bytes.slice().get(b); return b; } } catch (Exception e) { logger.error("Unable to get object from bytes for type {}", type.getName(), e); } return null; }
From source file:com.easemob.dataexport.utils.ConversionUtils.java
public static Object object(Class<?> type, ByteBuffer bytes) { try {//from w w w . java 2 s . co m if (Long.class.isAssignableFrom(type)) { return bytes.slice().getLong(); } else if (UUID.class.isAssignableFrom(type)) { return uuid(bytes); } else if (String.class.isAssignableFrom(type)) { return string(bytes); } else if (Boolean.class.isAssignableFrom(type)) { return bytes.slice().get() != 0; } else if (Integer.class.isAssignableFrom(type)) { return bytes.slice().getInt(); } else if (Double.class.isAssignableFrom(type)) { return bytes.slice().getDouble(); } else if (Float.class.isAssignableFrom(type)) { return bytes.slice().getFloat(); } else if (ByteBuffer.class.isAssignableFrom(type)) { return bytes.duplicate(); } else if (byte[].class.isAssignableFrom(type)) { byte[] b = new byte[bytes.remaining()]; bytes.slice().get(b); return b; } } catch (Exception e) { logger.error("Unable to get object from bytes for type " + type.getName(), e); } return null; }
From source file:ga.rugal.jpt.common.tracker.common.Torrent.java
private static String hashFiles(List<File> files, int pieceLenght) throws InterruptedException, IOException { int threads = getHashingThreadsCount(); ExecutorService executor = Executors.newFixedThreadPool(threads); ByteBuffer buffer = ByteBuffer.allocate(pieceLenght); List<Future<String>> results = new LinkedList<>(); StringBuilder hashes = new StringBuilder(); long length = 0L; int pieces = 0; long start = System.nanoTime(); for (File file : files) { LOG.info("Hashing data from {} with {} threads ({} pieces)...", new Object[] { file.getName(), threads, (int) (Math.ceil((double) file.length() / pieceLenght)) }); length += file.length();/*w w w . ja va2s .c o 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) { LOG.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 / pieceLenght)); LOG.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:com.healthmarketscience.jackcess.impl.PageChannel.java
/** * Write a page (or part of a page) to disk * @param page Page to write//from w w w . j a v a2 s .co m * @param pageNumber Page number to write the page to * @param pageOffset offset within the page at which to start writing the * page data */ public void writePage(ByteBuffer page, int pageNumber, int pageOffset) throws IOException { assertWriting(); validatePageNumber(pageNumber); page.rewind().position(pageOffset); int writeLen = page.remaining(); if ((writeLen + pageOffset) > getFormat().PAGE_SIZE) { throw new IllegalArgumentException("Page buffer is too large, size " + (writeLen + pageOffset)); } ByteBuffer encodedPage = page; if (pageNumber == 0) { // re-mask header applyHeaderMask(page); } else { if (!_codecHandler.canEncodePartialPage()) { if ((pageOffset > 0) && (writeLen < getFormat().PAGE_SIZE)) { // current codec handler cannot encode part of a page, so need to // copy the modified part into the current page contents in a temp // buffer so that we can encode the entire page ByteBuffer fullPage = _fullPageEncodeBufferH.setPage(this, pageNumber); // copy the modified part to the full page fullPage.position(pageOffset); fullPage.put(page); fullPage.rewind(); // reset so we can write the whole page page = fullPage; pageOffset = 0; writeLen = getFormat().PAGE_SIZE; } else { _fullPageEncodeBufferH.possiblyInvalidate(pageNumber, null); } } // re-encode page encodedPage = _codecHandler.encodePage(page, pageNumber, pageOffset); // reset position/limit in case they were affected by encoding encodedPage.position(pageOffset).limit(pageOffset + writeLen); } try { _channel.write(encodedPage, (getPageOffset(pageNumber) + pageOffset)); } finally { if (pageNumber == 0) { // de-mask header applyHeaderMask(page); } } }
From source file:com.newatlanta.appengine.nio.channels.GaeFileChannel.java
@Override public synchronized int write(ByteBuffer src) throws IOException { checkWriteOptions();/*from w ww . j av a2 s. c o m*/ int bytesWritten = 0; while (src.hasRemaining()) { int r = src.remaining(); initBuffer(r); if (calcBlockIndex(position + r - 1) == index) { // writing entirely within current block bytesWritten += writeBuffer(src); } else { // fill the current block then repeat loop int limit = src.limit(); src.limit(src.position() + (blockSize - buffer.position())); bytesWritten += writeBuffer(src); src.limit(limit); } } //flush(); return bytesWritten; }
From source file:io.lightlink.output.JSONResponseStream.java
public void writeUnquoted(Object value) { ByteBuffer byteBuffer = CHARSET.encode(value.toString()); write(byteBuffer.array(), byteBuffer.remaining()); }
From source file:cn.iie.haiep.hbase.value.Bytes.java
/** * This method will get a sequence of bytes from pos -> limit, * but will restore pos after.//from w w w.j av a 2s. c o m * @param buf * @return byte array */ public static byte[] getBytes(ByteBuffer buf) { int savedPos = buf.position(); byte[] newBytes = new byte[buf.remaining()]; buf.get(newBytes); buf.position(savedPos); return newBytes; }
From source file:io.lightlink.output.JSONResponseStream.java
public void writeInputStream(InputStream inputStream) { write('"');/*from w w w. j a v a 2 s. c o m*/ byte[] buffer = new byte[3 * 1024]; int length; try { while ((length = inputStream.read(buffer)) != -1) { String encodedBlock; if (length < buffer.length) { byte part[] = new byte[length]; System.arraycopy(buffer, 0, part, 0, length); encodedBlock = DatatypeConverter.printBase64Binary(part); } else { encodedBlock = DatatypeConverter.printBase64Binary(buffer); } ByteBuffer bbuffer = CHARSET.encode(encodedBlock); write(bbuffer.array(), bbuffer.remaining()); } write('"'); inputStream.close(); } catch (IOException e) { throw new RuntimeException(e.toString(), e); } }