Example usage for java.io OutputStreamWriter write

List of usage examples for java.io OutputStreamWriter write

Introduction

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

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:com.gdevelop.gwt.syncrpc.RemoteServiceSyncProxy.java

public Object doInvoke(RequestCallbackAdapter.ResponseReader responseReader, String requestData)
        throws Throwable {
    HttpURLConnection connection = null;
    InputStream is = null;//from  w ww .j  a  v a 2  s  . c  om
    int statusCode;

    if (DUMP_PAYLOAD) {
        log.debug("Send request to {}", remoteServiceURL);
        log.debug("Request payload: {}", requestData);
    }

    // Send request
    CookieHandler oldCookieHandler = CookieHandler.getDefault();
    try {
        CookieHandler.setDefault(cookieManager);

        URL url = new URL(remoteServiceURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty(RpcRequestBuilder.STRONG_NAME_HEADER, serializationPolicyName);
        connection.setRequestProperty(RpcRequestBuilder.MODULE_BASE_HEADER, moduleBaseURL);
        connection.setRequestProperty("Content-Type", "text/x-gwt-rpc; charset=utf-8");
        connection.setRequestProperty("Content-Length", "" + requestData.getBytes("UTF-8").length);

        CookieStore store = cookieManager.getCookieStore();
        String cookiesStr = "";

        for (HttpCookie cookie : store.getCookies()) {
            if (!"".equals(cookiesStr))
                cookiesStr += "; ";
            cookiesStr += cookie.getName() + "=" + cookie.getValue();
        }

        connection.setRequestProperty("Cookie", cookiesStr);

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(requestData);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        throw new InvocationException("IOException while sending RPC request", e);
    } finally {
        CookieHandler.setDefault(oldCookieHandler);
    }

    // Receive and process response
    try {

        is = connection.getInputStream();
        statusCode = connection.getResponseCode();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) > 0) {
            baos.write(buffer, 0, len);
        }
        String encodedResponse = baos.toString("UTF8");
        if (DUMP_PAYLOAD) {
            log.debug("Response code: {}", statusCode);
            log.debug("Response payload: {}", encodedResponse);
        }

        // System.out.println("Response payload (len = " + encodedResponse.length() + "): " + encodedResponse);
        if (statusCode != HttpURLConnection.HTTP_OK) {
            throw new StatusCodeException(statusCode, encodedResponse);
        } else if (encodedResponse == null) {
            // This can happen if the XHR is interrupted by the server dying
            throw new InvocationException("No response payload");
        } else if (isReturnValue(encodedResponse)) {
            encodedResponse = encodedResponse.substring(4);
            return responseReader.read(createStreamReader(encodedResponse));
        } else if (isThrownException(encodedResponse)) {
            encodedResponse = encodedResponse.substring(4);
            Throwable throwable = (Throwable) createStreamReader(encodedResponse).readObject();
            throw throwable;
        } else {
            throw new InvocationException("Unknown response " + encodedResponse);
        }
    } catch (IOException e) {

        log.error("error response: {}", IOUtils.toString(connection.getErrorStream()));
        throw new InvocationException("IOException while receiving RPC response", e);

    } catch (SerializationException e) {
        throw new InvocationException("Error while deserialization response", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ignore) {
            }
        }
        if (connection != null) {
            // connection.disconnect();
        }
    }
}

From source file:africastalkinggateway.AfricasTalkingGateway.java

private String sendPOSTRequest(HashMap<String, String> dataMap_, String urlString_) throws Exception {
    try {// w  w  w .j a  v  a 2 s  .  com
        String data = new String();
        Iterator<Entry<String, String>> it = dataMap_.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next();
            data += URLEncoder.encode(pairs.getKey().toString(), "UTF-8");
            data += "=" + URLEncoder.encode(pairs.getValue().toString(), "UTF-8");
            if (it.hasNext())
                data += "&";
        }
        URL url = new URL(urlString_);
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("apikey", _apiKey);
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(data);
        writer.flush();

        HttpURLConnection http_conn = (HttpURLConnection) conn;
        responseCode = http_conn.getResponseCode();

        BufferedReader reader;
        if (responseCode == HTTP_CODE_OK || responseCode == HTTP_CODE_CREATED)
            reader = new BufferedReader(new InputStreamReader(http_conn.getInputStream()));
        else
            reader = new BufferedReader(new InputStreamReader(http_conn.getErrorStream()));
        String response = reader.readLine();

        if (DEBUG)
            System.out.println(response);

        reader.close();
        return response;

    } catch (Exception e) {
        throw e;
    }
}

From source file:com.commerce4j.storefront.controllers.CatalogController.java

/**
 * @param request/*w ww  . jav  a2  s.c o m*/
 * @param response
 */
public void featuredBrands(HttpServletRequest request, HttpServletResponse response) {
    Map<String, Object> responseModel = new HashMap<String, Object>();
    response.setContentType(HTTP_HEADER_JSON);
    Gson gson = new GsonBuilder().create();

    BrandDAO brandDAO = (BrandDAO) getApplicationContext().getBean("brandDAO");
    List<BrandDTO> brands = brandDAO.findAllFeatured();

    responseModel.put("responseCode", SUCCESS);
    responseModel.put("responseMessage", "Login Completo");
    responseModel.put("brands", brands);

    // serialize output
    try {

        OutputStreamWriter os = new OutputStreamWriter(response.getOutputStream(), "UTF8");
        String data = gson.toJson(responseModel);
        os.write(data);

        os.flush();
        os.close();
    } catch (IOException e) {
        logger.fatal(e);
    }
}

From source file:fr.irit.sparql.Proxy.SparqlProxy.java

public boolean storeDataString(StringBuilder query)
        throws SparqlQueryMalFormedException, SparqlEndpointUnreachableException {
    boolean ret = true;
    SparqlProxy.cleanString(query);/*  w w w .ja  va 2s  .  com*/
    HttpURLConnection connection = null;
    try {
        String urlParameters = "update=" + URLEncoder.encode(query.toString(), "UTF-8");
        URL url = new URL(this.urlServer + "update");
        // Create connection
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");

        connection.setDoOutput(true);

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());

        writer.write(urlParameters);
        writer.flush();

        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String rep = "";
        while ((line = reader.readLine()) != null) {
            rep += line;
        }
        writer.close();
        reader.close();
    } catch (UnsupportedEncodingException ex) {
        throw new SparqlQueryMalFormedException("Encoding unsupported");
    } catch (MalformedURLException ex) {
        throw new SparqlQueryMalFormedException("Query malformed");
    } catch (IOException ex) {
        throw new SparqlEndpointUnreachableException(ex);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return ret;
}

From source file:org.teiid.arquillian.IntegrationTestRestWebserviceGeneration.java

private String httpCall(String url, String method, String params) throws Exception {
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setRequestMethod(method);
    connection.setDoOutput(true);/*ww  w . j av a2s  .  c  om*/

    if (method.equalsIgnoreCase("post")) {
        OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
        wr.write(params);
        wr.flush();
    }

    int code = connection.getResponseCode();
    if (code >= 400) {
        throw new TeiidRuntimeException(String.valueOf(code));
    }

    return ObjectConverterUtil
            .convertToString(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")));
}

From source file:net.sourceforge.atunes.kernel.modules.network.NetworkHandler.java

/**
 * Sends a POST request with given parameters and receives response with
 * given charset/* www . j  ava  2s. c  o  m*/
 * 
 * @param requestURL
 * @param params
 * @param charset
 * @return
 * @throws IOException
 */
@Override
public String readURL(final String requestURL, final Map<String, String> params, final String charset)
        throws IOException {
    URLConnection connection = getConnection(requestURL);
    connection.setUseCaches(false);
    connection.setDoInput(true);

    if (params != null && params.size() > 0) {
        connection.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(formatPOSTParameters(params));
        writer.flush();
    }

    InputStream input = null;
    try {
        input = connection.getInputStream();
        return IOUtils.toString(input, charset);
    } finally {
        ClosingUtils.close(input);
    }
}

From source file:edu.csh.coursebrowser.SchoolActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_course_browser);
    ListView lv = (ListView) this.findViewById(R.id.schools);
    this.setTitle("Course Browser");

    map_items = new HashMap<String, School>();
    map = new ArrayList<String>();
    this.sp = getPreferences(MODE_WORLD_READABLE);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, map);
    this.setTitle("Course Browser");

    if (!sp.contains("firstRun")) {
        SharedPreferences.Editor e = sp.edit();
        e.putBoolean("firstRun", false);
        e.commit();/*from w  ww . ja  va  2  s.  c  o m*/
        Intent intent = new Intent(SchoolActivity.this, AboutActivity.class);
        startActivity(intent);
    }

    addItem(new School("01", "Saunder's College of Business"));
    addItem(new School("03", "College of Engineering"));
    addItem(new School("05", "College of Liberal Arts"));
    addItem(new School("06", "Applied Science & Technology"));
    addItem(new School("08", "NTID"));
    addItem(new School("10", "College of Science"));
    addItem(new School("11", "Wellness"));
    addItem(new School("17", "Academic Services"));
    addItem(new School("20", "Imaging Arts and Sciences"));
    addItem(new School("30", "Interdisciplinary Studies"));
    addItem(new School("40", "GCCIS"));
    addItem(new School("50", "Institute for Sustainability"));

    lv.setAdapter(adapter);

    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            String s = ((TextView) arg1).getText().toString();
            final School school = map_items.get(s);
            new AsyncTask<String, String, String>() {
                ProgressDialog p;

                protected void onPreExecute() {
                    p = new ProgressDialog(SchoolActivity.this);
                    p.setTitle("Fetching Info");
                    p.setMessage("Contacting Server...");
                    p.setCancelable(false);
                    p.show();
                }

                protected String doInBackground(String... school) {
                    String params = "action=getDepartments&school=" + school[0] + "&quarter=20123";
                    Log.v("Params", params);
                    URL url;
                    String back = "";
                    try {
                        url = new URL("http://iota.csh.rit" + ".edu/schedule/js/browseAjax.php");

                        URLConnection conn = url.openConnection();
                        conn.setDoOutput(true);
                        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
                        writer.write(params);
                        writer.flush();
                        String line;
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(conn.getInputStream()));

                        while ((line = reader.readLine()) != null) {
                            Log.v("Back:", line);
                            back += line;
                        }
                        writer.close();
                        reader.close();
                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        return null;
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        return null;
                    }
                    return back;
                }

                protected void onPostExecute(String s) {
                    if (s == null || s == "") {
                        new AlertError(SchoolActivity.this, "IO Error!").show();
                        return;
                    }

                    try {
                        JSONObject jso = new JSONObject(s);
                        JSONArray jsa = new JSONArray(jso.getString("departments"));
                        ArrayList<Department> depts = new ArrayList<Department>();
                        for (int i = 0; i < jsa.length(); ++i) {
                            JSONObject obj = new JSONObject(jsa.get(i).toString());
                            depts.add(new Department(obj.getString("title"), obj.getString("id"),
                                    obj.getString("code")));
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        new AlertError(SchoolActivity.this, "Invalid JSON From Server").show();
                        p.dismiss();
                        return;
                    }

                    Intent intent = new Intent(SchoolActivity.this, DepartmentActivity.class);
                    intent.putExtra("from", school.deptName);
                    intent.putExtra("args", s);
                    intent.putExtra("qCode", sp.getString("quarter", "20122"));
                    startActivity(intent);
                    p.dismiss();
                }
            }.execute(school.deptNum);
        }

    });

}

From source file:fr.mby.saml2.sp.opensaml.query.engine.SloRequestQueryProcessor.java

/**
 * Send the SLO Response via the URL Api.
 * //  w w w  .  j  a  va 2  s . co  m
 * @param binding
 *            the binding to use
 * @param sloResponseRequest
 *            the SLO Response request
 */
protected void sendSloResponse(final SamlBindingEnum binding, final IOutgoingSaml sloResponseRequest) {
    URL sloUrl = null;
    HttpURLConnection sloConnexion = null;

    try {
        switch (binding) {
        case SAML_20_HTTP_REDIRECT:
            final String redirectUrl = sloResponseRequest.getHttpRedirectBindingUrl();

            sloUrl = new URL(redirectUrl);
            sloConnexion = (HttpURLConnection) sloUrl.openConnection();
            sloConnexion.setReadTimeout(10000);
            sloConnexion.connect();
            break;

        case SAML_20_HTTP_POST:
            final String sloEndpointUrl = sloResponseRequest.getEndpointUrl();
            final Collection<Entry<String, String>> sloPostParams = sloResponseRequest
                    .getHttpPostBindingParams();
            final StringBuffer samlDatas = new StringBuffer(1024);
            final Iterator<Entry<String, String>> itParams = sloPostParams.iterator();
            final Entry<String, String> firstParam = itParams.next();
            samlDatas.append(firstParam.getKey());
            samlDatas.append("=");
            samlDatas.append(firstParam.getValue());
            while (itParams.hasNext()) {
                final Entry<String, String> param = itParams.next();
                samlDatas.append("&");
                samlDatas.append(param.getKey());
                samlDatas.append("=");
                samlDatas.append(param.getValue());
            }

            sloUrl = new URL(sloEndpointUrl);
            sloConnexion = (HttpURLConnection) sloUrl.openConnection();
            sloConnexion.setDoInput(true);

            final OutputStreamWriter writer = new OutputStreamWriter(sloConnexion.getOutputStream());
            writer.write(samlDatas.toString());
            writer.flush();
            writer.close();

            sloConnexion.setReadTimeout(10000);
            sloConnexion.connect();
            break;

        default:
            break;
        }

        if (sloConnexion != null) {
            final InputStream responseStream = sloConnexion.getInputStream();

            final StringWriter writer = new StringWriter();
            IOUtils.copy(responseStream, writer, "UTF-8");
            final String response = writer.toString();

            this.logger.debug(String.format("HTTP response to SLO Request sent: [%s] ", response));

            final int responseCode = sloConnexion.getResponseCode();

            final String samlMessage = sloResponseRequest.getSamlMessage();
            final String endpointUrl = sloResponseRequest.getEndpointUrl();
            if (responseCode < 0) {
                this.logger.error("Unable to send SAML 2.0 Single Logout Response [{}] to endpoint URL [{}] !",
                        samlMessage, endpointUrl);
            } else if (responseCode == 200) {
                this.logger.info("SAML 2.0 Single Logout Request correctly sent to [{}] !", endpointUrl);
            } else {
                this.logger.error(
                        "HTTP response code: [{}] ! Error while sending SAML 2.0 Single Logout Request [{}] to endpoint URL [{}] !",
                        new Object[] { responseCode, samlMessage, endpointUrl });
            }
        }

    } catch (final MalformedURLException e) {
        this.logger.error(String.format("Malformed SAML SLO request URL: [%s] !", sloUrl.toExternalForm()), e);
    } catch (final IOException e) {
        this.logger.error(String.format("Unable to send SAML SLO request URL: [%s] !", sloUrl.toExternalForm()),
                e);
    } finally {
        sloConnexion.disconnect();
    }
}

From source file:com.epam.catgenome.manager.externaldb.HttpDataManager.java

private String getResultFromHttp(final String location, final JSONObject object)
        throws ExternalDbUnavailableException {
    HttpURLConnection conn = null;
    try {/*from   w w  w.  j  a  v  a 2 s  .  c  o m*/
        URL url = new URL(location);

        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty(CONTENT_TYPE, APPLICATION_JSON);

        OutputStreamWriter stream = new OutputStreamWriter(conn.getOutputStream(), Charset.defaultCharset());
        stream.write(object.toString());
        stream.flush();

        int status = conn.getResponseCode();

        while (true) {
            String header = conn.getHeaderField(HTTP_HEADER_RETRY_AFTER);
            long wait = 0;

            if (header != null) {
                wait = Integer.valueOf(header);
            }

            if (wait == 0) {
                break;
            }

            LOGGER.info(String.format(WAITING_FORMAT, wait));
            conn.disconnect();

            Thread.sleep(wait * MILLIS_IN_SECOND);

            conn = (HttpURLConnection) new URL(location).openConnection();
            conn.setDoInput(true);
            conn.connect();
            status = conn.getResponseCode();
        }
        return getHttpResult(status, location, conn);
    } catch (IOException | InterruptedException | ExternalDbUnavailableException e) {
        throw new ExternalDbUnavailableException(String.format(EXCEPTION_MESSAGE, location), e);

    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

}

From source file:ncbi2rkb.SparqlProxy.java

public boolean storeData(StringBuilder query) {
    boolean ret = true;
    query = SparqlProxy.makeQuery(query);
    HttpURLConnection connection = null;
    try {//from w  ww. j  a  va  2  s .  c o  m
        String urlParameters = "update=" + URLEncoder.encode(query.toString(), "UTF-8");
        URL url = new URL(this.urlServer + "update");
        //Create connection
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");

        connection.setDoOutput(true);

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());

        writer.write(urlParameters);
        writer.flush();

        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String rep = "";
        while ((line = reader.readLine()) != null) {
            rep += line;
        }
        writer.close();
        reader.close();
    } catch (Exception e) {
        System.err.println("ERROR UPDATE : " + e);
        SparqlProxy.saveQueryOnFile("Query.sparql", query.toString());
        ret = false;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return ret;
}