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.momock.http.HttpSession.java

void writeHeaders() {
    try {/*from  w  w w  .j  a v a2  s  .  c  o  m*/
        DataOutputStream dout = new DataOutputStream(new FileOutputStream(fileInfo));
        int headerCount = headers.size();
        dout.writeInt(headerCount);
        for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
            String key = entry.getKey();
            List<String> values = entry.getValue();
            dout.writeUTF(key);
            dout.writeInt(values.size());
            for (String value : values) {
                dout.writeUTF(value);
            }
        }
        dout.close();
    } catch (IOException e) {
        Logger.error(e);
    }
}

From source file:edu.cornell.med.icb.goby.compression.HybridChunkCodec2.java

@Override
public ByteArrayOutputStream encode(final Message readCollection) throws IOException {
    if (readCollection == null) {
        return null;
    }//from  w  w w  .  jav  a2  s .  c om
    final ByteArrayOutputStream result = new ByteArrayOutputStream();
    final DataOutputStream completeChunkData = new DataOutputStream(result);
    final ByteArrayOutputStream hybridStreamBytes = new ByteArrayOutputStream();
    final Message reducedProtoBuff = handler.compressCollection(readCollection, hybridStreamBytes);

    final int hybridStreamSize = hybridStreamBytes.size();
    final byte[] bytes = hybridStreamBytes.toByteArray();

    crc32.reset();
    crc32.update(bytes);
    final int crcChecksum = (int) crc32.getValue();
    completeChunkData.writeInt(hybridStreamSize);
    completeChunkData.writeInt(crcChecksum);
    completeChunkData.write(bytes);

    final ByteArrayOutputStream out = bzip2Codec.encode(reducedProtoBuff);

    final byte[] gzipBytes = out.toByteArray();
    final int gzipBytesSize = gzipBytes.length;
    completeChunkData.write(gzipBytes);
    completeChunkData.flush();
    if (debug && chunkIndex % 100 == 0) {

        //TODO remove compression of original collection. Only useful for stat collection
        final int originalBZip2Size = bzip2Codec.encode(readCollection).toByteArray().length;

        final int gain = originalBZip2Size - (gzipBytesSize + hybridStreamSize);
        LOG.info(String.format(
                "compressed size=%d gzip size=%d (original gzip=%d) percent compressed/(compressed+gzip) %g gain=%d, %g%% ",
                hybridStreamSize, gzipBytesSize, originalBZip2Size,
                100d * ((double) hybridStreamSize) / (hybridStreamSize + gzipBytesSize), gain,
                gain * 100d / originalBZip2Size));

    }
    chunkIndex++;
    return result;
}

From source file:edu.cornell.med.icb.goby.compression.HybridChunkCodec1.java

@Override
public ByteArrayOutputStream encode(final Message readCollection) throws IOException {
    if (readCollection == null) {
        return null;
    }//from  w  w w.j a v a 2  s.com
    final ByteArrayOutputStream result = new ByteArrayOutputStream();
    final DataOutputStream completeChunkData = new DataOutputStream(result);
    final ByteArrayOutputStream hybridStreamBytes = new ByteArrayOutputStream();
    final Message reducedProtoBuff = handler.compressCollection(readCollection, hybridStreamBytes);

    final int hybridStreamSize = hybridStreamBytes.size();
    final byte[] bytes = hybridStreamBytes.toByteArray();

    crc32.reset();
    crc32.update(bytes);
    final int crcChecksum = (int) crc32.getValue();
    completeChunkData.writeInt(hybridStreamSize);
    completeChunkData.writeInt(crcChecksum);
    completeChunkData.write(bytes);

    final ByteArrayOutputStream out = gzipCodec.encode(reducedProtoBuff);

    final byte[] gzipBytes = out.toByteArray();
    final int gzipBytesSize = gzipBytes.length;
    completeChunkData.write(gzipBytes);
    completeChunkData.flush();
    if (debug && chunkIndex % 100 == 0) {

        //TODO remove compression of original collection. Only useful for stat collection
        int originalGzipSize = gzipCodec.encode(readCollection).toByteArray().length;

        final int gain = originalGzipSize - (gzipBytesSize + hybridStreamSize);
        LOG.info(String.format(
                "compressed size=%d gzip size=%d (original gzip=%d) percent compressed/(compressed+gzip) %g gain=%d, %g%% ",
                hybridStreamSize, gzipBytesSize, originalGzipSize,
                100d * ((double) hybridStreamSize) / (hybridStreamSize + gzipBytesSize), gain,
                gain * 100d / originalGzipSize));

    }
    chunkIndex++;
    return result;
}

From source file:br.com.anteros.android.synchronism.communication.HttpConnectionClient.java

public MobileResponse sendReceiveData(MobileRequest mobileRequest) {
    sessionId = HttpConnectionSession.getInstance().getSessionId();

    add(mobileRequest.getFormattedHeader(), mobileRequest.getFormatedActions());
    MobileResponse mobileResponse = new MobileResponse();
    try {//w ww  .j a  va2  s.  c  om
        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onWaitServer();
        }

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onStatusConnectionServer("Conectando Servidor...");
        }

        /*
         * Define url e estabelece conexo
         */

        HttpPost httpPost = new HttpPost(url);

        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is
        // established.
        // The default value is zero, that means the timeout is not used.
        HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT_CONNECTION);
        // Set the default socket timeout (SO_TIMEOUT)
        // in milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setSoTimeout(httpParameters, TIMEOUT_SOCKET);

        if (httpClient == null)
            httpClient = new DefaultHttpClient(httpParameters);

        //

        /*
         * Setar o cookie da sesso
         */
        if ((sessionId != null) && (!"".equals(sessionId))) {
            httpPost.setHeader("Cookie", "JSESSIONID=" + sessionId);
        }
        httpPost.setHeader("User-Agent", "Android");
        httpPost.setHeader("Accept-Encoding", "gzip");

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onStatusConnectionServer("Enviando requisio...");
        }

        //
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream out = new DataOutputStream(baos);
        //

        /*
         * Escrever no output
         */
        out.writeInt(numOption);
        String aux[];
        for (int i = 0; i < opPOST.size(); i++) {
            aux = (String[]) opPOST.get(i);

            out.writeUTF(aux[0]);

            byte[] b = aux[1].getBytes();
            out.writeInt(b.length);
            out.write(b);

            aux = null;
        }
        out.flush();

        ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray());
        entity.setContentEncoding("UTF-8");
        httpPost.setEntity(entity);
        httpPost.addHeader("Connection", "Keep-Alive");
        httpPost.addHeader("Keep-Alive", "timeout=120000");

        out.close();
        //

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onStatusConnectionServer("Recebendo dados...");
        }

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onDebugMessage("Recebendo dados conexo");
        }

        /*
         * Aguardar resposta
         */
        HttpResponse httpResponse = httpClient.execute(httpPost);
        List result = null;
        StatusLine statusLine = httpResponse.getStatusLine();
        int code = statusLine.getStatusCode();
        if (code != 200) {
            String msg = "Erro RECEBENDO resposta do Servidor " + url + " - Cdigo do Erro HTTP " + code + "-"
                    + statusLine.getReasonPhrase();
            mobileResponse.setStatus(msg);
        } else {
            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onStatusConnectionServer("Resposta OK !");
            }

            /*
             * Ler cookie
             */
            String tmpSessionId = null;

            for (Cookie c : httpClient.getCookieStore().getCookies()) {
                if ("JSESSIONID".equals(c.getName())) {
                    tmpSessionId = c.getValue();
                }
            }

            if (tmpSessionId != null) {
                sessionId = tmpSessionId;
                HttpConnectionSession.getInstance().setSessionId(sessionId);
            }
            //

            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onStatusConnectionServer("Lendo dados...");
            }

            /*
             * Le os dados
             */
            HttpEntity entityResponse = httpResponse.getEntity();
            InputStream in = AndroidHttpClient.getUngzippedContent(entityResponse);

            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));

            String content = null;

            content = reader.readLine();
            String line = null;
            while ((line = reader.readLine()) != null) {
                content += line;
            }
            line = "";

            reader.close();
            reader = null;
            in.close();
            in = null;
            entityResponse.consumeContent();
            entityResponse = null;
            //

            StringTokenizer messagePart = new StringTokenizer(content, "#");
            content = null;

            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onDebugMessage("RECEBEU dados conexo");
            }

            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onStatusConnectionServer("Processando resposta... ");
            }

            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onDebugMessage("Converteu string dados conexo");
            }

            while (messagePart.hasMoreTokens()) {
                String resultData = messagePart.nextToken();
                resultData = resultData.substring(resultData.indexOf("*") + 1, resultData.length());
                if (result == null)
                    result = formatData(resultData);
                else
                    result.addAll(formatData(resultData));
            }
            messagePart = null;
        }

        if (result != null) {
            mobileResponse.setFormattedParameters(result);
            result.clear();
            result = null;
        }

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onEndServer();
        }

    } catch (SocketTimeoutException exTimeout) {
        exTimeout.printStackTrace();
        wrapException(mobileResponse, "No foi possvel CONECTAR ao Servidor " + url
                + ". Verifique sua conexo e se o servidor est em funcionamento.");
    } catch (Exception e) {
        e.printStackTrace();
        if ((e.getMessage() + "").contains("unreachable"))
            wrapException(mobileResponse,
                    "Voc est sem acesso a internet. Verifique sua conexo. No foi possvel conectar ao servidor  "
                            + url);
        else
            wrapException(mobileResponse,
                    "No foi possivel CONECTAR ao Servidor " + url + " " + e.getMessage());
    }
    return mobileResponse;
}

From source file:com.chaosinmotion.securechat.server.messages.NotificationSocket.java

/**
 * Internal method for sending a message to the specified device. This
 * encodes the message as a binary array and transmits it as a single 
 * packet to the listening device. This allows users to receive messages
 * during chat as soon as we are able to, for (more or less) just in time
 * messaging.//w w w .j  a v  a2  s .  co m
 * 
 * The packet returned here is similar to the packet returned by the
 * getmessages api, except we serialize as binary.
 * 
 * @param messageid
 * @param senderid
 * @param sendername
 * @param ts
 * @param message
 * @throws IOException 
 */
void sendMessage(int messageid, int senderid, String sendername, boolean toflag, Timestamp ts, byte[] message)
        throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);

    /*
     * Encode. First byte is 0x20
     */

    String date;
    synchronized (format) {
        date = format.format(ts);
    }

    /*
     * Formulate packet in expected format
     */
    dos.writeByte(0x20); // marker
    dos.writeBoolean(toflag);
    dos.writeInt(messageid);
    dos.writeInt(senderid);
    dos.writeUTF(date);
    dos.writeUTF(sendername);
    dos.writeInt(message.length);
    dos.write(message);

    /*
     * Flush and write packet to device. Our protocol does not depend on
     * the device actually receiving this message, as we wait until the
     * device deletes the messages by a separate command.
     */
    dos.flush();
    out.writeData(baos.toByteArray());
}

From source file:com.facebook.infrastructure.db.SuperColumn.java

public void serialize(IColumn column, DataOutputStream dos) throws IOException {
    SuperColumn superColumn = (SuperColumn) column;
    dos.writeUTF(superColumn.name());/* ww w  . j  a  va 2  s .co  m*/
    dos.writeLong(superColumn.getMarkedForDeleteAt());

    Collection<IColumn> columns = column.getSubColumns();
    int size = columns.size();
    dos.writeInt(size);

    /*
     * Add the total size of the columns. This is useful
     * to skip over all the columns in this super column
     * if we are not interested in this super column.
    */
    dos.writeInt(superColumn.getSizeOfAllColumns());
    // dos.writeInt(superColumn.size());

    for (IColumn subColumn : columns) {
        Column.serializer().serialize(subColumn, dos);
    }
}

From source file:org.apache.hadoop.hdfs.protocol.datatransfer.sasl.SaslDataTransferClient.java

/**
 * This method actually executes the client-side SASL handshake.
 *
 * @param underlyingOut connection output stream
 * @param underlyingIn connection input stream
 * @param userName SASL user name/*from  w w w.j  a v a2s.co m*/
 * @param saslProps properties of SASL negotiation
 * @param callbackHandler for responding to SASL callbacks
 * @return new pair of streams, wrapped after SASL negotiation
 * @throws IOException for any error
 */
private IOStreamPair doSaslHandshake(OutputStream underlyingOut, InputStream underlyingIn, String userName,
        Map<String, String> saslProps, CallbackHandler callbackHandler) throws IOException {

    DataOutputStream out = new DataOutputStream(underlyingOut);
    DataInputStream in = new DataInputStream(underlyingIn);

    SaslParticipant sasl = SaslParticipant.createClientSaslParticipant(userName, saslProps, callbackHandler);

    out.writeInt(SASL_TRANSFER_MAGIC_NUMBER);
    out.flush();

    try {
        // Start of handshake - "initial response" in SASL terminology.
        sendSaslMessage(out, new byte[0]);

        // step 1
        byte[] remoteResponse = readSaslMessage(in);
        byte[] localResponse = sasl.evaluateChallengeOrResponse(remoteResponse);
        List<CipherOption> cipherOptions = null;
        if (requestedQopContainsPrivacy(saslProps)) {
            // Negotiate cipher suites if configured.  Currently, the only supported
            // cipher suite is AES/CTR/NoPadding, but the protocol allows multiple
            // values for future expansion.
            String cipherSuites = conf.get(DFS_ENCRYPT_DATA_TRANSFER_CIPHER_SUITES_KEY);
            if (cipherSuites != null && !cipherSuites.isEmpty()) {
                if (!cipherSuites.equals(CipherSuite.AES_CTR_NOPADDING.getName())) {
                    throw new IOException(String.format("Invalid cipher suite, %s=%s",
                            DFS_ENCRYPT_DATA_TRANSFER_CIPHER_SUITES_KEY, cipherSuites));
                }
                CipherOption option = new CipherOption(CipherSuite.AES_CTR_NOPADDING);
                cipherOptions = Lists.newArrayListWithCapacity(1);
                cipherOptions.add(option);
            }
        }
        sendSaslMessageAndNegotiationCipherOptions(out, localResponse, cipherOptions);

        // step 2 (client-side only)
        SaslResponseWithNegotiatedCipherOption response = readSaslMessageAndNegotiatedCipherOption(in);
        localResponse = sasl.evaluateChallengeOrResponse(response.payload);
        assert localResponse == null;

        // SASL handshake is complete
        checkSaslComplete(sasl, saslProps);

        CipherOption cipherOption = null;
        if (sasl.isNegotiatedQopPrivacy()) {
            // Unwrap the negotiated cipher option
            cipherOption = unwrap(response.cipherOption, sasl);
        }

        // If negotiated cipher option is not null, we will use it to create 
        // stream pair.
        return cipherOption != null ? createStreamPair(conf, cipherOption, underlyingOut, underlyingIn, false)
                : sasl.createStreamPair(out, in);
    } catch (IOException ioe) {
        sendGenericSaslErrorMessage(out, ioe.getMessage());
        throw ioe;
    }
}

From source file:se.llbit.math.Octree.java

/**
 * Serialize this octree to a data output stream
 * @param out/*from w w  w. j  a v a2s  .c  o  m*/
 * @throws IOException
 */
public void store(DataOutputStream out) throws IOException {
    out.writeInt(depth);
    root.store(out);
}

From source file:org.apache.jackrabbit.core.persistence.mem.InMemBundlePersistenceManager.java

/**
 * Writes the content of the hash maps stores to the file system.
 *
 * @throws Exception if an error occurs//from  w  w  w .j  a v  a  2 s .co  m
 */
public synchronized void storeContents() throws Exception {
    // write bundles
    FileSystemResource fsRes = new FileSystemResource(wspFS, BUNDLE_FILE_PATH);
    fsRes.makeParentDirs();
    BufferedOutputStream bos = new BufferedOutputStream(fsRes.getOutputStream());
    DataOutputStream out = new DataOutputStream(bos);

    try {
        out.writeInt(bundleStore.size()); // number of entries
        // entries
        for (NodeId id : bundleStore.keySet()) {
            out.writeUTF(id.toString()); // id

            byte[] data = bundleStore.get(id);
            out.writeInt(data.length); // data length
            out.write(data); // data
        }
    } finally {
        out.close();
    }

    // write references
    fsRes = new FileSystemResource(wspFS, REFS_FILE_PATH);
    fsRes.makeParentDirs();
    bos = new BufferedOutputStream(fsRes.getOutputStream());
    out = new DataOutputStream(bos);

    try {
        out.writeInt(refsStore.size()); // number of entries
        // entries
        for (NodeId id : refsStore.keySet()) {
            out.writeUTF(id.toString()); // target id

            byte[] data = refsStore.get(id);
            out.writeInt(data.length); // data length
            out.write(data); // data
        }
    } finally {
        out.close();
    }

    if (!useFileBlobStore) {
        // write blobs
        fsRes = new FileSystemResource(wspFS, BLOBS_FILE_PATH);
        fsRes.makeParentDirs();
        bos = new BufferedOutputStream(fsRes.getOutputStream());
        out = new DataOutputStream(bos);

        try {
            out.writeInt(blobs.size()); // number of entries
            // entries
            for (String id : blobs.keySet()) {
                out.writeUTF(id); // id
                byte[] data = blobs.get(id);
                out.writeInt(data.length); // data length
                out.write(data); // data
            }
        } finally {
            out.close();
        }
    }
}

From source file:org.prorefactor.refactor.PUB.java

private void writeVersion(DataOutputStream out) throws IOException {
    out.writeInt(LAYOUT_VERSION);
}