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:com.atilika.kuromoji.trie.DoubleArrayTrie.java

public void write(OutputStream output) throws IOException {

    baseBuffer.rewind();/*from w  w  w . j  a v a2  s  . c o  m*/
    checkBuffer.rewind();
    tailBuffer.rewind();

    int baseCheckSize = Math.min(maxBaseCheckIndex + 64, baseBuffer.capacity());
    int tailSize = Math.min(tailIndex - TAIL_OFFSET + 64, tailBuffer.capacity());

    DataOutputStream dataOutput = new DataOutputStream(new BufferedOutputStream(output));

    dataOutput.writeBoolean(compact);
    dataOutput.writeInt(baseCheckSize);
    dataOutput.writeInt(tailSize);

    WritableByteChannel channel = Channels.newChannel(dataOutput);

    ByteBuffer tmpBuffer = ByteBuffer.allocate(baseCheckSize * 4);
    IntBuffer tmpIntBuffer = tmpBuffer.asIntBuffer();
    tmpIntBuffer.put(baseBuffer.array(), 0, baseCheckSize);
    tmpBuffer.rewind();
    channel.write(tmpBuffer);

    tmpBuffer = ByteBuffer.allocate(baseCheckSize * 4);
    tmpIntBuffer = tmpBuffer.asIntBuffer();
    tmpIntBuffer.put(checkBuffer.array(), 0, baseCheckSize);
    tmpBuffer.rewind();
    channel.write(tmpBuffer);

    tmpBuffer = ByteBuffer.allocate(tailSize * 2);
    CharBuffer tmpCharBuffer = tmpBuffer.asCharBuffer();
    tmpCharBuffer.put(tailBuffer.array(), 0, tailSize);
    tmpBuffer.rewind();
    channel.write(tmpBuffer);

    dataOutput.flush();
}

From source file:com.intel.xdk.device.Device.java

public void getRemoteData(String requestUrl, String requestMethod, String requestBody,
        CallbackContext callbackContext) {
    try {/*  ww w  .j a va  2  s  .c om*/
        URL url = new URL(requestUrl);
        connection = (HttpURLConnection) url.openConnection();

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

        connection.setRequestMethod(requestMethod);

        //Write requestBody
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(requestBody);
        outputStream.flush();
        outputStream.close();

        //Get response code and response message
        int responseCode = connection.getResponseCode();
        String responseMessage = connection.getResponseMessage();

        //Get response Message
        DataInputStream inputStream = new DataInputStream(connection.getInputStream());
        if (responseCode == 200) {
            String temp;
            String responseBody = "";
            while ((temp = inputStream.readLine()) != null) {
                responseBody += temp;
            }
            callbackContext.success(responseBody);
        } else {
            callbackContext.error("Fail to get the response, response code: " + responseCode
                    + ", response message: " + responseMessage);
        }

        inputStream.close();
    } catch (IOException e) {
        Log.d("request", e.getMessage());
    }
}

From source file:com.intel.xdk.device.Device.java

public void getRemoteData(String requestUrl, String requestMethod, String requestBody, String successCallback,
        String errorCallback) {//from  w  w w .ja  v  a  2 s.  c om
    Log.d("getRemoteData", "url: " + requestUrl + ", method: " + requestMethod + ", body: " + requestBody);

    try {
        URL url = new URL(requestUrl);
        connection = (HttpURLConnection) url.openConnection();

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

        connection.setRequestMethod(requestMethod);

        //Write requestBody
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(requestBody);
        outputStream.flush();
        outputStream.close();

        //Get response code and response message
        int responseCode = connection.getResponseCode();
        String responseMessage = connection.getResponseMessage();

        //Get response Message
        DataInputStream inputStream = new DataInputStream(connection.getInputStream());
        if (responseCode == 200) {
            String temp;
            String responseBody = "";
            while ((temp = inputStream.readLine()) != null) {
                responseBody += temp;
            }
            //callbackContext.success(responseBody);
            String js = "javascript:" + successCallback + "('" + responseBody + "');";
            injectJS(js);
        } else {
            //callbackContext.error("Fail to get the response, response code: " + responseCode + ", response message: " + responseMessage);
            String js = "javascript:" + errorCallback + "(" + "'response code :" + responseCode + "');";
            injectJS(js);
        }

        inputStream.close();
    } catch (IOException e) {
        Log.d("request", e.getMessage());
    }
}

From source file:net.mohatu.bloocoin.miner.SubmitListClass.java

private void submit() {
    for (int i = 0; i < solved.size(); i++) {
        try {/*from w  w  w.  java2s  . c o  m*/
            Socket sock = new Socket(this.url, this.port);
            String result = new String();
            DataInputStream is = new DataInputStream(sock.getInputStream());
            DataOutputStream os = null;
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            solution = solved.get(i);
            hash = DigestUtils.sha512Hex(solution);

            String command = "{\"cmd\":\"check" + "\",\"winning_string\":\"" + solution
                    + "\",\"winning_hash\":\"" + hash + "\",\"addr\":\"" + MainView.getAddr() + "\"}";
            os = new DataOutputStream(sock.getOutputStream());
            os.write(command.getBytes());

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                result += inputLine;
            }

            if (result.contains("\"success\": true")) {
                System.out.println("Result: Submitted");
                MainView.updateStatusText(solution + " submitted");
                Thread gc = new Thread(new CoinClass());
                gc.start();
            } else if (result.contains("\"success\": false")) {
                System.out.println("Result: Failed");
                MainView.updateStatusText("Submission of " + solution + " failed, already exists!");
            }
            is.close();
            os.close();
            os.flush();
            sock.close();
        } catch (UnknownHostException e) {
            MainView.updateStatusText("Submission of " + solution + " failed, connection failed!");
        } catch (IOException e) {
            MainView.updateStatusText("Submission of " + solution + " failed, connection failed!");
        }
    }
    Thread gc = new Thread(new CoinClass());
    gc.start();
}

From source file:net.mohatu.bloocoin.miner.SubmitList.java

private void submit() {
    for (int i = 0; i < solved.size(); i++) {
        try {//ww  w. j a va  2  s. co m
            Socket sock = new Socket(this.url, this.port);
            String result = new String();
            DataInputStream is = new DataInputStream(sock.getInputStream());
            DataOutputStream os = null;
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            solution = solved.get(i);
            hash = DigestUtils.sha512Hex(solution);

            String command = "{\"cmd\":\"check" + "\",\"winning_string\":\"" + solution
                    + "\",\"winning_hash\":\"" + hash + "\",\"addr\":\"" + Main.getAddr() + "\"}";
            os = new DataOutputStream(sock.getOutputStream());
            os.write(command.getBytes());

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                result += inputLine;
            }

            if (result.contains("\"success\": true")) {
                System.out.println("Result: Submitted");
                Main.updateStatusText(solution + " submitted", Color.blue);
                Thread gc = new Thread(new Coins());
                gc.start();
            } else if (result.contains("\"success\": false")) {
                System.out.println("Result: Failed");
                Main.updateStatusText("Submission of " + solution + " failed, already exists!", Color.red);
            }
            is.close();
            os.close();
            os.flush();
            sock.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            Main.updateStatusText("Submission of " + solution + " failed, connection failed!", Color.red);
        } catch (IOException e) {
            e.printStackTrace();
            Main.updateStatusText("Submission of " + solution + " failed, connection failed!", Color.red);
        }
    }
    Thread gc = new Thread(new Coins());
    gc.start();
}

From source file:de.wikilab.android.friendica01.TwAjax.java

private void runFileUpload() throws IOException {

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "d1934afa-f2e4-449b-99be-8be6ebfec594";
    Log.i("Andfrnd/TwAjax", "URL=" + getURL());
    URL url = new URL(getURL());
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    // Allow Inputs & Outputs
    connection.setDoInput(true);/* w  w  w .  jav a  2s.  co  m*/
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    // Enable POST method
    connection.setRequestMethod("POST");

    //generate auth header if user/pass are provided to this class
    if (this.myHttpAuthUser != null) {
        connection.setRequestProperty("Authorization", "Basic " + Base64
                .encodeToString((this.myHttpAuthUser + ":" + this.myHttpAuthPass).getBytes(), Base64.NO_WRAP));
    }
    //Log.i("Andfrnd","-->"+connection.getRequestProperty("Authorization")+"<--");

    connection.setRequestProperty("Host", url.getHost());
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    for (NameValuePair nvp : myPostData) {
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + nvp.getName() + "\"" + lineEnd);
        outputStream.writeBytes(lineEnd + nvp.getValue() + lineEnd);
    }
    for (PostFile pf : myPostFiles) {
        pf.writeToStream(outputStream, boundary);
    }
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

    // Responses from the server (code and message)
    myHttpStatus = connection.getResponseCode();

    outputStream.flush();
    outputStream.close();

    if (myHttpStatus < 400) {
        myResult = convertStreamToString(connection.getInputStream());
    } else {
        myResult = convertStreamToString(connection.getErrorStream());
    }

    success = true;
}

From source file:com.intel.xdk.device.Device.java

public void getRemoteDataWithID(String requestUrl, String requestMethod, String requestBody, int uuid,
        String successCallback, String errorCallback) {
    try {/*from  w ww.j  a v  a 2  s.  com*/
        URL url = new URL(requestUrl);
        connection = (HttpURLConnection) url.openConnection();

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

        connection.setRequestMethod(requestMethod);

        //Write requestBody
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(requestBody);
        outputStream.writeBytes("&uuid=" + uuid);
        outputStream.flush();
        outputStream.close();

        //Get response code and response message
        int responseCode = connection.getResponseCode();
        String responseMessage = connection.getResponseMessage();

        //Get response Message
        DataInputStream inputStream = new DataInputStream(connection.getInputStream());
        if (responseCode == 200) {
            String temp;
            String responseBody = "";
            while ((temp = inputStream.readLine()) != null) {
                responseBody += temp;
            }
            //callbackContext.success(responseBody);
            String js = "javascript:" + successCallback + "(" + uuid + ", '" + responseBody + "');";
            injectJS(js);
        } else {
            //callbackContext.error("Fail to get the response, response code: " + responseCode + ", response message: " + responseMessage);
            String js = "javascript:" + errorCallback + "(" + uuid + ", '" + "Fail to get the response" + "');";
            injectJS(js);
        }

        inputStream.close();
    } catch (IOException e) {
        Log.d("request", e.getMessage());
    }
}

From source file:com.intel.xdk.device.Device.java

public void getRemoteDataWithID(String requestUrl, String requestMethod, String requestBody, int uuid,
        CallbackContext callbackContext) {
    try {/*from   w w  w .  ja  v a2s  .  c o m*/
        URL url = new URL(requestUrl);
        connection = (HttpURLConnection) url.openConnection();

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

        connection.setRequestMethod(requestMethod);

        //Write requestBody
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(requestBody);
        outputStream.writeBytes("&uuid=" + uuid);
        outputStream.flush();
        outputStream.close();

        //Get response code and response message
        int responseCode = connection.getResponseCode();
        String responseMessage = connection.getResponseMessage();

        //Get response Message
        DataInputStream inputStream = new DataInputStream(connection.getInputStream());
        if (responseCode == 200) {
            String temp;
            String responseBody = "";
            while ((temp = inputStream.readLine()) != null) {
                responseBody += temp;
            }
            callbackContext.success(uuid + ", " + responseBody);
            //String js = "javascript:" + successCallback + "(" + uuid + ", '" + responseBody + "');";
            //injectJS(js);
        } else {
            callbackContext.error(uuid + ", Fail to get the response, response code: " + responseCode
                    + ", response message: " + responseMessage);
            //String js = "javascript:" + errorCallback + "(" + uuid + ", '" + "Fail to get the response" + "');";
            //injectJS(js);
        }

        inputStream.close();
    } catch (IOException e) {
        Log.d("request", e.getMessage());
    }
}

From source file:com.alibaba.akita.io.HttpInvoker.java

/**
 * post with files using URLConnection Impl
 * @param actionUrl URL to post/*from   ww  w.j  a  v a 2s.  c  o  m*/
 * @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 {
        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" + num + "\"; 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();
        return sb2.toString();
    } catch (IOException ioe) {
        throw new AkInvokeException(AkInvokeException.CODE_IO_EXCEPTION, "IO Exception", ioe);
    }
}

From source file:edu.ku.brc.specify.tools.FormDisplayer.java

/**
 * //from w w  w . j a  v  a 2  s.c o m
 */
private File checkForTemplateFiles(final String dstDirPath) {
    String templatePath = dstDirPath + File.separator + "schema_template.html";

    File templateFile = new File(templatePath); //$NON-NLS-1$
    if (templateFile.exists()) {
        return templateFile;
    }

    System.out.println(templatePath);
    try {
        File dstDirFile = new File(dstDirPath);
        if (!dstDirFile.exists()) {
            if (!dstDirFile.mkdirs()) {
                JOptionPane.showMessageDialog(null, "Error creating the site directory.");
            }
        }

        String zipFilePath = dstDirPath + File.separator + "site.zip";
        System.out.println("[" + zipFilePath + "]");

        String url = "http://files.specifysoftware.org/site.zip";
        HTTPGetter getter = new HTTPGetter();
        InputStream ins = getter.beginHTTPRequest(url);
        //DataInputStream  dins   = new DataInputStream(ins);
        DataOutputStream dos = new DataOutputStream(new FileOutputStream(zipFilePath));
        byte[] bytes = new byte[4096];

        int totalBytes = 0;
        /*while (dins.available() > 0)
        {
        int len = dins.read(bytes);
        dos.write(bytes, 0, len);
        totalBytes += len;
        System.out.println(len+" / "+totalBytes);
        }*/
        int numBytes = 0;
        do {
            numBytes = ins.read(bytes);
            if (numBytes > 0) {
                dos.write(bytes, 0, numBytes);
                totalBytes += numBytes;
                System.out.println(numBytes);
            }

        } while (numBytes > 0);

        dos.flush();
        dos.close();
        //dins.close();

        System.out.println(totalBytes);

        File zipFile = new File(zipFilePath);
        System.out.println("zipFile: " + zipFile + " exists: " + zipFile.exists());

        List<File> unzippedFiles = ZipFileHelper.getInstance().unzipToFiles(zipFile);
        for (File unzippedFile : unzippedFiles) {
            FileUtils.copyFileToDirectory(unzippedFile, dstDirFile);
        }

        if (templateFile.exists()) {
            return templateFile;
        }

    } catch (Exception ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, "You are missing the template that is needed to run this tool.");
    }
    return null;
}