Java Code Examples for java.nio.ByteBuffer#allocate()
The following examples show how to use
java.nio.ByteBuffer#allocate() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Server.java From big-c with Apache License 2.0 | 6 votes |
public Connection(SocketChannel channel, long lastContact) { this.channel = channel; this.lastContact = lastContact; this.data = null; this.dataLengthBuffer = ByteBuffer.allocate(4); this.unwrappedData = null; this.unwrappedDataLengthBuffer = ByteBuffer.allocate(4); this.socket = channel.socket(); this.addr = socket.getInetAddress(); if (addr == null) { this.hostAddress = "*Unknown*"; } else { this.hostAddress = addr.getHostAddress(); } this.remotePort = socket.getPort(); this.responseQueue = new LinkedList<Call>(); if (socketSendBufferSize != 0) { try { socket.setSendBufferSize(socketSendBufferSize); } catch (IOException e) { LOG.warn("Connection: unable to set socket send buffer size to " + socketSendBufferSize); } } }
Example 2
Source File: SasFileParser.java From parso with Apache License 2.0 | 6 votes |
/** * The function to convert an array of bytes into a double number. * * @param bytes a double number represented by an array of bytes. * @return a number of the double type that is the conversion result. */ private double bytesToDouble(byte[] bytes) { ByteBuffer original = byteArrayToByteBuffer(bytes); if (bytes.length < BYTES_IN_DOUBLE) { ByteBuffer byteBuffer = ByteBuffer.allocate(BYTES_IN_DOUBLE); if (sasFileProperties.getEndianness() == 1) { byteBuffer.position(BYTES_IN_DOUBLE - bytes.length); } byteBuffer.put(original); byteBuffer.order(original.order()); byteBuffer.position(0); original = byteBuffer; } return original.getDouble(); }
Example 3
Source File: TupleFilterSerializer.java From kylin with Apache License 2.0 | 6 votes |
public static byte[] serialize(TupleFilter rootFilter, Decorator decorator, IFilterCodeSystem<?> cs) { ByteBuffer buffer; int bufferSize = BUFFER_SIZE; while (true) { try { buffer = ByteBuffer.allocate(bufferSize); internalSerialize(rootFilter, decorator, buffer, cs); break; } catch (BufferOverflowException e) { if (bufferSize == (1 << 30)) throw e; logger.info("Buffer size {} cannot hold the filter, resizing to 2 times", bufferSize); bufferSize = bufferSize << 1; } } byte[] result = new byte[buffer.position()]; System.arraycopy(buffer.array(), 0, result, 0, buffer.position()); return result; }
Example 4
Source File: TestHFileDataBlockEncoder.java From hbase with Apache License 2.0 | 6 votes |
private HFileBlock getSampleHFileBlock(List<KeyValue> kvs, boolean useTag) { ByteBuffer keyValues = RedundantKVGenerator.convertKvToByteBuffer(kvs, includesMemstoreTS); int size = keyValues.limit(); ByteBuffer buf = ByteBuffer.allocate(size + HConstants.HFILEBLOCK_HEADER_SIZE); buf.position(HConstants.HFILEBLOCK_HEADER_SIZE); keyValues.rewind(); buf.put(keyValues); HFileContext meta = new HFileContextBuilder() .withIncludesMvcc(includesMemstoreTS) .withIncludesTags(useTag) .withHBaseCheckSum(true) .withCompression(Algorithm.NONE) .withBlockSize(0) .withChecksumType(ChecksumType.NULL) .build(); HFileBlock b = new HFileBlock(BlockType.DATA, size, size, -1, ByteBuff.wrap(buf), HFileBlock.FILL_HEADER, 0, 0, -1, meta, ByteBuffAllocator.HEAP); return b; }
Example 5
Source File: HelloAbsAioHandler.java From talent-aio with GNU Lesser General Public License v2.1 | 6 votes |
/** * 编码:把业务消息包编码为可以发送的ByteBuffer */ @Override public ByteBuffer encode(HelloPacket packet, GroupContext<Object, HelloPacket, Object> groupContext, ChannelContext<Object, HelloPacket, Object> channelContext) { byte[] body = packet.getBody(); int bodyLen = 0; if (body != null) { bodyLen = body.length; } int allLen = HelloPacket.HEADER_LENGHT + bodyLen; ByteBuffer buffer = ByteBuffer.allocate(allLen); buffer.order(groupContext.getByteOrder()); buffer.putInt(bodyLen); if (body != null) { buffer.put(body); } return buffer; }
Example 6
Source File: GZIPSerializer.java From jmonkeyengine with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public void writeObject(ByteBuffer buffer, Object object) throws IOException { if (!(object instanceof GZIPCompressedMessage)) return; Message message = ((GZIPCompressedMessage)object).getMessage(); ByteBuffer tempBuffer = ByteBuffer.allocate(512000); Serializer.writeClassAndObject(tempBuffer, message); ByteArrayOutputStream byteArrayOutput = new ByteArrayOutputStream(); GZIPOutputStream gzipOutput = new GZIPOutputStream(byteArrayOutput); tempBuffer.flip(); gzipOutput.write(tempBuffer.array(), 0, tempBuffer.limit()); gzipOutput.flush(); gzipOutput.finish(); gzipOutput.close(); buffer.put(byteArrayOutput.toByteArray()); }
Example 7
Source File: fsys.java From V8LogScanner with MIT License | 5 votes |
public static String readAllFromFile(Path path) { List<String> result = new ArrayList<>(); try (SeekableByteChannel sbc = Files.newByteChannel(path)) { ByteBuffer buf = ByteBuffer.allocate(1024 * 128); while (sbc.read(buf) > 0) { buf.rewind(); result.add(Charset.defaultCharset().decode(buf).toString()); buf.flip(); } } catch (IOException e) { ExcpReporting.LogError(fsys.class, e); } return String.join("\n", result); }
Example 8
Source File: HBaseStore.java From joyqueue with Apache License 2.0 | 5 votes |
@Override public SendLog getOneSendLog(Query query) throws JoyQueueException { QueryCondition queryCondition = query.getQueryCondition(); QueryCondition.RowKey rowKey = queryCondition.getRowKey(); try { // 4 + 8 + 16 + 16 ByteBuffer allocate = ByteBuffer.allocate(44); allocate.putInt(topicAppMapping.getTopicId(rowKey.getTopic())); allocate.putLong(rowKey.getTime()); allocate.put(Md5.INSTANCE.encrypt(rowKey.getBusinessId().getBytes(Charset.forName("utf-8")), null)); allocate.put(HBaseSerializer.hexStrToByteArray(rowKey.getMessageId())); // rowKey byte[] bytesRowKey = allocate.array(); Pair<byte[], byte[]> bytes = hBaseClient.getKV(namespace, sendLogTable, cf, col, bytesRowKey); SendLog log = HBaseSerializer.readSendLog(bytes); StringBuilder clientIp = new StringBuilder(); IpUtil.toAddress(log.getClientIp(), clientIp); log.setClientIpStr(clientIp.toString()); String topicName = topicAppMapping.getTopicName(log.getTopicId()); log.setTopic(topicName); String appName = topicAppMapping.getAppName(log.getAppId()); log.setApp(appName); return log; } catch (Exception e) { throw new JoyQueueException(JoyQueueCode.SE_IO_ERROR, e); } }
Example 9
Source File: TestHttp2Section_4_3.java From Tomcat8-Source-Read with MIT License | 5 votes |
@Test public void testHeaderContinuationNonContiguous() throws Exception { // HTTP2 upgrade http2Connect(); // Part 1 byte[] frameHeader = new byte[9]; ByteBuffer headersPayload = ByteBuffer.allocate(128); buildSimpleGetRequestPart1(frameHeader, headersPayload, 3); writeFrame(frameHeader, headersPayload); sendPing(); handleGoAwayResponse(1, Http2Error.COMPRESSION_ERROR); }
Example 10
Source File: BaseTx.java From xDrip with GNU General Public License v3.0 | 5 votes |
void init(final int length) { final int packet_length = length + HEADER_FOOTER_SIZE; data = ByteBuffer.allocate(packet_length); data.put(START_OF_MESSAGE); data.put((byte) packet_length); }
Example 11
Source File: RadiusBound.java From bytebuffer-collections with Apache License 2.0 | 5 votes |
@Override public byte[] getCacheKey() { final ByteBuffer minCoordsBuffer = ByteBuffer.allocate(coords.length * Floats.BYTES); minCoordsBuffer.asFloatBuffer().put(coords); final byte[] minCoordsCacheKey = minCoordsBuffer.array(); final ByteBuffer cacheKey = ByteBuffer .allocate(1 + minCoordsCacheKey.length + Ints.BYTES + Floats.BYTES) .put(minCoordsCacheKey) .putFloat(radius) .putInt(getLimit()) .put(CACHE_TYPE_ID); return cacheKey.array(); }
Example 12
Source File: BytesOutputStream.java From darks-codec with Apache License 2.0 | 5 votes |
public ByteBuffer newBufferHeadFirst(int size) { if (head == null) { head = new LinkedList<ByteBuffer>(); } ByteBuffer buf = ByteBuffer.allocate(size); head.addFirst(buf); return buf; }
Example 13
Source File: AbstractARM64Emulator.java From unidbg with Apache License 2.0 | 5 votes |
protected void setupTraps() { try (Keystone keystone = new Keystone(KeystoneArchitecture.Arm64, KeystoneMode.LittleEndian)) { unicorn.mem_map(LR, 0x10000, UnicornConst.UC_PROT_READ | UnicornConst.UC_PROT_EXEC); KeystoneEncoded encoded = keystone.assemble("b #0"); byte[] b0 = encoded.getMachineCode(); ByteBuffer buffer = ByteBuffer.allocate(0x10000); for (int i = 0; i < 0x10000; i += b0.length) { buffer.put(b0); } unicorn.mem_write(LR, buffer.array()); } }
Example 14
Source File: Lobstack.java From jelectrum with MIT License | 5 votes |
protected ByteBuffer loadAtLocation(long loc) throws IOException { if (loc == MAGIC_LOCATION_ZERO) return BB_ZERO; long file_t1 = System.nanoTime(); long file_idx = loc / SEGMENT_FILE_SIZE; long in_file_loc = loc % SEGMENT_FILE_SIZE; ByteBuffer bb = null; try(FileChannel fc = getDataFileChannelRead(file_idx)) { fc.position(in_file_loc); ByteBuffer lenbb = ByteBuffer.allocate(4); readBuffer(fc, lenbb); lenbb.rewind(); int len = lenbb.getInt(); byte[] buff = new byte[len]; bb = ByteBuffer.wrap(buff); readBuffer(fc, bb); bb.rewind(); } getTimeReport().addTime(System.nanoTime() - file_t1, "load_file"); long t1 = System.nanoTime(); ByteBuffer de_bb = decompress(bb); if (DEBUG) System.out.println("Decompress"); getTimeReport().addTime(System.nanoTime() - t1, "decompress"); return de_bb; }
Example 15
Source File: TestBuffer.java From code with Apache License 2.0 | 5 votes |
@Test public void test2() { String str = "abcde"; ByteBuffer buf = ByteBuffer.allocate(1024); buf.put(str.getBytes()); buf.flip(); byte[] dst = new byte[buf.limit()]; buf.get(dst, 0, 2); System.out.println(new String(dst, 0, 2)); System.out.println(buf.position()); // mark 标记position buf.mark(); buf.get(dst,2,2); System.out.println(new String(dst, 0, 2)); System.out.println(buf.position()); //reset() : 恢复到 mark 的位置 buf.reset(); System.out.println(buf.position()); //判断缓冲区中是否还有剩余数据 if(buf.hasRemaining()){ //获取缓冲区中可以操作的数量 System.out.println(buf.remaining()); } }
Example 16
Source File: LogTelnetHandler.java From dubbo-2.6.5 with Apache License 2.0 | 4 votes |
@Override public String telnet(Channel channel, String message) { long size = 0; File file = LoggerFactory.getFile(); StringBuffer buf = new StringBuffer(); if (message == null || message.trim().length() == 0) { buf.append("EXAMPLE: log error / log 100"); } else { String str[] = message.split(" "); if (!StringUtils.isInteger(str[0])) { LoggerFactory.setLevel(Level.valueOf(message.toUpperCase())); } else { int SHOW_LOG_LENGTH = Integer.parseInt(str[0]); if (file != null && file.exists()) { try { FileInputStream fis = new FileInputStream(file); FileChannel filechannel = fis.getChannel(); size = filechannel.size(); ByteBuffer bb; if (size <= SHOW_LOG_LENGTH) { bb = ByteBuffer.allocate((int) size); filechannel.read(bb, 0); } else { int pos = (int) (size - SHOW_LOG_LENGTH); bb = ByteBuffer.allocate(SHOW_LOG_LENGTH); filechannel.read(bb, pos); } bb.flip(); String content = new String(bb.array()).replace("<", "<") .replace(">", ">").replace("\n", "<br/><br/>"); buf.append("\r\ncontent:" + content); buf.append("\r\nmodified:" + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(new Date(file.lastModified())))); buf.append("\r\nsize:" + size + "\r\n"); } catch (Exception e) { buf.append(e.getMessage()); } } else { size = 0; buf.append("\r\nMESSAGE: log file not exists or log appender is console ."); } } } buf.append("\r\nCURRENT LOG LEVEL:" + LoggerFactory.getLevel()) .append("\r\nCURRENT LOG APPENDER:" + (file == null ? "console" : file.getAbsolutePath())); return buf.toString(); }
Example 17
Source File: JingleSocks5Transport.java From Conversations with GNU General Public License v3.0 | 4 votes |
private void acceptIncomingSocketConnection(final Socket socket) throws IOException { Log.d(Config.LOGTAG, "accepted connection from " + socket.getInetAddress().getHostAddress()); socket.setSoTimeout(SOCKET_TIMEOUT_DIRECT); final byte[] authBegin = new byte[2]; final InputStream inputStream = socket.getInputStream(); final OutputStream outputStream = socket.getOutputStream(); inputStream.read(authBegin); if (authBegin[0] != 0x5) { socket.close(); } final short methodCount = authBegin[1]; final byte[] methods = new byte[methodCount]; inputStream.read(methods); if (SocksSocketFactory.contains((byte) 0x00, methods)) { outputStream.write(new byte[]{0x05, 0x00}); } else { outputStream.write(new byte[]{0x05, (byte) 0xff}); } byte[] connectCommand = new byte[4]; inputStream.read(connectCommand); if (connectCommand[0] == 0x05 && connectCommand[1] == 0x01 && connectCommand[3] == 0x03) { int destinationCount = inputStream.read(); final byte[] destination = new byte[destinationCount]; inputStream.read(destination); final byte[] port = new byte[2]; inputStream.read(port); final String receivedDestination = new String(destination); final ByteBuffer response = ByteBuffer.allocate(7 + destination.length); final byte[] responseHeader; final boolean success; if (receivedDestination.equals(this.destination) && this.socket == null) { responseHeader = new byte[]{0x05, 0x00, 0x00, 0x03}; success = true; } else { Log.d(Config.LOGTAG, this.account.getJid().asBareJid() + ": destination mismatch. received " + receivedDestination + " (expected " + this.destination + ")"); responseHeader = new byte[]{0x05, 0x04, 0x00, 0x03}; success = false; } response.put(responseHeader); response.put((byte) destination.length); response.put(destination); response.put(port); outputStream.write(response.array()); outputStream.flush(); if (success) { Log.d(Config.LOGTAG, this.account.getJid().asBareJid() + ": successfully processed connection to candidate " + candidate.getHost() + ":" + candidate.getPort()); socket.setSoTimeout(0); this.socket = socket; this.inputStream = inputStream; this.outputStream = outputStream; this.isEstablished = true; FileBackend.close(serverSocket); } else { FileBackend.close(socket); } } else { socket.close(); } }
Example 18
Source File: PassthroughTranscoder.java From LiTr with BSD 2-Clause "Simplified" License | 4 votes |
@Override public int processNextFrame() { if (lastResult == RESULT_EOS_REACHED) { // we are done return lastResult; } // TranscoderJob expects the first result to be RESULT_OUTPUT_MEDIA_FORMAT_CHANGED, so that it can start the mediaMuxer if (!targetTrackAdded) { targetFormat = mediaSource.getTrackFormat(sourceTrack); if (duration > 0) { targetFormat.setLong(MediaFormat.KEY_DURATION, duration); } targetTrack = mediaMuxer.addTrack(targetFormat, targetTrack); targetTrackAdded = true; int bufferSize = targetFormat.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE); outputBuffer = ByteBuffer.allocate(bufferSize); lastResult = RESULT_OUTPUT_MEDIA_FORMAT_CHANGED; return lastResult; } int selectedTrack = mediaSource.getSampleTrackIndex(); if (selectedTrack != NO_SELECTED_TRACK && selectedTrack != sourceTrack) { lastResult = RESULT_FRAME_PROCESSED; return lastResult; } lastResult = RESULT_FRAME_PROCESSED; int bytesRead = mediaSource.readSampleData(outputBuffer, 0); if (bytesRead > 0) { int outputFlags = 0; long sampleTime = mediaSource.getSampleTime(); int inputFlags = mediaSource.getSampleFlags(); if ((inputFlags & MediaExtractor.SAMPLE_FLAG_SYNC) != 0) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { outputFlags = MediaCodec.BUFFER_FLAG_KEY_FRAME; } else { outputFlags = MediaCodec.BUFFER_FLAG_SYNC_FRAME; } } if (duration > 0) { progress = ((float) sampleTime) / duration; } outputBufferInfo.set(0, bytesRead, sampleTime, outputFlags); mediaMuxer.writeSampleData(targetTrack, outputBuffer, outputBufferInfo); mediaSource.advance(); } else { outputBuffer.clear(); progress = 1.0f; lastResult = RESULT_EOS_REACHED; Log.d(TAG, "Reach EoS on input stream"); } return lastResult; }
Example 19
Source File: SearchRequestMatchingRuleAssertionTest.java From directory-ldap-api with Apache License 2.0 | 4 votes |
/** * Tests an search request decode with a simple equality match filter. */ @Test public void testDecodeSearchRequestExtensibleMatch() throws DecoderException, EncoderException, LdapException { ByteBuffer stream = ByteBuffer.allocate( 0x63 ); stream.put( new byte[] { 0x30, 0x61, // LDAPMessage ::= SEQUENCE { 0x02, 0x01, 0x01, // messageID 0x63, 0x5C, // protocolOp CHOICE { // searchRequest SearchRequest, // // SearchRequest ::= [APPLICATION 3] SEQUENCE { 0x04, 0x11, // "dc=example,dc=com" 'd', 'c', '=', 'e', 'x', 'a', 'm', 'p', 'l', 'e', ',', 'd', 'c', '=', 'c', 'o', 'm', // scope ENUMERATED { 0x0A, 0x01, 0x00, // baseObject (0), ... // derefAliases ENUMERATED { 0x0A, 0x01, 0x02, // derefFindingBaseObj (2),... 0x02, 0x01, 0x02, // sizeLimit INTEGER (0 .. maxInt), (2) 0x02, 0x01, 0x03, // timeLimit INTEGER (0 .. maxInt), (3) 0x01, 0x01, ( byte ) 0xFF, // typesOnly BOOLEAN, (true) ( byte ) 0xA9, 0x21, // filter Filter, // // Filter ::= CHOICE { // extensibleMatch [9] MatchingRuleAssertion } // // MatchingRuleAssertion ::= SEQUENCE { ( byte ) 0x81, 0x13, // matchingRule [1] MatchingRuleId OPTIONAL, '1', '.', '2', '.', '8', '4', '0', '.', '4', '8', '0', '1', '8', '.', '1', '.', '2', '.', '2', ( byte ) 0x82, 0x02, // type [2] AttributeDescription OPTIONAL, 'c', 'n', ( byte ) 0x83, 0x03, // matchValue [3] AssertionValue, 'a', 'o', 'k', // dnAttributes [4] BOOLEAN DEFAULT FALSE } ( byte ) 0x84, 0x01, ( byte ) 0xFF, 0x30, 0x15, // AttributeDescriptionList ::= SEQUENCE OF AttributeDescription 0x04, 0x05, 'a', 't', 't', 'r', '0', // AttributeDescription ::= LDAPString 0x04, 0x05, 'a', 't', 't', 'r', '1', // AttributeDescription ::= LDAPString 0x04, 0x05, 'a', 't', 't', 'r', '2', // AttributeDescription ::= LDAPString }); stream.flip(); // Allocate a BindRequest Container LdapMessageContainer<SearchRequest> ldapMessageContainer = new LdapMessageContainer<>( codec ); Asn1Decoder.decode( stream, ldapMessageContainer ); SearchRequest searchRequest = ldapMessageContainer.getMessage(); assertEquals( 1, searchRequest.getMessageId() ); assertEquals( "dc=example,dc=com", searchRequest.getBase().toString() ); assertEquals( SearchScope.OBJECT, searchRequest.getScope() ); assertEquals( AliasDerefMode.DEREF_FINDING_BASE_OBJ, searchRequest.getDerefAliases() ); assertEquals( 2, searchRequest.getSizeLimit() ); assertEquals( 3, searchRequest.getTimeLimit() ); assertEquals( true, searchRequest.getTypesOnly() ); // The attributes List<String> attributes = searchRequest.getAttributes(); for ( String attribute : attributes ) { assertNotNull( attribute ); } // Check encode reverse Asn1Buffer buffer = new Asn1Buffer(); LdapEncoder.encodeMessage( buffer, codec, searchRequest ); assertArrayEquals( stream.array(), buffer.getBytes().array() ); }
Example 20
Source File: U2FTransportAndroidHID.java From android-u2f-bridge with Apache License 2.0 | 4 votes |
public byte[] exchange(byte tag, byte[] command) throws IOException { ByteArrayOutputStream response = new ByteArrayOutputStream(); byte[] responseData = null; int offset = 0; int responseSize; if (debug) { Log.d(LOG_TAG, "=> " + Dump.dump(command)); } command = helper.wrapCommandAPDU(tag, command, HID_BUFFER_SIZE); UsbRequest requestWrite = new UsbRequest(); if (!requestWrite.initialize(connection, out)) { throw new IOException(); } while (offset != command.length) { int blockSize = (command.length - offset > HID_BUFFER_SIZE ? HID_BUFFER_SIZE : command.length - offset); System.arraycopy(command, offset, transferBuffer, 0, blockSize); if (debug) { Log.d(LOG_TAG, "wire => " + Dump.dump(transferBuffer)); } if (!requestWrite.queue(ByteBuffer.wrap(transferBuffer), HID_BUFFER_SIZE)) { requestWrite.close(); throw new IOException(); } connection.requestWait(); offset += blockSize; } ByteBuffer responseBuffer = ByteBuffer.allocate(HID_BUFFER_SIZE); UsbRequest requestRead = new UsbRequest(); if (!requestRead.initialize(connection, in)) { requestRead.close(); requestWrite.close(); throw new IOException(); } while ((responseData = helper.unwrapResponseAPDU(tag, response.toByteArray(), HID_BUFFER_SIZE)) == null) { responseBuffer.clear(); if (!requestRead.queue(responseBuffer, HID_BUFFER_SIZE)) { requestRead.close(); requestWrite.close(); throw new IOException(); } connection.requestWait(); responseBuffer.rewind(); responseBuffer.get(transferBuffer, 0, HID_BUFFER_SIZE); if (debug) { Log.d(LOG_TAG, "wire <= " + Dump.dump(transferBuffer)); } response.write(transferBuffer, 0, HID_BUFFER_SIZE); } if (debug) { Log.d(LOG_TAG, "<= " + Dump.dump(responseData)); } requestWrite.close(); requestRead.close(); return responseData; }