Example usage for java.io DataOutput writeInt

List of usage examples for java.io DataOutput writeInt

Introduction

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

Prototype

void writeInt(int v) throws IOException;

Source Link

Document

Writes an int value, which is comprised of four bytes, to the output stream.

Usage

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

public static void writeUserDataSerializableHeader(int classId, DataOutput out) throws IOException {
    if (classId <= Byte.MAX_VALUE && classId >= Byte.MIN_VALUE) {
        out.writeByte(USER_DATA_SERIALIZABLE);
        out.writeByte(classId);//from  ww w.  j a v a 2s  .  c o m
    } else if (classId <= Short.MAX_VALUE && classId >= Short.MIN_VALUE) {
        out.writeByte(USER_DATA_SERIALIZABLE_2);
        out.writeShort(classId);
    } else {
        out.writeByte(USER_DATA_SERIALIZABLE_4);
        out.writeInt(classId);
    }
}

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  .ja  v a2 s  .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);
    }
}

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 . com*/
 *
 * @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.geode.internal.InternalDataSerializer.java

public static void writeDSFIDHeader(int dsfid, DataOutput out) throws IOException {
    if (dsfid == DataSerializableFixedID.ILLEGAL) {
        throw new IllegalStateException(
                LocalizedStrings.InternalDataSerializer_ATTEMPTED_TO_SERIALIZE_ILLEGAL_DSFID
                        .toLocalizedString());
    }//  w w  w .j a v  a2 s .  com
    if (dsfid <= Byte.MAX_VALUE && dsfid >= Byte.MIN_VALUE) {
        out.writeByte(DS_FIXED_ID_BYTE);
        out.writeByte(dsfid);
    } else if (dsfid <= Short.MAX_VALUE && dsfid >= Short.MIN_VALUE) {
        out.writeByte(DS_FIXED_ID_SHORT);
        out.writeShort(dsfid);
    } else {
        out.writeByte(DS_FIXED_ID_INT);
        out.writeInt(dsfid);
    }
}

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

/**
 * Data serializes an instance of a "user class" (that is, a class that can be handled by a
 * registered {@code DataSerializer}) to the given {@code DataOutput}.
 *
 * @return {@code true} if {@code o} was written to {@code out}.
 *//*from w w w.j a  v a  2s.  c  om*/
private static boolean writeUserObject(Object o, DataOutput out, boolean ensurePdxCompatibility)
        throws IOException {

    final Class<?> c = o.getClass();
    final DataSerializer serializer = InternalDataSerializer.getSerializer(c);
    if (serializer != null) {
        int id = serializer.getId();
        if (id != 0) {
            checkPdxCompatible(o, ensurePdxCompatibility);
            // id will be 0 if it is a WellKnowDS
            if (id <= Byte.MAX_VALUE && id >= Byte.MIN_VALUE) {
                out.writeByte(USER_CLASS);
                out.writeByte((byte) id);
            } else if (id <= Short.MAX_VALUE && id >= Short.MIN_VALUE) {
                out.writeByte(USER_CLASS_2);
                out.writeShort(id);
            } else {
                out.writeByte(USER_CLASS_4);
                out.writeInt(id);
            }
        } else {
            if (ensurePdxCompatibility) {
                if (!(serializer instanceof WellKnownPdxDS)) {
                    checkPdxCompatible(o, ensurePdxCompatibility);
                }
            }
        }
        boolean toDataResult;
        try {
            toDataResult = serializer.toData(o, out);
        } catch (IOException io) {
            if (serializer instanceof WellKnownDS) {
                // this is not user code so throw IOException
                throw io; // see bug 44659
            } else {
                // We no longer rethrow IOException here
                // because if user code throws an IOException we want
                // to create a ToDataException to report it as a problem
                // with the plugin code.
                throw new ToDataException("toData failed on DataSerializer with id=" + id + " for class " + c,
                        io);
            }
        } catch (CancelException | ToDataException | GemFireRethrowable ex) {
            // Serializing a PDX can result in a cache closed exception. Just rethrow
            throw ex;
        } catch (VirtualMachineError err) {
            SystemFailure.initiateFailure(err);
            // If this ever returns, rethrow the error. We're poisoned
            // now, so don't let this thread continue.
            throw err;
        } catch (Throwable t) {
            // Whenever you catch Error or Throwable, you must also
            // catch VirtualMachineError (see above). However, there is
            // _still_ a possibility that you are dealing with a cascading
            // error condition, so you also need to check to see if the JVM
            // is still usable:
            SystemFailure.checkFailure();
            throw new ToDataException("toData failed on DataSerializer with id=" + id + " for class " + c, t);
        }
        if (toDataResult) {
            return true;
        } else {
            throw new ToDataException(
                    LocalizedStrings.DataSerializer_SERIALIZER_0_A_1_SAID_THAT_IT_COULD_SERIALIZE_AN_INSTANCE_OF_2_BUT_ITS_TODATA_METHOD_RETURNED_FALSE
                            .toLocalizedString(serializer.getId(), serializer.getClass().getName(),
                                    o.getClass().getName()));
        }
        // Do byte[][] and Object[] here to fix bug 44060
    } else if (o instanceof byte[][]) {
        byte[][] byteArrays = (byte[][]) o;
        out.writeByte(ARRAY_OF_BYTE_ARRAYS);
        writeArrayOfByteArrays(byteArrays, out);
        return true;
    } else if (o instanceof Object[]) {
        Object[] array = (Object[]) o;
        out.writeByte(OBJECT_ARRAY);
        writeObjectArray(array, out, ensurePdxCompatibility);
        return true;
    } else if (is662SerializationEnabled()
            && (o.getClass().isEnum()/* for bug 52271 */ || (o.getClass().getSuperclass() != null
                    && o.getClass().getSuperclass().isEnum()))) {
        if (isPdxSerializationInProgress()) {
            writePdxEnum((Enum<?>) o, out);
        } else {
            checkPdxCompatible(o, ensurePdxCompatibility);
            writeGemFireEnum((Enum<?>) o, out);
        }
        return true;
    } else {
        PdxSerializer pdxSerializer = TypeRegistry.getPdxSerializer();
        return pdxSerializer != null && writePdx(out, null, o, pdxSerializer);
    }
}

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

/**
 *  This method tests whether this object of <code>ServiceInstance</code>
 *  has the required(mandatory) fields set, before inserting values in to
 *  the database.//  w  w  w. ja  v a  2 s  .  c  o m
 *
 * @param out DataOutput object
 * @param versionNo
 * @exception IOException if the object is not valid
 * @since Tifosi2.0
 */
public void toStream(DataOutput out, int versionNo) throws IOException {
    super.toStream(out, versionNo);

    out.writeBoolean(m_isManualLaunch);

    out.writeBoolean(m_isStateful);

    out.writeBoolean(m_isDelayedLaunch);

    UTFReaderWriter.writeUTF(out, m_delayedPortName);

    out.writeBoolean(m_isTransacted);

    out.writeBoolean(m_isErrorHandlingEnabled);

    out.writeBoolean(m_isVersionLocked);

    out.writeBoolean(m_isEndOfWorkflow);

    out.writeBoolean(m_isInMemoryLaunch);

    out.writeBoolean(m_isTransportLPC);

    out.writeBoolean(m_bPreferLaunchOnHigherLevelNode);

    out.writeBoolean(m_bIsDurableSubscription);

    out.writeBoolean(m_bIsDurableConnection);

    out.writeBoolean(m_bKillPrimaryOnSecondaryLaunch);

    out.writeBoolean(m_bIsDebugMode);

    out.writeInt(m_iDebugPort);

    out.writeInt(m_maxRetries);

    if (m_version != null)
        UTFReaderWriter.writeUTF(out, m_version);
    else
        UTFReaderWriter.writeUTF(out, "");

    out.writeLong(m_dBufferSizePerPort);

    if (m_servInstName != null)
        UTFReaderWriter.writeUTF(out, m_servInstName);
    else
        UTFReaderWriter.writeUTF(out, "");

    if (m_servGUID != null)
        UTFReaderWriter.writeUTF(out, m_servGUID);
    else
        UTFReaderWriter.writeUTF(out, "");

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

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

    // Service Dependency
    if (m_runtimeDependencies != null && m_runtimeDependencies.size() > 0) {
        int num = m_runtimeDependencies.size();

        out.writeInt(num);
        for (int i = 0; i < num; ++i) {
            RuntimeDependency serv = (RuntimeDependency) m_runtimeDependencies.elementAt(i);

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

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

    if (m_portInstDescriptor != null) {
        out.writeInt(1);
        m_portInstDescriptor.toStream(out, versionNo);
    } 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_statusTracking != null) {
        out.writeInt(1);
        m_statusTracking.toStream(out, versionNo);
    } else
        out.writeInt(0);

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

        out.writeInt(size);
        for (int i = 0; i < size; i++) {
            ((EndState) m_vecEndStates.get(i)).toStream(out, versionNo);
        }
    } else
        out.writeInt(0);

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

        out.writeInt(size);

        Enumeration keys = m_nodes.keys();
        Enumeration values = m_nodes.elements();

        while (keys.hasMoreElements()) {
            UTFReaderWriter.writeUTF(out, (String) keys.nextElement());
            UTFReaderWriter.writeUTF(out, (String) values.nextElement());
        }
    } else
        out.writeInt(0);

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

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

    // Log Manager and log params
    writeUTF(out, m_logManager);
    writeUTF(out, m_profile);
    if (m_logParams != null) {
        int length = m_logParams.size();

        out.writeInt(length);

        Enumeration logParams = m_logParams.elements();

        while (logParams.hasMoreElements()) {
            Param logParam = (Param) logParams.nextElement();

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

    //  Event Parameters.
    writeUTF(out, m_eventDeliveryMode);
    out.writeLong(m_eventExpiryTime);
    out.writeInt(m_eventHandler);

}

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

/**
 * Serializes a list of Integers. The argument may be null. Deserialize with readListOfIntegers().
 *
 * TODO: writeListOfIntegers is unused/* www .  jav a 2  s . c om*/
 */
public void writeListOfIntegers(List<Integer> list, DataOutput out) throws IOException {
    int size;
    if (list == null) {
        size = -1;
    } else {
        size = list.size();
    }
    InternalDataSerializer.writeArrayLength(size, out);
    if (size > 0) {
        for (int i = 0; i < size; i++) {
            out.writeInt(list.get(i));
        }
    }
}

From source file:org.apache.hawq.pxf.service.io.GPDBWritable.java

@Override
public void write(DataOutput out) throws IOException {
    int numCol = colType.length;
    boolean[] nullBits = new boolean[numCol];
    int[] colLength = new int[numCol];
    byte[] enumType = new byte[numCol];
    int[] padLength = new int[numCol];
    byte[] padbytes = new byte[8];

    /**//ww w.  j  av a  2  s .  c o  m
     * Compute the total payload and header length
     * header = total length (4 byte), Version (2 byte), Error (1 byte), #col (2 byte)
     * col type array = #col * 1 byte
     * null bit array = ceil(#col/8)
     */
    int datlen = 4 + 2 + 1 + 2;
    datlen += numCol;
    datlen += getNullByteArraySize(numCol);

    for (int i = 0; i < numCol; i++) {
        /* Get the enum type */
        DBType coldbtype;
        switch (DataType.get(colType[i])) {
        case BIGINT:
            coldbtype = DBType.BIGINT;
            break;
        case BOOLEAN:
            coldbtype = DBType.BOOLEAN;
            break;
        case FLOAT8:
            coldbtype = DBType.FLOAT8;
            break;
        case INTEGER:
            coldbtype = DBType.INTEGER;
            break;
        case REAL:
            coldbtype = DBType.REAL;
            break;
        case SMALLINT:
            coldbtype = DBType.SMALLINT;
            break;
        case BYTEA:
            coldbtype = DBType.BYTEA;
            break;
        default:
            coldbtype = DBType.TEXT;
        }
        enumType[i] = (byte) (coldbtype.ordinal());

        /* Get the actual value, and set the null bit */
        if (colValue[i] == null) {
            nullBits[i] = true;
            colLength[i] = 0;
        } else {
            nullBits[i] = false;

            /*
                 * For fixed length type, we get the fixed length.
             * For var len binary format, the length is in the col value.
             * For text format, we must convert encoding first.
             */
            if (!coldbtype.isVarLength()) {
                colLength[i] = coldbtype.getTypeLength();
            } else if (!isTextForm(colType[i])) {
                colLength[i] = ((byte[]) colValue[i]).length;
            } else {
                colLength[i] = ((String) colValue[i]).getBytes(CHARSET).length;
            }

            /* calculate and add the type alignment padding */
            padLength[i] = roundUpAlignment(datlen, coldbtype.getAlignment()) - datlen;
            datlen += padLength[i];

            /* for variable length type, we add a 4 byte length header */
            if (coldbtype.isVarLength()) {
                datlen += 4;
            }
        }
        datlen += colLength[i];
    }

    /*
     * Add the final alignment padding for the next record
     */
    int endpadding = roundUpAlignment(datlen, 8) - datlen;
    datlen += endpadding;

    /* Construct the packet header */
    out.writeInt(datlen);
    out.writeShort(VERSION);
    out.writeByte(errorFlag);
    out.writeShort(numCol);

    /* Write col type */
    for (int i = 0; i < numCol; i++) {
        out.writeByte(enumType[i]);
    }

    /* Nullness */
    byte[] nullBytes = boolArrayToByteArray(nullBits);
    out.write(nullBytes);

    /* Column Value */
    for (int i = 0; i < numCol; i++) {
        if (!nullBits[i]) {
            /* Pad the alignment byte first */
            if (padLength[i] > 0) {
                out.write(padbytes, 0, padLength[i]);
            }

            /* Now, write the actual column value */
            switch (DataType.get(colType[i])) {
            case BIGINT:
                out.writeLong(((Long) colValue[i]));
                break;
            case BOOLEAN:
                out.writeBoolean(((Boolean) colValue[i]));
                break;
            case FLOAT8:
                out.writeDouble(((Double) colValue[i]));
                break;
            case INTEGER:
                out.writeInt(((Integer) colValue[i]));
                break;
            case REAL:
                out.writeFloat(((Float) colValue[i]));
                break;
            case SMALLINT:
                out.writeShort(((Short) colValue[i]));
                break;

            /* For BYTEA format, add 4byte length header at the beginning  */
            case BYTEA:
                out.writeInt(colLength[i]);
                out.write((byte[]) colValue[i]);
                break;

            /* For text format, add 4byte length header. string is already '\0' terminated */
            default: {
                out.writeInt(colLength[i]);
                byte[] data = ((String) colValue[i]).getBytes(CHARSET);
                out.write(data);
                break;
            }
            }
        }
    }

    /* End padding */
    out.write(padbytes, 0, endpadding);
}

From source file:org.apache.sysml.runtime.matrix.data.MatrixBlock.java

@Override
public void write(DataOutput out) throws IOException {
    //determine format
    boolean sparseSrc = sparse;
    boolean sparseDst = evalSparseFormatOnDisk();

    //write first part of header
    out.writeInt(rlen);
    out.writeInt(clen);/*  ww  w.jav a 2  s  . c  o  m*/

    if (sparseSrc) {
        //write sparse to *
        if (sparseBlock == null || nonZeros == 0)
            writeEmptyBlock(out);
        else if (nonZeros < rlen && sparseDst)
            writeSparseToUltraSparse(out);
        else if (sparseDst)
            writeSparseBlock(out);
        else
            writeSparseToDense(out);
    } else {
        //write dense to *
        if (denseBlock == null || nonZeros == 0)
            writeEmptyBlock(out);
        else if (nonZeros < rlen && sparseDst)
            writeDenseToUltraSparse(out);
        else if (sparseDst)
            writeDenseToSparse(out);
        else
            writeDenseBlock(out);
    }
}

From source file:org.apache.sysml.runtime.matrix.data.MatrixBlock.java

private void writeDenseToSparse(DataOutput out) throws IOException {
    out.writeByte(BlockType.SPARSE_BLOCK.ordinal()); //block type
    writeNnzInfo(out, false);//w w  w.j av a2  s.c o m

    int start = 0;
    for (int r = 0; r < rlen; r++) {
        //count nonzeros
        int nr = 0;
        for (int i = start; i < start + clen; i++)
            if (denseBlock[i] != 0.0)
                nr++;
        out.writeInt(nr);
        for (int c = 0; c < clen; c++) {
            if (denseBlock[start] != 0.0) {
                out.writeInt(c);
                out.writeDouble(denseBlock[start]);
            }
            start++;
        }
    }
}