Example usage for java.io OutputStreamWriter flush

List of usage examples for java.io OutputStreamWriter flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:com.buglabs.dragonfly.util.WSHelper.java

protected static String post(URL url, String payload, Map props) throws IOException {
    String propstr = new String();

    for (Iterator i = props.keySet().iterator(); i.hasNext();) {
        String key = (String) i.next();
        propstr = propstr + URLEncoder.encode(key, "UTF-8") + "="
                + URLEncoder.encode((String) props.get(key), "UTF-8");
        if (i.hasNext()) {
            propstr = propstr + "&";
        }//  w  w  w. ja va  2s .c  o  m
    }

    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);

    OutputStreamWriter osr = new OutputStreamWriter(conn.getOutputStream());
    osr.write(propstr);
    osr.flush();

    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line, resp = new String("");
    while ((line = rd.readLine()) != null) {
        resp = resp + line + "\n";
    }
    osr.close();
    rd.close();

    return resp;
}

From source file:com.telefonica.iot.perseo.Utils.java

/**
 * Makes an HTTP POST to an URL sending an body. The URL and body are
 * represented as String./*from www. jav  a 2  s.c  om*/
 *
 * @param urlStr String representation of the URL
 * @param content Styring representation of the body to post
 *
 * @return if the request has been accompished
 */

public static boolean DoHTTPPost(String urlStr, String content) {
    try {
        URL url = new URL(urlStr);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setDoOutput(true);
        urlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        urlConn.setRequestProperty(Constants.CORRELATOR_HEADER, MDC.get(Constants.CORRELATOR_ID));
        urlConn.setRequestProperty(Constants.SERVICE_HEADER, MDC.get(Constants.SERVICE_FIELD));
        urlConn.setRequestProperty(Constants.SUBSERVICE_HEADER, MDC.get(Constants.SUBSERVICE_FIELD));
        urlConn.setRequestProperty(Constants.REALIP_HEADER, MDC.get(Constants.REALIP_FIELD));

        OutputStreamWriter printout = new OutputStreamWriter(urlConn.getOutputStream(),
                Charset.forName("UTF-8"));
        printout.write(content);
        printout.flush();
        printout.close();

        int code = urlConn.getResponseCode();
        String message = urlConn.getResponseMessage();
        logger.debug("action http response " + code + " " + message);
        if (code / 100 == 2) {
            InputStream input = urlConn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            for (String line; (line = reader.readLine()) != null;) {
                logger.info("action response body: " + line);
            }
            input.close();
            return true;

        } else {
            logger.error("action response is not OK: " + code + " " + message);
            InputStream error = urlConn.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(error));
            for (String line; (line = reader.readLine()) != null;) {
                logger.error("action error response body: " + line);
            }
            error.close();
            return false;
        }
    } catch (MalformedURLException me) {
        logger.error("exception MalformedURLException: " + me);
        return false;
    } catch (IOException ioe) {
        logger.error("exception IOException: " + ioe);
        return false;
    }
}

From source file:org.collectionspace.services.IntegrationTests.xmlreplay.XmlReplayTransport.java

public static ServiceResult doPOST_PUT(String urlString, String content, String contentRaw, String boundary,
        String method, String contentType, String authForTest, String fromTestID) throws Exception {
    ServiceResult result = new ServiceResult();
    result.method = method;//from  www  .  j  av a2  s . co m
    String deleteURL = "";
    String location = "";
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn;
        conn = (HttpURLConnection) url.openConnection();

        if (MULTIPART_MIXED.equalsIgnoreCase(contentType)) {
            conn.setRequestProperty("Accept", "multipart/mixed");
            conn.setRequestProperty("content-type", "multipart/mixed; boundary=" + boundary);
        } else {
            conn.setRequestProperty("Accept", "application/xml");
            conn.setRequestProperty("content-type", contentType);
        }
        conn.setRequestProperty("Authorization", "Basic " + authForTest); //TODO: remove test user : hard-coded as "dGVzdDp0ZXN0"
        conn.setRequestProperty("Connection", "close");
        conn.setRequestProperty("X-XmlReplay-fromTestID", fromTestID);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod(method); // "POST" or "PUT"
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(content);
        wr.flush();

        try {
            result.requestPayload = content;
            result.requestPayloadsRaw = contentRaw;
            result.responseCode = conn.getResponseCode();
            //System.out.println("responseCode: "+result.responseCode);
            if (400 <= result.responseCode && result.responseCode <= 499) {
                return result;
            }
            readStream(conn, result);
        } catch (Throwable t) {
            //System.err.println("ERROR getting content from response: "+t);
            result.error = t.toString();
        }
        wr.close();

        Map<String, List<String>> headers = conn.getHeaderFields();
        List<String> locations = headers.get("Location");
        if (locations != null) {
            String locationZero = locations.get(0);
            if (locationZero != null) {
                String[] segments = locationZero.split("/");
                location = segments[segments.length - 1];
                deleteURL = Tools.glue(urlString, "/", location);
            }
        }
        result.location = location;
        result.deleteURL = deleteURL;
        result.CSID = location;
    } catch (Throwable t2) {
        result.error = "ERROR in XmlReplayTransport: " + t2;
    }
    return result;
}

From source file:com.buglabs.dragonfly.util.WSHelper.java

protected static String post(URL url, Map props) throws IOException {
    String propstr = new String();

    for (Iterator i = props.keySet().iterator(); i.hasNext();) {
        String key = (String) i.next();
        propstr = propstr + URLEncoder.encode(key, "UTF-8") + "="
                + URLEncoder.encode((String) props.get(key), "UTF-8");
        if (i.hasNext()) {
            propstr = propstr + "&";
        }// ww w .  j  a v  a 2 s. com
    }

    SSLUtils.verifyHost();

    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);

    OutputStreamWriter osr = new OutputStreamWriter(conn.getOutputStream());
    osr.write(propstr);
    osr.flush();

    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line, resp = new String("");
    while ((line = rd.readLine()) != null) {
        resp = resp + line + "\n";
    }
    osr.close();
    rd.close();

    return resp;
}

From source file:CopyUtils.java

/**
 * Serialize chars from a <code>String</code> to bytes on an
 * <code>OutputStream</code>, and
 * flush the <code>OutputStream</code>.
 * @param input the <code>String</code> to read from
 * @param output the <code>OutputStream</code> to write to
 * @throws IOException In case of an I/O problem
 *///from w ww. j a v  a 2  s  .com
public static void copy(String input, OutputStream output) throws IOException {
    StringReader in = new StringReader(input);
    OutputStreamWriter out = new OutputStreamWriter(output);
    copy(in, out);
    // XXX Unless anyone is planning on rewriting OutputStreamWriter, we
    // have to flush here.
    out.flush();
}

From source file:com.amalto.workbench.utils.FileProvider.java

public static IFile createdTempFile(String templateString, String fileNameWithExtension, String charSet) {
    IFile file = null;//from  w  ww.jav  a  2  s.  c  o m
    if (templateString != null) {
        try {
            Project project = ProjectManager.getInstance().getCurrentProject();
            IProject prj = ResourceUtils.getProject(project);
            file = prj.getFile(new Path("temp/" + fileNameWithExtension)); //$NON-NLS-1$

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            OutputStreamWriter outputStreamWriter = null;
            if ((charSet == null) || (charSet.trim().isEmpty())) {
                outputStreamWriter = new OutputStreamWriter(outputStream);
            } else {
                outputStreamWriter = new OutputStreamWriter(outputStream, charSet);
            }

            outputStreamWriter.write(templateString);
            outputStreamWriter.flush();
            outputStreamWriter.close();

            ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
            if (file.exists()) {
                file.setContents(inputStream, true, false, null);
            } else {
                file.create(inputStream, true, null);
            }

            inputStream.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    return file;
}

From source file:CopyUtils.java

/**
 * Serialize chars from a <code>Reader</code> to bytes on an
 * <code>OutputStream</code>, and flush the <code>OutputStream</code>.
 * @param input the <code>Reader</code> to read from
 * @param output the <code>OutputStream</code> to write to
 * @throws IOException In case of an I/O problem
 *///  w  ww  .jav a  2 s .  com
public static void copy(Reader input, OutputStream output) throws IOException {
    OutputStreamWriter out = new OutputStreamWriter(output);
    copy(input, out);
    // XXX Unless anyone is planning on rewriting OutputStreamWriter, we
    // have to flush here.
    out.flush();
}

From source file:Main.java

public static String[] execSQL(String dbName, String query) {
    Process process = null;//from  ww  w  .  j  av  a  2s  .  c om
    Runtime runtime = Runtime.getRuntime();
    OutputStreamWriter outputStreamWriter;

    try {
        String command = dbName + " " + "'" + query + "'" + ";";
        process = runtime.exec("su");

        outputStreamWriter = new OutputStreamWriter(process.getOutputStream());

        outputStreamWriter.write("sqlite3 " + command);

        outputStreamWriter.flush();
        outputStreamWriter.close();
        outputStreamWriter.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    final InputStreamReader errorStreamReader = new InputStreamReader(process.getErrorStream());

    (new Thread() {
        @Override
        public void run() {
            try {

                BufferedReader bufferedReader = new BufferedReader(errorStreamReader);
                String s;
                while ((s = bufferedReader.readLine()) != null) {
                    Log.d("com.suraj.waext", "WhatsAppDBHelper:" + s);
                }

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    }).start();

    try {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String s;
        StringBuilder op = new StringBuilder();

        while ((s = bufferedReader.readLine()) != null) {
            op.append(s).append("\n");
        }

        return op.toString().split("\n");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;

}

From source file:Main.java

public static int doShellCommand(String[] cmds, StringBuilder log, boolean runAsRoot, boolean waitFor)
        throws Exception {

    Process proc = null;/*from www . ja va 2 s  .c  o m*/
    int exitCode = -1;

    if (runAsRoot)
        proc = Runtime.getRuntime().exec("su");
    else
        proc = Runtime.getRuntime().exec("sh");

    OutputStreamWriter out = new OutputStreamWriter(proc.getOutputStream());

    for (int i = 0; i < cmds.length; i++) {
        Log.d("the-onion-phone",
                "executing shell cmd: " + cmds[i] + "; runAsRoot=" + runAsRoot + ";waitFor=" + waitFor);

        out.write(cmds[i]);
        out.write("\n");
    }

    out.flush();
    out.write("exit\n");
    out.flush();

    if (waitFor) {

        final char buf[] = new char[10];

        // Consume the "stdout"
        InputStreamReader reader = new InputStreamReader(proc.getInputStream());
        int read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        // Consume the "stderr"
        reader = new InputStreamReader(proc.getErrorStream());
        read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        exitCode = proc.waitFor();

    }

    return exitCode;

}

From source file:ext.services.xml.XMLUtils.java

/**
 * Writes an object to a file as xml./*w  w w .j a va 2 s .  c  o m*/
 * 
 * @param object Object that should be writen to a xml file
 * @param filename filename
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void writeObjectToFile(Object object, String filename) throws IOException {
    OutputStreamWriter outputStreamWriter = null;
    try {
        outputStreamWriter = new OutputStreamWriter(new FileOutputStream(filename), "UTF-8");
        xStream.toXML(object, outputStreamWriter);
    } finally {
        if (outputStreamWriter != null) {
            outputStreamWriter.flush();
            outputStreamWriter.close();
        }
    }
}