Example usage for java.io DataOutputStream writeLong

List of usage examples for java.io DataOutputStream writeLong

Introduction

In this page you can find the example usage for java.io DataOutputStream writeLong.

Prototype

public final void writeLong(long v) throws IOException 

Source Link

Document

Writes a long to the underlying output stream as eight bytes, high byte first.

Usage

From source file:com.joey.software.MoorFLSI.RepeatImageTextReader.java

public void saveData(File f) throws IOException {
    DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f)));

    out.writeInt(imageData.size());//www.j av  a2 s .c  om
    out.writeInt(wide);
    out.writeInt(high);

    for (int i = 0; i < imageData.size(); i++) {
        System.out.println(i);
        out.writeLong(imageTime.get(i).getTime());
        for (int x = 0; x < wide; x++) {
            for (int y = 0; y < high; y++) {
                out.writeShort(imageData.get(i)[x][y]);
            }
        }
    }

    out.close();

}

From source file:com.jivesoftware.os.amza.service.AmzaService.java

private boolean streamBootstrap(long leadershipToken, DataOutputStream dos, MutableLong bytes,
        VersionedPartitionName versionedPartitionName, int stripe, LivelyEndState livelyEndState)
        throws Exception {

    dos.writeLong(leadershipToken);
    dos.writeLong(-1);/*  www  .  ja  v a 2 s  .c  o m*/
    dos.writeByte(0); // not online
    dos.writeByte(0); // last entry marker
    dos.writeByte(0); // last entry marker
    dos.writeByte(0); // streamedToEnd marker
    bytes.add(4);
    if (versionedPartitionName == null || livelyEndState == null) {
        // someone thinks we're a member for this partition
        return true;
    } else {
        // BOOTSTRAP'S BOOTSTRAPS!
        partitionCreator.get(versionedPartitionName, stripe);
        return false;
    }
}

From source file:net.sf.gazpachoquest.rest.auth.TokenStore.java

/**
 * Stores the current set of tokens to the token file
 *///from w ww  .  j a  v  a  2 s  . c o  m
private void saveTokens() {
    FileOutputStream fout = null;
    DataOutputStream keyOutputStream = null;
    try {
        File parent = tokenFile.getAbsoluteFile().getParentFile();
        log.info("Token File {} parent {} ", tokenFile, parent);
        if (!parent.exists()) {
            parent.mkdirs();
        }
        fout = new FileOutputStream(tmpTokenFile);
        keyOutputStream = new DataOutputStream(fout);
        keyOutputStream.writeInt(currentToken);
        keyOutputStream.writeLong(nextUpdate);
        for (int i = 0; i < currentTokens.length; i++) {
            if (currentTokens[i] == null) {
                keyOutputStream.writeInt(0);
            } else {
                keyOutputStream.writeInt(1);
                byte[] b = currentTokens[i].getEncoded();
                keyOutputStream.writeInt(b.length);
                keyOutputStream.write(b);
            }
        }
        keyOutputStream.close();
        tmpTokenFile.renameTo(tokenFile);
    } catch (IOException e) {
        log.error("Failed to save cookie keys " + e.getMessage());
    } finally {
        try {
            keyOutputStream.close();
        } catch (Exception e) {
        }
        try {
            fout.close();
        } catch (Exception e) {
        }

    }
}

From source file:com.p2p.misc.DeviceUtility.java

private void WriteData(OutputStream out, int cid, int lac) throws IOException {
    DataOutputStream dataOutputStream = new DataOutputStream(out);
    dataOutputStream.writeShort(21);//from  w  w w  .j av  a2  s .co  m
    dataOutputStream.writeLong(0);
    dataOutputStream.writeUTF("en");
    dataOutputStream.writeUTF("Android");
    dataOutputStream.writeUTF("1.0");
    dataOutputStream.writeUTF("Mobile");
    dataOutputStream.writeByte(27);
    dataOutputStream.writeInt(0);
    dataOutputStream.writeInt(0);
    dataOutputStream.writeInt(3);
    dataOutputStream.writeUTF("");

    dataOutputStream.writeInt(cid);
    dataOutputStream.writeInt(lac);

    dataOutputStream.writeInt(0);
    dataOutputStream.writeInt(0);
    dataOutputStream.writeInt(0);
    dataOutputStream.writeInt(0);
    dataOutputStream.flush();
}

From source file:com.trigger_context.Main_Service.java

private void sendFile(DataOutputStream out, String Path) {
    Log.i(Main_Service.LOG_TAG, "SendFile--Start");
    File infile = new File(Path);
    String FileName = null;/*from   w w w.j a  v  a 2  s  .  c o m*/
    try {

        FileName = Path.substring(Path.lastIndexOf("/") + 1);
        out.writeUTF(FileName);
        out.writeLong(infile.length());
    } catch (IOException e) {
        Log.i(Main_Service.LOG_TAG, "SendFile--error sending filename length");
    }

    byte[] mybytearray = new byte[(int) infile.length()];

    FileInputStream fis = null;
    ;
    try {
        fis = new FileInputStream(infile);
    } catch (FileNotFoundException e1) {
        Log.i(Main_Service.LOG_TAG, "sendFile--Error file not found");
    }
    BufferedInputStream bis = new BufferedInputStream(fis);

    DataInputStream dis = new DataInputStream(bis);
    try {
        dis.readFully(mybytearray, 0, mybytearray.length);
    } catch (IOException e1) {
        Log.i(Main_Service.LOG_TAG, "sendFile--Error while reading bytes from file");

    }

    try {
        out.write(mybytearray, 0, mybytearray.length);
    } catch (IOException e1) {
        Log.i(Main_Service.LOG_TAG, "sendFile--error while sending");
    }

    try {
        dis.close();
        bis.close();
        fis.close();
    } catch (IOException e) {

        Log.i(Main_Service.LOG_TAG, "sendFile--error in closing streams");
    }

}

From source file:org.apache.jxtadoop.hdfs.server.datanode.BlockSender.java

/**
 * sendBlock() is used to read block and its metadata and stream the data to
 * either a client or to another datanode. 
 * /*  w w w  . ja v  a 2  s.  co  m*/
 * @param out  stream to which the block is written to
 * @param baseStream optional. if non-null, <code>out</code> is assumed to 
 *        be a wrapper over this stream. This enables optimizations for
 *        sending the data, e.g. 
 *        {@link SocketOutputStream#transferToFully(FileChannel, 
 *        long, int)}.
 * @param throttler for sending data.
 * @return total bytes reads, including crc.
 */
long sendBlock(DataOutputStream out, OutputStream baseStream, BlockTransferThrottler throttler)
        throws IOException {
    if (out == null) {
        throw new IOException("out stream is null");
    }
    this.throttler = throttler;

    long initialOffset = offset;
    long totalRead = 0;
    OutputStream streamForSendChunks = out;

    try {
        try {
            checksum.writeHeader(out);
            if (chunkOffsetOK) {
                out.writeLong(offset);
            }
            out.flush();
        } catch (IOException e) { //socket error
            throw ioeToSocketException(e);
        }

        int maxChunksPerPacket;
        int pktSize = DataNode.PKT_HEADER_LEN + SIZE_OF_INTEGER;

        if (transferToAllowed && !verifyChecksum && baseStream instanceof SocketOutputStream
                && blockIn instanceof FileInputStream) {

            FileChannel fileChannel = ((FileInputStream) blockIn).getChannel();

            // blockInPosition also indicates sendChunks() uses transferTo.
            blockInPosition = fileChannel.position();
            streamForSendChunks = baseStream;

            // assure a mininum buffer size.
            maxChunksPerPacket = (Math.max(BUFFER_SIZE, MIN_BUFFER_WITH_TRANSFERTO) + bytesPerChecksum - 1)
                    / bytesPerChecksum;

            // allocate smaller buffer while using transferTo(). 
            pktSize += checksumSize * maxChunksPerPacket;
        } else {
            maxChunksPerPacket = Math.max(1, (BUFFER_SIZE + bytesPerChecksum - 1) / bytesPerChecksum);
            pktSize += (bytesPerChecksum + checksumSize) * maxChunksPerPacket;
        }

        ByteBuffer pktBuf = ByteBuffer.allocate(pktSize);

        while (endOffset > offset) {
            long len = sendChunks(pktBuf, maxChunksPerPacket, streamForSendChunks);
            offset += len;
            totalRead += len + ((len + bytesPerChecksum - 1) / bytesPerChecksum * checksumSize);
            seqno++;
        }
        try {
            out.writeInt(0); // mark the end of block        
            out.flush();
        } catch (IOException e) { //socket error
            throw ioeToSocketException(e);
        }
    } finally {
        if (clientTraceFmt != null) {
            ClientTraceLog.info(String.format(clientTraceFmt, totalRead));
        }
        close();
    }

    blockReadFully = (initialOffset == 0 && offset >= blockLength);

    return totalRead;
}

From source file:com.sky.drovik.player.media.DiskCache.java

private void writeIndex() {
    File tempFile = null;//from   w  ww. ja va 2  s  .c  om
    final String tempFilePath = mCacheDirectoryPath;
    final String indexFilePath = getIndexFilePath();
    try {
        tempFile = File.createTempFile("DiskCache", null, new File(tempFilePath));
    } catch (Exception e) {
        Log.e(TAG, "Unable to create or tempFile " + tempFilePath);
        return;
    }
    try {
        final FileOutputStream fileOutput = new FileOutputStream(tempFile);
        final BufferedOutputStream bufferedOutput = new BufferedOutputStream(fileOutput, 1024);
        final DataOutputStream dataOutput = new DataOutputStream(bufferedOutput);

        // Write the index header.
        final int numRecords = mIndexMap.size();
        dataOutput.writeInt(INDEX_HEADER_MAGIC);
        dataOutput.writeInt(INDEX_HEADER_VERSION);
        dataOutput.writeShort(mTailChunk);
        dataOutput.writeInt(numRecords);

        // Write the records.
        for (int i = 0; i < numRecords; ++i) {
            final long key = mIndexMap.keyAt(i);
            final Record record = mIndexMap.valueAt(i);
            dataOutput.writeLong(key);
            dataOutput.writeShort(record.chunk);
            dataOutput.writeInt(record.offset);
            dataOutput.writeInt(record.size);
            dataOutput.writeInt(record.sizeOnDisk);
            dataOutput.writeLong(record.timestamp);
        }

        // Close the file.
        dataOutput.close();

        // Log.d(TAG, "Wrote index with " + numRecords + " records.");

        // Atomically overwrite the old index file.
        tempFile.renameTo(new File(indexFilePath));
    } catch (Exception e) {
        // Was unable to perform the operation, we delete the temp file
        Log.e(TAG, "Unable to write the index file " + indexFilePath);
        tempFile.delete();
    }
}

From source file:org.apache.hadoop.hdfs.server.datanode.RaidBlockSender.java

/**
 * sendBlock() is used to read block and its metadata and stream the data to
 * either a client or to another datanode. 
 * //from  w ww  . j  ava  2  s  . co  m
 * @param out  stream to which the block is written to
 * @param baseStream optional. if non-null, <code>out</code> is assumed to 
 *        be a wrapper over this stream. This enables optimizations for
 *        sending the data, e.g. 
 *        {@link SocketOutputStream#transferToFully(FileChannel, 
 *        long, int)}.
 * @return total bytes reads, including crc.
 */
public long sendBlock(DataOutputStream out, OutputStream baseStream) throws IOException {
    if (out == null) {
        throw new IOException("out stream is null");
    }

    long initialOffset = offset;
    long totalRead = 0;
    OutputStream streamForSendChunks = out;

    final long startTime = ClientTraceLog.isInfoEnabled() ? System.nanoTime() : 0;
    try {
        try {
            checksum.writeHeader(out);
            if (chunkOffsetOK) {
                out.writeLong(offset);
            }
            out.flush();
        } catch (IOException e) { //socket error
            throw ioeToSocketException(e);
        }

        int maxChunksPerPacket;
        int pktSize = PacketHeader.PKT_HEADER_LEN;

        if (transferToAllowed && !verifyChecksum && baseStream instanceof SocketOutputStream
                && blockIn instanceof FileInputStream) {

            FileChannel fileChannel = ((FileInputStream) blockIn).getChannel();

            // blockInPosition also indicates sendChunks() uses transferTo.
            blockInPosition = fileChannel.position();
            streamForSendChunks = baseStream;

            // assure a mininum buffer size.
            maxChunksPerPacket = (Math.max(BUFFER_SIZE, MIN_BUFFER_WITH_TRANSFERTO) + bytesPerChecksum - 1)
                    / bytesPerChecksum;

            // allocate smaller buffer while using transferTo(). 
            pktSize += checksumSize * maxChunksPerPacket;
        } else {
            maxChunksPerPacket = Math.max(1, (BUFFER_SIZE + bytesPerChecksum - 1) / bytesPerChecksum);
            pktSize += (bytesPerChecksum + checksumSize) * maxChunksPerPacket;
        }

        ByteBuffer pktBuf = ByteBuffer.allocate(pktSize);

        while (endOffset > offset) {
            long len = sendChunks(pktBuf, maxChunksPerPacket, streamForSendChunks);
            offset += len;
            totalRead += len + ((len + bytesPerChecksum - 1) / bytesPerChecksum * checksumSize);
            seqno++;
        }
        try {
            // send an empty packet to mark the end of the block
            sendChunks(pktBuf, maxChunksPerPacket, streamForSendChunks);
            out.flush();
        } catch (IOException e) { //socket error
            throw ioeToSocketException(e);
        }
    } finally {
        if (clientTraceFmt != null) {
            final long endTime = System.nanoTime();
            ClientTraceLog.info(String.format(clientTraceFmt, totalRead, initialOffset, endTime - startTime));
        }
        close();
    }

    blockReadFully = initialOffset == 0 && offset >= replicaVisibleLength;

    return totalRead;
}

From source file:com.jivesoftware.os.amza.service.AmzaService.java

private boolean streamOnline(RingMember ringMember, VersionedPartitionName versionedPartitionName,
        long highestTransactionId, long leadershipToken, long limit, DataOutputStream dos, MutableLong bytes,
        HighwaterStorage highwaterStorage, PartitionStripe.RowStreamer streamer) throws Exception {

    ackWaters.set(ringMember, versionedPartitionName, highestTransactionId, leadershipToken);
    dos.writeLong(leadershipToken);
    dos.writeLong(versionedPartitionName.getPartitionVersion());
    dos.writeByte(1); // fully online
    bytes.increment();/*from  w  ww  . ja  v a 2 s.  com*/
    RingTopology ring = ringStoreReader.getRing(versionedPartitionName.getPartitionName().getRingName(), -1);
    for (int i = 0; i < ring.entries.size(); i++) {
        if (ring.rootMemberIndex != i) {
            RingMemberAndHost entry = ring.entries.get(i);
            long highwatermark = highwaterStorage.get(entry.ringMember, versionedPartitionName);
            byte[] ringMemberBytes = entry.ringMember.toBytes();
            dos.writeByte(1);
            dos.writeInt(ringMemberBytes.length);
            dos.write(ringMemberBytes);
            dos.writeLong(highwatermark);
            bytes.add(1 + 4 + ringMemberBytes.length + 8);
        }
    }

    dos.writeByte(0); // last entry marker
    bytes.increment();

    long[] limited = new long[1];
    long[] lastRowTxId = { -1 };
    boolean streamedToEnd = streamer.stream((rowFP, rowTxId, rowType, row) -> {
        if (limited[0] >= limit && lastRowTxId[0] < rowTxId) {
            return false;
        }
        lastRowTxId[0] = rowTxId;
        dos.writeByte(1);
        dos.writeLong(rowTxId);
        dos.writeByte(rowType.toByte());
        dos.writeInt(row.length);
        dos.write(row);
        bytes.add(1 + 8 + 1 + 4 + row.length);
        limited[0]++;
        return true;
    });

    dos.writeByte(0); // last entry marker
    bytes.increment();
    dos.writeByte(streamedToEnd ? 1 : 0); // streamedToEnd marker
    bytes.increment();
    return false;
}

From source file:org.sakaiproject.nakamura.auth.trusted.TokenStore.java

/**
 * Save all the secureKeys to file/* ww w .jav a  2s .c o  m*/
 */
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE", justification = "Could be injected from annother bundle")
private void saveLocalSecretKeys() {
    FileOutputStream fout = null;
    DataOutputStream keyOutputStream = null;
    try {
        File parent = tokenFile.getAbsoluteFile().getParentFile();
        LOG.debug("Saving Local Secret Keys to {} ", tokenFile.getAbsoluteFile());
        if (!parent.exists()) {
            parent.mkdirs();
        }
        fout = new FileOutputStream(tmpTokenFile);
        keyOutputStream = new DataOutputStream(fout);
        keyOutputStream.writeInt(secretKeyId);
        keyOutputStream.writeLong(nextUpdate);
        for (int i = 0; i < secretKeyRingBuffer.length; i++) {
            if (secretKeyRingBuffer[i] == null) {
                keyOutputStream.writeInt(0);
            } else {
                keyOutputStream.writeInt(1);
                keyOutputStream.writeLong(secretKeyRingBuffer[i].getExpires());
                keyOutputStream.writeUTF(secretKeyRingBuffer[i].getServerId());
                byte[] b = secretKeyRingBuffer[i].getSecretKey().getEncoded();
                keyOutputStream.writeInt(b.length);
                keyOutputStream.write(b);
            }
        }
        keyOutputStream.close();
        if (!tmpTokenFile.renameTo(tokenFile)) {
            LOG.error(
                    "Failed to save cookie keys, rename of tokenFile failed. Reload of secure token keys will fail while this is happening. ");
        }
    } catch (IOException e) {
        LOG.error("Failed to save cookie keys " + e.getMessage());
    } finally {
        try {
            keyOutputStream.close();
        } catch (Exception e) {
        }
        try {
            fout.close();
        } catch (Exception e) {
        }

    }
}