Example usage for java.nio ByteBuffer limit

List of usage examples for java.nio ByteBuffer limit

Introduction

In this page you can find the example usage for java.nio ByteBuffer limit.

Prototype

public final int limit() 

Source Link

Document

Returns the limit of this buffer.

Usage

From source file:org.janusgraph.graphdb.tinkerpop.gremlin.server.auth.HMACAuthenticator.java

private byte[] toBytes(char[] chars) {
    CharBuffer charBuffer = CharBuffer.wrap(chars);
    ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
    byte[] bytes = Arrays.copyOfRange(byteBuffer.array(), byteBuffer.position(), byteBuffer.limit());
    Arrays.fill(charBuffer.array(), '\u0000'); //Clear sensitive data from memory
    Arrays.fill(byteBuffer.array(), (byte) 0); //Clear sensitive data from memory
    return bytes;
}

From source file:de.csdev.ebus.command.EBusCommandRegistry.java

/**
 * Checks if the given command method is acceptable for the unescaped telegram
 *
 * @param command/*from www .j a  va 2  s  . com*/
 * @param data
 * @return
 */
public boolean matchesCommand(IEBusCommandMethod command, ByteBuffer data) {

    Byte sourceAddress = (Byte) ObjectUtils.defaultIfNull(command.getSourceAddress(),
            Byte.valueOf((byte) 0x00));

    Byte targetAddress = (Byte) ObjectUtils.defaultIfNull(command.getDestinationAddress(),
            Byte.valueOf((byte) 0x00));

    try {

        ByteBuffer masterTelegram = EBusCommandUtils.buildMasterTelegram(command, sourceAddress, targetAddress,
                null);

        ByteBuffer mask = command.getMasterTelegramMask();

        for (int i = 0; i < mask.limit(); i++) {
            byte b = mask.get(i);

            if (b == (byte) 0xFF) {
                if (masterTelegram.get(i) != data.get(i)) {
                    break;
                }
            }
            if (i == mask.limit() - 1) {
                return true;
            }
        }
    } catch (EBusTypeException e) {
        logger.error("error!", e);
    }

    return false;
}

From source file:com.mellanox.jxio.Msg.java

private String toStringBB(ByteBuffer bb) {
    StringBuffer sb = new StringBuffer();
    sb.append("[pos=");
    sb.append(bb.position());//from  ww w.j av a2 s. com
    sb.append(" lim=");
    sb.append(bb.limit());
    sb.append(" cap=");
    sb.append(bb.capacity());
    sb.append("]");
    return sb.toString();
}

From source file:byps.test.TestSerializeInlineInstances.java

private void internalTestSerializeInlineInstance(Actor obj, String jsonText) throws BException {
    BOutput bout = transport.getOutput();
    bout.header.messageId = 123;//w w w .  java 2  s .c om
    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:net.fenyo.mail4hotspot.dns.Msg.java

private byte[] process(final AdvancedServices advancedServices, final Inet4Address address)
        throws GeneralException {
    // log.debug("processing message of type " + input_buffer[0]);
    // for (byte b : input_buffer) log.debug("received byte: [" + b + "]");

    if (input_buffer.length == 0)
        throw new GeneralException("invalid size");
    if (input_buffer[0] == 0) {
        // UTF-8 message type

        final ByteBuffer bb = ByteBuffer.allocate(input_buffer.length - 1);
        bb.put(input_buffer, 1, input_buffer.length - 1);
        bb.position(0);//from  w ww.jav a  2s .com
        final String query = Charset.forName("UTF-8").decode(bb).toString();
        // log.debug("RECEIVED query: [" + query + "]");

        final String reply = advancedServices.processQueryFromClient(query, address);

        // this buffer may not be backed by an accessible byte array, so we do not use Charset.forName("UTF-8").encode(reply).array() to fill output_buffer
        final ByteBuffer ob = Charset.forName("UTF-8").encode(reply);
        ob.get(output_buffer = new byte[ob.limit()]);

        output_size = output_buffer.length;

    } else {
        // binary message type
        // log.debug("processing binary message");

        final ByteBuffer bb = ByteBuffer.allocate(input_buffer[0]);
        bb.put(input_buffer, 1, input_buffer[0]);
        bb.position(0);
        final String query = Charset.forName("UTF-8").decode(bb).toString();
        //      log.debug("RECEIVED query: [" + query + "]");

        final BinaryMessageReply reply = advancedServices.processBinaryQueryFromClient(query,
                Arrays.copyOfRange(input_buffer, input_buffer[0] + 1, input_buffer.length), address);

        // this buffer may not be backed by an accessible byte array, so we do not use Charset.forName("UTF-8").encode(reply).array() to fill string_part
        final ByteBuffer ob = Charset.forName("UTF-8").encode(reply.reply_string);
        final byte[] string_part = new byte[ob.limit()];
        ob.get(string_part);

        if (string_part.length > 255)
            throw new GeneralException("string_part too long");
        output_buffer = new byte[string_part.length + reply.reply_data.length + 1];
        output_buffer[0] = (byte) string_part.length;
        for (int i = 0; i < string_part.length; i++)
            output_buffer[i + 1] = string_part[i];
        for (int i = 0; i < reply.reply_data.length; i++)
            output_buffer[string_part.length + i + 1] = reply.reply_data[i];
        output_size = output_buffer.length;
    }

    synchronized (compressed) {
        // http://docs.oracle.com/javase/7/docs/api/java/util/zip/Deflater.html#deflate(byte[])
        // log.debug("processing binary message: length before compressing: " + output_buffer.length);
        final Deflater compresser = new Deflater();
        compresser.setInput(output_buffer);
        compresser.finish();
        final int nbytes = compresser.deflate(compressed);
        //         log.debug("RET: " + nbytes);
        //         log.debug("COMPRESSED: " + compressed.length);
        // log.debug("processing binary message: length after compressing: " + nbytes);
        if (compressed.length == nbytes) {
            log.error("compressed buffer too small...");
            throw new GeneralException("compressed buffer too small...");
        }
        output_buffer = Arrays.copyOf(compressed, nbytes);
        output_size = output_buffer.length;
    }

    synchronized (is_processed) {
        is_processed = true;
    }

    return new byte[] { 'E', 0 }; // 'E'rror 0 == OK
}

From source file:org.apache.hadoop.hbase.ipc.IPCUtil.java

/**
 * @param codec/*from ww w  . java  2s. c  o m*/
 * @param cellBlock
 * @param offset
 * @param length
 * @return CellScanner to work against the content of <code>cellBlock</code>
 * @throws IOException
 */
CellScanner createCellScanner(final Codec codec, final CompressionCodec compressor, final byte[] cellBlock,
        final int offset, final int length) throws IOException {
    // If compressed, decompress it first before passing it on else we will leak compression
    // resources if the stream is not closed properly after we let it out.
    InputStream is = null;
    if (compressor != null) {
        // GZIPCodec fails w/ NPE if no configuration.
        if (compressor instanceof Configurable)
            ((Configurable) compressor).setConf(this.conf);
        Decompressor poolDecompressor = CodecPool.getDecompressor(compressor);
        CompressionInputStream cis = compressor
                .createInputStream(new ByteArrayInputStream(cellBlock, offset, length), poolDecompressor);
        ByteBufferOutputStream bbos = null;
        try {
            // TODO: This is ugly.  The buffer will be resized on us if we guess wrong.
            // TODO: Reuse buffers.
            bbos = new ByteBufferOutputStream((length - offset) * this.cellBlockDecompressionMultiplier);
            IOUtils.copy(cis, bbos);
            bbos.close();
            ByteBuffer bb = bbos.getByteBuffer();
            is = new ByteArrayInputStream(bb.array(), 0, bb.limit());
        } finally {
            if (is != null)
                is.close();
            if (bbos != null)
                bbos.close();

            CodecPool.returnDecompressor(poolDecompressor);
        }
    } else {
        is = new ByteArrayInputStream(cellBlock, offset, length);
    }
    return codec.getDecoder(is);
}

From source file:net.sf.jinsim.UDPChannel.java

@Override
protected synchronized int receive(ByteBuffer buffer) throws IOException {

    if (cacheBuffer.position() > 0 && cacheBuffer.hasRemaining()) {
        buffer.put(cacheBuffer);/* ww w  .j av a2 s. co  m*/
        return buffer.position();
    } else {
        byte[] data = new byte[buffer.limit()];
        cacheBuffer.clear();
        SocketAddress address = datagramChannel.receive(cacheBuffer);
        int size = cacheBuffer.position();
        if (address != null) {
            cacheBuffer.flip();
            int remaining = cacheBuffer.remaining();
            if (remaining > data.length) {
                remaining = data.length;
            }
            cacheBuffer.get(data, 0, remaining);
            buffer.put(data, 0, remaining);
            return data.length;
        }
        return size;
    }
    /*
    SocketAddress address = datagramChannel.receive(buffer);
    if (address != null) {
       System.out.println("has data: " + buffer.position());
       return buffer.position();
    }
    return 0;
    */
    /*
    DatagramSocket socket = datagramChannel.socket();
            
    receive(DatagramPacket p) 
    */
}

From source file:oz.hadoop.yarn.api.net.ApplicationContainerServerImpl.java

/**
 * /*w  w w .  ja v  a 2s . c  o  m*/
 */
void doWrite(SelectionKey selectionKey, ByteBuffer buffer) {
    ByteBuffer message = ByteBufferUtils.merge(ByteBuffer.allocate(4).putInt(buffer.limit() + 4), buffer);
    message.flip();

    selectionKey.attach(message);
    selectionKey.interestOps(SelectionKey.OP_WRITE);
}

From source file:com.bennavetta.appsite.file.ResourceService.java

public Resource create(String path, MediaType mime, ReadableByteChannel src) throws IOException {
    String normalized = PathUtils.normalize(path);
    log.debug("Creating resource {}", normalized);

    AppEngineFile file = fs.createNewBlobFile(mime.toString(), normalized);
    FileWriteChannel channel = fs.openWriteChannel(file, true);

    MessageDigest digest = null;//from   w  w  w. ja v  a2  s  . c  om
    try {
        digest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("MD5 not available", e);
    }
    ByteBuffer buf = ByteBuffer.allocateDirect(bufferSize.get());
    while (src.read(buf) != -1 || buf.position() != 0) {
        buf.flip();
        int read = channel.write(buf);
        if (read != 0) {
            int origPos = buf.position();
            int origLimit = buf.limit();
            buf.position(origPos - read);
            buf.limit(origPos);
            digest.update(buf);
            buf.limit(origLimit);
            buf.position(origPos);
        }

        buf.compact();
    }

    channel.closeFinally();
    Resource resource = new Resource(normalized, fs.getBlobKey(file).getKeyString(), digest.digest(), mime);
    resource.save();
    return resource;
}

From source file:org.eclipse.virgo.ide.manifest.internal.core.model.BundleManifest.java

protected void parseManifest(IDocument document) {
    try {/* w  w w. j  a  v  a 2 s  . c om*/
        headerMap = new HashMap<String, BundleManifestHeader>();
        BundleManifestHeader header = null;
        int l = 0;
        for (; l < document.getNumberOfLines(); l++) {
            IRegion lineInfo = document.getLineInformation(l);
            String line = document.get(lineInfo.getOffset(), lineInfo.getLength());
            // test lines' length
            Charset charset = Charset.forName("UTF-8"); //$NON-NLS-1$
            String lineDelimiter = document.getLineDelimiter(l);
            if (lineDelimiter == null) {
                lineDelimiter = ""; //$NON-NLS-1$
            }
            ByteBuffer byteBuf = charset.encode(line);
            if (byteBuf.limit() + lineDelimiter.length() > 512) {
                error(IMarker.SEVERITY_ERROR, BundleManifestCoreMessages.BundleErrorReporter_lineTooLong,
                        l + 1);
                return;
            }
            // parse
            if (line.length() == 0) {
                // Empty Line
                if (l == 0) {
                    error(IMarker.SEVERITY_ERROR, BundleManifestCoreMessages.BundleErrorReporter_noMainSection,
                            1);
                    return;
                }
                /* flush last line */
                if (header != null) {
                    headerMap.put(header.getElementName().toLowerCase(), header);
                    header = null;
                }
                break; /* done processing main attributes */
            }
            if (line.charAt(0) == ' ') {
                // Continuation Line
                if (l == 0) { /* if no previous line */
                    error(IMarker.SEVERITY_ERROR, BundleManifestCoreMessages.BundleErrorReporter_noMainSection,
                            1);
                    return;
                }
                if (header != null) {
                    header.append(line.substring(1));
                }

                continue;
            }
            // Expecting New Header
            if (header != null) {
                headerMap.put(header.getElementName().toLowerCase(), header);
                header = null;
            }

            int colon = line.indexOf(':');
            if (colon == -1) { /* no colon */
                error(IMarker.SEVERITY_ERROR, BundleManifestCoreMessages.BundleErrorReporter_noColon, l + 1);
                return;
            }
            String headerName = getHeaderName(line);
            if (headerName == null) {
                error(IMarker.SEVERITY_ERROR, BundleManifestCoreMessages.BundleErrorReporter_invalidHeaderName,
                        l + 1);
                return;
            }
            if (line.length() < colon + 2 || line.charAt(colon + 1) != ' ') {
                error(IMarker.SEVERITY_ERROR, BundleManifestCoreMessages.BundleErrorReporter_noSpaceValue,
                        l + 1);
                return;
            }
            if ("Name".equals(headerName)) { //$NON-NLS-1$
                error(IMarker.SEVERITY_ERROR, BundleManifestCoreMessages.BundleErrorReporter_nameHeaderInMain,
                        l + 1);
                return;
            }
            header = new BundleManifestHeader(this, headerName, line.substring(colon + 2), l);
            if (headerMap.containsKey(header.getElementName().toLowerCase())) {
                error(IMarker.SEVERITY_WARNING, BundleManifestCoreMessages.BundleErrorReporter_duplicateHeader,
                        l + 1);
            }

        }
        if (header != null) {
            // lingering header, line not terminated
            error(IMarker.SEVERITY_ERROR, BundleManifestCoreMessages.BundleErrorReporter_noLineTermination,
                    l + 1);
            return;
        }
        // If there is any more headers, not starting with a Name header
        // the empty lines are a mistake, report it.
        for (; l < document.getNumberOfLines(); l++) {
            IRegion lineInfo = document.getLineInformation(l);
            String line = document.get(lineInfo.getOffset(), lineInfo.getLength());
            if (line.length() == 0) {
                continue;
            }
            if (!line.startsWith("Name:")) { //$NON-NLS-1$
                error(IMarker.SEVERITY_ERROR, BundleManifestCoreMessages.BundleErrorReporter_noNameHeader, l);
            }
            break;
        }

    } catch (BadLocationException ble) {
    }
}