List of usage examples for java.nio ByteBuffer array
public final byte[] array()
From source file:io.fabric8.maven.docker.access.log.LogRequestor.java
private boolean readStreamFrame(InputStream is) throws IOException, LogCallback.DoneException { // Read the header, which is composed of eight bytes. The first byte is an integer // indicating the stream type (0 = stdin, 1 = stdout, 2 = stderr), the next three are thrown // out, and the final four are the size of the remaining stream as an integer. ByteBuffer headerBuffer = ByteBuffer.allocate(8); headerBuffer.order(ByteOrder.BIG_ENDIAN); try {/* w w w. j ava 2 s . co m*/ this.readFully(is, headerBuffer.array()); } catch (NoBytesReadException e) { // Not bytes read for stream. Return false to stop consuming stream. return false; } catch (EOFException e) { throw new IOException("Failed to read log header. Could not read all 8 bytes. " + e.getMessage(), e); } // Grab the stream type (stdout, stderr, stdin) from first byte and throw away other 3 bytes. int type = headerBuffer.get(); // Skip three bytes, then read size from remaining four bytes. int size = headerBuffer.getInt(4); // Ignore empty messages and keep reading. if (size <= 0) { return true; } // Read the actual message ByteBuffer payload = ByteBuffer.allocate(size); try { ByteStreams.readFully(is, payload.array()); } catch (EOFException e) { throw new IOException("Failed to read log message. Could not read all " + size + " bytes. " + e.getMessage() + " [ Header: " + Hex.encodeHexString(headerBuffer.array()) + "]", e); } String message = Charsets.UTF_8.newDecoder().decode(payload).toString(); callLogCallback(type, message); return true; }
From source file:de.hofuniversity.iisys.neo4j.websock.query.encoding.unsafe.DeflateJsonQueryHandler.java
@Override public WebsockQuery decode(ByteBuffer buff) throws DecodeException { WebsockQuery query = null;/*from w w w . j a v a 2s . com*/ try { //decompress final byte[] incoming = buff.array(); fInflater.setInput(incoming); int totalSize = 0; int read = fInflater.inflate(fBuffer); while (read > 0) { totalSize += read; fBuffers.add(Arrays.copyOf(fBuffer, read)); read = fInflater.inflate(fBuffer); } //TODO: directly add final slice? // showed negative impact on performance final byte[] data = fuse(totalSize).array(); final JSONObject obj = new JSONObject(new String(data)); if (fDebug) { fTotalBytesIn += incoming.length; fLogger.log(Level.FINEST, "received compressed JSON message: " + incoming.length + " bytes\n" + "total bytes received: " + fTotalBytesIn); } query = JsonConverter.fromJson(obj); } catch (Exception e) { e.printStackTrace(); throw new DecodeException(buff, "failed to decode JSON", e); } return query; }
From source file:io.druid.query.search.FragmentSearchQuerySpec.java
@Override public byte[] getCacheKey() { if (values == null) { return ByteBuffer.allocate(2).put(CACHE_TYPE_ID).put(caseSensitive ? (byte) 1 : 0).array(); }/* w w w . j a v a2 s . co m*/ final byte[][] valuesBytes = new byte[values.size()][]; int valuesBytesSize = 0; int index = 0; for (String value : values) { valuesBytes[index] = StringUtils.toUtf8(value); valuesBytesSize += valuesBytes[index].length; ++index; } final ByteBuffer queryCacheKey = ByteBuffer.allocate(2 + valuesBytesSize).put(CACHE_TYPE_ID) .put(caseSensitive ? (byte) 1 : 0); for (byte[] bytes : valuesBytes) { queryCacheKey.put(bytes); } return queryCacheKey.array(); }
From source file:io.druid.query.aggregation.HistogramAggregatorFactory.java
@Override public byte[] getCacheKey() { byte[] fieldNameBytes = StringUtils.toUtf8(fieldName); ByteBuffer buf = ByteBuffer.allocate(1 + fieldNameBytes.length + Floats.BYTES * breaks.length) .put(CACHE_TYPE_ID).put(fieldNameBytes).put((byte) 0xFF); buf.asFloatBuffer().put(breaks);//from w w w .j ava2 s . com return buf.array(); }
From source file:com.alibaba.napoli.metamorphosis.client.consumer.RecoverStorageManager.java
@Override public void append(final String group, final Message message) throws IOException { final Store store = this.getOrCreateStore(message.getTopic(), group); long key = message.getId(); IOException error = null;//from ww w. ja v a 2 s . co m for (int i = 0; i < 5; i++) { try { final ByteBuffer buf = ByteBuffer.allocate(16); buf.putLong(key); store.add(buf.array(), this.serializer.encodeObject(message)); return; } catch (final IOException e) { final String msg = e.getMessage(); // key?? if (msg.contains("??")) { error = e; log.warn("recover store,key=" + key + "," + e.getMessage() + ",retry..."); key += this.count.incrementAndGet(); } else { throw e; } } } if (error != null) { throw error; } }
From source file:at.treedb.util.SevenZip.java
/** * Returns the data of an archive entry// ww w . j a v a 2 s .co m * * @param path * archive entry path * @return binary archive data * @throws Exception */ public byte[] getData(String path) throws Exception { ArchiveEntry entry = entryMap.get(path); if (entry == null) { throw new Exception("SevenZipAccess.getData(): Path not found: " + path); } ByteBuffer buf = ByteBuffer.allocate(entry.getLength()); channel.read(buf, entry.getOffset()); return buf.array(); }
From source file:com.navercorp.pinpoint.common.server.bo.codec.stat.AgentStatEncoderTest.java
@Test public void stats_should_be_encoded_and_decoded_into_same_value() { long initialTimestamp = System.currentTimeMillis(); int numStats = RandomUtils.nextInt(1, 21); List<TestAgentStat> expectedAgentStats = this.createTestAgentStats(initialTimestamp, numStats); long baseTimestamp = AgentStatUtils.getBaseTimestamp(initialTimestamp); long timestampDelta = initialTimestamp - baseTimestamp; ByteBuffer qualifierBuffer = encoder.encodeQualifier(timestampDelta); ByteBuffer valueBuffer = encoder.encodeValue(expectedAgentStats); Buffer encodedQualifierBuffer = new FixedBuffer(qualifierBuffer.array()); Buffer encodedValueBuffer = new FixedBuffer(valueBuffer.array()); AgentStatDecodingContext context = new AgentStatDecodingContext(); context.setAgentId(AGENT_ID);//from www .j ava2 s . c om context.setBaseTimestamp(baseTimestamp); List<TestAgentStat> decodedAgentStats = decode(encodedQualifierBuffer, encodedValueBuffer, context); verify(expectedAgentStats, decodedAgentStats); }
From source file:de.hofuniversity.iisys.neo4j.websock.query.encoding.unsafe.DeflateJsonQueryHandler.java
@Override public boolean willDecode(ByteBuffer buff) { boolean valid = true; //TODO: actually check whether it's a query try {/*ww w . j a v a2 s . c o m*/ //decompress fInflater.setInput(buff.array()); int totalSize = 0; int read = fInflater.inflate(fBuffer); while (read > 0) { totalSize += read; fBuffers.add(Arrays.copyOf(fBuffer, read)); read = fInflater.inflate(fBuffer); } //TODO: directly add final slice? // showed negative impact on performance final byte[] data = fuse(totalSize).array(); new JSONObject(new String(data)); } catch (Exception e) { valid = false; } return valid; }
From source file:com.joyent.manta.client.MantaClientSeekableByteChannelIT.java
@Test public final void readFromDifferentPositions() throws IOException { final String name = UUID.randomUUID().toString(); final String path = testPathPrefix + name; mantaClient.put(path, TEST_DATA);//from w w w .j a va2 s.co m try (SeekableByteChannel channel = mantaClient.getSeekableByteChannel(path)) { ByteBuffer first5Bytes = ByteBuffer.allocate(5); channel.read(first5Bytes); String firstPos = new String(first5Bytes.array(), StandardCharsets.UTF_8); Assert.assertEquals(firstPos, TEST_DATA.substring(0, 5), "Couldn't read the same bytes as written"); try (SeekableByteChannel channel2 = channel.position(7L)) { ByteBuffer seventhTo12thBytes = ByteBuffer.allocate(5); channel2.read(seventhTo12thBytes); String secondPos = new String(seventhTo12thBytes.array(), StandardCharsets.UTF_8); Assert.assertEquals(secondPos, TEST_DATA.substring(7, 12), "Couldn't read the same bytes as written"); } } }
From source file:io.druid.segment.data.CompressedObjectStrategy.java
@Override public byte[] toBytes(ResourceHolder<T> holder) { T val = holder.get(); ByteBuffer buf = bufferFor(val); converter.combine(buf, val); return compressor.compress(buf.array()); }