List of usage examples for java.nio ByteBuffer position
public final int position()
From source file:byps.test.TestSerializeInlineInstances.java
private void internalTestSerializeInlineInstance(Actor obj, String jsonText) throws BException { BOutput bout = transport.getOutput(); bout.header.messageId = 123;//from w w w . j ava 2 s .c o m bout.header.targetId = new BTargetId(1, 1, 2); bout.store(obj); ByteBuffer buf = bout.toByteBuffer(); TestUtils.printBuffer(log, buf); if (TestUtils.protocol == BProtocolJson.BINARY_MODEL && jsonText != null) { try { String jsonTextR = new String(buf.array(), buf.position(), buf.limit(), "UTF-8"); TestUtils.assertEquals(log, "jsonText", jsonText, jsonTextR); } catch (UnsupportedEncodingException ignored) { } } BInput bin = transport.getInput(null, buf); Object objR = (Object) bin.load(); TestUtils.assertEquals(log, "obj.class", obj.getClass(), objR.getClass()); if (obj.position == null) { obj.position = new Matrix2D(); } TestUtils.assertEquals(log, "obj", obj, objR); }
From source file:edu.umass.cs.gigapaxos.paxospackets.AcceptReplyPacket.java
/** * @param bbuf/*from w w w. j av a 2s .c om*/ * @throws UnsupportedEncodingException * @throws UnknownHostException */ public AcceptReplyPacket(ByteBuffer bbuf) throws UnsupportedEncodingException, UnknownHostException { super(bbuf); int paxosIDLength = this.getPaxosID().getBytes(CHARSET).length; assert (bbuf.position() == SIZEOF_PAXOSPACKET_FIXED + paxosIDLength); this.acceptor = bbuf.getInt(); this.ballot = new Ballot(bbuf.getInt(), bbuf.getInt()); this.slotNumber = bbuf.getInt(); this.maxCheckpointedSlot = bbuf.getInt(); this.requestID = bbuf.getLong(); if (bbuf.get() == (byte) 1) this.setDigestRequest(); assert (bbuf.position() == SIZEOF_PAXOSPACKET_FIXED + paxosIDLength + SIZEOF_ACCEPTREPLY) : bbuf.position() + " != [" + SIZEOF_PAXOSPACKET_FIXED + " + " + paxosIDLength + " + " + SIZEOF_ACCEPTREPLY + "]"; }
From source file:libepg.epg.section.sectionreconstructor.SectionReconstructor.java
/** * ??????????????????//www .j a va2 s . c o m * ByteBuffer?array()???????????????????? * */ private synchronized void addToReturnObject(ByteBuffer buf, Set<byte[]> dest) { byte[] BeforeCutDown = buf.array(); byte[] AfterCutDown = new byte[buf.position()]; System.arraycopy(BeforeCutDown, 0, AfterCutDown, 0, AfterCutDown.length); if (LOG.isTraceEnabled()) { MessageFormat msg1 = new MessageFormat("\n??={0}\n?={1}"); Object[] parameters1 = { Hex.encodeHexString(BeforeCutDown), Hex.encodeHexString(AfterCutDown) }; LOG.trace(msg1.format(parameters1)); } if (dest.add(AfterCutDown)) { if (LOG.isTraceEnabled()) { MessageFormat msg2 = new MessageFormat("\n???={0}"); Object[] parameters2 = { Hex.encodeHexString(AfterCutDown) }; LOG.trace(msg2.format(parameters2)); } } else if (LOG.isTraceEnabled()) { MessageFormat msg3 = new MessageFormat("\n???????={0}"); Object[] parameters3 = { Hex.encodeHexString(AfterCutDown) }; LOG.trace(msg3.format(parameters3)); } }
From source file:com.doplgangr.secrecy.FileSystem.File.java
public java.io.File readFile(CryptStateListener listener) { decrypting = true;/*from w w w . j ava 2 s. c om*/ InputStream is = null; OutputStream out = null; java.io.File outputFile = null; try { outputFile = java.io.File.createTempFile("tmp" + name, "." + FileType, storage.getTempFolder()); outputFile.mkdirs(); outputFile.createNewFile(); AES_Encryptor enc = new AES_Encryptor(key); is = new CipherInputStream(new FileInputStream(file), enc.decryptstream()); listener.setMax((int) file.length()); ReadableByteChannel inChannel = Channels.newChannel(is); FileChannel outChannel = new FileOutputStream(outputFile).getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate(Config.bufferSize); while (inChannel.read(byteBuffer) >= 0 || byteBuffer.position() > 0) { byteBuffer.flip(); outChannel.write(byteBuffer); byteBuffer.compact(); listener.updateProgress((int) outChannel.size()); } inChannel.close(); outChannel.close(); Util.log(outputFile.getName(), outputFile.length()); return outputFile; } catch (FileNotFoundException e) { listener.onFailed(2); Util.log("Encrypted File is missing", e.getMessage()); } catch (IOException e) { Util.log("IO Exception while decrypting", e.getMessage()); if (e.getMessage().contains("pad block corrupted")) listener.onFailed(1); else e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { listener.Finished(); decrypting = false; try { if (is != null) { is.close(); } if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } // An error occured. Too Bad if (outputFile != null) storage.purgeFile(outputFile); return null; }
From source file:com.kylinolap.common.hll.HyperLogLogPlusCounter.java
public void writeRegisters(final ByteBuffer out) throws IOException { int startPos = out.position(); final int indexLen = getRegisterIndexSize(); int size = size(); // decide output scheme -- map (3*size bytes) or array (2^p bytes) byte scheme;// w w w .j a v a 2 s . c o m if ((indexLen + 1) * size < m) scheme = 0; // map else scheme = 1; // array out.put(scheme); if (scheme == 0) { // map scheme BytesUtil.writeVInt(size, out); for (int i = 0; i < m; i++) { if (registers[i] > 0) { BytesUtil.writeUnsigned(i, indexLen, out); out.put(registers[i]); } } } else { // array scheme for (int i = 0; i < m; i++) { out.put(registers[i]); } } // do compression if needed int len = out.position() - startPos; if (len < COMPRESSION_THRESHOLD) return; scheme |= COMPRESSION_FLAG; byte[] compressed = DEFAULT_COMPRESSOR.compress(out, startPos + 1, len - 1); out.position(startPos); out.put(scheme); BytesUtil.writeVInt(compressed.length, out); out.put(compressed); }
From source file:com.l2jfree.loginserver.network.L2Client.java
@Override public boolean decrypt(ByteBuffer buf, int size) { boolean ret = false; try {//from w w w. j a v a2s .c o m ret = getLoginCrypt().decrypt(buf.array(), buf.position(), size); } catch (IOException e) { e.printStackTrace(); closeNow(); return false; } if (!ret) { byte[] dump = new byte[size]; System.arraycopy(buf.array(), buf.position(), dump, 0, size); _log.warn("Wrong checksum from client: " + toString()); closeNow(); } return ret; }
From source file:org.muckebox.android.net.DownloadRunnable.java
private void handleReceivedData(ByteBuffer data) throws IOException { if (!BufferUtils.isEmpty(data)) { mBytesTotal += data.position(); if (mOutputStream != null) { mOutputStream.write(data.array(), 0, data.position()); }/*w w w . j a v a 2s. c o m*/ Chunk chunk = new Chunk(); chunk.bytesTotal = mBytesTotal; chunk.buffer = data; if (mHandler != null) mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DATA_RECEIVED, (int) mTrackId, 0, chunk)); } }
From source file:com.joyent.manta.http.entity.DigestedEntity.java
@Override public void writeTo(final OutputStream out) throws IOException { digest.reset(); // reset the digest state in case we're in a retry // If our wrapped entity is backed by a buffer of some form // we can read easily read the whole buffer into our message digest. if (wrapped instanceof MemoryBackedEntity) { final MemoryBackedEntity entity = (MemoryBackedEntity) wrapped; final ByteBuffer backingBuffer = entity.getBackingBuffer(); if (backingBuffer.hasArray()) { final byte[] bytes = backingBuffer.array(); final int offset = backingBuffer.arrayOffset(); final int position = backingBuffer.position(); final int limit = backingBuffer.limit(); digest.update(bytes, offset + position, limit - position); backingBuffer.position(limit); wrapped.writeTo(out);/*w w w. java 2 s . c o m*/ } } else { try (DigestOutputStream dout = new DigestOutputStream(digest); TeeOutputStream teeOut = new TeeOutputStream(out, dout)) { wrapped.writeTo(teeOut); teeOut.flush(); } } }
From source file:com.spectralogic.ds3client.helpers.channels.WindowedSeekableByteChannel_Test.java
@Test(timeout = 1000) public void writePositionTracking() throws IOException { try (final ByteArraySeekableByteChannel channel = new ByteArraySeekableByteChannel()) { final Object lock = new Object(); try (final WindowedSeekableByteChannel window = new WindowedSeekableByteChannel(channel, lock, 2L, 7L)) {/*w w w .ja v a2 s.c o m*/ ByteBuffer buffer = Charset.forName("UTF-8").encode("bbb"); assertThat(window.write(buffer), is(3)); assertThat(buffer.position(), is(3)); buffer = Charset.forName("UTF-8").encode("cccc"); assertThat(window.write(buffer), is(4)); assertThat(buffer.position(), is(4)); channel.position(0); assertThat(channel.toString(), is("\0\0bbbcccc")); } } }
From source file:edu.tsinghua.lumaqq.qq.packets.PacketHelper.java
/** * ByteBuffer??InPacket?buf???length/* ww w . j a va 2s . c o m*/ * ???bufposition?length? * * @param buf * ByteBuffer * @param type * * @param length * * @param debug * @return InPacket * @throws PacketParseException * ?? */ private InPacket parseIn(ByteBuffer buf, int length, QQUser user, boolean debug) throws PacketParseException { // ??? int offset = buf.position(); // ? try { InPacket ret = parser.parseIncoming(buf, length, user); boolean duplicated = isDuplicated(ret); boolean needReply = parser.isDuplicatedNeedReply(ret); if (duplicated && !needReply && !debug) return null; else { ret.setDuplicated(duplicated); return ret; } } catch (PacketParseException e) { throw e; } finally { buf.position(offset + length); parser = null; } }