Example usage for java.io DataOutputStream writeInt

List of usage examples for java.io DataOutputStream writeInt

Introduction

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

Prototype

public final void writeInt(int v) throws IOException 

Source Link

Document

Writes an int to the underlying output stream as four bytes, high byte first.

Usage

From source file:com.adito.notification.Notifier.java

void write(Message message) throws IOException {
    if (log.isDebugEnabled())
        log.debug("Writing message " + message.getId() + " '" + message.getSubject() + "' to disk");
    FileOutputStream fout = new FileOutputStream(
            new File(queueDirectory, String.valueOf(message.getId()) + ".msg"));
    try {/*  w w  w.  ja  v a 2s  .  c  o m*/
        DataOutputStream dout = new DataOutputStream(fout);
        dout.writeLong(message.getId());
        dout.writeUTF(message.getSinkName());
        dout.writeBoolean(message.isUrgent());
        dout.writeUTF(message.getSubject());
        for (Iterator i = message.getRecipients().iterator(); i.hasNext();) {
            Recipient r = (Recipient) i.next();
            dout.writeInt(r.getRecipientType());
            dout.writeUTF(r.getRecipientAlias() == null ? "" : r.getRecipientAlias());
            dout.writeUTF(r.getRealmName() == null ? "" : r.getRealmName());
        }
        dout.writeInt(0);
        for (Iterator i = message.getParameterNames(); i.hasNext();) {
            String key = (String) i.next();
            dout.writeInt(1);
            dout.writeUTF(key);
            dout.writeUTF(message.getParameter(key));
        }
        dout.writeInt(0);
        dout.writeUTF(message.getContent());
        dout.writeUTF(message.getLastMessage());
    } finally {
        fout.close();
    }
}

From source file:com.panet.imeta.trans.steps.blockingstep.BlockingStep.java

private boolean addBuffer(RowMetaInterface rowMeta, Object[] r) {
    if (r != null) {
        data.buffer.add(r); // Save row
    }/*  ww  w  .j  a v a  2s . c  o m*/

    // Time to write to disk: buffer in core is full!
    if (data.buffer.size() == meta.getCacheSize() // Buffer is full: dump to disk 
            || (data.files.size() > 0 && r == null && data.buffer.size() > 0) // No more records: join from disk 
    ) {
        // Then write them to disk...
        DataOutputStream dos;
        GZIPOutputStream gzos;
        int p;

        try {
            FileObject fileObject = KettleVFS.createTempFile(meta.getPrefix(), ".tmp",
                    environmentSubstitute(meta.getDirectory()));

            data.files.add(fileObject); // Remember the files!
            OutputStream outputStream = KettleVFS.getOutputStream(fileObject, false);
            if (meta.getCompress()) {
                gzos = new GZIPOutputStream(new BufferedOutputStream(outputStream));
                dos = new DataOutputStream(gzos);
            } else {
                dos = new DataOutputStream(outputStream);
                gzos = null;
            }

            // How many records do we have?
            dos.writeInt(data.buffer.size());

            for (p = 0; p < data.buffer.size(); p++) {
                // Just write the data, nothing else
                rowMeta.writeData(dos, (Object[]) data.buffer.get(p));
            }
            // Close temp-file
            dos.close(); // close data stream
            if (gzos != null) {
                gzos.close(); // close gzip stream
            }
            outputStream.close(); // close file stream
        } catch (Exception e) {
            logError("Error processing tmp-file: " + e.toString());
            return false;
        }

        data.buffer.clear();
    }

    return true;
}

From source file:bobs.is.compress.sevenzip.SevenZOutputFile.java

/**
 * Finishes the addition of entries to this archive, without closing it.
 * /* ww  w  .  j  ava  2  s. c o m*/
 * @throws IOException if archive is already closed.
 */
public void finish() throws IOException {
    if (finished) {
        throw new IOException("This archive has already been finished");
    }
    finished = true;

    final long headerPosition = file.getFilePointer();

    final ByteArrayOutputStream headerBaos = new ByteArrayOutputStream();
    final DataOutputStream header = new DataOutputStream(headerBaos);

    writeHeader(header);
    header.flush();
    final byte[] headerBytes = headerBaos.toByteArray();
    file.write(headerBytes);

    final CRC32 crc32 = new CRC32();

    // signature header
    file.seek(0);
    file.write(SevenZFile.sevenZSignature);
    // version
    file.write(0);
    file.write(2);

    // start header
    final ByteArrayOutputStream startHeaderBaos = new ByteArrayOutputStream();
    final DataOutputStream startHeaderStream = new DataOutputStream(startHeaderBaos);
    startHeaderStream.writeLong(Long.reverseBytes(headerPosition - SevenZFile.SIGNATURE_HEADER_SIZE));
    startHeaderStream.writeLong(Long.reverseBytes(0xffffFFFFL & headerBytes.length));
    crc32.reset();
    crc32.update(headerBytes);
    startHeaderStream.writeInt(Integer.reverseBytes((int) crc32.getValue()));
    startHeaderStream.flush();
    final byte[] startHeaderBytes = startHeaderBaos.toByteArray();
    crc32.reset();
    crc32.update(startHeaderBytes);
    file.writeInt(Integer.reverseBytes((int) crc32.getValue()));
    file.write(startHeaderBytes);
}

From source file:org.pentaho.di.trans.steps.blockingstep.BlockingStep.java

private boolean addBuffer(RowMetaInterface rowMeta, Object[] r) {
    if (r != null) {
        data.buffer.add(r); // Save row
    }/*from ww  w  .  ja va  2  s.  c  o m*/

    // Time to write to disk: buffer in core is full!
    if (data.buffer.size() == meta.getCacheSize() // Buffer is full: dump to disk
            || (data.files.size() > 0 && r == null && data.buffer.size() > 0) // No more records: join from disk
    ) {
        // Then write them to disk...
        DataOutputStream dos;
        GZIPOutputStream gzos;
        int p;

        try {
            FileObject fileObject = KettleVFS.createTempFile(meta.getPrefix(), ".tmp",
                    environmentSubstitute(meta.getDirectory()), getTransMeta());

            data.files.add(fileObject); // Remember the files!
            OutputStream outputStream = KettleVFS.getOutputStream(fileObject, false);
            if (meta.getCompress()) {
                gzos = new GZIPOutputStream(new BufferedOutputStream(outputStream));
                dos = new DataOutputStream(gzos);
            } else {
                dos = new DataOutputStream(outputStream);
                gzos = null;
            }

            // How many records do we have?
            dos.writeInt(data.buffer.size());

            for (p = 0; p < data.buffer.size(); p++) {
                // Just write the data, nothing else
                rowMeta.writeData(dos, data.buffer.get(p));
            }
            // Close temp-file
            dos.close(); // close data stream
            if (gzos != null) {
                gzos.close(); // close gzip stream
            }
            outputStream.close(); // close file stream
        } catch (Exception e) {
            logError("Error processing tmp-file: " + e.toString());
            return false;
        }

        data.buffer.clear();
    }

    return true;
}

From source file:org.mhisoft.wallet.service.AttachmentService.java

/**
 * Create a new attachment store.//  w w w  .  ja v  a 2  s . c o  m
 *
 * @param filename
 * @param model
 * @param encryptor
 */
public void newAttachmentStore(final String filename, final WalletModel model, final PBEEncryptor encryptor) {

    FileAccessTable t = new FileAccessTable();
    for (WalletItem item : model.getItemsFlatList()) {
        if (item.getAttachmentEntry() != null && item.getAttachmentEntry().getFileName() != null)
            t.addEntry(item.getAttachmentEntry());
    }

    DataOutputStream dataOut = null;
    if (t.getSize() > 0) {
        //new store
        //write it out
        try {
            dataOut = new DataOutputStream(new FileOutputStream(new File(filename)));

            //write the total number of entries first
            /*#0*/
            dataOut.writeInt(t.getEntries().size());
            //itemStartPos = 4;

            writeFileEntries(model, false, null, 4, dataOut, t, model.getEncryptorForRead(), encryptor);

            dataOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
            DialogUtils.getInstance().error("Error writing attachment entries.", e.getMessage());
        } finally {
            if (dataOut != null)
                try {
                    dataOut.close();
                } catch (IOException e) {
                    //e.printStackTrace();
                }
        }

        //now clear the access flag on the item
        for (WalletItem item : model.getItemsFlatList()) {
            if (item.getAttachmentEntry() != null && item.getAttachmentEntry().getFile() != null //
                    && item.getAttachmentEntry().getAccessFlag() != null) {
                item.getAttachmentEntry().setAccessFlag(FileAccessFlag.None);
            }
        }

    }
}

From source file:be.ibridge.kettle.trans.step.sortrows.SortRows.java

private boolean addBuffer(Row r) {
    if (r != null) {
        data.buffer.add(r); // Save row
    }/*from  ww  w .  ja v  a  2 s  .  co m*/
    if (data.files.size() == 0 && r == null) // No more records: sort buffer
    {
        quickSort(data.buffer);
    }

    // time to write to disk: buffer is full!
    if (data.buffer.size() == meta.getSortSize() // Buffer is full: sort & dump to disk 
            || (data.files.size() > 0 && r == null && data.buffer.size() > 0) // No more records: join from disk 
    ) {
        // First sort the rows in buffer[]
        quickSort(data.buffer);

        // Then write them to disk...
        DataOutputStream dos;
        GZIPOutputStream gzos;
        int p;

        try {
            FileObject fileObject = KettleVFS.createTempFile(meta.getPrefix(), ".tmp",
                    StringUtil.environmentSubstitute(meta.getDirectory()));

            data.files.add(fileObject); // Remember the files!
            OutputStream outputStream = fileObject.getContent().getOutputStream();
            if (meta.getCompress()) {
                gzos = new GZIPOutputStream(new BufferedOutputStream(outputStream));
                dos = new DataOutputStream(gzos);
            } else {
                dos = new DataOutputStream(outputStream);
                gzos = null;
            }

            // How many records do we have?
            dos.writeInt(data.buffer.size());

            for (p = 0; p < data.buffer.size(); p++) {
                if (p == 0) {
                    // Save the metadata, keep it in memory
                    data.rowMeta.add(new Row(((Row) data.buffer.get(p))));
                }
                // Just write the data, nothing else
                ((Row) data.buffer.get(p)).writeData(dos);
            }
            // Close temp-file
            dos.close(); // close data stream
            if (gzos != null) {
                gzos.close(); // close gzip stream
            }
            outputStream.close(); // close file stream
        } catch (Exception e) {
            logError("Error processing temp-file: " + e.toString());
            return false;
        }

        data.buffer.clear();
    }

    return true;
}

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);//w  w w  .j  ava2 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.jivesoftware.os.amza.service.AmzaService.java

@Override
public void availableRowsStream(boolean system, ChunkWriteable writeable, RingMember remoteRingMember,
        TimestampedRingHost remoteTimestampedRingHost, long takeSessionId, long sharedKey,
        long heartbeatIntervalMillis) throws Exception {

    ringStoreWriter.register(remoteRingMember, remoteTimestampedRingHost.ringHost,
            remoteTimestampedRingHost.timestampId, false);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new SnappyOutputStream(out), 8192));

    takeCoordinator.availableRowsStream(system, ringStoreReader, partitionStripeProvider, remoteRingMember,
            takeSessionId, sharedKey, heartbeatIntervalMillis, (partitionName, txId) -> {
                dos.write(1);/*from  www.j a va2s.  c  o  m*/
                byte[] bytes = partitionName.toBytes();
                dos.writeInt(bytes.length);
                dos.write(bytes);
                dos.writeLong(txId);
            }, () -> {
                if (dos.size() > 0) {
                    dos.flush();
                    byte[] chunk = out.toByteArray();
                    writeable.write(chunk);
                    /*LOG.info("Offered rows for {} length={}", remoteRingMember, chunk.length);*/
                    out.reset();
                }
                return null;
            }, () -> {
                dos.write(1);
                dos.writeInt(0);
                dos.flush();
                writeable.write(out.toByteArray());
                out.reset();
                return null;
            });
    dos.write(0);
    dos.flush();
    writeable.write(out.toByteArray());
}

From source file:org.latticesoft.util.common.CryptoHelper.java

public String encode(String input) {
    if (this.keyPair == null || input == null || input.length() == 0) {
        return "";
    }/*from  www . java  2  s  .  c o m*/
    int index = 0;
    int diff = 0;
    StringBuffer sb = new StringBuffer();
    String algor = this.getInstanceAlgorithm();
    PublicKey pubKey = null;
    SecureRandom srand = null;
    Cipher rsaEnc = null;
    ByteArrayOutputStream baos = null;
    DataOutputStream dos = null;
    byte[] data = input.getBytes();
    int bufferSize = strength / 32;
    byte[] buffer = new byte[bufferSize];
    byte[] tmp = null;
    String output = null;

    try {
        pubKey = this.keyPair.getPublic();
        srand = SecureRandom.getInstance(this.secureRandomAlgorithm, this.secureRandomProviderName);
        rsaEnc = Cipher.getInstance(algor, this.providerName);
        rsaEnc.init(Cipher.ENCRYPT_MODE, pubKey, srand);

        baos = new ByteArrayOutputStream();
        dos = new DataOutputStream(baos);
        while (index < data.length) {
            diff = data.length - index;
            if (diff > buffer.length) {
                diff = buffer.length;
            }
            NumeralUtil.resetByteArray(buffer);
            System.arraycopy(data, index, buffer, 0, diff);
            tmp = rsaEnc.doFinal(buffer, 0, buffer.length);
            if (tmp != null) {
                dos.writeInt(tmp.length);
                dos.write(tmp);
                NumeralUtil.resetByteArray(tmp);
            }
            tmp = null;//*/
            index += diff;
        }
        output = NumeralUtil.toHexString(baos.toByteArray());
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Error in encryption", e);
        }
    }
    return output;
}

From source file:org.nuxeo.ecm.core.blob.binary.AESBinaryManager.java

/**
 * Encrypts the given input stream into the given output stream, while also computing the digest of the input
 * stream./*w w  w. j a  v  a  2  s  .co m*/
 * <p>
 * File format version 1 (values are in network order):
 * <ul>
 * <li>10 bytes: magic number "NUXEOCRYPT"
 * <li>1 byte: file format version = 1
 * <li>1 byte: use keystore = 1, use PBKDF2 = 2
 * <li>if use PBKDF2:
 * <ul>
 * <li>4 bytes: salt length = n
 * <li>n bytes: salt data
 * </ul>
 * <li>4 bytes: IV length = p
 * <li>p bytes: IV data
 * <li>x bytes: encrypted stream
 * </ul>
 *
 * @param in the input stream containing the data
 * @param file the file containing the encrypted data
 * @return the digest of the input stream
 */
@Override
public String storeAndDigest(InputStream in, OutputStream out) throws IOException {
    out.write(FILE_MAGIC);
    DataOutputStream data = new DataOutputStream(out);
    data.writeByte(FILE_VERSION_1);

    try {
        // get digest to use
        MessageDigest messageDigest = MessageDigest.getInstance(digestAlgorithm);

        // secret key
        Key secret;
        if (usePBKDF2) {
            data.writeByte(USE_PBKDF2);
            // generate a salt
            byte[] salt = new byte[16];
            RANDOM.nextBytes(salt);
            // generate secret key
            secret = generateSecretKey(salt);
            // write salt
            data.writeInt(salt.length);
            data.write(salt);
        } else {
            data.writeByte(USE_KEYSTORE);
            // find secret key from keystore
            secret = getSecretKey();
        }

        // cipher
        Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, secret);

        // write IV
        byte[] iv = cipher.getIV();
        data.writeInt(iv.length);
        data.write(iv);

        // digest and write the encrypted data
        CipherAndDigestOutputStream cipherOut = new CipherAndDigestOutputStream(out, cipher, messageDigest);
        IOUtils.copy(in, cipherOut);
        cipherOut.close();
        byte[] digest = cipherOut.getDigest();
        return toHexString(digest);
    } catch (GeneralSecurityException e) {
        throw new NuxeoException(e);
    }

}