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:io.druid.query.search.ContainsSearchQuerySpec.java

@Override
public byte[] getCacheKey() {
    if (value == null) {
        return ByteBuffer.allocate(2).put(CACHE_TYPE_ID).put(caseSensitive ? (byte) 1 : 0).array();
    }//from   w  ww  .j ava 2  s .  c  om

    byte[] valueBytes = StringUtils.toUtf8(value);

    return ByteBuffer.allocate(2 + valueBytes.length).put(CACHE_TYPE_ID).put(caseSensitive ? (byte) 1 : 0)
            .put(valueBytes).array();
}

From source file:com.sm.store.Utils.java

public static byte[] putShort(short k) {
    return ByteBuffer.allocate(2).putShort(k).array();
}

From source file:com.buaa.cfs.common.oncrpc.XDR.java

/**
 * Construct a new XDR message buffer./*w w w . ja v a 2s . c  om*/
 *
 * @param initialCapacity
 *          the initial capacity of the buffer.
 */
public XDR(int initialCapacity) {
    this(ByteBuffer.allocate(initialCapacity), State.WRITING);
}

From source file:com.byteatebit.nbserver.simple.TestSimpleNbServer.java

@Test
public void testWriteClose() throws IOException {
    // Create a task to be executed following the acceptance of a new connection to the server socketChannel.
    // This task is the application entry point.
    // This task will write out the message "Hello and Goodbye" and then close the connection.
    ISocketChannelHandler socketChannelHandler = (nbContext, socket) -> WriteMessageTask.Builder.builder()
            .withByteBuffer(ByteBuffer.allocate(2048)).build()
            .writeMessage("Hello and Goodbye\n".getBytes(StandardCharsets.UTF_8), nbContext, socket,
                    () -> IOUtils.closeQuietly(socket), (e) -> LOG.error("Write failed", e));
    // create the server
    SimpleNbServer simpleNbServer = SimpleNbServer.Builder.builder()
            .withConfig(/*from   www. j a v  a2  s. co  m*/
                    SimpleNbServerConfig.builder().withListenAddress("localhost").withListenPort(1111).build())
            // Here we configure the provider for the listening socketChannel.  In this case,
            // a TCP server socketChannel will be created using the default TcpAcceptedConnectionHandler
            // to handle incoming connections and pass them off to the socketChannelHandler
            .withConnectorFactory(TcpConnectorFactory.Builder.builder()
                    // supply the application entry point
                    .withConnectedSocketTask(socketChannelHandler).build())
            .build();
    try {
        simpleNbServer.start();
        Socket socket = new Socket("localhost", 1111);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
        String message = reader.readLine();
        System.out.println("Received message '" + message + "' from the server");
        Assert.assertEquals("Hello and Goodbye", message);
        socket.close();
    } finally {
        simpleNbServer.shutdown();
    }
}

From source file:com.ec2box.manage.util.OTPUtil.java

/**
 * verifies code for OTP secret per time interval
 *
 * @param secret shared secret//  www.  j a v a2 s .  c  o m
 * @param token  verification token
 * @param time   time representation to calculate OTP
 * @return true if success
 */
private static boolean verifyToken(String secret, long token, long time) {

    long calculated = -1;

    byte[] key = new Base32().decode(secret);

    SecretKeySpec secretKey = new SecretKeySpec(key, "HmacSHA1");

    try {
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] hash = mac.doFinal(ByteBuffer.allocate(8).putLong(time).array());

        int offset = hash[hash.length - 1] & 0xF;
        for (int i = 0; i < 4; ++i) {
            calculated <<= 8;
            calculated |= (hash[offset + i] & 0xFF);
        }

        calculated &= 0x7FFFFFFF;
        calculated %= 1000000;
    } catch (Exception ex) {
        log.error(ex.toString(), ex);
    }

    return calculated != -1 && calculated == token;

}

From source file:com.keybox.manage.util.OTPUtil.java

/**
 * verifies code for OTP secret per time interval
 *
 * @param secret shared secret/*from w  w w  .  j  av  a2 s . c  om*/
 * @param token  verification token
 * @param time   time representation to calculate OTP
 * @return true if success
 */
private static boolean verifyToken(String secret, long token, long time) {

    long calculated = -1;

    byte[] key = new Base32().decode(secret);

    SecretKeySpec secretKey = new SecretKeySpec(key, "HmacSHA1");

    try {
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] hash = mac.doFinal(ByteBuffer.allocate(8).putLong(time).array());

        int offset = hash[hash.length - 1] & 0xF;
        for (int i = 0; i < 4; ++i) {
            calculated <<= 8;
            calculated |= (hash[offset + i] & 0xFF);
        }

        calculated &= 0x7FFFFFFF;
        calculated %= 1000000;
    } catch (Exception ex) {
        log.error(ex.toString(), ex);
    }

    return (calculated != -1 && calculated == token);

}

From source file:ConversionUtil.java

public static byte[] convertToByteArray(long value) {

    byte[] bytes = new byte[8];
    ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
    buffer.putLong(value);//  w w  w .  ja v  a2s  . co m
    return buffer.array();
    // buffer.get(bytes);
    /*
    for (int i =0;i<bytes.length; ++i) {
    int offset = (bytes.length -i-1) *8;
    bytes[i] = (byte)((value & (0xff << offset)) >>> offset);
    }
     */
    // return bytes;

}

From source file:com.ebay.pulsar.analytics.metricstore.druid.query.model.TimeSeriesQuery.java

public byte[] cacheKey() {
    BaseFilter filter = this.getFilter();
    byte[] filterBytes = filter == null ? new byte[] {} : filter.cacheKey();
    byte[] aggregatorBytes = QueryCacheHelper.computeAggregatorBytes(this.getAggregations());
    byte[] intervalsBytes = QueryCacheHelper.computeIntervalsBytes(this.getIntervals());

    List<BasePostAggregator> postaggregators = this.getPostAggregations();
    byte[] postaggregatorBytes = postaggregators == null ? new byte[] {}
            : QueryCacheHelper.computePostAggregatorBytes(postaggregators);
    if (this.getGranularity() instanceof BaseGranularity) {
        byte[] granularityBytes = ((BaseGranularity) this.getGranularity()).cacheKey();
        return ByteBuffer
                .allocate(1 + granularityBytes.length + filterBytes.length + aggregatorBytes.length
                        + intervalsBytes.length + postaggregatorBytes.length)
                .put(TIMESERIES_QUERY).put(granularityBytes).put(filterBytes).put(aggregatorBytes)
                .put(intervalsBytes).put(postaggregatorBytes).array();
    }//from   w w  w  .j a v a 2  s .c o m
    return null;
}

From source file:com.esri.geoevent.solutions.adapter.geomessage.DefenseOutboundAdapter.java

@SuppressWarnings("incomplete-switch")
@Override//from w w  w  . j a v a  2 s .c  o  m
public synchronized void receive(GeoEvent geoEvent) {

    ByteBuffer byteBuffer = ByteBuffer.allocate(10 * 1024);
    Integer wkid = -1;
    String message = "";

    message += "<geomessage v=\"1.0\">\n\r";
    message += "<_type>";
    message += messageType;
    message += "</_type>\n\r";
    message += "<_action>";
    message += "update";
    message += "</_action>\n\r";
    String messageid = UUID.randomUUID().toString();
    message += "<_id>";
    message += "{" + messageid + "}";
    message += "</_id>\n\r";
    MapGeometry geom = geoEvent.getGeometry();
    if (geom.getGeometry().getType() == com.esri.core.geometry.Geometry.Type.Point) {
        Point p = (Point) geom.getGeometry();
        message += "<_control_points>";
        message += ((Double) p.getX()).toString();
        message += ",";
        message += ((Double) p.getY()).toString();
        message += "</_control_points>\n\r";
        wkid = ((Integer) geom.getSpatialReference().getID());
    }

    if (wkid > 0) {
        String wkidValue = wkid.toString();
        message += "<_wkid>";
        message += wkidValue.toString();
        message += "</_wkid>\n\r";
    }
    GeoEventDefinition definition = geoEvent.getGeoEventDefinition();
    for (FieldDefinition fieldDefinition : definition.getFieldDefinitions()) {

        String attributeName = fieldDefinition.getName();
        Object value = geoEvent.getField(attributeName);

        if (value == null || value.equals("null")) {
            continue;
        }
        FieldType t = fieldDefinition.getType();
        if (t != FieldType.Geometry) {
            message += "<" + attributeName + ">";

            switch (t) {
            case String:
                // if(((String)value).isEmpty())
                // continue;
                message += value;
                break;
            case Date:
                Date date = (Date) value;
                message += (formatter.format(date));
                break;
            case Double:
                Double doubleValue = (Double) value;
                message += doubleValue.toString();
                break;
            case Float:
                Float floatValue = (Float) value;
                message += floatValue.toString();
                break;

            case Integer:
                Integer intValue = (Integer) value;
                message += intValue.toString();
                break;
            case Long:
                Long longValue = (Long) value;
                message += longValue.toString();
                break;
            case Short:
                Short shortValue = (Short) value;
                message += shortValue.toString();
                break;
            case Boolean:
                Boolean booleanValue = (Boolean) value;
                message += booleanValue.toString();
                break;

            }
            message += "</" + attributeName + ">\n\r";
        } else {
            if (definition.getIndexOf(attributeName) == definition.getIndexOf("GEOMETRY")) {
                continue;
            } else {
                String json = GeometryEngine.geometryToJson(wkid, (Geometry) value);
                message += "<" + attributeName + ">";
                message += json;
                message += "</" + attributeName + ">\n\r";
            }
            break;
        }

    }
    message += "</geomessage>";
    // stringBuffer.append("</geomessages>");
    message += "\r\n";

    ByteBuffer buf = charset.encode(message);
    if (buf.position() > 0)
        buf.flip();

    try {
        byteBuffer.put(buf);
    } catch (BufferOverflowException ex) {
        LOG.error(
                "Csv Outbound Adapter does not have enough room in the buffer to hold the outgoing data.  Either the receiving transport object is too slow to process the data, or the data message is too big.");
    }
    byteBuffer.flip();
    super.receive(byteBuffer, geoEvent.getTrackId(), geoEvent);
    byteBuffer.clear();
}

From source file:com.web.searchlocal.flashpaper.thread.Covnert2SwfTask.java

/** 
 * //from   ww  w  .j ava2s .c om
 */
public void excute() {
    String tmpOutFile = outFile.getPath().concat(File.separator)
            .concat(inFile.getName().replaceAll("[.]{1}.*$", ".swf"));
    List<String> commandArray = new ArrayList<String>();
    commandArray.add(defaultCommand);
    commandArray.add(inFile.getPath());
    commandArray.add("-o");
    commandArray.add(tmpOutFile);
    ProcessBuilder pbObj = new ProcessBuilder();
    pbObj.command(commandArray);
    pbObj.directory(outFile);
    pbObj.redirectErrorStream(true);
    try {
        Process proObj = pbObj.start();
        final InputStream ins = proObj.getInputStream();
        final ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        Thread th = new Thread() {
            public void run() {
                ReadableByteChannel rbcObj = Channels.newChannel(ins);
                try {
                    while (rbcObj.read(byteBuffer) != -1) {
                        byteBuffer.flip();
                        logger.info(java.nio.charset.Charset.defaultCharset().decode(byteBuffer));
                        byteBuffer.clear();
                    }
                } catch (IOException e) {
                    logger.error(e);
                }
            }
        };
        th.setDaemon(true);
        th.start();
        try {
            proObj.waitFor();
            logger.error("??." + tmpOutFile);
        } catch (InterruptedException e) {
            logger.error(e);
        }
    } catch (IOException e) {
        logger.error(e);
    }
}