Example usage for java.nio ByteBuffer putLong

List of usage examples for java.nio ByteBuffer putLong

Introduction

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

Prototype

public abstract ByteBuffer putLong(long value);

Source Link

Document

Writes the given long to the current position and increases the position by 8.

Usage

From source file:com.healthmarketscience.jackcess.impl.OleUtil.java

private static byte[] writePackageHeader(OleBlob.Builder oleBuilder, long contentLen) {

    byte[] prettyNameBytes = getZeroTermStrBytes(oleBuilder.getPrettyName());
    String className = oleBuilder.getClassName();
    String typeName = oleBuilder.getTypeName();
    if (className == null) {
        className = typeName;/* w  w  w .  ja v a 2 s.co m*/
    } else if (typeName == null) {
        typeName = className;
    }
    byte[] classNameBytes = getZeroTermStrBytes(className);
    byte[] typeNameBytes = getZeroTermStrBytes(typeName);

    int packageHeaderLen = 20 + prettyNameBytes.length + classNameBytes.length;

    int oleHeaderLen = 24 + typeNameBytes.length;

    byte[] headerBytes = new byte[packageHeaderLen + oleHeaderLen];

    ByteBuffer bb = PageChannel.wrap(headerBytes);

    // write outer package header
    bb.putShort((short) PACKAGE_SIGNATURE);
    bb.putShort((short) packageHeaderLen);
    bb.putInt(PACKAGE_OBJECT_TYPE);
    bb.putShort((short) prettyNameBytes.length);
    bb.putShort((short) classNameBytes.length);
    int prettyNameOff = bb.position() + 8;
    bb.putShort((short) prettyNameOff);
    bb.putShort((short) (prettyNameOff + prettyNameBytes.length));
    bb.putInt(-1);
    bb.put(prettyNameBytes);
    bb.put(classNameBytes);

    // put ole header
    bb.putInt(OLE_VERSION);
    bb.putInt(OLE_FORMAT);
    bb.putInt(typeNameBytes.length);
    bb.put(typeNameBytes);
    bb.putLong(0L);
    bb.putInt((int) contentLen);

    return headerBytes;
}

From source file:com.esri.geoevent.test.performance.ClockSync.java

@Override
public void run() {
    DatagramSocket socket = null;
    try {/*  www.  j  a  v a 2  s  .c  o  m*/
        byte[] incomingBuffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(incomingBuffer, incomingBuffer.length);

        ByteBuffer bb = ByteBuffer.allocate(8);
        DatagramPacket outgoingPacket = new DatagramPacket(bb.array(), 0, 8, null, port);
        socket = new DatagramSocket(port);
        socket.setSoTimeout(100);
        while (isRunning.get()) {
            try {
                socket.receive(packet);
                long now = System.currentTimeMillis();
                bb.putLong(now);
                outgoingPacket.setAddress(packet.getAddress());
                outgoingPacket.setPort(packet.getPort());
                socket.send(outgoingPacket);
                bb.clear();
                //System.out.println("Sent the time " + now);
            } catch (SocketTimeoutException ex) {
                // Do nothing if nothing was sent.
            }
        }
    } catch (BindException e) {
        // port is in use - increment and try again
        port++;
        this.run();
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(socket);
    }
}

From source file:com.ottogroup.bi.spqr.pipeline.statistics.MicroPipelineStatistics.java

/**
 * Convert this {@link MicroPipelineStatistics} instance into its byte array representation 
 * @return//w w  w.  j  a v a  2s .c om
 */
public byte[] toByteArray() {

    /////////////////////////////////////////////////////////
    // describes how the size of the result array is computed
    //      SIZE_OF_INT + 
    //      SIZE_OF_LONG + 
    //      SIZE_OF_LONG + 
    //      SIZE_OF_INT + 
    //      SIZE_OF_INT + 
    //      SIZE_OF_INT + 
    //      SIZE_OF_INT + 
    //      SIZE_OF_INT +
    //      SIZE_OF_INT +
    //      SIZE_OF_INT +
    //      procNodeId.length +
    //      pid.length +
    //      cid.length +
    //      (SIZE_OF_INT * 3)); <-- add extra int's 
    //           for storing the field sizes of processingNodeId, pipelineId and componentId
    //           which are required when extracting content from byte array      
    // >> 11x SIZE_OF_INT 
    // >>  3x SIZE_OF_LONG
    //
    // ByteBuffer buffer = ByteBuffer.allocate(11 * SIZE_OF_INT + 3 * SIZE_OF_LONG + procNodeId.length + pid.length + cid.length);

    // allocated buffer

    byte[] procNodeId = (this.processingNodeId != null ? this.processingNodeId.getBytes() : new byte[0]);
    byte[] pid = (this.pipelineId != null ? this.pipelineId.getBytes() : new byte[0]);
    byte[] cid = (this.componentId != null ? this.componentId.getBytes() : new byte[0]);

    ByteBuffer buffer = ByteBuffer
            .allocate(11 * SIZE_OF_INT + 2 * SIZE_OF_LONG + procNodeId.length + pid.length + cid.length);

    buffer.putInt(this.numOfMessages);
    buffer.putLong(this.startTime);
    buffer.putLong(this.endTime);
    buffer.putInt(this.minDuration);
    buffer.putInt(this.maxDuration);
    buffer.putInt(this.avgDuration);
    buffer.putInt(this.minSize);
    buffer.putInt(this.maxSize);
    buffer.putInt(this.avgSize);
    buffer.putInt(this.errors);
    buffer.putInt(procNodeId.length);
    buffer.put(procNodeId);
    buffer.putInt(pid.length);
    buffer.put(pid);
    buffer.putInt(cid.length);
    buffer.put(cid);

    return buffer.array();
}

From source file:au.org.ala.delta.io.BinFile.java

public void writeLong(long value) {
    ByteBuffer b = ByteBuffer.allocate(8);
    b.order(ByteOrder.LITTLE_ENDIAN);
    b.putLong(value);
    writeBytes(b);/*from   www.j a  v  a 2  s. co  m*/
}

From source file:com.yobidrive.diskmap.needles.Needle.java

public void putNeedleInBuffer(ByteBuffer result) throws Exception {
    int startPosition = result.position();
    result.limit(result.capacity());//from  ww  w .  j a v a  2 s. c  o m
    result.putInt(MAGICSTART);
    result.putLong(needleNumber);
    result.put(flags);
    result.putInt(keyBytes.length);
    result.put(keyBytes);
    result.putInt(version == null ? 0 : version.toBytes().length);
    if (version != null)
        result.put(version.toBytes());
    result.putInt(previousNeedle == null ? -1 : previousNeedle.getNeedleFileNumber()); // Chaining
    result.putLong(previousNeedle == null ? -1L : previousNeedle.getNeedleOffset()); // Chaining
    result.putInt(originalFileNumber); // Original needle location (for cleaning)
    result.putInt(originalSize); // Original needle size (for cleaning)
    result.putInt(data == null ? 0 : data.length);
    if (data != null)
        result.put(data);
    result.putInt(MAGICEND);
    result.put(hashMD5());
    while (((result.position() - startPosition) % 256) > 0) {
        result.put(PADDING);
    }
    result.flip();
}

From source file:com.urbancode.terraform.main.Main.java

/**
 * Initializes Terraform so it can execute the given commands.
 * Here is the order of operations:/*from   ww w .jav  a  2s .  c  o m*/
 * Parses the credentials file and verifies the given credentials.
 * Generates a random string for this environment, which is appended to the output xml file.
 * Parses the xml file.
 * Runs the specified command (create, destroy, etc).
 * @throws XmlParsingException
 * @throws IOException
 * @throws CredentialsException
 * @throws CreationException
 * @throws DestructionException
 * @throws RestorationException
 */
public void execute() throws XmlParsingException, IOException, CredentialsException, CreationException,
        DestructionException, RestorationException {
    TerraformContext context = null;
    try {
        // parse xml and set context
        context = parseContext(inputXmlFile);

        Credentials credentials = parseCredentials(credsFile);

        context.setCredentials(credentials);
        if (AllowedCommands.CREATE.getCommandName().equalsIgnoreCase(command)) {
            // create new file if creating a new environment
            UUID uuid = UUID.randomUUID();
            //convert uuid to base 62 (allowed chars: 0-9 a-z A-Z)
            ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
            bb.putLong(uuid.getMostSignificantBits());
            bb.putLong(uuid.getLeastSignificantBits());
            String suffix = Base64.encodeBase64URLSafeString(bb.array());
            suffix = suffix.replaceAll("-", "Y");
            suffix = suffix.replaceAll("_", "Z");
            suffix = suffix.substring(0, 4);
            if (context.getEnvironment() != null) {
                context.getEnvironment().addSuffixToEnvName(suffix);
                log.debug("UUID for env " + context.getEnvironment().getName() + " is " + suffix);
            } else {
                throw new NullPointerException("No environment on context!");
            }

            String name = context.getEnvironment().getName();
            log.debug("Output filename = " + name);
            outputXmlFile = new File("env-" + name + ".xml");

            log.debug("Calling create() on context");
            context.create();
        } else if (AllowedCommands.DESTROY.getCommandName().equalsIgnoreCase(command)) {
            String suffix = parseSuffix(context.getEnvironment().getName());
            context.getEnvironment().setSuffix(suffix);
            log.debug("found suffix " + suffix);
            // write out instance failure regardless of success or failure
            outputXmlFile = inputXmlFile;
            log.debug("Calling destroy() on context");
            context.destroy();
        } else if (AllowedCommands.SUSPEND.getCommandName().equalsIgnoreCase(command)) {
            outputXmlFile = inputXmlFile;
            log.debug("Calling restore() on context");
            log.info("Attempting to suspend power on all instances/VMs in the environment.");
            context.restore();
            if (context instanceof ContextVmware) {
                SuspendCommand newCommand = new SuspendCommand((ContextVmware) context);
                newCommand.execute();
            } else if (context instanceof ContextAWS) {
                com.urbancode.terraform.commands.aws.SuspendCommand newCommand = new com.urbancode.terraform.commands.aws.SuspendCommand(
                        (ContextAWS) context);
                newCommand.execute();
            } else {
                log.warn("Could not resolve context to call command \"" + command + "\"");
            }
        } else if (AllowedCommands.RESUME.getCommandName().equalsIgnoreCase(command)) {
            outputXmlFile = inputXmlFile;
            log.debug("Calling restore() on context");
            context.restore();
            log.info("Attempting to power on all instances/VMs in the environment.");
            if (context instanceof ContextVmware) {
                ResumeCommand newCommand = new ResumeCommand((ContextVmware) context);
                newCommand.execute();
            } else if (context instanceof ContextAWS) {
                com.urbancode.terraform.commands.aws.ResumeCommand newCommand = new com.urbancode.terraform.commands.aws.ResumeCommand(
                        (ContextAWS) context);
                newCommand.execute();
            }

            else {
                log.warn("Could not resolve context to call command \"" + command + "\"");
            }
        } else if (AllowedCommands.TAKE_SNAPSHOT.getCommandName().equalsIgnoreCase(command)) {
            outputXmlFile = inputXmlFile;
            log.debug("Calling restore() on context");
            context.restore();
            log.info("Attempting to take snapshots of all instances/VMs in the environment.");
            if (context instanceof ContextVmware) {
                TakeSnapshotCommand newCommand = new TakeSnapshotCommand((ContextVmware) context);
                newCommand.execute();
            } else if (context instanceof ContextAWS) {
                log.warn("Taking snapshots is not currently supported with Terraform and AWS.");
            }

            else {
                log.warn("Could not resolve context to call command \"" + command + "\"");
            }
        }
    } catch (ParserConfigurationException e1) {
        throw new XmlParsingException("ParserConfigurationException: " + e1.getMessage(), e1);
    } catch (SAXException e2) {
        throw new XmlParsingException("SAXException: " + e2.getMessage(), e2);
    } finally {
        if (context != null && context.doWriteContext() && outputXmlFile != null) {
            log.debug("Writing context out to " + outputXmlFile);
            writeEnvToXml(outputXmlFile, context);
        }
    }
}

From source file:net.dv8tion.jda.audio.AudioWebSocket.java

private void setupUdpKeepAliveThread() {
    udpKeepAliveThread = new Thread("AudioWebSocket UDP-KeepAlive Guild: " + guild.getId()) {
        @Override//from ww w .  jav a2  s.  c om
        public void run() {
            while (socket.isOpen() && !udpSocket.isClosed() && !this.isInterrupted()) {
                long seq = 0;
                try {
                    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES + 1);
                    buffer.put((byte) 0xC9);
                    buffer.putLong(seq);
                    DatagramPacket keepAlivePacket = new DatagramPacket(buffer.array(), buffer.array().length,
                            address);
                    udpSocket.send(keepAlivePacket);

                    Thread.sleep(5000); //Wait 5 seconds to send next keepAlivePacket.
                } catch (NoRouteToHostException e) {
                    LOG.warn("Closing AudioConnection due to inability to ping audio packets.");
                    LOG.warn("Cannot send audio packet because JDA navigate the route to Discord.\n"
                            + "Are you sure you have internet connection? It is likely that you've lost connection.");
                    AudioWebSocket.this.close(true, -1);
                    break;
                } catch (IOException e) {
                    LOG.log(e);
                } catch (InterruptedException e) {
                    //We were asked to close.
                    //                        e.printStackTrace();
                }
            }
        }
    };
    udpKeepAliveThread.setPriority(Thread.NORM_PRIORITY + 1);
    udpKeepAliveThread.setDaemon(true);
    udpKeepAliveThread.start();
}

From source file:xbird.util.nio.RemoteMemoryMappedFile.java

private void sendRequest(final ByteChannel channel, final long startOffset, final long endOffset,
        final int aryLength) throws IOException {
    byte[] bFilePath = StringUtils.getBytes(_filePath);
    int buflen = bFilePath.length + 29;//+ 4 + 4 + 4 + 8 + 8 + 1;
    if (buflen > RemotePagingService.MAX_COMMAND_BUFLEN) {
        throw new IllegalStateException("command size exceeds limit in MAX_COMMAND_BUFLEN("
                + RemotePagingService.MAX_COMMAND_BUFLEN + "): " + buflen + " bytes");
    }/*w  w w  .  j  a  va  2  s .c  o  m*/
    ByteBuffer oprBuf = ByteBuffer.allocate(buflen);
    oprBuf.putInt(buflen - 4);
    oprBuf.putInt(RemotePagingService.COMMAND_READ);
    oprBuf.putInt(bFilePath.length); // #1
    oprBuf.put(bFilePath); // #2
    oprBuf.putLong(startOffset); // #3
    oprBuf.putLong(endOffset); // #4
    oprBuf.put((byte) (_bigEndian ? 1 : 0)); // # 5 is big endian?
    oprBuf.flip();
    NIOUtils.writeFully(channel, oprBuf);
}

From source file:voldemort.store.cachestore.impl.ChannelStore.java

public void writeIndexBlock(CacheBlock<byte[]> block, long keyOffset2Len, FileChannel channel)
        throws IOException {
    long pos = OFFSET + (long) block.getRecordNo() * RECORD_SIZE;
    checkFileSize(pos, RECORD_SIZE);//from   w  w  w.j  a v  a2  s  .  co  m
    ByteBuffer buf = ByteBuffer.allocate(RECORD_SIZE);
    buf.put(block.getStatus());
    buf.putLong(keyOffset2Len);
    buf.putLong(block.getDataOffset2Len());
    buf.putLong(block.getBlock2Version());
    buf.putShort(block.getNode());
    buf.flip();
    channel.write(buf, pos);
}

From source file:com.l2jfree.loginserver.L2LoginIdentifier.java

private synchronized void load() {
    if (isLoaded())
        return;//from   w  w  w.j  a  v a 2s . c o m

    File f = new File(System.getProperty("user.home", null), FILENAME);
    ByteBuffer bb = ByteBuffer.allocateDirect(8);

    if (!f.exists() || f.length() != 8) {
        _uid = getRandomUID();
        _loaded = true;
        _log.info("A new UID has been generated for this login server.");

        FileOutputStream fos = null;
        try {
            f.createNewFile();
            fos = new FileOutputStream(f);
            FileChannel fc = fos.getChannel();
            bb.putLong(getUID());
            bb.flip();
            fc.write(bb);
            fos.flush();
        } catch (IOException e) {
            _log.warn("Could not store login server's UID!", e);
        } finally {
            IOUtils.closeQuietly(fos);
            f.setReadOnly();
        }
    } else {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(f);
            FileChannel fc = fis.getChannel();
            fc.read(bb);
        } catch (IOException e) {
            _log.warn("Could not read stored login server's UID!", e);
        } finally {
            IOUtils.closeQuietly(fis);
        }

        if (bb.position() > 0) {
            bb.flip();
            _uid = bb.getLong();
        } else
            _uid = getRandomUID();
        _loaded = true;
    }
}