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:org.syncany.operations.init.ApplicationLink.java

private byte[] getPlaintextStorageXml() throws Exception {
    ByteArrayOutputStream plaintextByteArrayOutputStream = new ByteArrayOutputStream();
    DataOutputStream plaintextOutputStream = new DataOutputStream(plaintextByteArrayOutputStream);
    plaintextOutputStream.writeInt(transferSettings.getType().getBytes().length);
    plaintextOutputStream.write(transferSettings.getType().getBytes());

    GZIPOutputStream plaintextGzipOutputStream = new GZIPOutputStream(plaintextOutputStream);
    new Persister(new Format(0)).write(transferSettings, plaintextGzipOutputStream);
    plaintextGzipOutputStream.close();/*from   w w  w .jav a  2  s  . co  m*/

    return plaintextByteArrayOutputStream.toByteArray();
}

From source file:org.structr.core.graph.SyncCommand.java

public static void serialize(DataOutputStream outputStream, Object obj) throws IOException {

    if (obj != null) {

        Class clazz = obj.getClass();
        Byte type = typeMap.get(clazz);

        if (type != null) {

            if (clazz.isArray()) {

                Object[] array = (Object[]) obj;

                outputStream.writeByte(type);
                outputStream.writeInt(array.length);

                // serialize array
                for (Object o : (Object[]) obj) {
                    serialize(outputStream, o);
                }/*from   www.  j a  v  a 2s.  c  o  m*/

            } else {

                outputStream.writeByte(type);
                writeObject(outputStream, type, obj);

                //outputStream.writeUTF(obj.toString());
            }

        } else {

            logger.log(Level.WARNING, "Unable to serialize object of type {0}, type not supported",
                    obj.getClass());
        }

    } else {

        // null value
        outputStream.writeByte((byte) 127);
    }

    outputStream.flush();
}

From source file:org.chromium.chrome.browser.tabmodel.TabPersistentStore.java

/**
 * Serializes data from a {@link TabModelSelector} into a byte array.
 * @param standardInfo      Info about the regular {@link TabModel}.
 * @param incognitoInfo     Info about the Incognito {@link TabModel}.
 * @param tabsBeingRestored Tabs that are in the process of being restored.
 * @return                  {@code byte[]} containing the serialized state of {@code selector}.
 *//*from  w w w.ja  v a 2s  .com*/
public static byte[] serializeMetadata(TabModelMetadata standardInfo, TabModelMetadata incognitoInfo,
        @Nullable List<TabRestoreDetails> tabsBeingRestored) throws IOException {
    ThreadUtils.assertOnUiThread();

    int standardCount = standardInfo.ids.size();
    int incognitoCount = incognitoInfo.ids.size();

    // Determine how many Tabs there are, including those not yet been added to the TabLists.
    int numAlreadyLoaded = incognitoCount + standardCount;
    int numStillBeingLoaded = tabsBeingRestored == null ? 0 : tabsBeingRestored.size();
    int numTabsTotal = numStillBeingLoaded + numAlreadyLoaded;

    // Save the index file containing the list of tabs to restore.
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    DataOutputStream stream = new DataOutputStream(output);
    stream.writeInt(SAVED_STATE_VERSION);
    stream.writeInt(numTabsTotal);
    stream.writeInt(incognitoCount);
    stream.writeInt(incognitoInfo.index);
    stream.writeInt(standardInfo.index + incognitoCount);
    Log.d(TAG, "Serializing tab lists; counts: " + standardCount + ", " + incognitoCount + ", "
            + (tabsBeingRestored == null ? 0 : tabsBeingRestored.size()));

    // Save incognito state first, so when we load, if the incognito files are unreadable
    // we can fall back easily onto the standard selected tab.
    for (int i = 0; i < incognitoCount; i++) {
        stream.writeInt(incognitoInfo.ids.get(i));
        stream.writeUTF(incognitoInfo.urls.get(i));
    }
    for (int i = 0; i < standardCount; i++) {
        stream.writeInt(standardInfo.ids.get(i));
        stream.writeUTF(standardInfo.urls.get(i));
    }

    // Write out information about the tabs that haven't finished being loaded.
    // We shouldn't have to worry about Tab duplication because the tab details are processed
    // only on the UI Thread.
    if (tabsBeingRestored != null) {
        for (TabRestoreDetails details : tabsBeingRestored) {
            stream.writeInt(details.id);
            stream.writeUTF(details.url);
        }
    }

    stream.close();
    return output.toByteArray();
}

From source file:org.apache.hadoop.hbase.io.hfile.TestFixedFileTrailer.java

private void serializeAsWritable(DataOutputStream output, FixedFileTrailer fft) throws IOException {
    BlockType.TRAILER.write(output);/*from  w  w w. jav a2s.  c  om*/
    output.writeLong(fft.getFileInfoOffset());
    output.writeLong(fft.getLoadOnOpenDataOffset());
    output.writeInt(fft.getDataIndexCount());
    output.writeLong(fft.getUncompressedDataIndexSize());
    output.writeInt(fft.getMetaIndexCount());
    output.writeLong(fft.getTotalUncompressedBytes());
    output.writeLong(fft.getEntryCount());
    output.writeInt(fft.getCompressionCodec().ordinal());
    output.writeInt(fft.getNumDataIndexLevels());
    output.writeLong(fft.getFirstDataBlockOffset());
    output.writeLong(fft.getLastDataBlockOffset());
    Bytes.writeStringFixedSize(output, fft.getComparatorClassName(), MAX_COMPARATOR_NAME_LENGTH);
    output.writeInt(FixedFileTrailer.materializeVersion(fft.getMajorVersion(), fft.getMinorVersion()));
}

From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java

private static byte[] createTcpMessage(byte[] msg) throws IOException {
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bao);
    // 0 is pkiReq
    int msgType = 0;
    int len = msg.length;
    // return msg length = msg.length + 3; 1 byte version, 1 byte flags and
    // 1 byte message type
    dos.writeInt(len + 3);
    dos.writeByte(10);/*from   ww w.j a v  a 2 s. c  o m*/
    dos.writeByte(0); // 1 if we should close, 0 otherwise
    dos.writeByte(msgType);
    dos.write(msg);
    dos.flush();
    return bao.toByteArray();
}

From source file:org.xenei.bloomgraph.SerializableNode.java

/**
 * write string to the output. Writes the length first then the data. writes
 * -1 for a null. Data are encodes as UTF-8.
 * //w  w w.jav  a2s  . c o  m
 * @param os
 *            The output to write to
 * @param s
 *            The string to write.
 * @throws IOException
 */
private void write(DataOutputStream os, String s) throws IOException {
    if (s == null) {
        os.writeInt(-1);
    } else {
        byte[] b = encodeString(s);
        os.writeInt(b.length);
        if (b.length > 0) {
            os.write(b);
        }
    }
}

From source file:org.apache.apex.malhar.lib.function.FunctionOperator.java

private byte[] functionClassData(Function f) {
    Class<? extends Function> classT = f.getClass();

    byte[] classBytes = null;
    byte[] classNameBytes = null;
    String className = classT.getName();
    try {/* w  w  w  . j  av a  2  s  . c o  m*/
        classNameBytes = className.replace('.', '/').getBytes();
        classBytes = IOUtils.toByteArray(
                classT.getClassLoader().getResourceAsStream(className.replace('.', '/') + ".class"));
        int cursor = 0;
        for (int j = 0; j < classBytes.length; j++) {
            if (classBytes[j] != classNameBytes[cursor]) {
                cursor = 0;
            } else {
                cursor++;
            }

            if (cursor == classNameBytes.length) {
                for (int p = 0; p < classNameBytes.length; p++) {
                    if (classBytes[j - p] == '$') {
                        classBytes[j - p] = '_';
                    }
                }
                cursor = 0;
            }
        }
        ClassReader cr = new ClassReader(new ByteArrayInputStream(classBytes));
        ClassWriter cw = new ClassWriter(0);
        AnnonymousClassModifier annonymousClassModifier = new AnnonymousClassModifier(Opcodes.ASM4, cw);
        cr.accept(annonymousClassModifier, 0);
        classBytes = cw.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    int dataLength = classNameBytes.length + 4 + 4;

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(dataLength);
    DataOutputStream output = new DataOutputStream(byteArrayOutputStream);

    try {
        output.writeInt(classNameBytes.length);
        output.write(className.replace('$', '_').getBytes());
        output.writeInt(classBytes.length);
        output.write(classBytes);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            output.flush();
            output.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    return byteArrayOutputStream.toByteArray();

}

From source file:ReadWriteStreams.java

public void writeStream(String[] sData, boolean[] bData, int[] iData) {
    try {/*w  ww.j a  v a 2s. com*/
        // Write data into an internal byte array
        ByteArrayOutputStream strmBytes = new ByteArrayOutputStream();

        // Write Java data types into the above byte array
        DataOutputStream strmDataType = new DataOutputStream(strmBytes);

        byte[] record;

        for (int i = 0; i < sData.length; i++) {
            // Write Java data types      
            strmDataType.writeUTF(sData[i]);
            strmDataType.writeBoolean(bData[i]);
            strmDataType.writeInt(iData[i]);

            // Clear any buffered data
            strmDataType.flush();

            // Get stream data into byte array and write record
            record = strmBytes.toByteArray();
            rs.addRecord(record, 0, record.length);

            // Toss any data in the internal array so writes 
            // starts at beginning (of the internal array)
            strmBytes.reset();
        }

        strmBytes.close();
        strmDataType.close();

    } catch (Exception e) {
        db(e.toString());
    }
}

From source file:org.structr.core.graph.SyncCommand.java

private static void writeObject(final DataOutputStream outputStream, final byte type, final Object value)
        throws IOException {

    switch (type) {

    case 0:/*from  ww  w  . j  a  v  a 2  s. co  m*/
    case 1:
        outputStream.writeByte((byte) value);
        break;

    case 2:
    case 3:
        outputStream.writeShort((short) value);
        break;

    case 4:
    case 5:
        outputStream.writeInt((int) value);
        break;

    case 6:
    case 7:
        outputStream.writeLong((long) value);
        break;

    case 8:
    case 9:
        outputStream.writeFloat((float) value);
        break;

    case 10:
    case 11:
        outputStream.writeDouble((double) value);
        break;

    case 12:
    case 13:
        outputStream.writeChar((char) value);
        break;

    case 14:
    case 15:
        serializeData(outputStream, ((String) value).getBytes("UTF-8"));

        // this doesn't work with very long strings
        //outputStream.writeUTF((String)value);
        break;

    case 16:
    case 17:
        outputStream.writeBoolean((boolean) value);
        break;
    }
}

From source file:com.msopentech.thali.utilities.universal.HttpKeySocksProxyClientConnOperator.java

@Override
public void openConnection(final OperatedClientConnection conn, final HttpHost target, final InetAddress local,
        final HttpContext context, final HttpParams params) throws IOException {
    Socket socket = null;/*from  w  w  w .jav a2s  . co m*/
    Socket sslSocket = null;
    try {
        if (conn == null || target == null || params == null) {
            throw new IllegalArgumentException("Required argument may not be null");
        }
        if (conn.isOpen()) {
            throw new IllegalStateException("Connection must not be open");
        }

        // The original NetCipher code uses a SchemeSocketFactory class that isn't supported by the version
        // of Apache that ships standard with Android. It also doesn't support the layered socket factory
        // interface either. We work around this later on but for now we just get our HttpKeySSLSocketFactory
        Scheme scheme = schemeRegistry.getScheme(target.getSchemeName());
        HttpKeySSLSocketFactory httpKeySSLSocketFactory = (HttpKeySSLSocketFactory) scheme.getSocketFactory();

        int port = scheme.resolvePort(target.getPort());
        String host = target.getHostName();

        // Perform explicit SOCKS4a connection request. SOCKS4a supports remote host name resolution
        // (i.e., Tor resolves the hostname, which may be an onion address).
        // The Android (Apache Harmony) Socket class appears to support only SOCKS4 and throws an
        // exception on an address created using INetAddress.createUnresolved() -- so the typical
        // technique for using Java SOCKS4a/5 doesn't appear to work on Android:
        // https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/java/net/PlainSocketImpl.java
        // See also: http://www.mit.edu/~foley/TinFoil/src/tinfoil/TorLib.java, for a similar implementation

        // From http://en.wikipedia.org/wiki/SOCKS#SOCKS4a:
        //
        // field 1: SOCKS version number, 1 byte, must be 0x04 for this version
        // field 2: command code, 1 byte:
        //     0x01 = establish a TCP/IP stream connection
        //     0x02 = establish a TCP/IP port binding
        // field 3: network byte order port number, 2 bytes
        // field 4: deliberate invalid IP address, 4 bytes, first three must be 0x00 and the last one must not be 0x00
        // field 5: the user ID string, variable length, terminated with a null (0x00)
        // field 6: the domain name of the host we want to contact, variable length, terminated with a null (0x00)

        socket = new Socket();
        conn.opening(socket, target);
        socket.setSoTimeout(READ_TIMEOUT_MILLISECONDS);
        socket.connect(proxy.address(), CONNECT_TIMEOUT_MILLISECONDS);

        DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
        outputStream.write((byte) 0x04);
        outputStream.write((byte) 0x01);
        outputStream.writeShort((short) port);
        outputStream.writeInt(0x01);
        outputStream.write((byte) 0x00);
        outputStream.write(host.getBytes());
        outputStream.write((byte) 0x00);

        DataInputStream inputStream = new DataInputStream(socket.getInputStream());
        if (inputStream.readByte() != (byte) 0x00 || inputStream.readByte() != (byte) 0x5a) {
            throw new IOException("SOCKS4a connect failed");
        }
        inputStream.readShort();
        inputStream.readInt();

        // In the NetCipher code we cast to SchemeLayeredSocketFactory and call createLayeredSocket which amongst
        // other things takes 'params' as an argument. But none of this is supported in Android. When I looked in
        // Java at what createLayeredSocket was actually doing it was just calling createSocket with exactly the
        // arguments used below (it ignored params completely). So we should be good.
        sslSocket = ((HttpKeySSLSocketFactory) httpKeySSLSocketFactory).createSocket(socket, host, port, true);
        conn.opening(sslSocket, target);
        sslSocket.setSoTimeout(READ_TIMEOUT_MILLISECONDS);
        prepareSocket(sslSocket, context, params);
        conn.openCompleted(httpKeySSLSocketFactory.isSecure(sslSocket), params);
        // TODO: clarify which connection throws java.net.SocketTimeoutException?
    } catch (IOException e) {
        try {
            if (sslSocket != null) {
                sslSocket.close();
            }
            if (socket != null) {
                socket.close();
            }
        } catch (IOException ioe) {
        }
        throw e;
    }
}