Example usage for java.nio ByteBuffer allocate

List of usage examples for java.nio ByteBuffer allocate

Introduction

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

Prototype

public static ByteBuffer allocate(int capacity) 

Source Link

Document

Creates a byte buffer based on a newly allocated byte array.

Usage

From source file:org.lable.rfc3881.auditlogger.adapter.hbase.HBaseAdapter.java

static byte[] columnQualifierSuffixFor(Identifiable identifiable) {
    List<String> parts = identifiable.identifyingStack();
    // Account for the separator bytes.
    int targetLength = parts.size() - 1;
    for (String part : parts) {
        if (part != null) {
            targetLength += part.length();
        }/*  w  ww  .ja v  a 2s .  com*/
    }

    ByteBuffer buffer = ByteBuffer.allocate(targetLength);
    boolean first = true;
    for (String part : parts) {
        if (!first) {
            buffer.put(NULL_BYTE);
        } else {
            first = false;
        }

        if (part != null) {
            buffer.put(toBytes(part));
        }
    }

    return buffer.array();
}

From source file:com.rogoman.easyauth.Authenticator.java

/**
 * Generates a verification code based on the passed secret and a challenge value.
 *
 * @param secret         passed secret key
 * @param challengeValue passed challenge value
 * @return generated code/*from  ww  w. j av  a  2  s .  c  o  m*/
 * @exception java.security.InvalidKeyException if the secret passed has an invalid format
 * @exception com.rogoman.easyauth.AuthenticatorException if there is another problem in computing the code value
 */
protected String getCodeInternal(final String secret, final long challengeValue)
        throws InvalidKeyException, AuthenticatorException {
    long chlg = challengeValue;

    byte[] challenge = ByteBuffer.allocate(8).putLong(challengeValue).array();

    byte[] key = Base32Encoding.toBytes(secret);
    for (int i = secret.length(); i < key.length; i++) {
        key[i] = 0;
    }

    byte[] hash;
    try {
        hash = HMAC.hmacDigest(challenge, key, CRYPTO_ALGORITHM);
    } catch (final NoSuchAlgorithmException e) {
        throw new AuthenticatorException("HmacSHA1 algorithm is not present in your JVM.", e);
    }

    int offset = hash[hash.length - 1] & 0xf;

    long truncatedHash = 0;
    for (int j = 0; j < 4; j++) {
        truncatedHash <<= 8;
        int absValue = (int) hash[offset + j] & 0xFF;
        truncatedHash |= absValue;
    }

    truncatedHash &= 0x7FFFFFFF;
    truncatedHash %= 1000000;

    String code = Long.toString(truncatedHash);
    return StringUtils.leftPad(code, 6, '0');
}

From source file:com.byteatebit.nbecho.perfclient.NbEchoPerfClient.java

@Override
public void accept(INbContext nbContext, SocketChannel socketChannel) {
    boolean connectionFinished = false;
    int taskId = createTaskId();
    try {//from ww w  .j  a  v  a2 s .com
        connectionFinished = socketChannel.finishConnect();
    } catch (IOException e) {
        LOG.error("Could not complete socket connection.", e);
    }
    if (!connectionFinished) {
        LOG.error("Could not complete socket connection.  Closing socket channel");
        IOUtils.closeQuietly(socketChannel);
        countDownLatch.countDown();
        return;
    }
    WriteMessageTask writeMessageTask = WriteMessageTask.Builder.builder()
            .withByteBuffer(ByteBuffer.allocate(1024)).build();
    ReadDelimitedMessageTask readMessageTask = ReadDelimitedMessageTask.Builder.builder()
            .withByteBuffer(ByteBuffer.allocate(1024)).withDelimiter(MESSAGE_DELIMITER).build();
    clientTask(nbContext, socketChannel, readMessageTask, writeMessageTask, numRequests, taskId);
}

From source file:com.l2jfree.network.mmocore.ReadWriteThread.java

public ReadWriteThread(MMOController<T, RP, SP> mmoController, MMOConfig config,
        PacketHandler<T, RP, SP> packetHandler) throws IOException {
    super(mmoController, config);

    _bufferSize = config.getBufferSize();
    _helperBufferCount = config.getHelperBufferCount();
    _maxOutgoingPacketsPerPass = config.getMaxOutgoingPacketsPerPass();
    _maxIncomingPacketsPerPass = config.getMaxIncomingPacketsPerPass();
    _maxOutgoingBytesPerPass = config.getMaxOutgoingBytesPerPass();
    _maxIncomingBytesPerPass = config.getMaxIncomingBytesPerPass();
    _byteOrder = config.getByteOrder();//from  w w w .ja v a 2 s . c o  m

    _directWriteBuffer = ByteBuffer.allocateDirect(getBufferSize()).order(getByteOrder());
    _writeBuffer = ByteBuffer.allocate(getBufferSize()).order(getByteOrder());
    _readBuffer = ByteBuffer.allocate(getBufferSize()).order(getByteOrder());

    _bufferPool = new ArrayDeque<ByteBuffer>(getHelperBufferCount());
    for (int i = 0; i < getHelperBufferCount(); i++)
        getFreeBuffers().addLast(ByteBuffer.allocate(getBufferSize()).order(getByteOrder()));
    _mmoBuffer = new MMOBuffer();
    _dataSizeHolder = new DataSizeHolder();

    _packetHandler = packetHandler;
    _pendingClose = FastList.newInstance();
}

From source file:byps.BWire.java

/**
 * Reads a ByteBuffer from an InputStream
 * Closes the InputStream./*from  ww w .  ja v a2s  .  c  o m*/
 * @param is
 * @return
 * @throws IOException
 */
public static ByteBuffer bufferFromStream(InputStream is, Boolean gzip) throws IOException {
    if (is == null)
        return null;
    try {
        ByteBuffer ibuf = ByteBuffer.allocate(10 * 1000);

        if (gzip != null) {
            if (gzip) {
                is = new GZIPInputStream(is);
            }
        } else {
            if (!is.markSupported())
                is = new BufferedInputStream(is, 2);
            is.mark(2);
            int magic = is.read() | (is.read() << 8);
            is.reset();
            if (magic == GZIPInputStream.GZIP_MAGIC) {
                is = new GZIPInputStream(is);
            }
        }

        ReadableByteChannel rch = Channels.newChannel(is);
        while (rch.read(ibuf) != -1) {
            if (ibuf.remaining() == 0) {
                ByteBuffer nbuf = ByteBuffer.allocate(ibuf.capacity() * 2);
                ibuf.flip();
                nbuf.put(ibuf);
                ibuf = nbuf;
            }
        }

        ibuf.flip();
        return ibuf;
    } finally {
        is.close();
    }
}

From source file:de.undercouch.bson4jackson.io.StaticBuffers.java

/**
 * @see #charBuffer(Key, int)//from ww w  .  j a  va  2s  . c  o  m
 */
public ByteBuffer byteBuffer(Key key, int minSize) {
    minSize = Math.max(minSize, GLOBAL_MIN_SIZE);

    ByteBuffer r = _byteBuffers[key.ordinal()];
    if (r == null || r.capacity() < minSize) {
        r = ByteBuffer.allocate(minSize);
    } else {
        _byteBuffers[key.ordinal()] = null;
        r.clear();
    }
    return r;
}

From source file:io.dstream.hadoop.TypeAwareWritable.java

/**
 * NOTE: The below code is temporary and both conversion and ser/deser will be exposed through externally 
 * configurable framework!//from  w w w .  j  ava 2 s .c om
 * 
 * @param value
 * @return
 */
private void determineValueType(Object value) {
    if (value instanceof Integer) {
        this.valueEncoder.valueType = INTEGER;
        this.valueEncoder.valueBytes = ByteBuffer.allocate(4).putInt((Integer) value).array();
    } else if (value instanceof Long) {
        this.valueEncoder.valueType = LONG;
        this.valueEncoder.valueBytes = ByteBuffer.allocate(8).putLong((Long) value).array();
    } else if (value == null) {
        this.valueEncoder.valueType = NULL;
    } else {
        ObjectOutputStream oos = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(value);
            this.valueEncoder.valueType = OBJECT;
            this.valueEncoder.valueBytes = bos.toByteArray();
        } catch (Exception e) {
            throw new IllegalStateException("Failed to serialize value: " + value, e);
        } finally {
            try {
                if (oos != null) {
                    oos.close();
                }
            } catch (Exception e2) {
                /*ignore*/}
        }
    }
}

From source file:tachyon.master.RawTables.java

/**
 * Get the metadata of the specified raw table. It will return a duplication.
 *
 * @param tableId The id of the raw table
 * @return null if it has no metadata, or a duplication of the metadata
 *//*from  w w w.  j a va 2 s  .c o m*/
public synchronized ByteBuffer getMetadata(int tableId) {
    Pair<Integer, ByteBuffer> data = mData.get(tableId);

    if (null == data) {
        return null;
    }

    ByteBuffer ret = ByteBuffer.allocate(data.getSecond().capacity());
    ret.put(data.getSecond().array());
    ret.flip();

    return ret;
}

From source file:com.cate.javatransmitter.FileHandler.java

public void setFile(Path inputPath) {
    //TODO add file selection
    this.inputPath = inputPath;
    try {//from  w w w . jav a  2 s.  co m
        this.sbc = Files.newByteChannel(inputPath, StandardOpenOption.READ);
        this.nofChunks = (int) Math.ceil((double) (sbc.size()) / packetSize);
        System.out.println("File Size = " + sbc.size() + " Bytes");
        System.out.println("File Size = " + sbc.size() + " Bytes");
    } catch (IOException ex) {
        Logger.getLogger(FileHandler.class.getName()).log(Level.SEVERE, null, ex);
        System.exit(0);
    }
    this.chunkCounter = 0;
    buf = ByteBuffer.allocate(packetSize);

    //catch (IOException x) {
    //    System.out.println("caught exception: " + x);        
    //        return null;
    //    }        
    //            
}

From source file:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java

private static String readFromSocket(SocketChannel client) throws IOException {
    ByteBuffer readBuf = ByteBuffer.allocate(256);
    LOG.info("Reading from client");
    client.read(readBuf);//from  www . j a v a2 s .c o m
    readBuf.flip();
    return StandardCharsets.US_ASCII.decode(readBuf).toString();
}