本文整理汇总了Java中org.apache.mina.common.ByteBuffer.position方法的典型用法代码示例。如果您正苦于以下问题:Java ByteBuffer.position方法的具体用法?Java ByteBuffer.position怎么用?Java ByteBuffer.position使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.mina.common.ByteBuffer
的用法示例。
在下文中一共展示了ByteBuffer.position方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: decode
import org.apache.mina.common.ByteBuffer; //导入方法依赖的package包/类
public MessageDecoderResult decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out)
throws ProtocolCodecException {
int messageCount = 0;
while (parseMessage(in, out)) {
messageCount++;
}
if (messageCount > 0) {
// Mina will compact the buffer because we can't detect a header
if (in.remaining() < HEADER_PATTERN.length) {
position = 0;
}
return MessageDecoderResult.OK;
} else {
// Mina will compact the buffer
position -= in.position();
return MessageDecoderResult.NEED_DATA;
}
}
示例2: appendDebugInformation
import org.apache.mina.common.ByteBuffer; //导入方法依赖的package包/类
private String appendDebugInformation(ByteBuffer buffer, String text) {
int mark = buffer.position();
try {
StringBuilder sb = new StringBuilder(text);
sb.append("\nBuffer debug info: ").append(getBufferDebugInfo(buffer));
buffer.position(0);
sb.append("\nBuffer contents: ");
try {
final byte[] array = new byte[buffer.limit()];
for(int i = 0; i < array.length; ++i)
array[i] = buffer.get();
sb.append(new String(array, "ISO-8859-1"));
} catch (Exception e) {
sb.append(buffer.getHexDump());
}
text = sb.toString();
} finally {
buffer.position(mark);
}
return text;
}
示例3: messageReceived
import org.apache.mina.common.ByteBuffer; //导入方法依赖的package包/类
@Override
public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
// Decode the bytebuffer and print it to the stdout
if (enabled && message instanceof ByteBuffer) {
ByteBuffer byteBuffer = (ByteBuffer) message;
// Keep current position in the buffer
int currentPos = byteBuffer.position();
// Decode buffer
Charset encoder = Charset.forName("UTF-8");
CharBuffer charBuffer = encoder.decode(byteBuffer.buf());
// Print buffer content
System.out.println(prefix + " - RECV (" + session.hashCode() + "): " + charBuffer);
// Reset to old position in the buffer
byteBuffer.position(currentPos);
}
// Pass the message to the next filter
super.messageReceived(nextFilter, session, message);
}
示例4: AMQShortString
import org.apache.mina.common.ByteBuffer; //导入方法依赖的package包/类
private AMQShortString(ByteBuffer data, final int length)
{
if (length > MAX_LENGTH)
{
throw new IllegalArgumentException("Cannot create AMQShortString with number of octets over 255!");
}
if(data.isDirect() || data.isReadOnly())
{
byte[] dataBytes = new byte[length];
data.get(dataBytes);
_data = dataBytes;
_offset = 0;
}
else
{
_data = data.array();
_offset = data.arrayOffset() + data.position();
data.skip(length);
}
_length = length;
}
示例5: doDecodeDataBlock
import org.apache.mina.common.ByteBuffer; //导入方法依赖的package包/类
/**
* Decodes AMQP data, delegating the decoding to an {@link AMQDataBlockDecoder}.
*
* @param session The Mina session.
* @param in The raw byte buffer.
* @param out The Mina object output gatherer to write decoded objects to.
*
* @return <tt>true</tt> if the data was decoded, <tt>false<tt> if more is needed and the data should accumulate.
*
* @throws Exception If the data cannot be decoded for any reason.
*/
protected boolean doDecodeDataBlock(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception
{
int pos = in.position();
boolean enoughData = _dataBlockDecoder.decodable(in.buf());
in.position(pos);
if (!enoughData)
{
// returning false means it will leave the contents in the buffer and
// call us again when more data has been read
return false;
}
else
{
_dataBlockDecoder.decode(session, in, out);
return true;
}
}
示例6: handleError
import org.apache.mina.common.ByteBuffer; //导入方法依赖的package包/类
private void handleError(ByteBuffer buffer, int recoveryPosition, String text,
boolean disconnect) throws ProtocolCodecException {
buffer.position(recoveryPosition);
position = recoveryPosition;
state = SEEKING_HEADER;
text = appendDebugInformation(buffer, text);
if (disconnect) {
throw new CriticalProtocolCodecException(text);
} else {
log.error(text);
}
}
示例7: doDecode
import org.apache.mina.common.ByteBuffer; //导入方法依赖的package包/类
@Override
protected boolean doDecode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out)
throws Exception {
final int origonPos = in.position();
final int packetLength = in.remaining();
if(packetLength<PROTOCOL_HEADER_LENGTH){
in.position(origonPos);
return false;
}
int flag = in.getInt();
int chid = in.getInt();
int pcode = in.getInt();
int len = in.getInt();
if (flag != TairConstant.TAIR_PACKET_FLAG)
throw new IOException("flag error, except: " + TairConstant.TAIR_PACKET_FLAG + ", but get " + flag);
if (in.remaining() < len) {
in.position(origonPos);
return false;
}
if(isDebugEnabled){
final String remoteIP = ((InetSocketAddress) session.getRemoteAddress()).toString();
StringBuilder receiveTimeInfo = new StringBuilder();
receiveTimeInfo.append("receive response from [").append(remoteIP).append("],time is: ");
receiveTimeInfo.append(System.currentTimeMillis());
receiveTimeInfo.append(", channel id: ").append(chid);
LOGGER.debug(receiveTimeInfo.toString());
}
byte[] data = new byte[len];
in.get(data);
if (isDebugEnabled)
LOGGER.debug(TairUtil.toHex(data));
BasePacket returnPacket = pstreamer.decodePacket(pcode, data);
TairResponse response=new TairResponse();
response.setRequestId(chid);
response.setResponse(returnPacket);
out.write(response);
return true;
}
示例8: parseMessage
import org.apache.mina.common.ByteBuffer; //导入方法依赖的package包/类
/**
* This method cannot move the buffer position until a message is found or an error
* has occurred. Otherwise, MINA will compact the buffer and we lose data.
*/
private boolean parseMessage(ByteBuffer in, ProtocolDecoderOutput out)
throws ProtocolCodecException {
try {
boolean messageFound = false;
while (in.hasRemaining() && !messageFound) {
if (state == SEEKING_HEADER) {
int headerOffset = indexOf(in, position, HEADER_PATTERN);
if (headerOffset == -1) {
break;
}
in.position(headerOffset);
if (log.isDebugEnabled()) {
log.debug("detected header: " + getBufferDebugInfo(in));
}
position = headerOffset + HEADER_PATTERN.length;
state = SEEKING_END;
}
if (state == SEEKING_END) {
boolean finded = startsWith(in, position, CHECKSUM_PATTERN);
while(!finded && in.limit() > position) {
position += 1;
finded = startsWith(in, position, CHECKSUM_PATTERN);
}
if(!finded) {
break;
}
position += CHECKSUM_PATTERN.length;
state = SEEKING_HEADER;
String messageString = getMessageString(in);
out.write(messageString.replace("\r", ""));
messageFound = true;
resetState();
}
}
return messageFound;
} catch (Throwable t) {
state = SEEKING_HEADER;
position = 0;
if (t instanceof ProtocolCodecException) {
throw (ProtocolCodecException) t;
} else {
throw new ProtocolCodecException(t);
}
}
}
示例9: getBufferDebugInfo
import org.apache.mina.common.ByteBuffer; //导入方法依赖的package包/类
private String getBufferDebugInfo(ByteBuffer in) {
return "pos=" + in.position() + ",lim=" + in.limit() + ",rem=" + in.remaining()
+ ",offset=" + position + ",state=" + state;
}
示例10: getMessageString
import org.apache.mina.common.ByteBuffer; //导入方法依赖的package包/类
private String getMessageString(ByteBuffer buffer) throws UnsupportedEncodingException {
byte[] data = new byte[position - buffer.position()];
buffer.get(data);
return new String(data, charsetEncoding);
}
示例11: readObject
import org.apache.mina.common.ByteBuffer; //导入方法依赖的package包/类
/**
* Read object from StreamMessage ByteBuffer content
*
* @param wrapMsgContent ByteBuffer which contains data
* @param encoding message encoding
* @return Object extracted from ByteBuffer
* @throws JMSException
* @throws CharacterCodingException
*/
private Object readObject(ByteBuffer wrapMsgContent, String encoding)
throws JMSException, CharacterCodingException {
int position = wrapMsgContent.position();
checkAvailable(1, wrapMsgContent);
byte wireType = wrapMsgContent.get();
Object result = null;
try {
switch (wireType) {
case BOOLEAN_TYPE:
checkAvailable(1, wrapMsgContent);
result = wrapMsgContent.get() != 0;
break;
case BYTE_TYPE:
checkAvailable(1, wrapMsgContent);
result = wrapMsgContent.get();
break;
case BYTEARRAY_TYPE:
checkAvailable(4, wrapMsgContent);
int size = wrapMsgContent.getInt();
if (size == -1) {
result = null;
} else {
byteArrayRemaining = size;
byte[] bytesResult = new byte[size];
readBytesImpl(wrapMsgContent, bytesResult);
result = bytesResult;
}
break;
case SHORT_TYPE:
checkAvailable(2, wrapMsgContent);
result = wrapMsgContent.getShort();
break;
case CHAR_TYPE:
checkAvailable(2, wrapMsgContent);
result = wrapMsgContent.getChar();
break;
case INT_TYPE:
checkAvailable(4, wrapMsgContent);
result = wrapMsgContent.getInt();
break;
case LONG_TYPE:
checkAvailable(8, wrapMsgContent);
result = wrapMsgContent.getLong();
break;
case FLOAT_TYPE:
checkAvailable(4, wrapMsgContent);
result = wrapMsgContent.getFloat();
break;
case DOUBLE_TYPE:
checkAvailable(8, wrapMsgContent);
result = wrapMsgContent.getDouble();
break;
case NULL_STRING_TYPE:
result = null;
break;
case STRING_TYPE:
checkAvailable(1, wrapMsgContent);
result = wrapMsgContent.getString(Charset.forName(encoding).newDecoder());
break;
}
return result;
} catch (RuntimeException e) {
wrapMsgContent.position(position);
throw e;
}
}
示例12: putDataInBuffer
import org.apache.mina.common.ByteBuffer; //导入方法依赖的package包/类
private void putDataInBuffer(ByteBuffer buffer)
{
if (_encodedForm != null)
{
if(buffer.isDirect() || buffer.isReadOnly())
{
ByteBuffer encodedForm = _encodedForm.duplicate();
if (encodedForm.position() != 0)
{
encodedForm.flip();
}
buffer.put(encodedForm);
}
else
{
buffer.put(_encodedForm.array(),_encodedForm.arrayOffset(),(int)_encodedSize);
}
}
else if (_properties != null)
{
final Iterator<Map.Entry<AMQShortString, AMQTypedValue>> it = _properties.entrySet().iterator();
// If there are values then write out the encoded Size... could check _encodedSize != 0
// write out the total length, which we have kept up to date as data is added
while (it.hasNext())
{
final Map.Entry<AMQShortString, AMQTypedValue> me = it.next();
try
{
if (_logger.isDebugEnabled())
{
_logger.debug("Writing Property:" + me.getKey() + " Type:" + me.getValue().getType() + " Value:"
+ me.getValue().getValue());
_logger.debug("Buffer Position:" + buffer.position() + " Remaining:" + buffer.remaining());
}
// Write the actual parameter name
EncodingUtils.writeShortStringBytes(buffer, me.getKey());
me.getValue().writeToBuffer(buffer);
}
catch (Exception e)
{
if (_logger.isDebugEnabled())
{
_logger.debug("Exception thrown:" + e);
_logger.debug("Writing Property:" + me.getKey() + " Type:" + me.getValue().getType() + " Value:"
+ me.getValue().getValue());
_logger.debug("Buffer Position:" + buffer.position() + " Remaining:" + buffer.remaining());
}
throw new RuntimeException(e);
}
}
}
}
示例13: decode
import org.apache.mina.common.ByteBuffer; //导入方法依赖的package包/类
/**
* Cumulates content of <tt>in</tt> into internal buffer and forwards
* decoding request to {@link #doDecode(IoSession, ByteBuffer, ProtocolDecoderOutput)}.
* <tt>doDecode()</tt> is invoked repeatedly until it returns <tt>false</tt>
* and the cumulative buffer is compacted after decoding ends.
*
* @throws IllegalStateException if your <tt>doDecode()</tt> returned
* <tt>true</tt> not consuming the cumulative buffer.
*/
public void decode( IoSession session, ByteBuffer in,
ProtocolDecoderOutput out ) throws Exception
{
ByteBuffer buf = ( ByteBuffer ) session.getAttribute( BUFFER );
// if we have a session buffer, append data to that otherwise
// use the buffer read from the network directly
if( buf != null )
{
buf.put( in );
buf.flip();
}
else
{
buf = in;
}
for( ;; )
{
int oldPos = buf.position();
boolean decoded = doDecode( session, buf, out );
if( decoded )
{
if( buf.position() == oldPos )
{
throw new IllegalStateException(
"doDecode() can't return true when buffer is not consumed." );
}
if( !buf.hasRemaining() )
{
break;
}
}
else
{
break;
}
}
// if there is any data left that cannot be decoded, we store
// it in a buffer in the session and next time this decoder is
// invoked the session buffer gets appended to
if ( buf.hasRemaining() )
{
storeRemainingInSession( buf, session );
}
else
{
removeSessionBuffer( session );
}
}
示例14: decodeBuffer
import org.apache.mina.common.ByteBuffer; //导入方法依赖的package包/类
public ArrayList<AMQDataBlock> decodeBuffer(java.nio.ByteBuffer buf) throws AMQFrameDecodingException, AMQProtocolVersionException
{
// get prior remaining data from accumulator
ArrayList<AMQDataBlock> dataBlocks = new ArrayList<AMQDataBlock>();
ByteBuffer msg;
// if we have a session buffer, append data to that otherwise
// use the buffer read from the network directly
if( _remainingBuf != null )
{
_remainingBuf.put(buf);
_remainingBuf.flip();
msg = _remainingBuf;
}
else
{
msg = ByteBuffer.wrap(buf);
}
if (_expectProtocolInitiation
|| (firstDecode
&& (msg.remaining() > 0)
&& (msg.get(msg.position()) == (byte)'A')))
{
if (_piDecoder.decodable(msg.buf()))
{
dataBlocks.add(new ProtocolInitiation(msg.buf()));
}
}
else
{
boolean enoughData = true;
while (enoughData)
{
int pos = msg.position();
enoughData = _dataBlockDecoder.decodable(msg);
msg.position(pos);
if (enoughData)
{
dataBlocks.add(_dataBlockDecoder.createAndPopulateFrame(_bodyFactory, msg));
}
else
{
_remainingBuf = SIMPLE_BYTE_BUFFER_ALLOCATOR.allocate(msg.remaining(), false);
_remainingBuf.setAutoExpand(true);
_remainingBuf.put(msg);
}
}
}
if(firstDecode && dataBlocks.size() > 0)
{
firstDecode = false;
}
return dataBlocks;
}