List of usage examples for java.nio ByteBuffer position
public final int position()
From source file:android.framework.util.jar.Manifest.java
private static void writeEntry(OutputStream os, Attributes.Name name, String value, CharsetEncoder encoder, ByteBuffer bBuf) throws IOException { String nameString = name.getName(); os.write(nameString.getBytes(Charsets.US_ASCII)); os.write(VALUE_SEPARATOR);/* ww w . j ava2 s . co m*/ encoder.reset(); bBuf.clear().limit(LINE_LENGTH_LIMIT - nameString.length() - 2); CharBuffer cBuf = CharBuffer.wrap(value); while (true) { CoderResult r = encoder.encode(cBuf, bBuf, true); if (CoderResult.UNDERFLOW == r) { r = encoder.flush(bBuf); } os.write(bBuf.array(), bBuf.arrayOffset(), bBuf.position()); os.write(LINE_SEPARATOR); if (CoderResult.UNDERFLOW == r) { break; } os.write(' '); bBuf.clear().limit(LINE_LENGTH_LIMIT - 1); } }
From source file:de.csdev.ebus.command.EBusCommandUtils.java
/** * Build an escaped telegram part for a slave answer * * @param slaveData/*from w w w. j a va 2 s . c o m*/ * @return * @throws EBusTypeException */ public static ByteBuffer buildPartSlave(byte[] slaveData) throws EBusTypeException { ByteBuffer buf = ByteBuffer.allocate(50); buf.put(EBusConsts.ACK_OK); // ACK // if payload available if (slaveData != null && slaveData.length > 0) { buf.put((byte) slaveData.length); // NN - Length // add the escaped bytes for (byte b : slaveData) { buf.put(escapeSymbol(b)); } // calculate crc byte crc8 = EBusUtils.crc8(buf.array(), buf.position()); // add the crc, maybe escaped buf.put(escapeSymbol(crc8)); } else { // only set len = 0 buf.put((byte) 0x00); // NN - Length } // set limit and reset position buf.limit(buf.position()); buf.position(0); return buf; }
From source file:com.fujitsu.dc.test.jersey.bar.BarInstallTestUtils.java
/** * bar?.//from w w w .j a v a 2 s. co m * @param barFile bar? * @return ??bar */ public static byte[] readBarFile(File barFile) { InputStream is = ClassLoader.getSystemResourceAsStream(barFile.getPath()); ByteBuffer buff = ByteBuffer.allocate(READ_BUFFER_SIZE); log.debug(String.valueOf(buff.capacity())); try { byte[] bbuf = new byte[SIZE_KB]; int size; while ((size = is.read(bbuf)) != -1) { buff.put(bbuf, 0, size); } } catch (IOException e) { throw new RuntimeException("failed to load bar file:" + barFile.getPath(), e); } finally { try { is.close(); } catch (IOException e) { throw new RuntimeException("failed to close bar file:" + barFile.getPath(), e); } } int size = buff.position(); buff.flip(); byte[] retv = new byte[size]; buff.get(retv, 0, size); return retv; }
From source file:com.linkedin.databus.core.DbusEventV2.java
public static int serializeEvent(DbusEventKey key, ByteBuffer buf, DbusEventInfo dbusEventInfo) { // Serialize a DbusEventV2 that has exact same contents as a DbusEventV1. final int start = buf.position(); buf.put(DbusEventFactory.DBUS_EVENT_V2); buf.putInt(MAGIC);// ww w . j a v a 2 s .co m buf.putInt(0); // Header len placeholder buf.putInt(0); // Header crc placeholder buf.putInt(0); // Body CRC placeholder buf.putInt(0); // total length placeholder short attributes = 0; attributes = setOpCode(dbusEventInfo.getOpCode(), attributes, dbusEventInfo.getSrcId()); attributes = setKeyType(key, attributes); if (dbusEventInfo.isEnableTracing()) { attributes |= FLAG_TRACE_ON; } if (dbusEventInfo.isReplicated()) { attributes |= FLAG_IS_REPLICATED; } DbusEventPart metadata = dbusEventInfo.getMetadata(); if (shouldEncodePayloadPart(dbusEventInfo)) { attributes |= FLAG_HAS_PAYLOAD_PART; } if (metadata != null) { attributes |= FLAG_HAS_PAYLOAD_METADATA_PART; } buf.putShort(attributes); buf.putLong(dbusEventInfo.getTimeStampInNanos()); buf.putInt(dbusEventInfo.getSrcId()); buf.putShort(dbusEventInfo.getpPartitionId()); buf.putLong(dbusEventInfo.getSequenceId()); // Fixed part of header is done. Now for the variable header part setKey(buf, key); final int hdrEndPos = buf.position(); if (metadata != null) { metadata.encode(buf); } if ((attributes & FLAG_HAS_PAYLOAD_PART) != 0) { ByteBuffer bb = dbusEventInfo.getValueByteBuffer(); if (bb == null) { // Special case to encode when there is no data. bb = ByteBuffer.allocate(1).order(buf.order()); bb.limit(0); } DbusEventPart valuePart = new DbusEventPart(SchemaDigestType.MD5, dbusEventInfo.getSchemaId(), dbusEventInfo.getPayloadSchemaVersion(), bb); valuePart.encode(buf); } final int end = buf.position(); buf.putInt(start + HeaderLenOffset, hdrEndPos - start); buf.putInt(start + TotalLenOffset, end - start); long bodyCrc = ByteBufferCRC32.getChecksum(buf, hdrEndPos, end - hdrEndPos); Utils.putUnsignedInt(buf, start + BodyCrcOffset, bodyCrc); // Header CRC if (dbusEventInfo.isAutocommit()) { // Do the body CRC first, since that is included in the header CRC long hdrCrc = ByteBufferCRC32.getChecksum(buf, start + BodyCrcOffset, hdrEndPos - start - BodyCrcOffset); Utils.putUnsignedInt(buf, start + HeaderCrcOffset, hdrCrc); } return buf.position() - start; }
From source file:com.healthmarketscience.jackcess.impl.OleUtil.java
private static byte[] writePackageHeader(OleBlob.Builder oleBuilder, long contentLen) { byte[] prettyNameBytes = getZeroTermStrBytes(oleBuilder.getPrettyName()); String className = oleBuilder.getClassName(); String typeName = oleBuilder.getTypeName(); if (className == null) { className = typeName;//from w w w. j a v a 2 s . co m } else if (typeName == null) { typeName = className; } byte[] classNameBytes = getZeroTermStrBytes(className); byte[] typeNameBytes = getZeroTermStrBytes(typeName); int packageHeaderLen = 20 + prettyNameBytes.length + classNameBytes.length; int oleHeaderLen = 24 + typeNameBytes.length; byte[] headerBytes = new byte[packageHeaderLen + oleHeaderLen]; ByteBuffer bb = PageChannel.wrap(headerBytes); // write outer package header bb.putShort((short) PACKAGE_SIGNATURE); bb.putShort((short) packageHeaderLen); bb.putInt(PACKAGE_OBJECT_TYPE); bb.putShort((short) prettyNameBytes.length); bb.putShort((short) classNameBytes.length); int prettyNameOff = bb.position() + 8; bb.putShort((short) prettyNameOff); bb.putShort((short) (prettyNameOff + prettyNameBytes.length)); bb.putInt(-1); bb.put(prettyNameBytes); bb.put(classNameBytes); // put ole header bb.putInt(OLE_VERSION); bb.putInt(OLE_FORMAT); bb.putInt(typeNameBytes.length); bb.put(typeNameBytes); bb.putLong(0L); bb.putInt((int) contentLen); return headerBytes; }
From source file:de.csdev.ebus.command.EBusCommandUtils.java
/** * Build a complete telegram for master/slave, master/master and broadcasts * * @param source// ww w .j a va2 s . c o m * @param target * @param command * @param masterData * @param slaveData * @return * @throws EBusTypeException */ public static ByteBuffer buildCompleteTelegram(byte source, byte target, byte[] command, byte[] masterData, byte[] slaveData) throws EBusTypeException { boolean isMastereMaster = EBusUtils.isMasterAddress(target); boolean isBroadcast = target == EBusConsts.BROADCAST_ADDRESS; boolean isMasterSlave = !isMastereMaster && !isBroadcast; ByteBuffer buf = ByteBuffer.allocate(50); buf.put(buildPartMasterTelegram(source, target, command, masterData)); // if used compute a complete telegram if (isMasterSlave && slaveData != null) { ByteBuffer slaveTelegramPart = buildPartSlave(slaveData); buf.put(slaveTelegramPart); buf.put(EBusConsts.ACK_OK); buf.put(EBusConsts.SYN); } if (isMastereMaster) { buf.put(EBusConsts.ACK_OK); buf.put(EBusConsts.SYN); } if (isBroadcast) { buf.put(EBusConsts.SYN); } // set limit and reset position buf.limit(buf.position()); buf.position(0); return buf; }
From source file:net.phoenix.thrift.hello.SpringHelloService.java
@Override public ByteBuffer testBinary(ByteBuffer name) throws TException { try {//from w ww .j a v a 2 s.co m String result = new String(name.array(), name.position(), name.limit() - name.position(), "UTF-8"); result = "Hello " + result; return ByteBuffer.wrap(result.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new TException(e); } }
From source file:com.openteach.diamond.network.waverider.network.Packet.java
/** * ??Packet, ??//from w w w . ja v a 2s .c o m * @param inputBuffer * @return * @throws IOException, InterruptedException */ public static Packet parse(BlockingQueue<ByteBuffer> inputBuffer, NetWorkEndPoint endPoint, SocketChannel channel) throws IOException, InterruptedException { // Buffer for packet header byte[] tmpBuf = new byte[NetWorkConstants.DEFAULT_NETWORK_BUFFER_SIZE]; ByteBuffer header = ByteBuffer.allocate(Packet.getHeaderSize()); ByteBuffer currentBuffer = null; int rest = 0; boolean isRemove = false; // ? while (true) { while ((currentBuffer = inputBuffer.peek()) == null) { if (!endPoint.notifyRead(channel)) { throw new IOException("Socket closed by other thread"); } // ? //endPoint.waitMoreData(5); // FIXME 2ms //Thread.sleep(1); Thread.yield(); } isRemove = false; rest = header.capacity() - header.position(); if (currentBuffer.remaining() >= rest) { if (currentBuffer.remaining() == rest) { isRemove = true; } currentBuffer.get(tmpBuf, 0, rest); header.put(tmpBuf, 0, rest); if (isRemove) { inputBuffer.remove(); } break; } else { header.put(currentBuffer); inputBuffer.remove(); } } header.flip(); // , ??? // ? Integer size = header.getInt(Packet.getLengthPosition()); // For test /*if(size < 0 || size > 100000) { logger.info("Error"); }*/ //logger.debug(new StringBuilder("Try to allocate ").append(size).append(" bytes memory")); ByteBuffer buffer = ByteBuffer.allocate(size); buffer.put(header); header.clear(); // ? while (true) { while ((currentBuffer = inputBuffer.peek()) == null) { endPoint.notifyRead(channel); Thread.sleep(1000); } isRemove = false; rest = buffer.capacity() - buffer.position(); if (currentBuffer.remaining() >= rest) { if (currentBuffer.remaining() == rest) { isRemove = true; } currentBuffer.get(tmpBuf, 0, rest); buffer.put(tmpBuf, 0, rest); if (isRemove) { inputBuffer.remove(); } break; } else { buffer.put(currentBuffer); inputBuffer.remove(); } } //buffer.position(0); buffer.flip(); Packet packet = Packet.unmarshall(buffer); //logger.info("Parse one packet from network"); //packet.dump(); return packet; }
From source file:com.bennavetta.appsite.file.ResourceService.java
private void copy(ReadableByteChannel src, WritableByteChannel dest) throws IOException { ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize.get()); while (src.read(buffer) != -1 || buffer.position() != 0) { buffer.flip();//from w w w .j av a2 s . c o m dest.write(buffer); buffer.compact(); } }
From source file:com.github.neoio.net.message.staging.memory.MemoryMessageStaging.java
@Override public void writePrimaryStaging(ByteBuffer buffer, int length) throws NetIOException { primaryStage.write(buffer.array(), buffer.position(), length); buffer.position(buffer.limit());/*from w ww.j av a 2 s . co m*/ }