List of usage examples for java.nio ByteBuffer limit
public final int limit()
From source file:org.apache.cassandra.db.HintedHandOffManager.java
private static String[] getTableAndCFNames(ByteBuffer joined) { int index = ByteBufferUtil.lastIndexOf(joined, SEPARATOR.getBytes(UTF_8)[0], joined.limit()); if (index == -1 || index < (joined.position() + 1)) throw new RuntimeException("Corrupted hint name " + ByteBufferUtil.bytesToHex(joined)); try {/*from w ww .ja va 2 s . co m*/ return new String[] { ByteBufferUtil.string(joined, joined.position(), index - joined.position()), ByteBufferUtil.string(joined, index + 1, joined.limit() - (index + 1)) }; } catch (CharacterCodingException e) { throw new RuntimeException(e); } }
From source file:com.tongbanjie.tarzan.rpc.protocol.RpcCommand.java
public static RpcCommand decode(final ByteBuffer byteBuffer) { ///*from w w w . jav a 2 s . co m*/ int length = byteBuffer.limit(); //?? 1byte byte protocolType = byteBuffer.get(); //Header 4type int headerLength = byteBuffer.getInt(); //Header byte[] headerData = new byte[headerLength]; byteBuffer.get(headerData); RpcCommand cmd = headerDecode(headerData, getProtocolType(protocolType)); //body int bodyLength = length - 5 - headerLength; byte[] bodyData = null; if (bodyLength > 0) { bodyData = new byte[bodyLength]; byteBuffer.get(bodyData); } cmd.body = bodyData; return cmd; }
From source file:com.github.chenxiaolong.dualbootpatcher.RomUtils.java
private static boolean usesLiveWallpaper(RomInformation info, MbtoolInterface iface) throws IOException, MbtoolException, MbtoolCommandException { String wallpaperInfoPath = info.getDataPath() + "/system/users/0/wallpaper_info.xml"; int id = -1;/*from w ww . j av a 2 s. co m*/ try { id = iface.fileOpen(wallpaperInfoPath, new short[] { FileOpenFlag.RDONLY }, 0); StatBuf sb = iface.fileStat(id); // Check file size if (sb.st_size < 0 || sb.st_size > 1024) { return false; } // Read file into memory byte[] data = new byte[(int) sb.st_size]; int nWritten = 0; while (nWritten < data.length) { ByteBuffer newData = iface.fileRead(id, 10240); int nRead = newData.limit() - newData.position(); newData.get(data, nWritten, nRead); nWritten += nRead; } iface.fileClose(id); id = -1; String xml = new String(data, Charsets.UTF_8); return xml.contains("component="); } finally { if (id >= 0) { try { iface.fileClose(id); } catch (IOException e) { // Ignore } } } }
From source file:Main.java
/** * Returns new byte buffer whose content is a shared subsequence of this buffer's content * between the specified start (inclusive) and end (exclusive) positions. As opposed to * {@link ByteBuffer#slice()}, the returned buffer's byte order is the same as the source * buffer's byte order.// www . j a v a 2 s . co m */ private static ByteBuffer sliceFromTo(final ByteBuffer source, final int start, final int end) { if (start < 0) { throw new IllegalArgumentException("start: " + start); } if (end < start) { throw new IllegalArgumentException("end < start: " + end + " < " + start); } final int capacity = source.capacity(); if (end > source.capacity()) { throw new IllegalArgumentException("end > capacity: " + end + " > " + capacity); } final int originalLimit = source.limit(); final int originalPosition = source.position(); try { source.position(0); source.limit(end); source.position(start); final ByteBuffer result = source.slice(); result.order(source.order()); return result; } finally { source.position(0); source.limit(originalLimit); source.position(originalPosition); } }
From source file:org.apache.cassandra.utils.ByteBufferUtil.java
public static String bytesToHex(ByteBuffer bytes) { StringBuilder sb = new StringBuilder(); for (int i = bytes.position(); i < bytes.limit(); i++) { int bint = bytes.get(i) & 0xff; if (bint <= 0xF) // toHexString does not 0 pad its results. sb.append("0"); sb.append(Integer.toHexString(bint)); }/* w w w . j av a 2s. com*/ return sb.toString(); }
From source file:com.healthmarketscience.jackcess.impl.office.EncryptionHeader.java
public static EncryptionHeader read(ByteBuffer encProvBuf, Set<CryptoAlgorithm> validCryptoAlgos, Set<HashAlgorithm> validHashAlgos) { // read length of header int headerLen = encProvBuf.getInt(); // read header (temporarily narrowing buf to header) int curLimit = encProvBuf.limit(); int curPos = encProvBuf.position(); encProvBuf.limit(curPos + headerLen); EncryptionHeader header = new EncryptionHeader(encProvBuf); // verify parameters if (!validCryptoAlgos.contains(header.getCryptoAlgorithm())) { throw new IllegalStateException(header + " crypto algorithm must be one of " + validCryptoAlgos); }/*from ww w . j a v a 2 s. com*/ if (!validHashAlgos.contains(header.getHashAlgorithm())) { throw new IllegalStateException(header + " hash algorithm must be one of " + validHashAlgos); } int keySize = header.getKeySize(); if (!header.getCryptoAlgorithm().isValidKeySize(keySize)) { throw new IllegalStateException(header + " key size is outside allowable range"); } if ((keySize % 8) != 0) { throw new IllegalStateException(header + " key size must be multiple of 8"); } // move to after header encProvBuf.limit(curLimit); encProvBuf.position(curPos + headerLen); return header; }
From source file:com.github.chenxiaolong.dualbootpatcher.RomUtils.java
public static CacheWallpaperResult cacheWallpaper(Context context, RomInformation info, MbtoolInterface iface) throws IOException, MbtoolException, MbtoolCommandException { if (usesLiveWallpaper(info, iface)) { // We can't render a snapshot of a live wallpaper return CacheWallpaperResult.USES_LIVE_WALLPAPER; }//from w w w . j av a 2 s . c om String wallpaperPath = info.getDataPath() + "/system/users/0/wallpaper"; File wallpaperCacheFile = new File(info.getWallpaperPath()); FileOutputStream fos = null; int id = -1; try { id = iface.fileOpen(wallpaperPath, new short[] {}, 0); // Check if we need to re-cache the file StatBuf sb = iface.fileStat(id); if (wallpaperCacheFile.exists() && wallpaperCacheFile.lastModified() / 1000 > sb.st_mtime) { Log.d(TAG, "Wallpaper for " + info.getId() + " has not been changed"); return CacheWallpaperResult.UP_TO_DATE; } // Ignore large wallpapers if (sb.st_size < 0 || sb.st_size > 20 * 1024 * 1024) { return CacheWallpaperResult.FAILED; } // Read file into memory byte[] data = new byte[(int) sb.st_size]; int nWritten = 0; while (nWritten < data.length) { ByteBuffer newData = iface.fileRead(id, 10240); int nRead = newData.limit() - newData.position(); newData.get(data, nWritten, nRead); nWritten += nRead; } iface.fileClose(id); id = -1; fos = new FileOutputStream(wallpaperCacheFile); // Compression can be very slow (more than 10 seconds) for a large wallpaper, so we'll // just cache the actual file instead fos.write(data); // Load into bitmap //Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); //if (bitmap == null) { // return false; //} //bitmap.compress(Bitmap.CompressFormat.WEBP, 100, fos); //bitmap.recycle(); // Invalidate picasso cache Picasso.with(context).invalidate(wallpaperCacheFile); Log.d(TAG, "Wallpaper for " + info.getId() + " has been cached"); return CacheWallpaperResult.UPDATED; } finally { if (id >= 0) { try { iface.fileClose(id); } catch (IOException e) { // Ignore } } IOUtils.closeQuietly(fos); } }
From source file:org.apache.solr.handler.TestBlobHandler.java
public static void postData(CloudSolrClient cloudClient, String baseUrl, String blobName, ByteBuffer bytarr) throws IOException { HttpPost httpPost = null;//from w w w . ja va 2 s. com HttpEntity entity; String response = null; try { httpPost = new HttpPost(baseUrl + "/.system/blob/" + blobName); httpPost.setHeader("Content-Type", "application/octet-stream"); httpPost.setEntity(new ByteArrayEntity(bytarr.array(), bytarr.arrayOffset(), bytarr.limit())); entity = cloudClient.getLbClient().getHttpClient().execute(httpPost).getEntity(); try { response = EntityUtils.toString(entity, StandardCharsets.UTF_8); Map m = (Map) ObjectBuilder.getVal(new JSONParser(new StringReader(response))); assertFalse("Error in posting blob " + getAsString(m), m.containsKey("error")); } catch (JSONParser.ParseException e) { log.error("$ERROR$", response, e); fail(); } } finally { httpPost.releaseConnection(); } }
From source file:com.unister.semweb.drums.TestUtils.java
/** * Reads from the given numbe of elements (<code>numberOfElementsToRead</code>) from the given file from the * beginning./* www.j av a2 s . c om*/ */ public static List<DummyKVStorable> readFrom(String filename, int numberOfElementsToRead) throws Exception { HeaderIndexFile<DummyKVStorable> file = new HeaderIndexFile<DummyKVStorable>(filename, AccessMode.READ_ONLY, 1, TestUtils.gp); ByteBuffer dataBuffer = ByteBuffer.allocate(numberOfElementsToRead * TestUtils.gp.getElementSize()); file.read(0, dataBuffer); dataBuffer.flip(); List<DummyKVStorable> readData = new ArrayList<DummyKVStorable>(); while (dataBuffer.position() < dataBuffer.limit()) { byte[] oneLinkData = new byte[TestUtils.gp.getElementSize()]; dataBuffer.get(oneLinkData); DummyKVStorable oneDate = TestUtils.gp.getPrototype().fromByteBuffer(ByteBuffer.wrap(oneLinkData)); readData.add(oneDate); } file.close(); return readData; }
From source file:io.mycat.util.ByteBufferUtil.java
/** * ByteBuffer adaptation of org.apache.commons.lang3.ArrayUtils.lastIndexOf method * * @param buffer the array to traverse for looking for the object, may be <code>null</code> * @param valueToFind the value to find/*from w ww .j a v a 2 s . c o m*/ * @param startIndex the start index (i.e. BB position) to travers backwards from * @return the last index (i.e. BB position) of the value within the array * [between buffer.position() and buffer.limit()]; <code>-1</code> if not found. */ public static int lastIndexOf(ByteBuffer buffer, byte valueToFind, int startIndex) { assert buffer != null; if (startIndex < buffer.position()) { return -1; } else if (startIndex >= buffer.limit()) { startIndex = buffer.limit() - 1; } for (int i = startIndex; i >= buffer.position(); i--) { if (valueToFind == buffer.get(i)) { return i; } } return -1; }