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:ManagerQuery.java

private void notifyEvent(double valueNum, Rule rule) {
    Properties conf2 = new Properties();

    try {/*from   w  w  w . j  ava  2  s . com*/
        FileInputStream in = new FileInputStream("./config.properties");
        conf2.load(in);
        in.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex);
    }

    String url = conf2.getProperty("notificatorRestInterfaceUrl");
    String charset = java.nio.charset.StandardCharsets.UTF_8.name();
    String apiUsr = conf2.getProperty("notificatorRestInterfaceUsr");
    String apiPwd = conf2.getProperty("notificatorRestInterfacePwd");
    String operation = "notifyEvent";
    String generatorOriginalName = rule.getWidgetTitle();
    String generatorOriginalType = rule.getMetricName();
    String containerName = rule.getDashboardTitle();
    String eventType = rule.getEventType();
    String value = Double.toString(valueNum);

    Calendar date = new GregorianCalendar();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String eventTime = sdf.format(date.getTime());
    String appName = "Dashboard Manager";
    String params = null;

    URL obj = null;
    HttpURLConnection con = null;
    try {
        obj = new URL(url);
        con = (HttpURLConnection) obj.openConnection();

        con.setRequestMethod("POST");
        con.setRequestProperty("Accept-Charset", charset);
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);

        params = String.format(
                "apiUsr=%s&apiPwd=%s&appName=%s&operation=%s&generatorOriginalName=%s&generatorOriginalType=%s&containerName=%s&eventType=%s&eventTime=%s&value=%s",
                URLEncoder.encode(apiUsr, charset), URLEncoder.encode(apiPwd, charset),
                URLEncoder.encode(appName, charset), URLEncoder.encode(operation, charset),
                URLEncoder.encode(generatorOriginalName, charset),
                URLEncoder.encode(generatorOriginalType, charset), URLEncoder.encode(containerName, charset),
                URLEncoder.encode(eventType, charset), URLEncoder.encode(eventTime, charset),
                URLEncoder.encode(value, charset));
    } catch (MalformedURLException ex) {
        Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex);
    }

    // Questo rende la chiamata una POST
    con.setDoOutput(true);
    DataOutputStream wr = null;

    try {
        wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(params);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        String responseMessage = con.getResponseMessage();
    } catch (IOException ex) {
        Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.maverick.ssl.https.HttpsURLConnection.java

void writeRequest(OutputStream out) throws IOException {
    DataOutputStream data = new DataOutputStream(new BufferedOutputStream(out));
    if ((doOutput) && (output == null)) {
        throw new IOException(Messages.getString("HttpsURLConnection.noPOSTData")); //$NON-NLS-1$
    }// w w  w  . jav  a 2 s  . com
    if (ifModifiedSince != 0) {
        Date date = new Date(ifModifiedSince);
        SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy hh:mm:ss z"); //$NON-NLS-1$
        formatter.setTimeZone(TimeZone.getTimeZone("GMT")); //$NON-NLS-1$
        setRequestProperty("If-Modified-Since", formatter.format(date)); //$NON-NLS-1$
    }
    if (doOutput) {
        setRequestProperty("Content-length", "" + output.size()); //$NON-NLS-1$ //$NON-NLS-2$
    }

    data.writeBytes((doOutput ? "POST" : "GET") + " " + (url.getFile().equals("") ? "/" : url.getFile()) //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$//$NON-NLS-5$
            + " HTTP/1.0\r\n"); //$NON-NLS-1$

    for (int i = 0; i < requestKeys.size(); ++i) {
        String key = (String) requestKeys.elementAt(i);
        if (!key.startsWith("Proxy-")) { //$NON-NLS-1$
            data.writeBytes(key + ": " + requestValues.elementAt(i) + "\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
        }
    }
    data.writeBytes("\r\n"); //$NON-NLS-1$
    data.flush();
    if (doOutput) {
        output.writeTo(out);
    }
    out.flush();
}

From source file:com.ebay.erl.mobius.core.collection.BigTupleList.java

/**
 * Flush {@link Tuple}s in {@link #buffer_in_memory} into
 * disk, and new local file will be created by {@link #newLocalFile()}
 * and store the {@link File} reference in {@link #buffer_on_disk} for
 * future reference./*w  ww.j  a  v  a2  s .  c  om*/
 */
private void flushToDisk() {
    this.flushing = true;
    File localFile;

    if (this.buffer_in_memory.size() == 0) {
        // no tuple in memory
        return;
    }
    long start = System.currentTimeMillis();
    long availableMemory = this.availableMemory();

    String message = Thread.currentThread().toString() + " BID[" + this._ID + "] "
            + "writing in-memory tuples (" + getNumberFormat().format(this.buffer_in_memory.size())
            + " entries) into disk, " + "available memory:" + availableMemory / _MB + "MB.";

    LOGGER.info(message);
    if (this.reporter != null) {
        this.reporter.setStatus(message);
        this.reporter.progress();
    }

    try {
        // check if we still have enough local space to prevent 
        // full of disk exception.
        long freeDiskSpace = this.workOutput.getFreeSpace() / _MB;
        if (freeDiskSpace < 300) {
            // less than 300MB free space left, throw
            // exceptions
            throw new IOException("Not enough space left (" + freeDiskSpace + "MB remaining) on "
                    + this.workOutput.getAbsolutePath() + ".");
        }

        localFile = this.newLocalFile();
        DataOutputStream out = new DataOutputStream(
                new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(localFile))));

        // write the tuple schema in the header
        String[] tupleSchema = this.buffer_in_memory.get(0).getSchema();
        out.writeInt(tupleSchema.length);
        if (tupleSchema.length == 0)
            throw new IllegalArgumentException("Tuple with empty schema!");
        for (String aColumn : tupleSchema) {
            out.writeUTF(aColumn);
        }

        // write number of tuple in this file
        out.writeLong(this.buffer_in_memory.size());

        if (this.comparator != null) {
            // sort the Tuple in memory first
            Collections.sort(this.buffer_in_memory, this.comparator);
        }

        // write all the tuple in memory buffer
        long counts = 0L;
        for (Tuple aTuple : this.buffer_in_memory) {
            aTuple.write(out);
            counts++;
            if (counts % 5000 == 0 && this.reporter != null)// report every 5000 IO
                this.reporter.progress();
        }
        out.flush();
        out.close();

        // clear memory buffer
        this.buffer_in_memory.clear();

        long end = System.currentTimeMillis();

        LOGGER.info(Thread.currentThread().toString() + " BID[" + this._ID + "] " + "Write has completed, cost "
                + ((end - start) / 1000) + " seconds, " + "available memory:" + this.availableMemory() / _MB
                + "MB, " + "wrote to:" + localFile.getAbsolutePath() + "(size:"
                + localFile.getTotalSpace() / _MB + "MB) , " + "in memory tuples numbers:"
                + this.buffer_in_memory.size());

        this.flushing = false;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.basho.riak.pbc.RiakClient.java

public ByteString[] store(RiakObject[] values, RequestMeta meta) throws IOException {

    RiakConnection c = getConnection();/*from  w  w  w.j  a  v a  2s  .c o  m*/
    try {
        BulkReader reader = new BulkReader(c, values.length);
        Thread worker = new Thread(reader);
        worker.start();

        DataOutputStream dout = c.getOutputStream();

        for (int i = 0; i < values.length; i++) {
            RiakObject value = values[i];

            RiakKvPB.RpbPutReq.Builder builder = RiakKvPB.RpbPutReq.newBuilder().setBucket(value.getBucketBS())
                    .setKey(value.getKeyBS()).setContent(value.buildContent());

            if (value.getVclock() != null) {
                builder.setVclock(value.getVclock());
            }

            builder.setReturnBody(true);

            if (meta != null) {

                if (meta.writeQuorum != null) {
                    builder.setW(meta.writeQuorum.intValue());
                }

                if (meta.durableWriteQuorum != null) {
                    builder.setDw(meta.durableWriteQuorum.intValue());
                }
            }

            RpbPutReq req = builder.build();

            int len = req.getSerializedSize();
            dout.writeInt(len + 1);
            dout.write(MSG_PutReq);
            req.writeTo(dout);
        }

        dout.flush();

        try {
            worker.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return reader.vclocks;
    } finally {
        release(c);
    }
}

From source file:com.stratuscom.harvester.codebase.ClassServer.java

private boolean processRequest(Socket sock) {
    try {/*from   w w w  .ja va 2s.  co m*/
        DataOutputStream out = new DataOutputStream(sock.getOutputStream());
        String req;
        try {
            req = getInput(sock, true);
        } catch (Exception e) {
            logger.log(Level.FINE, "reading request", e);
            return true;
        }
        if (req == null) {
            return true;
        }
        String[] args = new String[3];
        boolean get = req.startsWith("GET ");
        if (!get && !req.startsWith("HEAD ")) {
            processBadRequest(args, out);
        }
        String path = parsePathFromRequest(req, get);
        if (path == null) {
            return processBadRequest(args, out);
        }
        if (args != null) {
            args[0] = path;
        }
        args[1] = sock.getInetAddress().getHostName();
        args[2] = Integer.toString(sock.getPort());

        logger.log(Level.FINER,
                get ? MessageNames.CLASS_SERVER_RECEIVED_REQUEST : MessageNames.CLASS_SERVER_RECEIVED_PROBE,
                args);
        byte[] bytes;
        try {
            bytes = getBytes(path);
        } catch (Exception e) {
            logger.log(Level.WARNING, MessageNames.CLASS_SERVER_EXCEPTION_GETTING_BYTES, e);
            out.writeBytes("HTTP/1.0 500 Internal Error\r\n\r\n");
            out.flush();
            return true;
        }
        if (bytes == null) {
            logger.log(Level.FINE, MessageNames.CLASS_SERVER_NO_CONTENT_FOUND, path);
            out.writeBytes("HTTP/1.0 404 Not Found\r\n\r\n");
            out.flush();
            return true;
        }
        writeHeader(out, bytes);
        if (get) {
            out.write(bytes);
        }
        out.flush();
        return false;
    } catch (Exception e) {
        logger.log(Level.FINE, MessageNames.CLASS_SERVER_EXCEPTION_WRITING_RESPONSE, e);
    } finally {
        try {
            sock.close();
        } catch (IOException e) {
        }
    }
    return false;
}

From source file:com.bjorsond.android.timeline.sync.ServerUploader.java

protected static void uploadFile(String locationFilename, String saveFilename) {
    System.out.println("saving " + locationFilename + "!! ");
    if (!saveFilename.contains("."))
        saveFilename = saveFilename + Utilities.getExtension(locationFilename);

    if (!fileExistsOnServer(saveFilename)) {

        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;

        String pathToOurFile = locationFilename;
        String urlServer = "http://folk.ntnu.no/bjornava/upload/upload.php";
        //         String urlServer = "http://timelinegamified.appspot.com/upload.php";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024 * 1024;

        try {/*  w w w. j  a v a  2s .  c  o  m*/
            FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));

            URL url = new URL(urlServer);
            connection = (HttpURLConnection) url.openConnection();

            // Allow Inputs & Outputs
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

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

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

            outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                    + saveFilename + "\"" + lineEnd);
            outputStream.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // Read file
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {
                outputStream.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

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

            // Responses from the server (code and message)
            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

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

            System.out.println("Server response: " + serverResponseCode + " Message: " + serverResponseMessage);
        } catch (Exception ex) {
            //Exception handling
        }
    } else {
        System.out.println("image exists on server");
    }
}

From source file:com.nks.nksmod.otaupdater.DownloadsActivity.java

private void flashFiles(String[] files, boolean backup, boolean wipeCache, boolean wipeData) {
    try {/*from   w  w w. j av a  2 s.co m*/
        Process p = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(p.getOutputStream());
        os.writeBytes("echo 'NKS MOD Updater'\n");
        os.writeBytes("mkdir -p /cache/recovery/\n");
        os.writeBytes("rm -rf /cache/recovery/command\n");
        os.writeBytes("rm -rf /cache/recovery/extendedcommand\n");
        os.writeBytes("rm -rf /cache/recovery/update.zip\n");
        os.writeBytes("rm -rf /cache/recovery/nksmod.zip\n");
        os.writeBytes("echo 'boot-recovery' >> /cache/recovery/command\n");

        if (backup) {
            os.writeBytes("echo '--nandroid' >> /cache/recovery/command\n");
        }
        if (wipeData) {
            /* os.writeBytes("echo '--wipe_data' >> /cache/recovery/command\n"); */
        }
        if (wipeCache) {
            /* os.writeBytes("echo '--wipe_cache' >> /cache/recovery/command\n"); */
        }

        for (String file : files) {
            os.writeBytes("cp " + file + " /cache/recovery/nksmod.zip\n");
            os.writeBytes("echo '--update_package=/cache/recovery/nksmod.zip' >> /cache/recovery/command\n");
        }

        String rebootCmd = PropUtils.getRebootCmd();
        if (!rebootCmd.equals("$$NULL$$")) {
            os.writeBytes("sync\n");
            if (rebootCmd.endsWith(".sh")) {
                os.writeBytes("sh " + rebootCmd + "\n");
            } else {
                os.writeBytes(rebootCmd + "\n");
            }
        }

        os.writeBytes("sync\n");
        os.writeBytes("exit\n");
        os.flush();
        p.waitFor();
        ((PowerManager) getSystemService(POWER_SERVICE)).reboot("recovery");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.kyne.webby.rtk.web.WebServer.java

/**
 * Read a print a static file (js, css, html or png).
 * @param path the path to the file/*from   w  w  w  .ja v  a 2  s  .c  om*/
 * @param type the mimetype
 * @param jsStates some javascripts variables that may be initialized in the printed content. Null if not required.
 * @param clientSocket the client-side socket
 */
public void printStaticFile(final String path, final String type, final Socket clientSocket,
        final Map<String, String> jsStates) {
    try {
        final File htmlPage = new File(path);
        if (htmlPage.exists()) {
            final DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
            out.writeBytes("HTTP/1.1 200 OK\r\n");
            out.writeBytes("Content-Type: " + type + "; charset=utf-8\r\n");
            out.writeBytes("Cache-Control: no-cache \r\n");
            out.writeBytes("Server: Bukkit Webby\r\n");
            out.writeBytes("Connection: Close\r\n\r\n");
            if (jsStates != null) {
                out.writeBytes("<script type='text/javascript'>");
                for (final String var : jsStates.keySet()) {
                    out.writeBytes("var " + var + " = '" + jsStates.get(var) + "';");
                }
                out.writeBytes("</script>");
            }
            if (!this.htmlCache.containsKey(path)) { //Pages are static, so we can "pre-read" them. Dynamic content will be rendered with javascript
                final FileInputStream fis = new FileInputStream(htmlPage);
                final byte fileContent[] = new byte[(int) htmlPage.length()];
                fis.read(fileContent);
                fis.close();
                this.htmlCache.put(path, fileContent);
            } else {
                LogHelper.debug("File will be added in Webby's cache");
            }
            out.write(this.htmlCache.get(path));
            out.flush();
            out.close();
        } else {
            LogHelper.warn("Requested file " + path + " can't be found");
        }
    } catch (final SocketException e) {
        /* Or not ! */
    } catch (final Exception e) {
        LogHelper.error(e.getMessage(), e);
    }
}

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

public JSONObject makeSendMoneyRequest(String accessToken, CitrusUser toUser, Amount amount, String message) {
    HttpsURLConnection conn;//from   w  ww.j a  va 2 s  . c o m
    DataOutputStream wr = null;
    JSONObject txnDetails = null;
    BufferedReader in = null;

    try {
        String url = null;

        StringBuffer postDataBuff = new StringBuffer("amount=");
        postDataBuff.append(amount.getValue());

        postDataBuff.append("&currency=");
        postDataBuff.append(amount.getCurrency());

        postDataBuff.append("&message=");
        postDataBuff.append(message);

        if (!TextUtils.isEmpty(toUser.getEmailId())) {
            url = urls.getString(base_url) + urls.getString("transfer");
            postDataBuff.append("&to=");
            postDataBuff.append(toUser.getEmailId());

        } else if (!TextUtils.isEmpty(toUser.getMobileNo())) {
            url = urls.getString(base_url) + urls.getString("suspensetransfer");

            postDataBuff.append("&to=");
            postDataBuff.append(toUser.getMobileNo());

        }

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

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

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

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

        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + postDataBuff.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:org.caboclo.clients.OneDriveClient.java

@Override
public void putFile(File file, String path) throws IOException {
    final String BOUNDARY_STRING = "3i2ndDfv2rThIsIsPrOjEcTSYNceEMCPROTOTYPEfj3q2f";

    //We use the directory name (without actual file name) to get folder ID
    int indDirName = path.replace("/", "\\").lastIndexOf("\\");
    String targetFolderId = getFolderID(path.substring(0, indDirName));
    System.out.printf("Put file: %s\tId: %s\n", path, targetFolderId);

    if (targetFolderId == null || targetFolderId.isEmpty()) {
        return;//from  ww w  .  j a v  a 2s . c o m
    }

    URL connectURL = new URL("https://apis.live.net/v5.0/" + targetFolderId + "/files?"
            + "state=MyNewFileState&redirect_uri=https://login.live.com/oauth20_desktop.srf" + "&access_token="
            + accessToken);
    HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY_STRING);
    // set read & write
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.connect();
    // set body
    DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
    dos.writeBytes("--" + BOUNDARY_STRING + "\r\n");
    dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
            + URLEncoder.encode(file.getName(), "UTF-8") + "\"\r\n");
    dos.writeBytes("Content-Type: application/octet-stream\r\n");
    dos.writeBytes("\r\n");

    FileInputStream fileInputStream = new FileInputStream(file);
    int fileSize = fileInputStream.available();
    int maxBufferSize = 8 * 1024;
    int bufferSize = Math.min(fileSize, maxBufferSize);
    byte[] buffer = new byte[bufferSize];

    // send file
    int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    while (bytesRead > 0) {

        // Upload file part(s)
        dos.write(buffer, 0, bytesRead);

        int bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, buffer.length);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }
    fileInputStream.close();
    // send file end

    dos.writeBytes("\r\n");
    dos.writeBytes("--" + BOUNDARY_STRING + "--\r\n");

    dos.flush();

    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line = null;
    StringBuilder sbuilder = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        sbuilder.append(line);
    }

    String fileId = null;
    try {
        JSONObject json = new JSONObject(sbuilder.toString());
        fileId = json.getString("id");
        //System.out.println("File ID is: " + fileId);
        //System.out.println("File name is: " + json.getString("name"));
        //System.out.println("File uploaded sucessfully.");
    } catch (JSONException e) {
        Logger.getLogger(OneDriveClient.class.getName()).log(Level.WARNING,
                "Error uploading file " + file.getName(), e);
    }
}