Example usage for java.io DataOutputStream flush

List of usage examples for java.io DataOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this data output stream.

Usage

From source file:hd3gtv.embddb.network.DataBlock.java

byte[] getBytes(Protocol protocol) throws IOException {
    checkIfNotEmpty();//  w w  w.j a  v a 2s .com

    ByteArrayOutputStream byte_array_out_stream = new ByteArrayOutputStream(Protocol.BUFFER_SIZE);

    DataOutputStream dos = new DataOutputStream(byte_array_out_stream);
    dos.write(Protocol.APP_SOCKET_HEADER_TAG);
    dos.writeInt(Protocol.VERSION);

    /**
     * Start header name
     */
    dos.writeByte(0);
    byte[] request_name_data = request_name.getBytes(Protocol.UTF8);
    dos.writeInt(request_name_data.length);
    dos.write(request_name_data);

    /**
     * Start datas payload
     */
    dos.writeByte(1);

    /**
     * Get datas from zip
     */
    ZipOutputStream zos = new ZipOutputStream(dos);
    zos.setLevel(3);
    entries.forEach(entry -> {
        try {
            entry.toZip(zos);
        } catch (IOException e) {
            log.error("Can't add to zip", e);
        }
    });
    zos.flush();
    zos.finish();
    zos.close();

    dos.flush();
    dos.close();

    byte[] result = byte_array_out_stream.toByteArray();

    if (log.isTraceEnabled()) {
        log.trace("Make raw datas for " + request_name + Hexview.LINESEPARATOR + Hexview.tracelog(result));
    }

    return result;
}

From source file:com.jivesoftware.os.amza.service.replication.http.endpoints.AmzaReplicationRestEndpoints.java

@POST
@Consumes(MediaType.APPLICATION_JSON)//from  w ww  .j  a va  2 s. c om
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Path("/rows/stream/{ringMemberString}/{versionedPartitionName}/{takeSessionId}/{txId}/{leadershipToken}/{limit}")
public Response rowsStream(@PathParam("ringMemberString") String ringMemberString,
        @PathParam("versionedPartitionName") String versionedPartitionName,
        @PathParam("takeSessionId") long takeSessionId, @PathParam("txId") long txId,
        @PathParam("leadershipToken") long leadershipToken, @PathParam("limit") long limit,
        byte[] takeSharedKey) {

    try {
        amzaStats.rowsStream.increment();

        StreamingOutput stream = (OutputStream os) -> {
            os.flush();
            BufferedOutputStream bos = new BufferedOutputStream(new SnappyOutputStream(os), 8192); // TODO expose to config
            final DataOutputStream dos = new DataOutputStream(bos);
            try {
                amzaInstance.rowsStream(dos, new RingMember(ringMemberString),
                        VersionedPartitionName.fromBase64(versionedPartitionName, amzaInterner), takeSessionId,
                        objectMapper.readValue(takeSharedKey, Long.class), txId, leadershipToken, limit);
            } catch (IOException x) {
                if (x.getCause() instanceof TimeoutException) {
                    LOG.error("Timed out while streaming takes");
                } else {
                    LOG.error("Failed to stream takes.", x);
                }
                throw x;
            } catch (Exception x) {
                LOG.error("Failed to stream takes.", x);
                throw new IOException("Failed to stream takes.", x);
            } finally {
                dos.flush();
                amzaStats.rowsStream.decrement();
                amzaStats.completedRowsStream.increment();
            }
        };
        return Response.ok(stream).build();
    } catch (Exception x) {
        Object[] vals = new Object[] { ringMemberString, versionedPartitionName, txId };
        LOG.warn("Failed to rowsStream {} {} {}. ", vals, x);
        return ResponseHelper.INSTANCE.errorResponse("Failed to rowsStream " + Arrays.toString(vals), x);
    }
}

From source file:org.kuali.ole.docstore.common.client.DocstoreRestClient.java

private RestResponse sendPostForAcquisitionSearch(String url, String urlParameters) {

    StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), 200, "OK");
    HttpResponse httpResponse = new BasicHttpResponse(statusLine);
    String postResponse = null;//from   w w  w .j  ava  2 s.  c  o  m
    try {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
        int responseCode = con.getResponseCode();
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        postResponse = response.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }

    RestResponse response = new RestResponse();
    response.setContentType("text/html; charset=utf-8");
    response.setResponseBody(postResponse);
    response.setResponse(httpResponse);
    return response;
}

From source file:ca.farrelltonsolar.classic.PVOutputUploader.java

private boolean doUpload(ChargeController controller) throws InterruptedException, IOException {
    String uploadDateString = controller.uploadDate();
    String SID = controller.getSID();
    String fName = controller.getPVOutputLogFilename();
    if (fName != null && fName.length() > 0 && SID != null && SID.length() > 0) {
        DateTime logDate = PVOutputService.LogDate();
        int numberOfDays = Constants.PVOUTPUT_RECORD_LIMIT;
        if (uploadDateString.length() > 0) {
            DateTime uploadDate = DateTime.parse(uploadDateString, DateTimeFormat.forPattern("yyyy-MM-dd"));
            numberOfDays = Days.daysBetween(uploadDate, logDate).getDays();
        }//from w w  w .  j  a  va2s .com
        numberOfDays = numberOfDays > Constants.PVOUTPUT_RECORD_LIMIT ? Constants.PVOUTPUT_RECORD_LIMIT
                : numberOfDays; // limit to 20 days as per pvOutput limits
        if (numberOfDays > 0) {
            Log.d(getClass().getName(), String.format("PVOutput uploading: %s for %d days on thread: %s", fName,
                    numberOfDays, Thread.currentThread().getName()));
            DateTime now = DateTime.now();
            String UploadDate = DateTimeFormat.forPattern("yyyy-MM-dd").print(now);
            Bundle logs = load(fName);
            float[] mData = logs.getFloatArray(String.valueOf(Constants.CLASSIC_KWHOUR_DAILY_CATEGORY)); // kWh/day
            boolean uploadDateRecorded = false;
            for (int i = 0; i < numberOfDays; i++) {
                logDate = logDate.minusDays(1); // latest log entry is for yesterday
                Socket pvOutputSocket = Connect(pvOutput);
                DataOutputStream outputStream = new DataOutputStream(
                        new BufferedOutputStream(pvOutputSocket.getOutputStream()));
                String dateStamp = DateTimeFormat.forPattern("yyyyMMdd").print(logDate);
                StringBuilder feed = new StringBuilder("GET /service/r2/addoutput.jsp");
                feed.append("?key=");
                feed.append(APIKey);
                feed.append("&sid=");
                feed.append(SID);
                feed.append("&d=");
                feed.append(dateStamp);
                feed.append("&g=");
                String wh = String.valueOf(mData[i] * 100);
                feed.append(wh);
                feed.append("\r\n");
                feed.append("Host: ");
                feed.append(pvOutput);
                feed.append("\r\n");
                feed.append("\r\n");
                String resp = feed.toString();
                outputStream.writeBytes(resp);
                outputStream.flush();
                pvOutputSocket.close();
                if (uploadDateRecorded == false) {
                    controller.setUploadDate(UploadDate);
                    uploadDateRecorded = true;
                }
                Thread.sleep(Constants.PVOUTPUT_RATE_LIMIT); // rate limit
            }
            return true;
        }
    }
    return false;
}

From source file:com.splout.db.dnode.HttpFileExchanger.java

public void send(final String tablespace, final int partition, final long version, final File binaryFile,
        final String url, boolean blockUntilComplete) {
    Future<?> future = clientExecutors.submit(new Runnable() {
        @Override/*w w w  .j a v a  2s . c o  m*/
        public void run() {
            DataOutputStream writer = null;
            InputStream input = null;
            try {
                HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                connection.setChunkedStreamingMode(config.getInt(FetcherProperties.DOWNLOAD_BUFFER));
                connection.setDoOutput(true);
                connection.setRequestProperty("filename", binaryFile.getName());
                connection.setRequestProperty("tablespace", tablespace);
                connection.setRequestProperty("partition", partition + "");
                connection.setRequestProperty("version", version + "");

                Checksum checkSum = new CRC32();

                writer = new DataOutputStream(new GZIPOutputStream(connection.getOutputStream()));
                // 1 - write file size
                writer.writeLong(binaryFile.length());
                writer.flush();
                // 2 - write file content
                input = new FileInputStream(binaryFile);
                byte[] buffer = new byte[config.getInt(FetcherProperties.DOWNLOAD_BUFFER)];
                long wrote = 0;
                for (int length = 0; (length = input.read(buffer)) > 0;) {
                    writer.write(buffer, 0, length);
                    checkSum.update(buffer, 0, length);
                    wrote += length;
                }
                // 3 - add the CRC so that we can verify the download
                writer.writeLong(checkSum.getValue());
                writer.flush();
                log.info("Sent file " + binaryFile + " to " + url + " with #bytes: " + wrote + " and checksum: "
                        + checkSum.getValue());
            } catch (IOException e) {
                log.error(e);
            } finally {
                try {
                    if (input != null) {
                        input.close();
                    }
                    if (writer != null) {
                        writer.close();
                    }
                } catch (IOException ignore) {
                }
            }
        }
    });
    try {
        if (blockUntilComplete) {
            while (future.isDone() || future.isCancelled()) {
                Thread.sleep(1000);
            }
        }
    } catch (InterruptedException e) {
        // interrupted!
    }
}

From source file:edu.pdx.cecs.orcycle.UserInfoUploader.java

boolean uploadUserInfoV4() {
    boolean result = false;
    final String postUrl = mCtx.getResources().getString(R.string.post_url);

    try {//from   w  w w .  j  a v  a2  s  .  c o  m
        JSONArray userResponses = getUserResponsesJSON();

        URL url = new URL(postUrl);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        conn.setRequestProperty("Cycleatl-Protocol-Version", "4");

        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        JSONObject jsonUser;
        if (null != (jsonUser = getUserJSON())) {
            try {
                String deviceId = userId;

                dos.writeBytes(fieldSep + ContentField("user") + jsonUser.toString() + "\r\n");
                dos.writeBytes(
                        fieldSep + ContentField("version") + String.valueOf(kSaveProtocolVersion4) + "\r\n");
                dos.writeBytes(fieldSep + ContentField("device") + deviceId + "\r\n");
                dos.writeBytes(fieldSep + ContentField("userResponses") + userResponses.toString() + "\r\n");
                dos.writeBytes(fieldSep);
                dos.flush();
            } catch (Exception ex) {
                Log.e(MODULE_TAG, ex.getMessage());
                return false;
            } finally {
                dos.close();
            }
            int serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();
            // JSONObject responseData = new JSONObject(serverResponseMessage);
            Log.v("Jason", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
            if (serverResponseCode == 201 || serverResponseCode == 202) {
                // TODO: Record somehow that data was uploaded successfully
                result = true;
            }
        } else {
            result = false;
        }
    } catch (IllegalStateException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (JSONException e) {
        e.printStackTrace();
        return false;
    }
    return result;
}

From source file:com.example.will.sendpic.Camera2BasicFragment.java

private String sendFileGetResult(File file, String url, int port, int secTimeout) {
    Socket s = new Socket();
    String res = "Fail";

    try {/*from   ww  w .  j a  v a 2  s  .co m*/
        s.connect(new InetSocketAddress(url, port), secTimeout * 1000);
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] sendBytes = new byte[1024 * 4];
        int len = 0;

        while ((len = fis.read(sendBytes, 0, sendBytes.length)) > 0) {
            dos.write(sendBytes, 0, len);
            dos.flush();
        }
        s.shutdownOutput();

        //get the result from server
        //you can change the protocol
        InputStream in = s.getInputStream();
        byte[] result = new byte[1024];
        int num = in.read(result);

        res = new String(result, 0, num);
        System.out.println(res);

        //closing resources
        s.close();
        dos.close();
        fis.close();
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return res;
}

From source file:com.curso.listadapter.net.RESTClient.java

/**
 * upload multipart/*from   w w w. j a  v  a  2 s  . c om*/
 * this method receive the file to be uploaded
 * */
@SuppressWarnings("deprecation")
public String uploadMultiPart(Map<String, File> files) throws Exception {
    disableSSLCertificateChecking();
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    DataInputStream inStream = null;
    try {
        URL endpoint = new URL(url);
        conn = (HttpURLConnection) endpoint.openConnection();
        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);

        dos = new DataOutputStream(conn.getOutputStream());
        String post = "";

        //WRITE ALL THE PARAMS
        for (NameValuePair p : params)
            post += writeMultipartParam(p);
        dos.flush();
        //END WRITE ALL THE PARAMS

        //BEGIN THE UPLOAD
        ArrayList<FileInputStream> inputStreams = new ArrayList<FileInputStream>();
        for (Entry<String, File> entry : files.entrySet()) {
            post += lineEnd;
            post += twoHyphens + boundary + lineEnd;
            String NameParamImage = entry.getKey();
            File file = entry.getValue();
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;
            FileInputStream fileInputStream = new FileInputStream(file);

            post += "Content-Disposition: attachment; name=\"" + NameParamImage + "\"; filename=\""
                    + file.getName() + "\"" + lineEnd;
            String mimetype = getMimeType(file.getName());
            post += "Content-Type: " + mimetype + lineEnd;
            post += "Content-Transfer-Encoding: binary" + lineEnd + lineEnd;

            dos.write(post.toString().getBytes("UTF-8"));

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                inputStreams.add(fileInputStream);
            }

            Log.d("Test", post);
            dos.flush();
            post = "";
        }

        //END THE UPLOAD

        dos.writeBytes(lineEnd);

        dos.writeBytes(twoHyphens + boundary + twoHyphens);
        //            for(FileInputStream inputStream: inputStreams){
        //               inputStream.close();
        //            }
        dos.flush();
        dos.close();
        conn.connect();
        Log.d("upload", "finish flush:" + conn.getResponseCode());
    } catch (MalformedURLException ex) {
        Log.e("Debug", "error: " + ex.getMessage(), ex);
    } catch (IOException ioe) {
        Log.e("Debug", "error: " + ioe.getMessage(), ioe);
    }
    try {
        String response_data = "";
        inStream = new DataInputStream(conn.getInputStream());
        String str;
        while ((str = inStream.readLine()) != null) {
            response_data += str;
        }
        inStream.close();
        return response_data;
    } catch (IOException ioex) {
        Log.e("Debug", "error: " + ioex.getMessage(), ioex);
    }
    return null;
}

From source file:edu.ncsu.asbransc.mouflon.recorder.UploadFile.java

protected boolean uploadFile(File fileToUpload) {
    String lineEnding = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    boolean success = true;
    HttpURLConnection connection = null;
    try {//from  w  ww.  j  a  v  a  2s . c o  m
        URL dest = new URL("http://mouflon.csc.ncsu.edu/cgi-bin/upload.cgi");
        connection = (HttpURLConnection) dest.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        connection.setChunkedStreamingMode(0);
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.writeBytes(twoHyphens + boundary + lineEnding);
        //Log.i("uploadFile", fileToUpload.getName());
        out.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""
                + fileToUpload.getName() + "\"" + lineEnding);
        out.writeBytes("Content-Type: application/octet-stream" + lineEnding);
        out.writeBytes("Content-Transfer-Encoding: base64" + lineEnding);
        out.writeBytes(lineEnding);
        encodeFileBase64(fileToUpload, out); //TODO this works fine for small files but for some file size between 256k and 2M it begins failing.

        out.writeBytes(lineEnding);
        out.writeBytes(twoHyphens + boundary + twoHyphens + lineEnding);
        //Log.i("UploadTest", "File uploaded");
        out.flush();
        out.close();

    } catch (Exception e) {
        e.printStackTrace();
        success = false;
    }
    try {
        BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
        byte[] resp = new byte[80];
        int read = 0;
        if ((read = in.read(resp)) > 0) {
            String responseString = new String(resp, 0, read);
            //Log.i("uploadFile", responseString);
            if (!responseString.equals(fileToUpload.getName())) {
                //Log.e("Upload", "File upload failed");
            }
        }
        //else 
        //Log.e("Upload", "No response received from server");

    } catch (Exception e) {
        e.printStackTrace();
        success = false;
    }
    return success;
}

From source file:com.jivesoftware.os.amza.service.AmzaService.java

@Override
public void availableRowsStream(boolean system, ChunkWriteable writeable, RingMember remoteRingMember,
        TimestampedRingHost remoteTimestampedRingHost, long takeSessionId, long sharedKey,
        long heartbeatIntervalMillis) throws Exception {

    ringStoreWriter.register(remoteRingMember, remoteTimestampedRingHost.ringHost,
            remoteTimestampedRingHost.timestampId, false);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new SnappyOutputStream(out), 8192));

    takeCoordinator.availableRowsStream(system, ringStoreReader, partitionStripeProvider, remoteRingMember,
            takeSessionId, sharedKey, heartbeatIntervalMillis, (partitionName, txId) -> {
                dos.write(1);/*ww  w  .j  a  v  a 2  s. c o  m*/
                byte[] bytes = partitionName.toBytes();
                dos.writeInt(bytes.length);
                dos.write(bytes);
                dos.writeLong(txId);
            }, () -> {
                if (dos.size() > 0) {
                    dos.flush();
                    byte[] chunk = out.toByteArray();
                    writeable.write(chunk);
                    /*LOG.info("Offered rows for {} length={}", remoteRingMember, chunk.length);*/
                    out.reset();
                }
                return null;
            }, () -> {
                dos.write(1);
                dos.writeInt(0);
                dos.flush();
                writeable.write(out.toByteArray());
                out.reset();
                return null;
            });
    dos.write(0);
    dos.flush();
    writeable.write(out.toByteArray());
}