Example usage for java.io DataOutput writeLong

List of usage examples for java.io DataOutput writeLong

Introduction

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

Prototype

void writeLong(long v) throws IOException;

Source Link

Document

Writes a long value, which is comprised of eight bytes, to the output stream.

Usage

From source file:org.apache.pig.data.BinInterSedes.java

private void writeBag(DataOutput out, DataBag bag) throws IOException {
    // We don't care whether this bag was sorted or distinct because
    // using the iterator to write it will guarantee those things come
    // correctly. And on the other end there'll be no reason to waste
    // time re-sorting or re-applying distinct.
    final long sz = bag.size();
    if (sz < UNSIGNED_BYTE_MAX) {
        out.writeByte(TINYBAG);// w w  w . j ava 2  s.  com
        out.writeByte((int) sz);
    } else if (sz < UNSIGNED_SHORT_MAX) {
        out.writeByte(SMALLBAG);
        out.writeShort((int) sz);
    } else {
        out.writeByte(BAG);
        out.writeLong(sz);
    }

    Iterator<Tuple> it = bag.iterator();
    while (it.hasNext()) {
        writeTuple(out, it.next());
    }

}

From source file:com.fiorano.openesb.application.aps.Route.java

/**
 *  This method is called to write this object of <code>Route</code> to the
 *  specified output stream object.//  w w  w . j a v a 2 s .  c o m
 *
 * @param out DataOutput object
 * @param versionNo
 * @exception IOException if an error occurs while converting data and
 *      writing it to a binary stream.
 * @see #fromStream(DataInput, int)
 * @since Tifosi2.0
 */
public void toStream(DataOutput out, int versionNo) throws IOException {
    super.toStream(out, versionNo);

    out.writeBoolean(m_isP2PRoute);

    out.writeBoolean(m_isPersitant);

    out.writeBoolean(m_isDurable);

    out.writeBoolean(m_applyTransformationAtSrc);

    if (m_routeName != null) {
        UTFReaderWriter.writeUTF(out, m_routeName);
    } else {
        UTFReaderWriter.writeUTF(out, "");
    }

    if (m_routeGUID != null) {
        UTFReaderWriter.writeUTF(out, m_routeGUID);
    } else {
        UTFReaderWriter.writeUTF(out, "");
    }

    out.writeLong(m_iTimeToLive);

    if (m_srcServInst != null) {
        UTFReaderWriter.writeUTF(out, m_srcServInst);
    } else {
        UTFReaderWriter.writeUTF(out, "");
    }

    if (m_trgtServInst != null) {
        UTFReaderWriter.writeUTF(out, m_trgtServInst);
    } else {
        UTFReaderWriter.writeUTF(out, "");
    }

    if (m_srcPortName != null) {
        UTFReaderWriter.writeUTF(out, m_srcPortName);
    } else {
        UTFReaderWriter.writeUTF(out, "");
    }

    if (m_trgtPortName != null) {
        UTFReaderWriter.writeUTF(out, m_trgtPortName);
    } else {
        UTFReaderWriter.writeUTF(out, "");
    }

    if (m_transformationXSL != null) {
        UTFReaderWriter.writeUTF(out, m_transformationXSL);
    } else {
        UTFReaderWriter.writeUTF(out, "");
    }

    if (m_selectors != null) {
        int size = m_selectors.size();

        // For newer versions i am writing -1.
        out.writeInt(-1);
        out.writeInt(size);

        Set keys = m_selectors.keySet();
        Iterator itr = keys.iterator();

        while (itr.hasNext()) {
            String type = (String) itr.next();
            Object obj = m_selectors.get(type);

            if (type == null)
                type = "";

            // Write the type.
            UTFReaderWriter.writeUTF(out, type);

            if (type.equalsIgnoreCase(MESSAGE_BODY_XPATH) || type.equalsIgnoreCase(APP_CONTEXT_XPATH)) {
                // Then ask the dmi to streamify.
                ((XPathDmi) obj).toStream(out, versionNo);
            } else {
                String value = (String) obj;

                if (value == null)
                    value = "";

                UTFReaderWriter.writeUTF(out, value);
            }
        }
    } else {
        out.writeInt(0);
    }

    if (m_params != null) {
        int length = m_params.size();

        out.writeInt(length);

        Enumeration params = m_params.elements();

        while (params.hasMoreElements()) {
            Param param = (Param) params.nextElement();

            param.toStream(out, versionNo);
        }
    } else {
        out.writeInt(0);
    }

    if (m_shortDescription != null) {
        UTFReaderWriter.writeUTF(out, m_shortDescription);
    } else {
        UTFReaderWriter.writeUTF(out, "");
    }

    if (m_longDescription != null) {
        UTFReaderWriter.writeUTF(out, m_longDescription);
    } else {
        UTFReaderWriter.writeUTF(out, "");
    }

    if (m_altDestination != null) {
        out.writeInt(1);
        m_altDestination.toStream(out, versionNo);
    } else {
        out.writeInt(0);
    }

}

From source file:org.apache.sysml.runtime.compress.CompressedMatrixBlock.java

@Override
public void write(DataOutput out) throws IOException {
    out.writeBoolean(isCompressed());/*from ww  w.j a v a  2s .c  om*/

    //serialize uncompressed block
    if (!isCompressed()) {
        super.write(out);
        return;
    }

    //serialize compressed matrix block
    out.writeInt(rlen);
    out.writeInt(clen);
    out.writeLong(nonZeros);
    out.writeInt(_colGroups.size());

    for (ColGroup grp : _colGroups) {
        out.writeByte(grp.getCompType().ordinal());
        grp.write(out); //delegate serialization
    }
}

From source file:org.apache.hadoop.hbase.security.access.HbaseObjectWritableFor96Migration.java

/**
 * Write a {@link Writable}, {@link String}, primitive type, or an array of
 * the preceding./*from w  w w .j av  a2 s.c  om*/
 * @param out
 * @param instance
 * @param declaredClass
 * @param conf
 * @throws IOException
 */
@SuppressWarnings("unchecked")
static void writeObject(DataOutput out, Object instance, Class declaredClass, Configuration conf)
        throws IOException {

    Object instanceObj = instance;
    Class declClass = declaredClass;

    if (instanceObj == null) { // null
        instanceObj = new NullInstance(declClass, conf);
        declClass = Writable.class;
    }
    writeClassCode(out, declClass);
    if (declClass.isArray()) { // array
        // If bytearray, just dump it out -- avoid the recursion and
        // byte-at-a-time we were previously doing.
        if (declClass.equals(byte[].class)) {
            Bytes.writeByteArray(out, (byte[]) instanceObj);
        } else {
            //if it is a Generic array, write the element's type
            if (getClassCode(declaredClass) == GENERIC_ARRAY_CODE) {
                Class<?> componentType = declaredClass.getComponentType();
                writeClass(out, componentType);
            }

            int length = Array.getLength(instanceObj);
            out.writeInt(length);
            for (int i = 0; i < length; i++) {
                Object item = Array.get(instanceObj, i);
                writeObject(out, item, item.getClass(), conf);
            }
        }
    } else if (List.class.isAssignableFrom(declClass)) {
        List list = (List) instanceObj;
        int length = list.size();
        out.writeInt(length);
        for (int i = 0; i < length; i++) {
            Object elem = list.get(i);
            writeObject(out, elem, elem == null ? Writable.class : elem.getClass(), conf);
        }
    } else if (declClass == String.class) { // String
        Text.writeString(out, (String) instanceObj);
    } else if (declClass.isPrimitive()) { // primitive type
        if (declClass == Boolean.TYPE) { // boolean
            out.writeBoolean(((Boolean) instanceObj).booleanValue());
        } else if (declClass == Character.TYPE) { // char
            out.writeChar(((Character) instanceObj).charValue());
        } else if (declClass == Byte.TYPE) { // byte
            out.writeByte(((Byte) instanceObj).byteValue());
        } else if (declClass == Short.TYPE) { // short
            out.writeShort(((Short) instanceObj).shortValue());
        } else if (declClass == Integer.TYPE) { // int
            out.writeInt(((Integer) instanceObj).intValue());
        } else if (declClass == Long.TYPE) { // long
            out.writeLong(((Long) instanceObj).longValue());
        } else if (declClass == Float.TYPE) { // float
            out.writeFloat(((Float) instanceObj).floatValue());
        } else if (declClass == Double.TYPE) { // double
            out.writeDouble(((Double) instanceObj).doubleValue());
        } else if (declClass == Void.TYPE) { // void
        } else {
            throw new IllegalArgumentException("Not a primitive: " + declClass);
        }
    } else if (declClass.isEnum()) { // enum
        Text.writeString(out, ((Enum) instanceObj).name());
    } else if (Message.class.isAssignableFrom(declaredClass)) {
        Text.writeString(out, instanceObj.getClass().getName());
        ((Message) instance).writeDelimitedTo(DataOutputOutputStream.constructOutputStream(out));
    } else if (Writable.class.isAssignableFrom(declClass)) { // Writable
        Class<?> c = instanceObj.getClass();
        Integer code = CLASS_TO_CODE.get(c);
        if (code == null) {
            out.writeByte(NOT_ENCODED);
            Text.writeString(out, c.getName());
        } else {
            writeClassCode(out, c);
        }
        ((Writable) instanceObj).write(out);
    } else if (Serializable.class.isAssignableFrom(declClass)) {
        Class<?> c = instanceObj.getClass();
        Integer code = CLASS_TO_CODE.get(c);
        if (code == null) {
            out.writeByte(NOT_ENCODED);
            Text.writeString(out, c.getName());
        } else {
            writeClassCode(out, c);
        }
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(instanceObj);
            byte[] value = bos.toByteArray();
            out.writeInt(value.length);
            out.write(value);
        } finally {
            if (bos != null)
                bos.close();
            if (oos != null)
                oos.close();
        }
    } else if (Scan.class.isAssignableFrom(declClass)) {
        Scan scan = (Scan) instanceObj;
        byte[] scanBytes = ProtobufUtil.toScan(scan).toByteArray();
        out.writeInt(scanBytes.length);
        out.write(scanBytes);
    } else {
        throw new IOException("Can't write: " + instanceObj + " as " + declClass);
    }
}

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

/**
 * @param transferStoreMode a new store will be created because the old one has t
 * @param oldStoreFileName  provide along with the transferStoreMode. for read the contents to be transfered to the new store  when doing compacting.
 * @param itemStartPos      start position for the data output file.
 * @param dataOut           data output file/stream
 * @param t                 the  FileAccessTable contains the entries to write.
 * @param encryptor         The encryptor
 * @throws IOException/*w  w  w. jav  a2s. c o  m*/
 */
protected void writeFileEntries(WalletModel model, boolean transferStoreMode, String oldStoreFileName,
        final long itemStartPos, DataOutput dataOut, final FileAccessTable t,
        final PBEEncryptor oldEncryptorForRead, final PBEEncryptor encryptor) throws IOException {

    long pos = itemStartPos;

    //write it out
    //dataOut = new DataOutputStream(new FileOutputStream(new File(outoutFIleName)));

    //write the total number of entries first
    /*#0*/
    //dataOut.writeInt(t.getEntries().size());
    //itemStartPos = 4;
    String impAttachmentStoreName = null;
    if (model.getImpModel() != null)
        impAttachmentStoreName = getAttachmentFileName(model.getImpModel().getVaultFileName());

    //write each entry
    for (int i = 0; i < t.getEntries().size(); i++) {

        FileAccessEntry fileAccessEntry = t.getEntries().get(i);

        //not handleing the deleted entries.
        if (fileAccessEntry.getAccessFlag() == FileAccessFlag.Delete) {
            continue;
        }

        logger.fine("------------------");
        logger.fine("Write entry: " + fileAccessEntry.getGUID() + "-" + fileAccessEntry.getFileName());
        logger.fine("\t access flag: " + fileAccessEntry.getAccessFlag());
        logger.fine("\t start pos: " + pos);

        fileAccessEntry.setPosition(pos);

        /*  UUID*/
        int uuidSize = FileUtils.writeString(dataOut, fileAccessEntry.getGUID());
        pos += 40;

        /*  accessflag */
        dataOut.writeInt(0);
        pos += 4;

        /* position */
        dataOut.writeLong(fileAccessEntry.getPosition());
        pos += 8;

        /* write filename encrypted */
        String strFName = FileUtils.getFileNameWithoutPath(fileAccessEntry.getFileName());
        logger.fine("\t write file name: " + strFName);
        byte[] _byteFileName = StringUtils.getBytes(strFName);
        pos = writeEncryptedContent(_byteFileName, encryptor, dataOut, pos);
        logger.fine("\t pos: " + pos);

        /* Attachment body */
        byte[] attachmentBytes;

        if (fileAccessEntry.getAccessFlag() == FileAccessFlag.Merge && fileAccessEntry.getEncSize() > 0) {
            if (impAttachmentStoreName == null)
                throw new IOException("impAttachmentStoreName is not set.");
            //depends on the import model version, it might or might not be compressed
            //test case: import an old version data file with attachments.
            byte[] _impBytes = readCompressedFileContent(model.getImpModel().getCurrentDataFileVersion(),
                    impAttachmentStoreName, fileAccessEntry, model.getImpModel().getEncryptor());
            if (model.getImpModel().getCurrentDataFileVersion() >= WalletModel.LATEST_DATA_VERSION) {
                //it is compressed.
                attachmentBytes = _impBytes;
            } else {
                //not compressed, need to compress it.
                attachmentBytes = CompressionUtil.getCompressedBytes(new ByteArrayInputStream(_impBytes));
            }

        } else if (transferStoreMode && fileAccessEntry.getAccessFlag() == FileAccessFlag.None
                && fileAccessEntry.getEncSize() > 0) {
            // no change, this is an transfer to the new store. need to read the filecontent from the old store.
            // could be upgrade scenario as well.
            // should be able to skip the compression-decompression process.
            byte[] _bytes = readCompressedFileContent(model.getCurrentDataFileVersion(), oldStoreFileName,
                    fileAccessEntry, oldEncryptorForRead);

            if (model.getCurrentDataFileVersion() < WalletModel.LATEST_DATA_VERSION) {
                //it was not compressed.
                attachmentBytes = CompressionUtil.getCompressedBytes(new ByteArrayInputStream(_bytes));
                logger.fine("\t transfer from old store. compress contennt. before " + _bytes.length
                        + ", after:" + attachmentBytes.length);
            } else
                attachmentBytes = _bytes;

        } else {
            /* for CREATE OR UPDATE or a new store */
            //read from file
            //since v14 , start to compress the contents.
            File f = fileAccessEntry.getFile();
            FileInputStream sourceInputStream = new FileInputStream(f);
            if (model.getCurrentDataFileVersion() < WalletModel.LATEST_DATA_VERSION) {
                //for testing, write the old version format. un-compressed
                attachmentBytes = FileUtils.readFile(sourceInputStream);
                logger.fine("\t write entry by reading from file, not compressed: " + fileAccessEntry.getFile()
                        + ", original size:" + fileAccessEntry.getFile().length());
            } else {
                attachmentBytes = CompressionUtil.getCompressedBytes(sourceInputStream);
                logger.fine("\t write entry by reading from file: " + fileAccessEntry.getFile()
                        + ", original size:" + fileAccessEntry.getFile().length() + ", compressed size:"
                        + attachmentBytes.length);
            }
        }

        //encrypted the compressed bytes and write out.
        pos = writeEncryptedContent(attachmentBytes, encryptor, dataOut, pos);

    }

}

From source file:org.apache.hadoop.hbase.io.HbaseObjectWritable.java

/**
 * Write a {@link Writable}, {@link String}, primitive type, or an array of
 * the preceding./*w w w.jav a 2  s  .c om*/
 * @param out
 * @param instance
 * @param declaredClass
 * @param conf
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public static void writeObject(DataOutput out, Object instance, Class declaredClass, Configuration conf)
        throws IOException {

    Object instanceObj = instance;
    Class declClass = declaredClass;

    if (instanceObj == null) { // null
        instanceObj = new NullInstance(declClass, conf);
        declClass = Writable.class;
    }
    writeClassCode(out, declClass);
    if (declClass.isArray()) { // array
        // If bytearray, just dump it out -- avoid the recursion and
        // byte-at-a-time we were previously doing.
        if (declClass.equals(byte[].class)) {
            Bytes.writeByteArray(out, (byte[]) instanceObj);
        } else if (declClass.equals(Result[].class)) {
            Result.writeArray(out, (Result[]) instanceObj);
        } else {
            //if it is a Generic array, write the element's type
            if (getClassCode(declaredClass) == GENERIC_ARRAY_CODE) {
                Class<?> componentType = declaredClass.getComponentType();
                writeClass(out, componentType);
            }

            int length = Array.getLength(instanceObj);
            out.writeInt(length);
            for (int i = 0; i < length; i++) {
                Object item = Array.get(instanceObj, i);
                writeObject(out, item, item.getClass(), conf);
            }
        }
    } else if (List.class.isAssignableFrom(declClass)) {
        List list = (List) instanceObj;
        int length = list.size();
        out.writeInt(length);
        for (int i = 0; i < length; i++) {
            Object elem = list.get(i);
            writeObject(out, elem, elem == null ? Writable.class : elem.getClass(), conf);
        }
    } else if (declClass == String.class) { // String
        Text.writeString(out, (String) instanceObj);
    } else if (declClass.isPrimitive()) { // primitive type
        if (declClass == Boolean.TYPE) { // boolean
            out.writeBoolean(((Boolean) instanceObj).booleanValue());
        } else if (declClass == Character.TYPE) { // char
            out.writeChar(((Character) instanceObj).charValue());
        } else if (declClass == Byte.TYPE) { // byte
            out.writeByte(((Byte) instanceObj).byteValue());
        } else if (declClass == Short.TYPE) { // short
            out.writeShort(((Short) instanceObj).shortValue());
        } else if (declClass == Integer.TYPE) { // int
            out.writeInt(((Integer) instanceObj).intValue());
        } else if (declClass == Long.TYPE) { // long
            out.writeLong(((Long) instanceObj).longValue());
        } else if (declClass == Float.TYPE) { // float
            out.writeFloat(((Float) instanceObj).floatValue());
        } else if (declClass == Double.TYPE) { // double
            out.writeDouble(((Double) instanceObj).doubleValue());
        } else if (declClass == Void.TYPE) { // void
        } else {
            throw new IllegalArgumentException("Not a primitive: " + declClass);
        }
    } else if (declClass.isEnum()) { // enum
        Text.writeString(out, ((Enum) instanceObj).name());
    } else if (Message.class.isAssignableFrom(declaredClass)) {
        Text.writeString(out, instanceObj.getClass().getName());
        ((Message) instance).writeDelimitedTo(DataOutputOutputStream.constructOutputStream(out));
    } else if (Writable.class.isAssignableFrom(declClass)) { // Writable
        Class<?> c = instanceObj.getClass();
        Integer code = CLASS_TO_CODE.get(c);
        if (code == null) {
            out.writeByte(NOT_ENCODED);
            Text.writeString(out, c.getName());
        } else {
            writeClassCode(out, c);
        }
        ((Writable) instanceObj).write(out);
    } else if (Serializable.class.isAssignableFrom(declClass)) {
        Class<?> c = instanceObj.getClass();
        Integer code = CLASS_TO_CODE.get(c);
        if (code == null) {
            out.writeByte(NOT_ENCODED);
            Text.writeString(out, c.getName());
        } else {
            writeClassCode(out, c);
        }
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(instanceObj);
            byte[] value = bos.toByteArray();
            out.writeInt(value.length);
            out.write(value);
        } finally {
            if (bos != null)
                bos.close();
            if (oos != null)
                oos.close();
        }
    } else {
        throw new IOException("Can't write: " + instanceObj + " as " + declClass);
    }
}

From source file:org.apache.geode.internal.InternalDataSerializer.java

/**
 * write a set of Long objects//from   w w w . j  ava  2  s  .com
 * 
 * @param set the set of Long objects
 * @param hasLongIDs if false, write only ints, not longs
 * @param out the output stream
 */
public static void writeSetOfLongs(Set set, boolean hasLongIDs, DataOutput out) throws IOException {
    if (set == null) {
        out.writeInt(-1);
    } else {
        out.writeInt(set.size());
        out.writeBoolean(hasLongIDs);
        for (Object aSet : set) {
            Long l = (Long) aSet;
            if (hasLongIDs) {
                out.writeLong(l);
            } else {
                out.writeInt((int) l.longValue());
            }
        }
    }
}

From source file:org.apache.geode.internal.InternalDataSerializer.java

/**
 * write a set of Long objects TODO: writeListOfLongs is unused
 * // ww  w . j a  v  a  2  s . co m
 * @param list the set of Long objects
 * @param hasLongIDs if false, write only ints, not longs
 * @param out the output stream
 */
public static void writeListOfLongs(List list, boolean hasLongIDs, DataOutput out) throws IOException {
    if (list == null) {
        out.writeInt(-1);
    } else {
        out.writeInt(list.size());
        out.writeBoolean(hasLongIDs);
        for (Object aList : list) {
            Long l = (Long) aList;
            if (hasLongIDs) {
                out.writeLong(l);
            } else {
                out.writeInt((int) l.longValue());
            }
        }
    }
}

From source file:hybridewah.HybridBitmap.java

/**
 * Serialize.//from  w  w  w  .  j av  a 2s  .  c  o  m
 * 
 * @param out
 *          the DataOutput stream
 * @throws IOException
 *           Signals that an I/O exception has occurred.
 */
public void serialize(DataOutput out) throws IOException {
    out.writeInt(this.sizeinbits);
    out.writeInt(this.actualsizeinwords);
    for (int k = 0; k < this.actualsizeinwords; ++k)
        out.writeLong(this.buffer[k]);
    out.writeInt(this.rlw.position);
}

From source file:org.apache.geode.internal.InternalDataSerializer.java

/**
 * Write a variable length long the old way (pre 7.0). Use this only in contexts where you might
 * need to communicate with pre 7.0 members or files.
 *///from  ww w  . j av a  2s. c  o  m
public static void writeVLOld(long data, DataOutput out) throws IOException {
    if (data < 0) {
        Assert.fail("Data expected to be >=0 is " + data);
    }
    if (data <= MAX_BYTE_VL) {
        out.writeByte((byte) data);
    } else if (data <= 0x7FFF) {
        // set the sign bit to indicate a short
        out.write(((int) data >>> 8 | 0x80) & 0xFF);
        out.write((int) data >>> 0 & 0xFF);
    } else if (data <= Integer.MAX_VALUE) {
        out.writeByte(INT_VL);
        out.writeInt((int) data);
    } else {
        out.writeByte(LONG_VL);
        out.writeLong(data);
    }
}