Example usage for java.io OutputStreamWriter close

List of usage examples for java.io OutputStreamWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:com.example.httpjson.AppEngineClient.java

public void put(URL uri, Map<String, List<String>> headers, byte[] body) {
    PUT put = new PUT(uri, headers, body);

    URL url = null;//w  w  w.j av a  2  s.co m
    try {
        url = new URL("http://www.example.com/resource");
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    HttpURLConnection httpCon = null;
    try {
        httpCon = (HttpURLConnection) url.openConnection();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        httpCon.setDoOutput(true);
        httpCon.setRequestMethod("PUT");
        OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
        out.write("Resource content from PUT!!! ");
        out.close();
        httpCon.getInputStream();
    } catch (ProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:ca.etsmtl.applets.etsmobile.api.SignetBackgroundThread.java

@SuppressWarnings("unchecked")
public T fetchArray() {
    ArrayList<E> array = new ArrayList<E>();

    try {/*ww w  .  j a v a 2  s  . com*/
        final StringBuilder sb = new StringBuilder();
        sb.append(urlStr);
        sb.append("/");
        sb.append(action);

        final Gson gson = new Gson();
        final String bodyParamsString = gson.toJson(bodyParams);

        final URL url = new URL(sb.toString());
        final URLConnection conn = url.openConnection();
        conn.addRequestProperty("Content-Type", "application/json");
        conn.addRequestProperty("charset", "utf-8");

        conn.setDoOutput(true);
        final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(bodyParamsString);
        wr.flush();

        final StringWriter writer = new StringWriter();
        final InputStream in = conn.getInputStream();
        IOUtils.copy(in, writer);
        in.close();
        wr.close();

        final String jsonString = writer.toString();

        final ArrayList<E> objectList = new ArrayList<E>();

        JSONObject jsonObject;
        jsonObject = new JSONObject(jsonString);

        JSONArray jsonRootArray;
        jsonRootArray = jsonObject.getJSONObject("d").getJSONArray(liste);
        android.util.Log.d("JSON", jsonRootArray.toString());
        for (int i = 0; i < jsonRootArray.length(); i++) {
            objectList.add(gson.fromJson(jsonRootArray.getJSONObject(i).toString(), typeOfClass));
        }

        array = objectList;
    } catch (final IOException e) {
        e.printStackTrace();
    } catch (final JSONException e) {
        e.printStackTrace();
    }

    return (T) array;
}

From source file:com.amastigote.xdu.query.module.WaterAndElectricity.java

private Document getPage(String output_data, String host_suffix) throws IOException {
    URL url = new URL(HOST + host_suffix);
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setDoOutput(true);
    httpURLConnection.setRequestMethod("POST");
    httpURLConnection.setUseCaches(false);
    httpURLConnection.setInstanceFollowRedirects(false);
    httpURLConnection.setRequestProperty("Cookie", "ASP.NET_SessionId=" + ASP_dot_NET_SessionId);

    httpURLConnection.connect();/*from  ww  w  . j a  v a2 s. c o  m*/
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream(),
            "UTF-8");
    outputStreamWriter.write(output_data);
    outputStreamWriter.flush();
    outputStreamWriter.close();
    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(httpURLConnection.getInputStream()));

    String temp;
    String htmlPage = "";
    while ((temp = bufferedReader.readLine()) != null)
        htmlPage += temp;

    bufferedReader.close();
    httpURLConnection.disconnect();

    htmlPage = htmlPage.replaceAll("&nbsp;", " ");

    return Jsoup.parse(htmlPage);
}

From source file:com.mitre.holdshort.AlertLogger.java

public void writeDataToFtpServer(LoggedAlert currentAlert) {
    try {/*from w  w w.jav a 2s  . c om*/
        alertFTPClient.changeWorkingDirectory("/data");
        OutputStream os = alertFTPClient.storeFileStream(airport + "_" + System.currentTimeMillis() + ".dat");
        OutputStreamWriter osw = new OutputStreamWriter(os);
        osw.write(currentAlert.getAlertString());
        osw.close();
        logOldAlerts();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:game.Clue.JerseyClient.java

public void sendPOST() {
    System.out.println("POST method called");
    try {/*  ww w.  j av a  2 s.c om*/

        JSONObject jsonObject = new JSONObject("{player:Brian}");
        URL url = new URL(
                "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/game/");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        //setDoOutput(true);
        connection.setRequestProperty("POST", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        System.out.println(jsonObject.toString());
        out.write("{" + jsonObject.toString());

        System.out.println("Sent PUT message to server");
        out.close();

    } catch (Exception e) {
        System.out.println("\nError while calling REST POST Service");
        System.out.println(e);
    }

}

From source file:com.theisleoffavalon.mcmanager.mobile.RestClient.java

/**
 * Sends a JSONRPC request//w  ww .  java  2 s.c  o  m
 * 
 * @param request
 *            The request to send
 * @return The response
 */
private JSONObject sendJSONRPC(JSONObject request) {
    JSONObject ret = null;

    try {
        HttpURLConnection conn = (HttpURLConnection) this.rootUrl.openConnection();
        conn.setRequestMethod("POST");
        conn.setChunkedStreamingMode(0);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        OutputStreamWriter osw = new OutputStreamWriter(new BufferedOutputStream(conn.getOutputStream()));
        request.writeJSONString(osw);
        osw.close();

        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStreamReader isr = new InputStreamReader(new BufferedInputStream(conn.getInputStream()));
            ret = (JSONObject) new JSONParser().parse(isr);
        } else {
            Log.e("RestClient", String.format("Got %d instead of %d for HTTP Response", conn.getResponseCode(),
                    HttpURLConnection.HTTP_OK));
            return null;
        }

    } catch (IOException e) {
        Log.e("RestClient", "Error in sendJSONRPC", e);
    } catch (ParseException e) {
        Log.e("RestClient", "Parse return data error", e);
    }
    return ret;
}

From source file:com.EconnectTMS.CustomerInformation.java

public void Run(String IncomingMessage, String intid)
        throws MalformedURLException, UnsupportedEncodingException, IOException {

    try {/*from w w  w  .  j a v  a  2s.co m*/
        strRecievedData = IncomingMessage.split("#");
        processingcode = strRecievedData[0];
        switch (processingcode) {
        case "800000":
            AccountNumber = strRecievedData[1];
            URL url = new URL(CUSTOMER_DETAILS_URL);
            Map<String, String> params = new LinkedHashMap<>();

            params.put("username", CUSTOMER_DETAILS_USERNAME);
            params.put("password", CUSTOMER_DETAILS_PASSWORD);
            params.put("source", CUSTOMER_DETAILS_SOURCE_ID);
            params.put("account", AccountNumber);

            postData = new StringBuilder();
            for (Map.Entry<String, String> param : params.entrySet()) {
                if (postData.length() != 0) {
                    postData.append('&');
                }
                postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                postData.append('=');
                postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
            }
            urlParameters = postData.toString();
            conn = url.openConnection();
            conn.setDoOutput(true);

            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
            writer.write(urlParameters);
            writer.flush();

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

            while ((line = reader.readLine()) != null) {
                result += line;
            }
            writer.close();
            reader.close();

            JSONObject respobj = new JSONObject(result);
            if (respobj.has("FSTNAME") || respobj.has("MIDNAME") || respobj.has("LSTNAME")) {
                if (respobj.has("FSTNAME")) {
                    fname = respobj.get("FSTNAME").toString().toUpperCase() + ' ';
                }
                if (respobj.has("MIDNAME")) {
                    mname = respobj.get("MIDNAME").toString().toUpperCase() + ' ';
                }
                if (respobj.has("LSTNAME")) {
                    lname = respobj.get("LSTNAME").toString().toUpperCase() + ' ';
                }
                strCustomerName = fname + mname + lname;
            } else {
                strCustomerName = " ";
            }
            System.out.println("result:" + result);
            func.SendPOSResponse(strCustomerName + "#", intid);
            return;
        default:
            break;
        }
    } catch (Exception ex) {
        strCustomerName = "";
        func.log("\nSEVERE CustomerInformation() :: " + ex.getMessage() + "\n" + func.StackTraceWriter(ex),
                "ERROR");
    }
}

From source file:com.cw.litenote.operation.import_export.Import_webAct.java

void doCreate() {
    setContentView(R.layout.import_web);

    // web view/*from  w w w . j a  va  2 s. c om*/
    webView = (WebView) findViewById(R.id.webView);

    // cancel button
    Button btn_cancel = (Button) findViewById(R.id.import_web_cancel);
    btn_cancel.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            setResult(RESULT_CANCELED);
            if (webView.canGoBack()) {
                webView.goBack();
                content = null;
            } else
                finish();
        }
    });

    // import button
    btn_import = (Button) findViewById(R.id.import_web_import);
    btn_import.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            setResult(RESULT_OK);

            // import
            // save text in a file
            String dirName = "Download";
            String fileName = "temp.xml";
            String dirPath = Environment.getExternalStorageDirectory().toString() + "/" + dirName;
            File file = new File(dirPath, fileName);

            try {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                FileOutputStream fOut = new FileOutputStream(file);
                OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
                if (content != null) {
                    content = content.replaceAll("(?m)^[ \t]*\r?\n", "");
                }
                myOutWriter.append(content);
                myOutWriter.close();

                fOut.flush();
                fOut.close();
            } catch (IOException e) {
                Log.e("Exception", "File write failed: " + e.toString());
            }

            // import file content to DB
            Import_webAct_asyncTask task = new Import_webAct_asyncTask(Import_webAct.this, file.getPath());
            task.enableSaveDB(true);// view
            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }

    });

    webView.getSettings().setJavaScriptEnabled(true);

    // create instance
    final ImportInterface import_interface = new ImportInterface(webView);

    // load web content
    webView.addJavascriptInterface(import_interface, "INTERFACE");
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            btn_import.setVisibility(View.INVISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            System.out.println("Import_webAct / _setWebViewClient / url = " + url);
            view.loadUrl(
                    "javascript:window.INTERFACE.processContent(document.getElementsByTagName('body')[0].innerText);");
            if (!url.contains(homeUrl))
                btn_import.setVisibility(View.VISIBLE);
        }

    });

    // show toast
    webView.addJavascriptInterface(import_interface, "LiteNote");

    // load content to web view
    webView.loadUrl(homeUrl);
}

From source file:it.uniroma2.sag.kelp.linearization.nystrom.NystromMethod.java

/**
 * Save a Nystrom-based projection function in a file. If the .gz suffix is
 * used a compressed file is obtained/* ww  w  .ja va  2s .  co  m*/
 * 
 * @param outputFilePath
 *            the output file path
 * @throws FileNotFoundException
 * @throws IOException
 */
public void save(String outputFilePath) throws FileNotFoundException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    OutputStreamWriter out = new OutputStreamWriter(FileUtils.createOutputStream(outputFilePath), "utf8");
    mapper.writeValue(out, this);
    out.close();
}

From source file:orca.ip_assignment.ndl.RequestSaver.java

public boolean saveGraph(File f, SparseMultigraph<OrcaNode, OrcaLink> g) {
    assert (f != null);
    String ndl = convertGraphToNdl(g);
    if (ndl == null)
        return false;
    try {//from   w  ww.  ja va  2s  . com
        FileOutputStream fsw = new FileOutputStream(f);
        OutputStreamWriter out = new OutputStreamWriter(fsw, "UTF-8");
        out.write(ndl);
        out.close();
        return true;
    } catch (FileNotFoundException e) {
        ;
    } catch (UnsupportedEncodingException ex) {
        ;
    } catch (IOException ey) {
        ;
    }
    return false;
}