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:org.akita.io.HttpInvoker.java

/**
 * post with files using URLConnection Impl
 * @param actionUrl URL to post/*w w  w .  java 2s .c  om*/
 * @param params params to post
 * @param files files to post, support multi-files
 * @return response in String format
 * @throws IOException
 */
public static String postWithFilesUsingURLConnection(String actionUrl, ArrayList<NameValuePair> params,
        Map<String, File> files) throws AkInvokeException {
    try {
        Log.v(TAG, "post:" + actionUrl);
        if (params != null) {
            Log.v(TAG, "params:=====================");
            for (NameValuePair nvp : params) {
                Log.v(TAG, nvp.getName() + "=" + nvp.getValue());
            }
            Log.v(TAG, "params end:=====================");
        }

        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";

        URL uri = new URL(actionUrl);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();

        conn.setReadTimeout(60 * 1000);
        conn.setDoInput(true); // permit input
        conn.setDoOutput(true); // permit output
        conn.setUseCaches(false);
        conn.setRequestMethod("POST"); // Post Method
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);

        // firstly string params to add
        StringBuilder sb = new StringBuilder();
        for (NameValuePair nameValuePair : params) {
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINEND);
            sb.append("Content-Disposition: form-data; name=\"" + nameValuePair.getName() + "\"" + LINEND);
            sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
            sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
            sb.append(LINEND);
            sb.append(nameValuePair.getValue());
            sb.append(LINEND);
        }

        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        outStream.write(sb.toString().getBytes());
        // send files secondly
        if (files != null) {
            int num = 0;
            for (Map.Entry<String, File> file : files.entrySet()) {
                num++;
                if (file.getKey() == null || file.getValue() == null)
                    continue;
                else {
                    if (!file.getValue().exists()) {
                        throw new AkInvokeException(AkInvokeException.CODE_FILE_NOT_FOUND,
                                "The file to upload is not found.");
                    }
                }
                StringBuilder sb1 = new StringBuilder();
                sb1.append(PREFIX);
                sb1.append(BOUNDARY);
                sb1.append(LINEND);
                sb1.append("Content-Disposition: form-data; name=\"" + file.getKey() + "\"; filename=\""
                        + file.getKey() + "\"" + LINEND);
                sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
                sb1.append(LINEND);
                outStream.write(sb1.toString().getBytes());

                InputStream is = new FileInputStream(file.getValue());
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = is.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }

                is.close();
                outStream.write(LINEND.getBytes());
            }
        }

        // request end flag
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        outStream.write(end_data);
        outStream.flush();
        // get response code
        int res = conn.getResponseCode();
        InputStream in = conn.getInputStream();
        StringBuilder sb2 = new StringBuilder();
        if (res == 200) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"), 8192);
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb2.append(line + "\n");
            }
            reader.close();
        }
        outStream.close();
        conn.disconnect();
        Log.v(TAG, "response:" + sb2.toString());
        return sb2.toString();
    } catch (IOException ioe) {
        throw new AkInvokeException(AkInvokeException.CODE_IO_EXCEPTION, "IO Exception", ioe);
    }
}

From source file:com.akretion.kettle.steps.terminatooor.ScriptValuesAddedFunctions.java

public static void appendToFile(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {

    if (!isNull(ArgList) && !isUndefined(ArgList)) {
        try {/*from  w  w  w  .  ja  v  a  2s  .  co  m*/
            FileOutputStream file = new FileOutputStream((String) ArgList[0], true);
            DataOutputStream out = new DataOutputStream(file);
            out.writeBytes((String) ArgList[1]);
            out.flush();
            out.close();
        } catch (Exception er) {
            throw new RuntimeException(er.toString());
        }
    } else {
        throw new RuntimeException("The function call appendToFile requires arguments.");
    }
}

From source file:com.citrus.mobile.RESTclient.java

public JSONObject makeWithdrawRequest(String accessToken, double amount, String currency, String owner,
        String accountNumber, String ifscCode) {
    HttpsURLConnection conn;/*from  w  w  w.  j av a  2s  . co m*/
    DataOutputStream wr = null;
    JSONObject txnDetails = null;
    BufferedReader in = null;

    try {
        String url = urls.getString(base_url) + urls.getString(type);

        conn = (HttpsURLConnection) new URL(url).openConnection();

        //add reuqest header
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Bearer " + accessToken);

        StringBuffer buff = new StringBuffer("amount=");
        buff.append(amount);

        buff.append("&currency=");
        buff.append(currency);

        buff.append("&owner=");
        buff.append(owner);

        buff.append("&account=");
        buff.append(accountNumber);

        buff.append("&ifsc=");
        buff.append(ifscCode);

        conn.setDoOutput(true);
        wr = new DataOutputStream(conn.getOutputStream());

        wr.writeBytes(buff.toString());
        wr.flush();

        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + buff.toString());
        System.out.println("Response Code : " + responseCode);

        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

        txnDetails = new JSONObject(response.toString());

    } catch (JSONException exception) {
        exception.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            if (wr != null) {
                wr.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return txnDetails;
}

From source file:com.sim2dial.dialer.ChatFragment.java

private String uploadImage(String filePath, Bitmap file, int compressorQuality, final int imageSize) {
    String fileName;/*  w ww  .ja v  a2 s  .c o m*/
    if (filePath != null) {
        File sourceFile = new File(filePath);
        fileName = sourceFile.getName();
    } else {
        fileName = getString(R.string.temp_photo_name_with_date).replace("%s",
                String.valueOf(System.currentTimeMillis()));
    }

    if (getResources().getBoolean(R.bool.hash_images_as_name_before_upload)) {
        fileName = String.valueOf(hashBitmap(file)) + ".jpg";
    }

    String response = null;
    HttpURLConnection conn = null;
    try {
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "---------------------------14737809831466499882746641449";

        URL url = new URL(uploadServerUri);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        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("uploaded_file", fileName);

        ProgressOutputStream pos = new ProgressOutputStream(conn.getOutputStream());
        pos.setListener(new OutputStreamListener() {
            @Override
            public void onBytesWrite(int count) {
                bytesSent += count;
                progressBar.setProgress(bytesSent * 100 / imageSize);
            }
        });
        DataOutputStream dos = new DataOutputStream(pos);

        dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
        dos.writeBytes(
                "Content-Disposition: form-data; name=\"userfile\"; filename=\"" + fileName + "\"" + lineEnd);
        dos.writeBytes("Content-Type: application/octet-stream" + lineEnd);
        dos.writeBytes(lineEnd);

        file.compress(CompressFormat.JPEG, compressorQuality, dos);

        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

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

        InputStream is = conn.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        int bytesRead;
        byte[] bytes = new byte[1024];
        while ((bytesRead = is.read(bytes)) != -1) {
            baos.write(bytes, 0, bytesRead);
        }
        byte[] bytesReceived = baos.toByteArray();
        baos.close();
        is.close();

        response = new String(bytesReceived);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    return response;
}

From source file:com.panet.imeta.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java

public static void appendToFile(Context actualContext, Scriptable actualObject, Object[] ArgList,
        Function FunctionContext) {

    if (!isNull(ArgList) && !isUndefined(ArgList)) {
        try {/*from  w w w.  j  a  va 2 s.  co  m*/
            FileOutputStream file = new FileOutputStream(Context.toString(ArgList[0]), true);
            DataOutputStream out = new DataOutputStream(file);
            out.writeBytes(Context.toString(ArgList[1]));
            out.flush();
            out.close();
        } catch (Exception er) {
            throw Context.reportRuntimeError(er.toString());
        }
    } else {
        throw Context.reportRuntimeError("The function call appendToFile requires arguments.");
    }
}

From source file:org.xingjitong.ChatFragment.java

private String uploadImage(String filePath, Bitmap file, int compressorQuality, final int imageSize) {
    String fileName;//from w w  w .  j a  va  2  s  .c o  m
    if (filePath != null) {
        File sourceFile = new File(filePath);
        fileName = sourceFile.getName();
    } else {
        fileName = getString(R.string.temp_photo_name_with_date).replace("%s",
                String.valueOf(System.currentTimeMillis()));
    }

    String response = null;
    HttpURLConnection conn = null;
    try {
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "---------------------------14737809831466499882746641449";

        URL url = new URL(uploadServerUri);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        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("uploaded_file", fileName);

        ProgressOutputStream pos = new ProgressOutputStream(conn.getOutputStream());
        pos.setListener(new OutputStreamListener() {
            @Override
            public void onBytesWrite(int count) {
                bytesSent += count;
                progressBar.setProgress(bytesSent * 100 / imageSize);
            }
        });
        DataOutputStream dos = new DataOutputStream(pos);

        dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
        dos.writeBytes(
                "Content-Disposition: form-data; name=\"userfile\"; filename=\"" + fileName + "\"" + lineEnd);
        dos.writeBytes("Content-Type: application/octet-stream" + lineEnd);
        dos.writeBytes(lineEnd);

        file.compress(CompressFormat.JPEG, compressorQuality, dos);

        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

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

        InputStream is = conn.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        int bytesRead;
        byte[] bytes = new byte[1024];
        while ((bytesRead = is.read(bytes)) != -1) {
            baos.write(bytes, 0, bytesRead);
        }
        byte[] bytesReceived = baos.toByteArray();
        baos.close();
        is.close();

        response = new String(bytesReceived);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    return response;
}

From source file:com.att.android.arodatacollector.main.AROCollectorService.java

/**
 * Logs the output "dumpsys alarm" to the provided filename.
 *
 * Output contains list of scheduled alarms & historical alarm statistics since
 * device bootup.//from   w w w  .j  a  v a2 s  .c om
 *
 * Note: On Froyo & older Android OS versions dumpsys output consists of absolute
 * times (in ms), but on later versions is relative in the format 1h1m20s32ms.
 *
 * Requires root permission.
 *
 * @param file Alarm log output filename
 */
private void getAlarmInfo(String file) {
    Process sh = null;
    DataOutputStream os = null;
    try {
        sh = Runtime.getRuntime().exec("su");
        os = new DataOutputStream(sh.getOutputStream());
        String Command = "dumpsys alarm > " + mApp.getTcpDumpTraceFolderName() + file + "\n";
        os.writeBytes(Command);
        os.flush();
    } catch (IOException e) {
        Log.e(TAG, "exception in getAlarmInfo ", e);
    } finally {
        try {
            os.close();
        } catch (IOException e) {
            Log.e(TAG, "exception in getAlarmInfo closing output stream ", e);
        }
    }
}

From source file:bobs.is.compress.sevenzip.SevenZOutputFile.java

private void writeFileATimes(final DataOutput header) throws IOException {
    int numAccessDates = 0;
    for (final SevenZArchiveEntry entry : files) {
        if (entry.getHasAccessDate()) {
            ++numAccessDates;//from  ww  w .ja v  a  2s . c om
        }
    }
    if (numAccessDates > 0) {
        header.write(NID.kATime);

        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final DataOutputStream out = new DataOutputStream(baos);
        if (numAccessDates != files.size()) {
            out.write(0);
            final BitSet aTimes = new BitSet(files.size());
            for (int i = 0; i < files.size(); i++) {
                aTimes.set(i, files.get(i).getHasAccessDate());
            }
            writeBits(out, aTimes, files.size());
        } else {
            out.write(1); // "allAreDefined" == true
        }
        out.write(0);
        for (final SevenZArchiveEntry entry : files) {
            if (entry.getHasAccessDate()) {
                out.writeLong(Long.reverseBytes(SevenZArchiveEntry.javaTimeToNtfsTime(entry.getAccessDate())));
            }
        }
        out.flush();
        final byte[] contents = baos.toByteArray();
        writeUint64(header, contents.length);
        header.write(contents);
    }
}

From source file:bobs.is.compress.sevenzip.SevenZOutputFile.java

private void writeFileWindowsAttributes(final DataOutput header) throws IOException {
    int numWindowsAttributes = 0;
    for (final SevenZArchiveEntry entry : files) {
        if (entry.getHasWindowsAttributes()) {
            ++numWindowsAttributes;/*from ww w  .j  a  v  a2  s.  co  m*/
        }
    }
    if (numWindowsAttributes > 0) {
        header.write(NID.kWinAttributes);

        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final DataOutputStream out = new DataOutputStream(baos);
        if (numWindowsAttributes != files.size()) {
            out.write(0);
            final BitSet attributes = new BitSet(files.size());
            for (int i = 0; i < files.size(); i++) {
                attributes.set(i, files.get(i).getHasWindowsAttributes());
            }
            writeBits(out, attributes, files.size());
        } else {
            out.write(1); // "allAreDefined" == true
        }
        out.write(0);
        for (final SevenZArchiveEntry entry : files) {
            if (entry.getHasWindowsAttributes()) {
                out.writeInt(Integer.reverseBytes(entry.getWindowsAttributes()));
            }
        }
        out.flush();
        final byte[] contents = baos.toByteArray();
        writeUint64(header, contents.length);
        header.write(contents);
    }
}

From source file:iracing.webapi.IracingWebApi.java

private String doPostRequestUrlEncoded(boolean needForumCookie, String url, String parameters)
        throws IOException, LoginException {
    if (!cookieMap.containsKey(JSESSIONID)) {
        if (login() != LoginResponse.Success)
            return null;
    }/*from  w ww. j  av a  2s  . c  o m*/
    if (needForumCookie && !cookieMap.containsKey(JFORUMSESSIONID)) {
        if (!forumLoginAndGetCookie())
            return null;
    }
    String output = null;
    try {
        // URL of CGI-Bin script.
        URL oUrl = new URL(url);
        // URL connection channel.
        HttpURLConnection urlConn = (HttpURLConnection) oUrl.openConnection();
        // Let the run-time system (RTS) know that we want input.
        urlConn.setDoInput(true);
        // Let the RTS know that we want to do output.
        urlConn.setDoOutput(true);
        // No caching, we want the real thing.
        urlConn.setUseCaches(false);
        urlConn.addRequestProperty(COOKIE, cookie);

        // request to have the response gzipped (bringing a 3.5Mb response down to 175kb)
        urlConn.addRequestProperty("Accept-Encoding", "gzip");

        urlConn.setRequestMethod("POST");
        // Specify the content type.
        urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        DataOutputStream printout = new DataOutputStream(urlConn.getOutputStream());
        try {
            printout.writeBytes(parameters);
            printout.flush();
        } finally {
            printout.close();
        }

        output = getResponseText(urlConn);
        //            System.out.println(output);

        urlConn.disconnect();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return output;
}