Example usage for java.io DataOutputStream DataOutputStream

List of usage examples for java.io DataOutputStream DataOutputStream

Introduction

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

Prototype

public DataOutputStream(OutputStream out) 

Source Link

Document

Creates a new data output stream to write data to the specified underlying output stream.

Usage

From source file:edu.cornell.med.icb.goby.counts.TestCountsReader.java

@Before
public void createCounts() throws IOException {
    ByteArrayOutputStream stream = new ByteArrayOutputStream(100000);
    ByteArrayOutputStream indexByteArrayOutputStream = new ByteArrayOutputStream(100000);
    DataOutput indexOutput = new DataOutputStream(indexByteArrayOutputStream);
    CountsWriterI writerI = new CountsWriter(stream);
    writerI.appendCount(0, 10); // before- Position=0  count-after=0
    writerI.appendCount(1, 10); // before- Position=10
    writerI.appendCount(2, 10); // before- Position=20
    writerI.appendCount(3, 10); // before- Position=30    count-after=3
    writerI.appendCount(10, 10); // before- Position=40   count-after=10
    writerI.appendCount(11, 10); // before- Position=50   count-after=11
    writerI.appendCount(9, 10); // before- Position=60
    writerI.appendCount(7, 10); // before- Position=70
    writerI.close();//from  www  .j ava  2  s . c  om

    byte[] bytes = stream.toByteArray();
    CountIndexBuilder indexBuilder = new CountIndexBuilder(1);
    indexBuilder.buildIndex(bytes, indexOutput);
    byte[] bytes1 = indexByteArrayOutputStream.toByteArray();

    reader = new CountsReader(new FastByteArrayInputStream(bytes),
            new DataInputStream(new ByteArrayInputStream(bytes1)));

}

From source file:yodlee.ysl.api.io.HTTP.java

public static String doPostUser(String url, Map<String, String> sessionTokens, String requestBody,
        boolean isEncodingNeeded) throws IOException {
    String mn = "doIO(POST : " + url + ", " + requestBody + "sessionTokens : " + sessionTokens + " )";
    System.out.println(fqcn + " :: " + mn);
    URL restURL = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("User-Agent", userAgent);
    if (isEncodingNeeded)
        //conn.setRequestProperty("Content-Type", contentTypeURLENCODED);
        conn.setRequestProperty("Content-Type", contentTypeJSON);
    else/*from   w  w w.  j  a  va  2s.  co  m*/
        conn.setRequestProperty("Content-Type", "text/plain;charset=UTF-8");

    conn.setRequestProperty("Authorization", sessionTokens.toString());
    conn.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(requestBody);
    wr.flush();
    wr.close();
    int responseCode = conn.getResponseCode();
    System.out.println(fqcn + " :: " + mn + " : " + "Sending 'HTTP POST' request");
    System.out.println(fqcn + " :: " + mn + " : " + "Response Code : " + responseCode);
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuilder jsonResponse = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        jsonResponse.append(inputLine);
    }
    in.close();
    System.out.println(fqcn + " :: " + mn + " : " + jsonResponse.toString());
    return new String(jsonResponse);
}

From source file:ml.shifu.shifu.util.IndependentTreeModelUtils.java

public boolean convertBinaryToZipSpec(File treeModelFile, File outputZipFile) {
    FileInputStream treeModelInputStream = null;
    ZipOutputStream zipOutputStream = null;

    try {//from w w w.  j  a v  a  2  s.c o  m
        treeModelInputStream = new FileInputStream(treeModelFile);
        IndependentTreeModel treeModel = IndependentTreeModel.loadFromStream(treeModelInputStream);
        List<List<TreeNode>> trees = treeModel.getTrees();
        treeModel.setTrees(null);
        if (CollectionUtils.isEmpty(trees)) {
            logger.error("No trees found in the tree model.");
            return false;
        }

        zipOutputStream = new ZipOutputStream(new FileOutputStream(outputZipFile));

        ZipEntry modelEntry = new ZipEntry(MODEL_CONF);
        zipOutputStream.putNextEntry(modelEntry);
        ByteArrayOutputStream byos = new ByteArrayOutputStream();
        JSONUtils.writeValue(new OutputStreamWriter(byos), treeModel);
        zipOutputStream.write(byos.toByteArray());
        IOUtils.closeQuietly(byos);

        ZipEntry treesEntry = new ZipEntry(MODEL_TREES);
        zipOutputStream.putNextEntry(treesEntry);
        DataOutputStream dataOutputStream = new DataOutputStream(zipOutputStream);
        dataOutputStream.writeInt(trees.size());
        for (List<TreeNode> forest : trees) {
            dataOutputStream.writeInt(forest.size());
            for (TreeNode treeNode : forest) {
                treeNode.write(dataOutputStream);
            }
        }
        IOUtils.closeQuietly(dataOutputStream);
    } catch (IOException e) {
        logger.error("Error occurred when convert the tree model to zip format.", e);
        return false;
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
        IOUtils.closeQuietly(treeModelInputStream);
    }

    return true;
}

From source file:edu.cornell.med.icb.goby.alignments.perms.PermutationWriter.java

public PermutationWriter(final String basename) {
    this.basename = AlignmentReaderImpl.getBasename(basename);
    DataOutputStream o = null;/*from  w ww . j  a v a 2  s . c  om*/
    try {
        o = new DataOutputStream(new FastBufferedOutputStream(new FileOutputStream(basename + ".perm")));

    } catch (FileNotFoundException e) {
        LOG.error(e);
        o = null;
    }
    output = o;

}

From source file:ioc.wiki.processingmanager.http.HttpFileSender.java

/**
 * Prepara la comanda a enviar al servidor, l'envia i rep la resposta en un string.
 * Cont informaci sobre el xit de guardar el fitxer al servidor.
 * @return Retorna un string amb la resposta del servidor. 
 *//*from  w w w  . j a  va 2  s.c  o m*/
@Override
public String sendCommand() {
    super.prepareCommand();
    try {

        ((HttpURLConnection) urlConnection).setRequestMethod(REQUEST_METHOD);
        urlConnection.setRequestProperty(PROPERTY_CONTENT_TYPE, content_type + boundary);
        DataOutputStream request = new DataOutputStream(urlConnection.getOutputStream());
        //Capalera fitxer

        request.writeBytes(twoHyphens + boundary + crlf);
        request.writeBytes(contentDispositionFile + quote + this.destFilename + quote + crlf);
        request.writeBytes(contentTypeFile + crlf);
        request.writeBytes(contentTransferEncodingFile + crlf);
        request.writeBytes(crlf);

        //IMAGE
        String base64Image = Base64.encodeBase64String(this.image);
        request.writeBytes(base64Image);

        //Tancament fitxer
        request.writeBytes(crlf);
        request.writeBytes(twoHyphens + boundary + twoHyphens + crlf);

        request.flush();
        request.close();

    } catch (IOException ex) {
        throw new ProcessingRtURLException(ex);
    }

    return super.receiveResponse();
}

From source file:com.alibaba.dragoon.common.protocol.transport.socket.SocketSessionImpl.java

public SocketSessionImpl(Socket socket, AtomicLong receivedBytes, AtomicLong receivedMessages,
        AtomicLong sentBytes, AtomicLong sentMessages) {
    super();/*from w w  w  . j  a v  a 2s.  c o m*/
    this.socket = socket;
    state = State.Established;

    this.receivedBytes = receivedBytes;
    this.receivedMessages = receivedMessages;
    this.sentBytes = sentBytes;
    this.sentMessages = sentMessages;

    try {
        dataInput = new DataInputStream(socket.getInputStream());
        writer = new DataOutputStream(socket.getOutputStream());
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException(e.getMessage(), e);
    } catch (IOException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:net.namecoin.NameCoinI2PResolver.HttpSession.java

public String executePost(String postdata) throws HttpSessionException {
    URL url;//from  ww  w  .jav  a  2s  .c o  m
    HttpURLConnection connection = null;
    try {
        //Create connection
        url = new URL(this.uri);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", POST_CONTENT_TYPE);
        connection.setRequestProperty("User-Agent", "java");

        if (!this.user.isEmpty() && !this.password.isEmpty()) {
            String authString = this.user + ":" + this.password;
            String authStringEnc = Base64.encodeBytes(authString.getBytes());
            connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        }

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(postdata);
        wr.flush();
        wr.close();

        //Get Response
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }

        rd.close();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new HttpSessionException("Server returned: " + connection.getResponseMessage());
        }

        return response.toString();

    } catch (Exception e) {
        throw new HttpSessionException(e.getMessage());
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.evilco.license.server.encoder.CompressedLicenseEncoder.java

/**
 * {@inheritDoc}/*from ww w  . ja v  a2  s.  co m*/
 */
@Override
public String encode(@Nonnull ILicense license) throws LicenseEncoderException {
    // define streams
    ByteArrayOutputStream outputStream = null;
    GZIPOutputStream gzipOutputStream = null;
    DataOutputStream dataOutputStream = null;

    // encode data
    try {
        // create stream instances
        outputStream = new ByteArrayOutputStream();
        gzipOutputStream = new GZIPOutputStream(outputStream);
        dataOutputStream = new DataOutputStream(gzipOutputStream);

        // encode data
        this.childEncoder.encode(license, dataOutputStream);

        // flush buffers
        gzipOutputStream.flush();
        outputStream.flush();
    } catch (IOException ex) {
        throw new LicenseEncoderException(ex);
    } finally {
        IOUtils.closeQuietly(dataOutputStream);
        IOUtils.closeQuietly(gzipOutputStream);
        IOUtils.closeQuietly(outputStream);
    }

    // Encode Base64
    String licenseText = BaseEncoding.base64().encode(outputStream.toByteArray());

    // split text into chunks
    Joiner joiner = Joiner.on("\n").skipNulls();
    return joiner.join(Splitter.fixedLength(LICENSE_CHUNK_WIDTH).split(licenseText));
}

From source file:de.burlov.ultracipher.core.Database.java

public String computeChecksum() {
    DigestOutputStream digest = new DigestOutputStream(new RIPEMD160Digest());
    DataOutputStream out = new DataOutputStream(digest);

    try {/*ww w. ja  va  2s.  c o m*/
        for (Entry<String, Long> entry : deletedEntries.entrySet()) {
            out.writeUTF(entry.getKey());
            out.writeLong(entry.getValue());
        }
        for (DataEntry entry : entries.values()) {
            out.writeUTF(entry.getId());
            out.writeUTF(entry.getName());
            out.writeUTF(entry.getTags());
            out.writeUTF(entry.getText());
        }
        out.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return new String(Hex.encode(digest.getDigest()));
}

From source file:com.appassit.common.Utils.java

/**
 * <p>//  w  ww . j ava 2s  . c o  m
 * Get UTF8 bytes from a string
 * </p>
 * 
 * @param string
 *            String
 * @return UTF8 byte array, or null if failed to get UTF8 byte array
 */
public static byte[] getUTF8Bytes(String string) {
    if (string == null)
        return new byte[0];

    try {
        return string.getBytes(ENCODING_UTF8);
    } catch (UnsupportedEncodingException e) {
        /*
         * If system doesn't support UTF-8, use another way
         */
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(bos);
            dos.writeUTF(string);
            byte[] jdata = bos.toByteArray();
            bos.close();
            dos.close();
            byte[] buff = new byte[jdata.length - 2];
            System.arraycopy(jdata, 2, buff, 0, buff.length);
            return buff;
        } catch (IOException ex) {
            return new byte[0];
        }
    }
}