Example usage for java.io DataOutputStream write

List of usage examples for java.io DataOutputStream write

Introduction

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

Prototype

public synchronized void write(int b) throws IOException 

Source Link

Document

Writes the specified byte (the low eight bits of the argument b) to the underlying output stream.

Usage

From source file:ClipboardExample.java

public void javaToNative(Object object, TransferData transferData) {
    if (!checkMyType(object) || !isSupportedType(transferData)) {
        DND.error(DND.ERROR_INVALID_DATA);
    }/*from   ww w  . j a v a2s . com*/
    MyType[] myTypes = (MyType[]) object;
    try {
        // write data to a byte array and then ask super to convert to
        // pMedium
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DataOutputStream writeOut = new DataOutputStream(out);
        for (int i = 0, length = myTypes.length; i < length; i++) {
            byte[] buffer = myTypes[i].firstName.getBytes();
            writeOut.writeInt(buffer.length);
            writeOut.write(buffer);
            buffer = myTypes[i].firstName.getBytes();
            writeOut.writeInt(buffer.length);
            writeOut.write(buffer);
        }
        byte[] buffer = out.toByteArray();
        writeOut.close();
        super.javaToNative(buffer, transferData);
    } catch (IOException e) {
    }
}

From source file:org.apache.hadoop.hdfs.tools.offlineImageViewer.TestOfflineImageViewer.java

private void changeLayoutVersion(File src, File dest, int newVersion) throws IOException {
    DataInputStream in = null;//from  w  ww. j  a v  a2 s  .c om
    DataOutputStream out = null;

    try {
        in = new DataInputStream(new FileInputStream(src));
        out = new DataOutputStream(new FileOutputStream(dest));

        in.readInt();
        out.writeInt(newVersion);

        byte[] b = new byte[1024];
        while (in.read(b) > 0) {
            out.write(b);
        }
    } finally {
        if (in != null)
            in.close();
        if (out != null)
            out.close();
    }
}

From source file:eu.vital.TrustManager.connectors.dms.DMSManager.java

private String queryDMSTest(String dms_endpoint, String body) throws UnsupportedEncodingException, IOException,
        KeyManagementException, NoSuchAlgorithmException, KeyStoreException {

    HttpURLConnection connection = null;
    // Of course everything will go over HTTPS (here we trust anything, we do not check the certificate)
    SSLContext sc = null;/*from w ww .j av  a2 s .  com*/
    try {
        sc = SSLContext.getInstance("TLS");
    } catch (NoSuchAlgorithmException e1) {

    }

    InputStream is;
    BufferedReader rd;
    char cbuf[] = new char[1000000];
    int len;

    String urlParameters = body; // test cookie is the user performing the evalaution
    // The array of resources to evaluate policies on must be included

    byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
    int postDataLength = postData.length;
    URL url = new URL(dms_URL + "/" + dms_endpoint);
    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");

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

        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.setRequestProperty("Cookie", cookie); // Include cookies (permissions evaluated for normal user, advanced user has the rights to evaluate)

        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.write(postData);
        wr.close();

        // Get Response
        int err = connection.getResponseCode();
        if (err >= 200 && err < 300) {

            is = connection.getInputStream();
            //             
            rd = new BufferedReader(new InputStreamReader(is));
            //                //StringBuilder rd2 = new StringBuilder();

            len = rd.read(cbuf);
            String resp2 = String.valueOf(cbuf).substring(0, len - 1);
            rd.close();
            return resp2;

            //            char[] buffer = new char[1024*1024];
            //            StringBuilder output = new StringBuilder();
            //            int readLength = 0;
            //            while (readLength != -1) {
            //                readLength = rd.read(buffer, 0, buffer.length);
            //                if (readLength != -1) {
            //                    output.append(buffer, 0, readLength);
            //                }
            //            }

            //                return output.toString();
        }

    } catch (Exception e) {
        throw new java.net.ConnectException();
        //log 
    } finally {
        if (connection != null) {
            connection.disconnect();

        }
    }
    return null;
}

From source file:com.haulmont.cuba.core.app.filestorage.amazon.AmazonS3FileStorage.java

@Override
public long saveStream(FileDescriptor fileDescr, InputStream inputStream) throws FileStorageException {
    Preconditions.checkNotNullArgument(fileDescr.getSize());

    int chunkSize = amazonS3Config.getChunkSize();
    long fileSize = fileDescr.getSize();
    URL amazonUrl = getAmazonUrl(fileDescr);
    // set the markers indicating we're going to send the upload as a series
    // of chunks:
    //   -- 'x-amz-content-sha256' is the fixed marker indicating chunked
    //      upload
    //   -- 'content-length' becomes the total size in bytes of the upload
    //      (including chunk headers),
    //   -- 'x-amz-decoded-content-length' is used to transmit the actual
    //      length of the data payload, less chunk headers
    Map<String, String> headers = new HashMap<>();
    headers.put("x-amz-storage-class", "REDUCED_REDUNDANCY");
    headers.put("x-amz-content-sha256", AWS4SignerForChunkedUpload.STREAMING_BODY_SHA256);
    headers.put("content-encoding", "aws-chunked");
    headers.put("x-amz-decoded-content-length", "" + fileSize);

    AWS4SignerForChunkedUpload signer = new AWS4SignerForChunkedUpload(amazonUrl, "PUT", "s3",
            amazonS3Config.getRegionName());

    // how big is the overall request stream going to be once we add the signature
    // 'headers' to each chunk?
    long totalLength = AWS4SignerForChunkedUpload.calculateChunkedContentLength(fileSize, chunkSize);
    headers.put("content-length", "" + totalLength);

    String authorization = signer.computeSignature(headers, null, // no query parameters
            AWS4SignerForChunkedUpload.STREAMING_BODY_SHA256, amazonS3Config.getAccessKey(),
            amazonS3Config.getSecretAccessKey());

    // place the computed signature into a formatted 'Authorization' header
    // and call S3
    headers.put("Authorization", authorization);

    // start consuming the data payload in blocks which we subsequently chunk; this prefixes
    // the data with a 'chunk header' containing signature data from the prior chunk (or header
    // signing, if the first chunk) plus length and other data. Each completed chunk is
    // written to the request stream and to complete the upload, we send a final chunk with
    // a zero-length data payload.

    try {//from  w w  w  .j av  a  2s. c om
        // first set up the connection
        HttpURLConnection connection = HttpUtils.createHttpConnection(amazonUrl, "PUT", headers);

        // get the request stream and start writing the user data as chunks, as outlined
        // above;
        int bytesRead;
        byte[] buffer = new byte[chunkSize];
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        //guarantees that it will read as many bytes as possible, this may not always be the case for
        //subclasses of InputStream
        while ((bytesRead = IOUtils.read(inputStream, buffer, 0, chunkSize)) > 0) {
            // process into a chunk
            byte[] chunk = signer.constructSignedChunk(bytesRead, buffer);

            // send the chunk
            outputStream.write(chunk);
            outputStream.flush();
        }

        // last step is to send a signed zero-length chunk to complete the upload
        byte[] finalChunk = signer.constructSignedChunk(0, buffer);
        outputStream.write(finalChunk);
        outputStream.flush();
        outputStream.close();

        // make the call to Amazon S3
        HttpUtils.HttpResponse httpResponse = HttpUtils.executeHttpRequest(connection);
        if (!httpResponse.isStatusOk()) {
            String message = String.format("Could not save file %s. %s", getFileName(fileDescr),
                    getInputStreamContent(httpResponse));
            throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, message);
        }
    } catch (IOException e) {
        throw new RuntimeException("Error when sending chunked upload request", e);
    }

    return fileDescr.getSize();
}

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. j  av 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;
    }//  w  w  w  .  java2 s. co  m
    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:bobs.is.compress.sevenzip.SevenZOutputFile.java

private void writeFileNames(final DataOutput header) throws IOException {
    header.write(NID.kName);//from w w  w  .j  a  v  a 2 s .c  o  m

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final DataOutputStream out = new DataOutputStream(baos);
    out.write(0);
    for (final SevenZArchiveEntry entry : files) {
        out.write(entry.getName().getBytes("UTF-16LE"));
        out.writeShort(0);
    }
    out.flush();
    final byte[] contents = baos.toByteArray();
    writeUint64(header, contents.length);
    header.write(contents);
}

From source file:org.apache.abdera.protocol.client.util.MultipartRelatedRequestEntity.java

private void writeInput(DataOutputStream out) throws IOException {
    if (contentType == null) {
        throw new NullPointerException("media content type can't be null");
    }/*  w w w.j  a  va  2 s .co m*/
    out.writeBytes("content-type: " + contentType + "\r\n");

    String contentId = entry.getContentSrc().toString();
    if (!contentId.matches("cid:.+")) {
        throw new IllegalArgumentException("entry content source is not a correct content-ID");
    }
    out.writeBytes("content-id: <" + contentId.substring(4) + ">\r\n\r\n");

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    while (input.read(buffer) != -1) {
        output.write(buffer);
    }

    Base64 base64 = new Base64();
    out.write(base64.encode(output.toByteArray()));
    out.writeBytes("\r\n" + "--" + boundary + "--");
}

From source file:com.polyvi.xface.extension.filetransfer.XFileTransferExt.java

/**
 * ?/*from   w  w  w  .  ja v a 2  s  .  c o  m*/
 * @param appWorkspace  ?
 * @param source        ?
 * @param target        ??
 * @param args          JSONArray
 * @param callbackCtx   nativejs
 *
 * args[2] fileKey       ?name file?
 * args[3] fileName      ??? image.jpg?
 * args[4] mimeType      ?mimeimage/jpeg?
 * args[5] params        HTTP????/
 * args[6] trustEveryone 
 * args[7] chunkedMode   ??????true
 * @return FileUploadResult
 */
private XExtensionResult upload(String appWorkspace, String source, String target, JSONArray args,
        XCallbackContext callbackCtx) {
    XLog.d(CLASS_NAME, "upload " + source + " to " + target);

    HttpURLConnection conn = null;
    try {
        String fileKey = getArgument(args, 2, "file");
        String fileName = getArgument(args, 3, "image.jpg");
        String mimeType = getArgument(args, 4, "image/jpeg");
        JSONObject params = args.optJSONObject(5);
        if (params == null) {
            params = new JSONObject();
        }
        boolean trustEveryone = args.optBoolean(6);
        boolean chunkedMode = args.optBoolean(7) || args.isNull(7);
        JSONObject headers = args.optJSONObject(8);
        if (headers == null && params != null) {
            headers = params.optJSONObject("headers");
        }
        String objectId = args.getString(9);
        //------------------ 
        URL url = new URL(target);
        conn = getURLConnection(url, trustEveryone);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);
        setCookieProperty(conn, target);
        // ??
        handleRequestHeader(headers, conn);
        byte[] extraBytes = extraBytesFromParams(params, fileKey);

        String midParams = "\"" + LINE_END + "Content-Type: " + mimeType + LINE_END + LINE_END;
        String tailParams = LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END;
        byte[] fileNameBytes = fileName.getBytes(ENCODING_TYPE);

        FileInputStream fileInputStream = (FileInputStream) getPathFromUri(appWorkspace, source);
        int maxBufferSize = XConstant.BUFFER_LEN;

        if (chunkedMode) {
            conn.setChunkedStreamingMode(maxBufferSize);
        } else {
            int stringLength = extraBytes.length + midParams.length() + tailParams.length()
                    + fileNameBytes.length;
            XLog.d(CLASS_NAME, "String Length: " + stringLength);
            int fixedLength = (int) fileInputStream.getChannel().size() + stringLength;
            XLog.d(CLASS_NAME, "Content Length: " + fixedLength);
            conn.setFixedLengthStreamingMode(fixedLength);
        }
        // ???
        OutputStream ouputStream = conn.getOutputStream();
        DataOutputStream dos = new DataOutputStream(ouputStream);
        dos.write(extraBytes);
        dos.write(fileNameBytes);
        dos.writeBytes(midParams);
        XFileUploadResult result = new XFileUploadResult();
        FileTransferProgress progress = new FileTransferProgress();
        int bytesAvailable = fileInputStream.available();
        int bufferSize = Math.min(bytesAvailable, maxBufferSize);
        byte[] buffer = new byte[bufferSize];
        int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        long totalBytes = 0;

        while (bytesRead > 0) {
            totalBytes += bytesRead;
            result.setBytesSent(totalBytes);
            dos.write(buffer, 0, bytesRead);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            if (objectId != null) {
                //?js??object ID?
                progress.setTotal(bytesAvailable);
                XLog.d(CLASS_NAME, "total=" + bytesAvailable);
                progress.setLoaded(totalBytes);
                progress.setLengthComputable(true);
                XExtensionResult progressResult = new XExtensionResult(XExtensionResult.Status.OK,
                        progress.toJSONObject());
                progressResult.setKeepCallback(true);
                callbackCtx.sendExtensionResult(progressResult);
            }
            synchronized (abortTriggered) {
                if (objectId != null && abortTriggered.contains(objectId)) {
                    abortTriggered.remove(objectId);
                    throw new AbortException(ABORT_EXCEPTION_UPLOAD_ABORTED);
                }
            }
        }
        dos.writeBytes(tailParams);
        fileInputStream.close();
        dos.flush();
        dos.close();
        checkConnection(conn);
        setUploadResult(result, conn);

        // 
        if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
            ((HttpsURLConnection) conn).setHostnameVerifier(mDefaultHostnameVerifier);
            HttpsURLConnection.setDefaultSSLSocketFactory(mDefaultSSLSocketFactory);
        }

        XLog.d(CLASS_NAME, "****** About to return a result from upload");
        return new XExtensionResult(XExtensionResult.Status.OK, result.toJSONObject());

    } catch (AbortException e) {
        JSONObject error = createFileTransferError(ABORTED_ERR, source, target, conn);
        return new XExtensionResult(XExtensionResult.Status.ERROR, error);
    } catch (FileNotFoundException e) {
        JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn);
        XLog.e(CLASS_NAME, error.toString());
        return new XExtensionResult(XExtensionResult.Status.ERROR, error);
    } catch (MalformedURLException e) {
        JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, conn);
        XLog.e(CLASS_NAME, error.toString());
        return new XExtensionResult(XExtensionResult.Status.ERROR, error);
    } catch (IOException e) {
        JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
        XLog.e(CLASS_NAME, error.toString());
        return new XExtensionResult(XExtensionResult.Status.IO_EXCEPTION, error);
    } catch (JSONException e) {
        XLog.e(CLASS_NAME, e.getMessage());
        return new XExtensionResult(XExtensionResult.Status.JSON_EXCEPTION);
    } catch (Throwable t) {
        JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
        XLog.e(CLASS_NAME, error.toString());
        return new XExtensionResult(XExtensionResult.Status.IO_EXCEPTION, error);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:net.tuples.doitfx.connector.crypto.PasswordManager.java

private boolean savePasscode(final String pSvcPair, final byte[] pPasscodeByteArray) {

    final FileOutputStream passcodeFileOutStm;
    final DataOutputStream passcodeDataOutStm;

    final byte[] encodedByteArray;

    final Path passCodeLocation = PathOptions.getDefaultConfigPath().resolve(pSvcPair)
            .resolve(passcodeFilename);/*from   w  w  w  .java2s . com*/

    encodedByteArray = Base64.encodeBase64(pPasscodeByteArray);

    try {
        passcodeFileOutStm = new FileOutputStream(passCodeLocation.toFile());
        passcodeDataOutStm = new DataOutputStream(passcodeFileOutStm);

        passcodeDataOutStm.write(encodedByteArray);

        passcodeDataOutStm.close();
        passcodeFileOutStm.close();

    } catch (IOException ex) {
        Logger.getLogger(PasswordManager.class.getName()).log(Level.SEVERE, null, ex);
    }

    return false;
}