Tabnine Logo
ByteBuffer
Code IndexAdd Tabnine to your IDE (free)

How to use
ByteBuffer
in
org.littleshoot.mina.common

Best Java code snippets using org.littleshoot.mina.common.ByteBuffer (Showing top 20 results out of 315)

origin: org.littleshoot/xmpp

  @Override
  public ByteBuffer getBody() {
    return ByteBuffer.wrap(body);
  }
};
origin: org.littleshoot/mina-port

@Override
public void write(int b) throws IOException {
  ByteBuffer buf = ByteBuffer.allocate(1);
  buf.put((byte) b);
  buf.flip();
  write(buf);
}
origin: org.littleshoot/mina-port

@Override
public boolean equals(Object o) {
  if (!(o instanceof ByteBuffer)) {
    return false;
  }
  ByteBuffer that = (ByteBuffer) o;
  if (this.remaining() != that.remaining()) {
    return false;
  }
  int p = this.position();
  for (int i = this.limit() - 1, j = that.limit() - 1; i >= p; i--, j--) {
    byte v1 = this.get(i);
    byte v2 = that.get(j);
    if (v1 != v2) {
      return false;
    }
  }
  return true;
}
origin: org.littleshoot/mina-port

@Override
public int hashCode() {
  int h = 1;
  int p = position();
  for (int i = limit() - 1; i >= p; i--) {
    h = 31 * h + get(i);
  }
  return h;
}
origin: org.littleshoot/mina-port

public IoSessionInputStream() {
  buf = ByteBuffer.allocate(16);
  buf.setAutoExpand(true);
  buf.limit(0);
}
origin: org.littleshoot/mina-port

/**
 * @see java.nio.Buffer#remaining()
 */
public int remaining() {
  return limit() - position();
}
origin: org.littleshoot/sip-stack

int oldPos = in.position();
int oldLimit = in.limit();
int count = matchCount;
while (in.hasRemaining())
  byte b = in.get();
  if (m_delimiterBuf.get(matchCount) == b)
    if (matchCount == m_delimiterBuf.limit())
      int pos = in.position();
      in.limit(pos);
      in.position(oldPos);
      buf.put(in);
      if (buf.position() > maxLineLength)
            + buf.position());
      buf.flip();
      buf.limit(buf.limit() - matchCount);
      final String headers = buf.getString(decoder);
      final Map<String, SipHeader> headersMap = 
        createHeadersMap(headers);
      buf.clear();
      in.limit(oldLimit);
origin: org.littleshoot/mina-port

  ByteBuffer tmp = ByteBuffer.allocate(2).setAutoExpand(true);
  tmp.putString(delimiter.getValue(), charset.newEncoder());
  tmp.flip();
  delimBuf = tmp;
int oldPos = in.position();
int oldLimit = in.limit();
while (in.hasRemaining()) {
  byte b = in.get();
  if (delimBuf.get(matchCount) == b) {
    matchCount++;
    if (matchCount == delimBuf.limit()) {
      int pos = in.position();
      in.limit(pos);
      in.position(oldPos);
      in.limit(oldLimit);
      in.position(pos);
        buf.flip();
        buf.limit(buf.limit() - matchCount);
        try {
          out.write(buf.getString(ctx.getDecoder()));
        } finally {
          buf.clear();
    in.position(Math.max(0, in.position() - matchCount));
    matchCount = 0;
origin: org.littleshoot/mina-port

private void readSession(DatagramChannel channel, RegistrationRequest req)
    throws Exception {
  ByteBuffer readBuf = ByteBuffer
      .allocate(((DatagramSessionConfig) req.config
          .getSessionConfig()).getReceiveBufferSize());
  try {
    SocketAddress remoteAddress = channel.receive(readBuf.buf());
    if (remoteAddress != null) {
      DatagramSessionImpl session = (DatagramSessionImpl) newSession(
          remoteAddress, req.address);
      readBuf.flip();
      ByteBuffer newBuf = ByteBuffer.allocate(readBuf.limit());
      newBuf.put(readBuf);
      newBuf.flip();
      session.increaseReadBytes(newBuf.remaining());
      session.getFilterChain().fireMessageReceived(session, newBuf);
    }
  } finally {
    readBuf.release();
  }
}
origin: org.littleshoot/stun-stack

private static UUID createTransactionId()
  {
  final UUID id = UUID.randomUUID();
  final byte[] idBytes = id.getRawBytes();
  final ByteBuffer idBuf = ByteBuffer.wrap(idBytes);
  
  // Lower the limit to make room for the magic cookie.
  idBuf.limit(idBytes.length - 4);
  
  final ByteBuffer newIdBuf = ByteBuffer.allocate(16);
  MinaUtils.putUnsignedInt(newIdBuf, MAGIC_COOKIE);
  newIdBuf.put(idBuf);
  newIdBuf.flip();
  
  return new UUID(MinaUtils.toByteArray(newIdBuf));
  }
origin: org.littleshoot/mina-port

public void write(ByteBuffer src) {
  synchronized (mutex) {
    if (closed) {
      return;
    }
    if (buf.hasRemaining()) {
      this.buf.compact();
      this.buf.put(src);
      this.buf.flip();
    } else {
      this.buf.clear();
      this.buf.put(src);
      this.buf.flip();
      mutex.notifyAll();
    }
  }
}
origin: org.littleshoot/mina-util

private static ByteBuffer createBuffer(final ByteBuffer buffer)
  {
  // We calculate this here because the final split buffer will not
  // necessarily have a size equal to the chunk size -- it will
  // usually be smaller.
  final ByteBuffer data = ByteBuffer.allocate(
    buffer.limit() - buffer.position());
  
  data.put(buffer);
  data.flip();
  return data;
  }
origin: org.littleshoot/mina-util

private static ByteBuffer createBuffer(final ByteBuffer buffer)
  {
  final ByteBuffer data = ByteBuffer.allocate(
    buffer.limit() - buffer.position());
  
  LOG.trace("Created buffer with capacity: "+data.capacity());
  data.put(buffer);
  data.rewind();
  return data;
  }
origin: org.littleshoot/mina-port

  public void encode(IoSession session, Object message,
      ProtocolEncoderOutput out) throws Exception {
    if (!(message instanceof Serializable)) {
      throw new NotSerializableException();
    }

    ByteBuffer buf = ByteBuffer.allocate(64);
    buf.setAutoExpand(true);
    buf.putObject(message);

    int objectSize = buf.position() - 4;
    if (objectSize > maxObjectSize) {
      buf.release();
      throw new IllegalArgumentException(
          "The encoded object is too big: " + objectSize + " (> "
              + maxObjectSize + ')');
    }

    buf.flip();
    out.write(buf);
  }
}
origin: org.littleshoot/stun-server

/**
 * Creates a new STUN server.
 * 
 * @param codecFactory The factory for creating STUN codecs.
 * @param ioHandler The IO handler, often a demuxing handler that
 * demultiplexes STUN with the media protocol.
 * @param threadName The name of the thread to use.
 */
public AbstractStunServer(final ProtocolCodecFactory codecFactory,
    final IoHandler ioHandler, final String threadName) {
  ByteBuffer.setUseDirectBuffers(false);
  ByteBuffer.setAllocator(new SimpleByteBufferAllocator());
  this.codecFactory = codecFactory;
  this.ioHandler = ioHandler;
  this.threadName = threadName;
}
origin: org.littleshoot/mina-port

public void encode(IoSession session, Object message,
    ProtocolEncoderOutput out) throws Exception {
  CharsetEncoder encoder = (CharsetEncoder) session.getAttribute(ENCODER);
  if (encoder == null) {
    encoder = charset.newEncoder();
    session.setAttribute(ENCODER, encoder);
  }
  String value = message.toString();
  ByteBuffer buf = ByteBuffer.allocate(value.length())
      .setAutoExpand(true);
  buf.putString(value, encoder);
  if (buf.position() > maxLineLength) {
    throw new IllegalArgumentException("Line length: " + buf.position());
  }
  buf.putString(delimiter.getValue(), encoder);
  buf.flip();
  out.write(buf);
}
origin: org.littleshoot/mina-port

public Object readObject() throws ClassNotFoundException, IOException {
  int objectSize = in.readInt();
  if (objectSize <= 0) {
    throw new StreamCorruptedException("Invalid objectSize: "
        + objectSize);
  }
  if (objectSize > maxObjectSize) {
    throw new StreamCorruptedException("ObjectSize too big: "
        + objectSize + " (expected: <= " + maxObjectSize + ')');
  }
  ByteBuffer buf = ByteBuffer.allocate(objectSize + 4, false);
  buf.putInt(objectSize);
  in.readFully(buf.array(), 4, objectSize);
  buf.position(0);
  buf.limit(objectSize + 4);
  Object answer = buf.getObject(classLoader);
  buf.release();
  return answer;
}
origin: org.littleshoot/mina-port

  buf.put(in);
  buf.flip();
} else {
  buf = in;
  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;
if (buf.hasRemaining()) {
  if (usingSessionBuffer)
    buf.compact();
  else
    storeRemainingInSession(buf, session);
origin: org.littleshoot/mina-port

  private void storeRemainingInSession(ByteBuffer buf, IoSession session) {
    ByteBuffer remainingBuf = ByteBuffer.allocate(buf.capacity());
    remainingBuf.setAutoExpand(true);
    remainingBuf.order(buf.order());
    remainingBuf.put(buf);
    session.setAttribute(BUFFER, remainingBuf);
  }
}
origin: org.littleshoot/mina-port

public void writeObject(Object obj) throws IOException {
  ByteBuffer buf = ByteBuffer.allocate(64, false);
  buf.setAutoExpand(true);
  buf.putObject(obj);
  int objectSize = buf.position() - 4;
  if (objectSize > maxObjectSize) {
    buf.release();
    throw new IllegalArgumentException(
        "The encoded object is too big: " + objectSize + " (> "
            + maxObjectSize + ')');
  }
  out.write(buf.array(), 0, buf.position());
  buf.release();
}
org.littleshoot.mina.commonByteBuffer

Javadoc

A byte buffer used by MINA applications.

This is a replacement for java.nio.ByteBuffer. Please refer to java.nio.ByteBuffer and java.nio.Buffer documentation for usage. MINA does not use NIO java.nio.ByteBuffer directly for two reasons:

  • It doesn't provide useful getters and putters such as fill, get/putString, and get/putAsciiInt() enough.
  • It is hard to distinguish if the buffer is created from MINA buffer pool or not. MINA have to return used buffers back to pool.
  • It is difficult to write variable-length data due to its fixed capacity

Allocation

You can get a heap buffer from buffer pool:

 
ByteBuffer buf = ByteBuffer.allocate(1024, false); 
you can also get a direct buffer from buffer pool:
 
ByteBuffer buf = ByteBuffer.allocate(1024, true); 
or you can let MINA choose:
 
ByteBuffer buf = ByteBuffer.allocate(1024); 

Acquire/Release

Please note that you never need to release the allocated buffer because MINA will release it automatically when:

  • You pass the buffer by calling IoSession#write(Object).
  • You pass the buffer by calling IoFilter.NextFilter#filterWrite(IoSession,IoFilter.WriteRequest).
  • You pass the buffer by calling ProtocolEncoderOutput#write(ByteBuffer).
And, you don't need to release any ByteBuffer which is passed as a parameter of IoHandler#messageReceived(IoSession,Object) method. They are released automatically when the method returns.

You have to release buffers manually by calling #release() when:

  • You allocated a buffer, but didn't pass the buffer to any of two methods above.
  • You called #acquire() to prevent the buffer from being released.

Wrapping existing NIO buffers and arrays

This class provides a few wrap(...) methods that wraps any NIO buffers and byte arrays. Wrapped MINA buffers are not returned to the buffer pool by default to prevent unexpected memory leakage by default. In case you want to make it pooled, you can call #setPooled(boolean)with true flag to enable pooling.

AutoExpand

Writing variable-length data using NIO ByteBuffers is not really easy, and it is because its size is fixed. MINA ByteBuffer introduces autoExpand property. If autoExpand property is true, you never get BufferOverflowException or IndexOutOfBoundsException (except when index is negative). It automatically expands its capacity and limit value. For example:

 
String greeting = messageBundle.getMessage( "hello" ); 
ByteBuffer buf = ByteBuffer.allocate( 16 ); 
// Turn on autoExpand (it is off by default) 
buf.setAutoExpand( true ); 
buf.putString( greeting, utf8encoder ); 
NIO ByteBuffer is reallocated by MINA ByteBuffer behind the scene if the encoded data is larger than 16 bytes. Its capacity and its limit will increase to the last position the string is written.

Derived Buffers

Derived buffers are the buffers which were created by #duplicate(), #slice(), or #asReadOnlyBuffer(). They are useful especially when you broadcast the same messages to multiple IoSessions. Please note that the derived buffers are neither pooled nor auto-expandable. Trying to expand a derived buffer will raise IllegalStateException.

Changing Buffer Allocation and Management Policy

MINA provides a ByteBufferAllocator interface to let you override the default buffer management behavior. There are two allocators provided out-of-the-box:

  • PooledByteBufferAllocator (Default)
  • SimpleByteBufferAllocator
You can change the allocator by calling #setAllocator(ByteBufferAllocator).

Most used methods

  • wrap
    Wraps the specified byte array into MINA heap buffer. Please note that MINA buffers are going to be
  • allocate
    Returns the buffer which is capable of the specified size.
  • flip
  • put
  • setAllocator
    Changes the current allocator with the specified one to manage the allocated buffers from now.
  • setUseDirectBuffers
  • get
  • hasRemaining
  • limit
  • position
  • remaining
  • capacity
    Changes the capacity of this buffer.
  • remaining,
  • capacity,
  • clear,
  • duplicate,
  • getString,
  • getUnsigned,
  • getUnsignedInt,
  • getUnsignedShort,
  • putString,
  • setAutoExpand

Popular in Java

  • Start an intent from android
  • requestLocationUpdates (LocationManager)
  • runOnUiThread (Activity)
  • scheduleAtFixedRate (Timer)
  • HttpURLConnection (java.net)
    An URLConnection for HTTP (RFC 2616 [http://tools.ietf.org/html/rfc2616]) used to send and receive d
  • Selector (java.nio.channels)
    A controller for the selection of SelectableChannel objects. Selectable channels can be registered w
  • Timestamp (java.sql)
    A Java representation of the SQL TIMESTAMP type. It provides the capability of representing the SQL
  • Scanner (java.util)
    A parser that parses a text string of primitive types and strings with the help of regular expressio
  • HttpServlet (javax.servlet.http)
    Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. A sub
  • JFrame (javax.swing)
  • Best IntelliJ plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now