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.jiubang.core.util.HttpUtils.java

/**
 * Send an HTTP(s) request with POST parameters.
 * //from  w ww  . j a va 2 s.  co m
 * @param parameters
 * @param url
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
static void doPost(Map<?, ?> parameters, URL url)
        throws UnsupportedEncodingException, IOException, KeyManagementException, NoSuchAlgorithmException {

    URLConnection cnx = getConnection(url);

    // Construct data
    StringBuilder dataBfr = new StringBuilder();
    Iterator<?> iKeys = parameters.keySet().iterator();
    while (iKeys.hasNext()) {
        if (dataBfr.length() != 0) {
            dataBfr.append('&');
        }
        String key = (String) iKeys.next();
        dataBfr.append(URLEncoder.encode(key, "UTF-8")).append('=')
                .append(URLEncoder.encode((String) parameters.get(key), "UTF-8"));
    }
    // POST data
    cnx.setDoOutput(true);

    OutputStreamWriter wr = new OutputStreamWriter(cnx.getOutputStream());
    Loger.d(LOG_TAG, "Posting crash report data");
    wr.write(dataBfr.toString());
    wr.flush();
    wr.close();

    Loger.d(LOG_TAG, "Reading response");
    BufferedReader rd = new BufferedReader(new InputStreamReader(cnx.getInputStream()));

    String line;
    while ((line = rd.readLine()) != null) {
        Loger.d(LOG_TAG, line);
    }
    rd.close();
}

From source file:org.acra.HttpUtils.java

/**
 * Send an HTTP(s) request with POST parameters.
 * //from   ww w  .  j a  va 2 s .c o  m
 * @param parameters
 * @param url
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
static void doPost(Map<?, ?> parameters, URL url)
        throws UnsupportedEncodingException, IOException, KeyManagementException, NoSuchAlgorithmException {

    URLConnection cnx = getConnection(url);

    // Construct data
    StringBuilder dataBfr = new StringBuilder();
    Iterator<?> iKeys = parameters.keySet().iterator();
    while (iKeys.hasNext()) {
        if (dataBfr.length() != 0) {
            dataBfr.append('&');
        }
        String key = (String) iKeys.next();
        dataBfr.append(URLEncoder.encode(key, "UTF-8")).append('=')
                .append(URLEncoder.encode((String) parameters.get(key), "UTF-8"));
    }
    // POST data
    cnx.setDoOutput(true);

    OutputStreamWriter wr = new OutputStreamWriter(cnx.getOutputStream());
    Log.d(LOG_TAG, "Posting crash report data");
    wr.write(dataBfr.toString());
    wr.flush();
    wr.close();

    Log.d(LOG_TAG, "Reading response");
    BufferedReader rd = new BufferedReader(new InputStreamReader(cnx.getInputStream()));

    String line;
    while ((line = rd.readLine()) != null) {
        Log.d(LOG_TAG, line);
    }
    rd.close();
}

From source file:de.innovationgate.utils.XStreamUtils.java

/**
 * Serializes an object to a UTF-8 encoded output stream
 * @param obj The object to write/*from   w  w w. j  a v  a2 s .co m*/
 * @param xstream The XStream instance to use
 * @param out The output stream to write to
 * @throws IOException
 */
public static void writeUtf8ToOutputStream(Object obj, XStream xstream, OutputStream out) throws IOException {
    BufferedOutputStream bufOut = new BufferedOutputStream(out);
    OutputStreamWriter writer;
    try {
        writer = new OutputStreamWriter(bufOut, "UTF-8");
        xstream.toXML(obj, writer);
        writer.flush();
        writer.close();
    } catch (UnsupportedEncodingException e) {
        // Cannot happen since Java always supports UTF-8
    }
}

From source file:com.ct855.util.HttpsClientUtil.java

public static String postUrl(String url, Map<String, String> params)
        throws IOException, NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException {
    //SSLContext??
    TrustManager[] trustAllCerts = new TrustManager[] { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    //SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    String data = "";
    for (String key : params.keySet()) {
        data += "&" + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(params.get(key), "UTF-8");
    }/*from  w ww.j  ava 2  s  .  c  o  m*/
    data = data.substring(1);

    System.out.println("postUrl=>data:" + data);
    URL aURL = new java.net.URL(url);
    HttpsURLConnection aConnection = (HttpsURLConnection) aURL.openConnection();
    aConnection.setSSLSocketFactory(ssf);
    aConnection.setDoOutput(true);
    aConnection.setDoInput(true);
    aConnection.setRequestMethod("POST");
    OutputStreamWriter streamToAuthorize = new java.io.OutputStreamWriter(aConnection.getOutputStream());
    streamToAuthorize.write(data);
    streamToAuthorize.flush();
    streamToAuthorize.close();
    InputStream resultStream = aConnection.getInputStream();
    BufferedReader aReader = new java.io.BufferedReader(new java.io.InputStreamReader(resultStream));
    StringBuffer aResponse = new StringBuffer();
    String aLine = aReader.readLine();
    while (aLine != null) {
        aResponse.append(aLine + "\n");
        aLine = aReader.readLine();
    }
    resultStream.close();
    return aResponse.toString();
}

From source file:org.eclipse.winery.repository.ext.export.yaml.YamlExportFileGenerator.java

private static void write2OutputStream(String strServiceTemplate, OutputStream out)
        throws ExportCommonException {
    try {//from   w  ww.  j  av  a 2  s  .  co m
        OutputStreamWriter osWriter = new OutputStreamWriter(out);
        osWriter.write(strServiceTemplate);
        osWriter.flush();
    } catch (IOException e) {
        throw new ExportCommonException("Write to file failed.", e);
    }
}

From source file:org.exoplatform.portal.webui.application.GadgetUtil.java

/**
 * Fetchs Metatada of gadget application, create the connection to shindig
 * server to get the metadata TODO cache the informations for better
 * performance//from w w w  .jav a2  s.co m
 * 
 * @return the string represents metadata of gadget application
 */
public static String fetchGagdetMetadata(String urlStr) {
    String result = null;

    ExoContainer container = ExoContainerContext.getCurrentContainer();
    GadgetRegistryService gadgetService = (GadgetRegistryService) container
            .getComponentInstanceOfType(GadgetRegistryService.class);
    try {
        String data = "{\"context\":{\"country\":\"" + gadgetService.getCountry() + "\",\"language\":\""
                + gadgetService.getLanguage() + "\"},\"gadgets\":[" + "{\"moduleId\":"
                + gadgetService.getModuleId() + ",\"url\":\"" + urlStr + "\",\"prefs\":[]}]}";
        // Send data
        String gadgetServer = getGadgetServerUrl();
        URL url = new URL(gadgetServer + (gadgetServer.endsWith("/") ? "" : "/") + "metadata");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();
        // Get the response
        result = IOUtils.toString(conn.getInputStream(), "UTF-8");
        wr.close();
    } catch (IOException ioexc) {
        ioexc.printStackTrace();
        return "{}";
    }
    return result;
}

From source file:org.identityconnectors.office365.jsontoken.JWTTokenHelper.java

/**
 * Get an access token from ACS (STS)./*from   w w w  .  j a  va 2 s  .co  m*/
 * @param stsUrl ACS STS Url.
 * @param assertion Assertion Token.
 * @param resource ExpiresIn name.
 * @return The OAuth access token.
 * @throws SampleAppException If the operation can not be completed successfully.
 */
public static String getOAuthAccessTokenFromACS(String stsUrl, String assertion, String resource)
        throws Exception {

    String accessToken = "";

    URL url = null;

    String data = null;

    data = URLEncoder.encode(JWTTokenHelper.claimTypeGrantType, "UTF-8") + "="
            + URLEncoder.encode("http://oauth.net/grant_type/jwt/1.0/bearer", "UTF-8");
    data += "&" + URLEncoder.encode(JWTTokenHelper.claimTypeAssertion, "UTF-8") + "="
            + URLEncoder.encode(assertion, "UTF-8");
    data += "&" + URLEncoder.encode(JWTTokenHelper.claimTypeResource, "UTF-8") + "="
            + URLEncoder.encode(resource, "UTF-8");

    url = new URL(stsUrl);

    URLConnection conn = url.openConnection();

    conn.setDoOutput(true);

    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    String line, response = "";

    while ((line = rd.readLine()) != null) {
        response += line;
    }

    wr.close();
    rd.close();

    accessToken = (new JSONObject(response)).optString("access_token");
    return String.format("%s%s", JWTTokenHelper.bearerTokenPrefix, accessToken);
}

From source file:cc.vileda.sipgatesync.api.SipgateApi.java

public static String getToken(final String username, final String password) {
    try {/*from www  .j  a  v a 2  s .c  o  m*/
        final HttpURLConnection urlConnection = getConnection("/authorization/token");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod("POST");
        JSONObject request = new JSONObject();
        request.put("username", username);
        request.put("password", password);
        OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
        Log.d("SipgateApi", request.getString("username"));
        wr.write(request.toString());
        wr.flush();
        StringBuilder sb = new StringBuilder();
        int HttpResult = urlConnection.getResponseCode();
        if (HttpResult == HttpURLConnection.HTTP_OK) {
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(urlConnection.getInputStream(), "utf-8"));
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            br.close();
            Log.d("SipgateApi", "" + sb.toString());
            final JSONObject response = new JSONObject(sb.toString());
            return response.getString("token");
        } else {
            System.out.println(urlConnection.getResponseMessage());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.intermine.api.mines.FriendlyMineQueryRunner.java

/**
 * Run a query via the web service//from  ww w.  j av  a2  s. c om
 *
 * @param urlString url to query
 * @return reader
 */
public static BufferedReader runWebServiceQuery(String urlString) {
    if (StringUtils.isEmpty(urlString)) {
        return null;
    }
    BufferedReader reader = null;
    try {
        if (!urlString.contains("?")) {
            // GET
            URL url = new URL(urlString);
            URLConnection conn = url.openConnection();
            conn.setConnectTimeout(CONNECT_TIMEOUT);
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            LOG.info("FriendlyMine URL (GET) " + urlString);
        } else {
            // POST
            String[] params = urlString.split("\\?");
            String newUrlString = params[0];
            String queryString = params[1];
            URL url = new URL(newUrlString);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(queryString);
            wr.flush();
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            LOG.info("FriendlyMine URL (POST) " + urlString);
        }
        return reader;
    } catch (Exception e) {
        LOG.info("Unable to access " + urlString + " exception: " + e.getMessage());
        return null;
    }
}

From source file:Main.java

/** Write the text provided to a File.
 * /*from  w  ww .ja v  a 2 s  .  co m*/
 * @param file the file to write to.
 * @param text the text to write.
 * @throws IOException
 */
public static void write(File file, String text) throws IOException {
    FileOutputStream out = null;
    try {
        file.getParentFile().mkdirs();
        file.delete();
        file.createNewFile();
        out = new FileOutputStream(file);
        OutputStreamWriter writer = new OutputStreamWriter(out);
        writer.write(text);
        writer.flush();
    } finally {
        try {
            out.close();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}