List of usage examples for java.nio ByteBuffer allocate
public static ByteBuffer allocate(int capacity)
From source file:com.metamx.collections.spatial.search.RectangularBound.java
@Override public byte[] getCacheKey() { ByteBuffer minCoordsBuffer = ByteBuffer.allocate(minCoords.length * Floats.BYTES); minCoordsBuffer.asFloatBuffer().put(minCoords); final byte[] minCoordsCacheKey = minCoordsBuffer.array(); ByteBuffer maxCoordsBuffer = ByteBuffer.allocate(maxCoords.length * Floats.BYTES); maxCoordsBuffer.asFloatBuffer().put(maxCoords); final byte[] maxCoordsCacheKey = maxCoordsBuffer.array(); final ByteBuffer cacheKey = ByteBuffer.allocate(1 + minCoordsCacheKey.length + maxCoordsCacheKey.length) .put(minCoordsCacheKey).put(maxCoordsCacheKey).put(CACHE_TYPE_ID); return cacheKey.array(); }
From source file:org.red5.stream.http.servlet.TransportSegmentFeeder.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)/*from ww w .j a v a 2 s. c o m*/ */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Segment feed requested"); // get red5 context and segmenter if (service == null) { ApplicationContext appCtx = (ApplicationContext) getServletContext() .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); service = (SegmenterService) appCtx.getBean("segmenter.service"); } // get the requested stream / segment String servletPath = request.getServletPath(); String streamName = servletPath.split("\\.")[0]; log.debug("Stream name: {}", streamName); if (service.isAvailable(streamName)) { response.setContentType("video/MP2T"); // data segment Segment segment = null; // setup buffers and output stream byte[] buf = new byte[188]; ByteBuffer buffer = ByteBuffer.allocate(188); ServletOutputStream sos = response.getOutputStream(); // loop segments while ((segment = service.getSegment(streamName)) != null) { do { buffer = segment.read(buffer); // log.trace("Limit - position: {}", (buffer.limit() - buffer.position())); if ((buffer.limit() - buffer.position()) == 188) { buffer.get(buf); // write down the output stream sos.write(buf); } else { log.info("Segment result has indicated a problem"); // verifies the currently requested stream segment // number against the currently active segment if (service.getSegment(streamName) == null) { log.debug("Requested segment is no longer available"); break; } } buffer.clear(); } while (segment.hasMoreData()); log.trace("Segment {} had no more data", segment.getIndex()); // flush sos.flush(); // segment had no more data segment.cleanupThreadLocal(); } buffer.clear(); buffer = null; } else { // let requester know that stream segment is not available response.sendError(404, "Requested segmented stream not found"); } }
From source file:de.nx42.maps4cim.map.texture.osm.OsmHash.java
protected static String getQueryHashLocation(Area bounds) throws IOException { /*//from w w w .ja v a2s . co m * - base64 encode, every char holds 6 bits (2^6 = 64) * - 3 chars per float = 18bit precision = enough for 3 sigificant digits * for numbers <256 (which is the case in WGS84) * - 4 values -> 12 chars. 72bit or 8 byte of information * - use URL safe encoding, or file name failures are expected! */ // calculate size: 4 values, 8 bits per byte int bufSize = (int) Math.ceil(4 * locationPrecision / 8.0); ByteBuffer byteBuf = ByteBuffer.allocate(bufSize); BitOutput bitOut = BitOutput.newInstance(byteBuf); // direct storeCoordinate(bounds.getMinLat(), bitOut); storeCoordinate(bounds.getMaxLat(), bitOut); storeCoordinate(bounds.getMinLon(), bitOut); storeCoordinate(bounds.getMaxLon(), bitOut); // get array, return as Base64 (URL safe) byte[] ar = byteBuf.array(); return Base64.encodeBase64URLSafeString(ar); }
From source file:com.sm.store.utils.FileStore.java
private void reset() throws IOException { ByteBuffer buf = ByteBuffer.allocate(RECORD_SIZE); long pos = OFFSET + (long) (totalRecord - 1) * RECORD_SIZE; indexChannel.read(buf, pos);//from w w w.ja v a2s . c om buf.rewind(); byte status = buf.get(); long keyLen = buf.getLong(); byte[] keys = readChannel(keyLen, keyChannel); long data = buf.getLong(); long block2version = buf.getLong(); CacheBlock block = new CacheBlock(totalRecord, data, block2version, status); byte[] datas = readChannel(block.getDataOffset2Len(), dataChannel); }
From source file:com.openteach.diamond.network.waverider.session.DefaultSession.java
public static void main(String[] args) { BlockingQueue<ByteBuffer> inputBuffer = new LinkedBlockingQueue<ByteBuffer>(); /*for (int i = 0; i < 10; i++) {*//*from ww w . j av a 2s. c o m*/ ByteBuffer byteBuffer = ByteBuffer.allocate(1024); byteBuffer.put(makePacket().marshall()); byteBuffer.put(makePacket().marshall()); byteBuffer.flip(); byte[] b = new byte[8]; ByteBuffer halfBuf0 = ByteBuffer.allocate(8); byteBuffer.get(b); halfBuf0.put(b); halfBuf0.flip(); inputBuffer.add(halfBuf0); inputBuffer.add(byteBuffer); /*}*/ int size = 0; int oldSize = size; long length = Packet.getHeaderSize(); ByteBuffer buffer = ByteBuffer.allocate(NetWorkConstants.DEFAULT_NETWORK_BUFFER_SIZE); ByteBuffer currentBuffer = null; while (size < length) { currentBuffer = inputBuffer.peek(); oldSize = size; int position = currentBuffer.position(); size += currentBuffer.remaining(); buffer.put(currentBuffer); if (size >= Packet.getHeaderSize()) { length = buffer.getLong(Packet.getLengthPosition()); } if (size <= length) { inputBuffer.remove(); } else { currentBuffer.position(position); buffer.position(buffer.position() - currentBuffer.remaining()); byte[] buf = new byte[(int) (length - oldSize)]; currentBuffer.get(buf); buffer.put(buf); } } // buffer.position(0); buffer.flip(); Packet packet = Packet.unmarshall(buffer); Command command = CommandFactory.createCommand(packet.getType(), packet.getPayLoad()); String str = new String(command.getPayLoad().array()); System.out.println(str); }
From source file:Main.java
/** * Decodes the specified URL as per RFC 3986, i.e. transforms * percent-encoded octets to characters by decoding with the UTF-8 character * set. This function is primarily intended for usage with * {@link URL} which unfortunately does not enforce proper URLs. As * such, this method will leniently accept invalid characters or malformed * percent-encoded octets and simply pass them literally through to the * result string. Except for rare edge cases, this will make unencoded URLs * pass through unaltered./*from w w w. j a v a2 s . c o m*/ * * @param url The URL to decode, may be {@code null}. * @return The decoded URL or {@code null} if the input was * {@code null}. */ static String decodeUrl(String url) { String decoded = url; if (url != null && url.indexOf('%') >= 0) { int n = url.length(); StringBuffer buffer = new StringBuffer(); ByteBuffer bytes = ByteBuffer.allocate(n); for (int i = 0; i < n;) { if (url.charAt(i) == '%') { try { do { byte octet = (byte) Integer.parseInt(url.substring(i + 1, i + 3), 16); bytes.put(octet); i += 3; } while (i < n && url.charAt(i) == '%'); continue; } catch (RuntimeException e) { // malformed percent-encoded octet, fall through and // append characters literally } finally { if (bytes.position() > 0) { bytes.flip(); buffer.append(UTF8.decode(bytes).toString()); bytes.clear(); } } } buffer.append(url.charAt(i++)); } decoded = buffer.toString(); } return decoded; }
From source file:com.clustercontrol.platform.infra.InfraJdbcExecutorSupport.java
public static void execInsertFileContent(String fileId, DataHandler handler) throws HinemosUnknown, InfraFileTooLarge { Connection conn = null;// w w w.ja v a2s .c om JpaTransactionManager tm = null; PGCopyOutputStream pgStream = null; FileOutputStream fos = null; BufferedInputStream bis = null; File tempFile = null; try { tm = new JpaTransactionManager(); conn = tm.getEntityManager().unwrap(java.sql.Connection.class); conn.setAutoCommit(false); pgStream = new PGCopyOutputStream((PGConnection) conn, "COPY binarydata.cc_infra_file_content(file_id, file_content) FROM STDIN WITH (FORMAT BINARY)"); String exportDirectory = HinemosPropertyUtil.getHinemosPropertyStr("infra.export.dir", HinemosPropertyDefault.getString(HinemosPropertyDefault.StringKey.INFRA_EXPORT_DIR)); tempFile = new File(exportDirectory + fileId); fos = new FileOutputStream(tempFile); handler.writeTo(fos); long fileLength = tempFile.length(); int maxSize = HinemosPropertyUtil.getHinemosPropertyNum(MAX_FILE_KEY, Long.valueOf(1024 * 1024 * 64)) .intValue(); // 64MB if (fileLength > maxSize) { throw new InfraFileTooLarge(String.format("File size is larger than the limit size(%d)", maxSize)); } pgStream.write(HEADER_SIGN_PART); pgStream.write(HEADER_FLG_FIELD_PART); pgStream.write(HEADER_EX_PART); pgStream.write(TUPLE_FIELD_COUNT_PART); pgStream.write(ByteBuffer.allocate(4).putInt(fileId.getBytes().length).array()); pgStream.write(fileId.getBytes()); pgStream.write(ByteBuffer.allocate(4).putInt((int) fileLength).array()); bis = new BufferedInputStream(new FileInputStream(tempFile)); byte[] buf = new byte[1024 * 1024]; int read; while ((read = bis.read(buf)) != -1) { pgStream.write(buf, 0, read); } pgStream.write(FILETRAILER); pgStream.flush(); if (!tm.isNestedEm()) { conn.commit(); } } catch (InfraFileTooLarge e) { log.warn(e.getMessage()); try { pgStream.close(); } catch (IOException e1) { log.warn(e1); } try { conn.rollback(); } catch (SQLException e1) { log.warn(e1); } throw e; } catch (Exception e) { log.warn(e.getMessage(), e); try { if (pgStream != null) pgStream.close(); } catch (IOException e1) { log.warn(e1); } try { if (conn != null) conn.rollback(); } catch (SQLException e1) { log.warn(e1); } throw new HinemosUnknown(e.getMessage(), e); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { log.warn(e.getMessage(), e); throw new HinemosUnknown(e.getMessage(), e); } } if (bis != null) { try { bis.close(); } catch (IOException e) { log.warn(e.getMessage(), e); throw new HinemosUnknown(e.getMessage(), e); } } if (pgStream != null) { try { pgStream.close(); } catch (IOException e) { log.warn(e.getMessage(), e); throw new HinemosUnknown(e.getMessage(), e); } } if (tm != null) { tm.close(); } if (tempFile == null) { log.debug("Fail to delete. tempFile is null"); } else if (!tempFile.delete()) { log.debug("Fail to delete " + tempFile.getAbsolutePath()); } } }
From source file:com.cerema.cloud2.lib.common.network.FileRequestEntity.java
@Override public void writeRequest(final OutputStream out) throws IOException { //byte[] tmp = new byte[4096]; ByteBuffer tmp = ByteBuffer.allocate(4096); int readResult = 0; // TODO(bprzybylski): each mem allocation can throw OutOfMemoryError we need to handle it // globally in some fashionable manner RandomAccessFile raf = new RandomAccessFile(mFile, "r"); FileChannel channel = raf.getChannel(); Iterator<OnDatatransferProgressListener> it = null; long transferred = 0; long size = mFile.length(); if (size == 0) size = -1;/*w w w .ja v a 2 s . c o m*/ try { while ((readResult = channel.read(tmp)) >= 0) { out.write(tmp.array(), 0, readResult); tmp.clear(); transferred += readResult; synchronized (mDataTransferListeners) { it = mDataTransferListeners.iterator(); while (it.hasNext()) { it.next().onTransferProgress(readResult, transferred, size, mFile.getAbsolutePath()); } } } } catch (IOException io) { Log_OC.e("FileRequestException", io.getMessage()); throw new RuntimeException( "Ugly solution to workaround the default policy of retries when the server falls while uploading ; temporal fix; really", io); } finally { channel.close(); raf.close(); } }
From source file:com.owncloud.android.lib.common.network.FileRequestEntity.java
@Override public void writeRequest(final OutputStream out) throws IOException { //byte[] tmp = new byte[4096]; ByteBuffer tmp = ByteBuffer.allocate(4096); int readResult = 0; // globally in some fashionable manner RandomAccessFile raf = new RandomAccessFile(mFile, "r"); FileChannel channel = raf.getChannel(); Iterator<OnDatatransferProgressListener> it = null; long transferred = 0; long size = mFile.length(); if (size == 0) size = -1;/* w w w . j a v a 2s. c o m*/ try { while ((readResult = channel.read(tmp)) >= 0) { out.write(tmp.array(), 0, readResult); tmp.clear(); transferred += readResult; synchronized (mDataTransferListeners) { it = mDataTransferListeners.iterator(); while (it.hasNext()) { it.next().onTransferProgress(readResult, transferred, size, mFile.getAbsolutePath()); } } } } catch (IOException io) { Log_OC.e("FileRequestException", io.getMessage()); throw new RuntimeException( "Ugly solution to workaround the default policy of retries when the server falls while uploading ; temporal fix; really", io); } finally { channel.close(); raf.close(); } }
From source file:de.hofuniversity.iisys.neo4j.websock.query.encoding.safe.TSafeDeflateJsonQueryHandler.java
private ByteBuffer fuse(List<byte[]> buffers, final int length) { //fuses the buffers into a single array of the target length final ByteBuffer bb = ByteBuffer.allocate(length); for (byte[] buffer : buffers) { if (buffer.length > length - bb.position()) { bb.put(buffer, 0, length - bb.position()); } else {//from w w w . j a va 2s. co m bb.put(buffer); } } //important bb.flip(); return bb; }