Example usage for java.nio ByteBuffer putInt

List of usage examples for java.nio ByteBuffer putInt

Introduction

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

Prototype

public abstract ByteBuffer putInt(int value);

Source Link

Document

Writes the given int to the current position and increases the position by 4.

Usage

From source file:edu.berkeley.sparrow.examples.ProtoFrontendAsync.java

public static List<TTaskSpec> generateJob(int numTasks, int benchmarkId, int benchmarkIterations) {
    // Pack task parameters
    ByteBuffer message = ByteBuffer.allocate(8);
    message.putInt(benchmarkId);
    message.putInt(benchmarkIterations);

    List<TTaskSpec> out = new ArrayList<TTaskSpec>();
    for (int taskId = 0; taskId < numTasks; taskId++) {
        TTaskSpec spec = new TTaskSpec();
        spec.setTaskId(Integer.toString(taskId));
        spec.setMessage(message.array());
        out.add(spec);/* www  .  j av a 2 s.c  o m*/
    }
    return out;
}

From source file:com.pushtechnology.diffusion.examples.runnable.RandomData.java

/**
 * Serialize a {@link RandomData} value as a {@link Binary} value.
 * @param randomData The {@link RandomData} value
 * @return The {@link Binary} value//from   w  w w. j  a v  a  2  s . com
 */
static Binary toBinary(RandomData randomData) {
    final ByteBuffer buffer = ByteBuffer.allocate(16);
    buffer.putInt(randomData.getId());
    buffer.putLong(randomData.getTimestamp());
    buffer.putInt(randomData.getRandomInt());
    return Diffusion.dataTypes().binary().readValue(buffer.array());
}

From source file:com.rom.jmultipatcher.Utils.java

public static byte[] byteArrayfromInt(final int dataSize) {

    ByteBuffer intBB = ByteBuffer.allocate(4);
    return intBB.putInt(dataSize).array();
}

From source file:org.apache.camel.converter.NIOConverter.java

@Converter
public static ByteBuffer toByteBuffer(Integer value) {
    ByteBuffer buf = ByteBuffer.allocate(4);
    buf.putInt(value);
    return buf;/*w  w  w.  j  a  v  a2  s.  c  om*/
}

From source file:com.astamuse.asta4d.web.util.SecureIdGenerator.java

public static String createEncryptedURLSafeId() {
    try {//from   ww w.j  a va 2s .  c o  m
        byte[] idBytes = IdGenerator.createIdBytes();

        ByteBuffer bb = ByteBuffer.allocate(idBytes.length + 4);
        bb.put(idBytes);

        // add random salt
        bb.putInt(sr.nextInt());

        MessageDigest crypt = MessageDigest.getInstance("SHA-1");
        return Base64.encodeBase64URLSafeString(crypt.digest(bb.array()));

    } catch (NoSuchAlgorithmException e) {
        // impossible
        throw new RuntimeException(e);
    }
}

From source file:Main.java

static ByteBuffer createMsg(int state, long leader, long zxid, long epoch) {
    byte requestBytes[] = new byte[28];
    ByteBuffer requestBuffer = ByteBuffer.wrap(requestBytes);

    /*/*w w  w.jav  a  2s.c om*/
     * Building notification packet to send
     */

    requestBuffer.clear();
    requestBuffer.putInt(state);
    requestBuffer.putLong(leader);
    requestBuffer.putLong(zxid);
    requestBuffer.putLong(epoch);

    return requestBuffer;
}

From source file:org.dkf.jmule.StoragePicker.java

public static String handle(Context context, int requestCode, int resultCode, Intent data) {
    String result = null;/*from www. j ava 2 s . c o m*/
    try {

        if (resultCode == Activity.RESULT_OK && requestCode == SELECT_FOLDER_REQUEST_CODE) {
            Uri treeUri = data.getData();

            ContentResolver cr = context.getContentResolver();

            Method takePersistableUriPermissionM = cr.getClass().getMethod("takePersistableUriPermission",
                    Uri.class, int.class);
            final int takeFlags = data.getFlags()
                    & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            takePersistableUriPermissionM.invoke(cr, treeUri, takeFlags);

            if (treeUri == null) {
                UIUtils.showShortMessage(context, R.string.storage_picker_treeuri_null);
                result = null;
            } else {
                DocumentFile file = DocumentFile.fromTreeUri(context, treeUri);
                if (!file.isDirectory()) {
                    UIUtils.showShortMessage(context, R.string.storage_picker_treeuri_not_directory);
                    result = null;
                } else if (!file.canWrite()) {
                    UIUtils.showShortMessage(context, R.string.storage_picker_treeuri_cant_write);
                    result = null;
                } else {
                    if (Platforms.get().saf()) {
                        LollipopFileSystem fs = (LollipopFileSystem) Platforms.fileSystem();
                        result = fs.getTreePath(treeUri);

                        // TODO - remove below code - only for testing SD card writing
                        File testFile = new File(result, "test_file.txt");
                        LOG.info("test file {}", testFile);

                        try {
                            Pair<ParcelFileDescriptor, DocumentFile> fd = fs.openFD(testFile, "rw");
                            if (fd != null && fd.first != null && fd.second != null) {
                                AndroidFileHandler ah = new AndroidFileHandler(testFile, fd.second, fd.first);
                                ByteBuffer bb = ByteBuffer.allocate(48);
                                bb.putInt(1).putInt(2).putInt(3).putInt(44).putInt(22);
                                bb.flip();
                                ah.getWriteChannel().write(bb);
                                ah.close();
                            } else {
                                LOG.error("unable to create file {}", testFile);
                            }
                        } catch (Exception e) {
                            LOG.error("unable to fill file {} error {}", testFile, e);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        UIUtils.showShortMessage(context, R.string.storage_picker_treeuri_error);
        LOG.error("Error handling folder selection {}", e);
        result = null;
    }

    return result;
}

From source file:org.apache.blur.console.util.NodeUtil.java

public static Map<String, Object> getZookeeperStatus() throws IOException {
    String[] connections = Config.getBlurConfig().get("blur.zookeeper.connection").split(",");
    Set<String> onlineZookeepers = new HashSet<String>();
    Set<String> offlineZookeepers = new HashSet<String>();

    for (String connection : connections) {
        Socket socket = null;//from   ww  w  .  j av a2s .  co  m
        InputStream response = null;
        OutputStream question = null;
        try {
            URI parsedConnection = new URI("my://" + connection);
            String host = parsedConnection.getHost();
            int port = parsedConnection.getPort() >= 0 ? parsedConnection.getPort() : 2181;
            byte[] reqBytes = new byte[4];
            ByteBuffer req = ByteBuffer.wrap(reqBytes);
            req.putInt(ByteBuffer.wrap("ruok".getBytes()).getInt());
            socket = new Socket();
            socket.setSoLinger(false, 10);
            socket.setSoTimeout(20000);
            parsedConnection.getPort();
            socket.connect(new InetSocketAddress(host, port));

            response = socket.getInputStream();
            question = socket.getOutputStream();

            question.write(reqBytes);

            byte[] resBytes = new byte[4];

            response.read(resBytes);
            String status = new String(resBytes);
            if (status.equals("imok")) {
                onlineZookeepers.add(connection);
            } else {
                offlineZookeepers.add(connection);
            }
            socket.close();
            response.close();
            question.close();
        } catch (Exception e) {
            offlineZookeepers.add(connection);
        } finally {
            if (socket != null) {
                socket.close();
            }
            if (response != null) {
                response.close();
            }
            if (question != null) {
                question.close();
            }
        }
    }

    Map<String, Object> data = new HashMap<String, Object>();

    data.put("online", onlineZookeepers);
    data.put("offline", offlineZookeepers);

    return data;
}

From source file:org.midonet.cluster.rest_api.models.Route.java

public static UUID idOf(org.midonet.midolman.layer3.Route route) {
    ByteBuffer buffer = ByteBuffer.allocate(50);
    buffer.putInt(route.dstNetworkAddr);
    buffer.putInt(route.srcNetworkAddr);
    buffer.putInt(route.nextHopGateway);
    buffer.putInt(route.weight);/*from ww  w . ja v a 2 s  . c o m*/
    buffer.put((byte) (route.dstNetworkLength & 0xFF));
    buffer.put((byte) (route.srcNetworkLength & 0xFF));
    buffer.putLong(route.nextHopPort.getMostSignificantBits());
    buffer.putLong(route.nextHopPort.getLeastSignificantBits());
    buffer.putLong(route.routerId.getMostSignificantBits());
    buffer.putLong(route.routerId.getLeastSignificantBits());
    return UUID.nameUUIDFromBytes(buffer.array());
}

From source file:ja.lingo.engine.util.EngineFiles.java

private static void appendFile(String fileName, FileOutputStream fos, boolean prependWithLength)
        throws IOException {
    FileInputStream fis = new FileInputStream(fileName);
    FileChannel fic = fis.getChannel();
    FileChannel foc = fos.getChannel();

    ByteBuffer buffer = ByteBuffer.allocate(COPY_BUFFER_SIZE);

    // put header: length (1 int = 4 bytes)
    if (prependWithLength) {
        buffer.putInt((int) new File(fileName).length());
    }/*from ww w  . j  a  v a  2 s  .  c  om*/

    // put body
    do {
        buffer.flip();
        foc.write(buffer);
        buffer.clear();
    } while (fic.read(buffer) != -1);
    fic.close();
    // NOTE: do not close 'foc'

    Files.delete(fileName);
}