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.megahardcore.config.MHCConfig.java

private void writeHeader() {
    if (mHeader == null)
        return;//from   w  w w.  j  av  a2  s .c o  m
    ByteArrayOutputStream memHeaderStream = null;
    OutputStreamWriter memWriter = null;
    try {
        //Write Header to a temporary file
        memHeaderStream = new ByteArrayOutputStream();
        memWriter = new OutputStreamWriter(memHeaderStream, Charset.forName("UTF-8").newEncoder());
        memWriter.write(mHeader.toString());
        memWriter.close();
        //Copy Header to the beginning of the config file
        IoHelper.writeHeader(mConfigFile, memHeaderStream);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (memHeaderStream != null)
                memHeaderStream.close();
            if (memWriter != null)
                memWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.mycompany.twitterapp.TwitterApp.java

public void saveToFile(long id, String tweet, String user, Orientation orientation) {
    OutputStreamWriter fileWriter = null;
    CSVPrinter csvFilePrinter = null;/*from w ww  .  j  a v  a2  s  .  c o m*/
    CSVFormat csvFileFormat = CSVFormat.DEFAULT;

    if (tweet != null) {
        try {
            fileWriter = new OutputStreamWriter(new FileOutputStream(tweetFileName, true), "UTF-8");

            csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
            csvFilePrinter.printRecord(id, orientation.name().toLowerCase(), tweet);

        } catch (IOException ex) {
            Logger.getLogger(TwitterApp.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fileWriter.flush();
                fileWriter.close();
                csvFilePrinter.close();
            } catch (IOException e) {
                System.out.println("Error while flushing/closing fileWriter/csvPrinter !!!");
                e.printStackTrace();
            }

        }
    } else {
        try {
            fileWriter = new OutputStreamWriter(new FileOutputStream(userFileName, true), "UTF-8");
            csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
            csvFilePrinter.printRecord(id, user, orientation.name().toLowerCase());

        } catch (IOException ex) {
            Logger.getLogger(TwitterApp.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fileWriter.flush();
                fileWriter.close();
                csvFilePrinter.close();
            } catch (IOException e) {
                System.out.println("Error while flushing/closing fileWriter/csvPrinter !!!");
                e.printStackTrace();
            }

        }
    }

}

From source file:com.createtank.payments.coinbase.CoinbaseApi.java

private boolean doTokenRequest(Map<String, String> params) throws IOException {
    Map<String, String> paramsBody = new HashMap<String, String>();
    paramsBody.put("client_id", clientId);
    paramsBody.put("client_secret", clientSecret);
    paramsBody.putAll(params);/*from   w ww .  ja v a  2  s  .  com*/

    String bodyStr = RequestClient.createRequestParams(paramsBody);
    System.out.println(bodyStr);
    HttpURLConnection conn = (HttpsURLConnection) new URL(OAUTH_BASE_URL + "/token").openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    writer.write(bodyStr);
    writer.flush();
    writer.close();

    int code = conn.getResponseCode();

    if (code == 401) {
        return false;
    } else if (code != 200) {
        throw new IOException("Got HTTP response code " + code);
    }
    String response = RequestClient.getResponseBody(conn.getInputStream());

    JsonParser parser = new JsonParser();
    JsonObject content = (JsonObject) parser.parse(response);
    System.out.print("content: " + content.toString());
    accessToken = content.get("access_token").getAsString();
    refreshToken = content.get("refresh_token").getAsString();
    return true;
}

From source file:com.entertailion.android.shapeways.api.ShapewaysClient.java

/**
 * Call a Shapeways API with POST//from ww  w .  j a v a  2  s  . c o  m
 * 
 * @param apiUrl
 * @return
 * @throws Exception
 */
private String postResponseOld(String apiUrl, Map<String, String> parameters) throws Exception {
    Log.d(LOG_TAG, "postResponse: url=" + apiUrl);
    URLConnection urlConnection = getUrlConnection(apiUrl, true);

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

    Request request = new Request(POST);
    request.addParameter(OAUTH_CONSUMER_KEY, consumerKey);
    request.addParameter(OAUTH_TOKEN, oauthToken);

    for (String key : parameters.keySet()) {
        request.addParameter(key, parameters.get(key));
    }

    request.sign(apiUrl, consumerSecret, oauthTokenSecret);
    outputStreamWriter.write(request.toString());
    outputStreamWriter.close();

    return readResponse(urlConnection.getInputStream());
}

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_course);
    // Show the Up button in the action bar.
    this.getActionBar().setHomeButtonEnabled(false);
    map_item = new HashMap<String, Course>();
    map = new ArrayList<String>();
    Bundle args = this.getIntent().getExtras();
    this.setTitle(args.getCharSequence("title"));
    try {/*from   w  w  w.jav a2 s  .c  o  m*/
        JSONObject jso = new JSONObject(args.get("args").toString());
        JSONArray jsa = new JSONArray(jso.getString("courses"));
        ListView lv = (ListView) this.findViewById(R.id.course_list);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, map);
        for (int i = 0; i < jsa.length(); ++i) {
            String s = jsa.getString(i);
            JSONObject obj = new JSONObject(s);
            Course course = new Course(obj.getString("title"), obj.getString("department"),
                    obj.getString("course"), obj.getString("description"), obj.getString("id"));
            addItem(course);
            Log.v("Added", course.toString());
        }
        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 Course course = map_item.get(s);
                new AsyncTask<String, String, String>() {
                    ProgressDialog p;

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

                    protected String doInBackground(String... dep) {
                        String params = "action=getSections&course=" + course.id;
                        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();
                            p.dismiss();
                            return null;
                        }
                        return back;
                    }

                    protected void onPostExecute(String s) {
                        if (s == null || s == "") {
                            new AlertError(CourseActivity.this, "IO Error!").show();
                            return;
                        }
                        try {
                            JSONObject jso = new JSONObject(s);
                            JSONArray jsa = new JSONArray(jso.getString("sections"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                            new AlertError(CourseActivity.this, "Invalid JSON From Server").show();
                            p.dismiss();
                            return;
                        }
                        Intent intent = new Intent(CourseActivity.this, SectionsActivity.class);
                        intent.putExtra("title", course.title);
                        intent.putExtra("id", course.id);
                        intent.putExtra("description", course.description);
                        intent.putExtra("args", s);
                        startActivity(intent);
                        p.dismiss();
                    }
                }.execute(course.id);
            }

        });

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        new AlertError(this, "Invalid JSON");
        e.printStackTrace();
    }

}

From source file:com.hangum.tadpole.importexport.core.dialogs.CsvToRDBImportDialog.java

private void saveLog() {
    try {/*from ww w  .j a  v  a2 s .c om*/
        if ("".equals(textSQL.getText())) { //$NON-NLS-1$
            MessageDialog.openWarning(null, Messages.get().Warning,
                    Messages.get().SQLToDBImportDialog_LogEmpty);
            return;
        }
        String filename = PublicTadpoleDefine.TEMP_DIR + userDB.getDisplay_name() + "_SQLImportResult.log"; //$NON-NLS-1$

        FileOutputStream fos = new FileOutputStream(filename);
        OutputStreamWriter bw = new OutputStreamWriter(fos, "UTF-8"); //$NON-NLS-1$

        bw.write(textSQL.getText());
        bw.close();

        String strImportResultLogContent = FileUtils.readFileToString(new File(filename));

        downloadExtFile(userDB.getDisplay_name() + "_SQLImportResult.log", strImportResultLogContent);//sbExportData.toString()); //$NON-NLS-1$
    } catch (Exception ee) {
        logger.error("log writer", ee); //$NON-NLS-1$
    }
}

From source file:fi.cosky.sdk.API.java

private <T extends BaseData> T sendRequest(Link l, Class<T> tClass, Object object) throws IOException {
    URL serverAddress;/*from   w  w w. ja va 2 s  .c o  m*/
    BufferedReader br;
    String result = "";
    HttpURLConnection connection = null;
    String url = l.getUri().contains("://") ? l.getUri() : this.baseUrl + l.getUri();
    try {
        String method = l.getMethod();
        String type = l.getType();

        serverAddress = new URL(url);
        connection = (HttpURLConnection) serverAddress.openConnection();
        boolean doOutput = doOutput(method);
        connection.setDoOutput(doOutput);
        connection.setRequestMethod(method);
        connection.setInstanceFollowRedirects(false);

        if (method.equals("GET") && useMimeTypes)
            if (type == null || type.equals("")) {
                addMimeTypeAcceptToRequest(object, tClass, connection);
            } else {
                connection.addRequestProperty("Accept", helper.getSupportedType(type));
            }
        if (!useMimeTypes)
            connection.setRequestProperty("Accept", "application/json");

        if (doOutput && useMimeTypes) {
            //this handles the case if the link is self made and the type field has not been set.
            if (type == null || type.equals("")) {
                addMimeTypeContentTypeToRequest(l, tClass, connection);
                addMimeTypeAcceptToRequest(l, tClass, connection);
            } else {
                connection.addRequestProperty("Accept", helper.getSupportedType(type));
                connection.addRequestProperty("Content-Type", helper.getSupportedType(type));
            }
        }

        if (!useMimeTypes)
            connection.setRequestProperty("Content-Type", "application/json");

        if (tokenData != null) {
            connection.addRequestProperty("Authorization",
                    tokenData.getTokenType() + " " + tokenData.getAccessToken());
        }

        addVersionNumberToHeader(object, url, connection);

        if (method.equals("POST") || method.equals("PUT")) {
            String json = object != null ? gson.toJson(object) : ""; //should handle the case when POST without object.
            connection.addRequestProperty("Content-Length", json.getBytes("UTF-8").length + "");
            OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
            osw.write(json);
            osw.flush();
            osw.close();
        }

        connection.connect();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED
                || connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER) {
            ResponseData data = new ResponseData();
            Link link = parseLocationLinkFromString(connection.getHeaderField("Location"));
            link.setType(type);
            data.setLocation(link);
            connection.disconnect();
            return (T) data;
        }

        if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            System.out.println(
                    "Authentication expired " + connection.getResponseMessage() + " trying to reauthenticate");
            if (retry && this.tokenData != null) {
                this.tokenData = null;
                retry = false;
                if (authenticate()) {
                    System.out.println("Reauthentication success, will continue with " + l.getMethod()
                            + " request on " + l.getRel());
                    return sendRequest(l, tClass, object);
                }
            } else
                throw new IOException(
                        "Tried to reauthenticate but failed, please check the credentials and status of NFleet-API");
        }

        if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
            return (T) objectCache.getObject(url);
        }

        if (connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) {
            return (T) new ResponseData();
        }

        if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST
                && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) {
            System.out.println("ErrorCode: " + connection.getResponseCode() + " "
                    + connection.getResponseMessage() + " " + url + ", verb: " + method);

            String errorString = readErrorStreamAndCloseConnection(connection);
            throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class);
        } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR) {
            if (retry) {
                System.out.println("Request caused internal server error, waiting " + RETRY_WAIT_TIME
                        + " ms and trying again.");
                return waitAndRetry(connection, l, tClass, object);
            } else {
                System.out.println("Requst caused internal server error, please contact dev@nfleet.fi");
                String errorString = readErrorStreamAndCloseConnection(connection);
                throw new IOException(errorString);
            }
        }

        if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_GATEWAY) {
            if (retry) {
                System.out.println("Could not connect to NFleet-API, waiting " + RETRY_WAIT_TIME
                        + " ms and trying again.");
                return waitAndRetry(connection, l, tClass, object);
            } else {
                System.out.println(
                        "Could not connect to NFleet-API, please check service status from http://status.nfleet.fi and try again later.");
                String errorString = readErrorStreamAndCloseConnection(connection);
                throw new IOException(errorString);
            }

        }

        result = readDataFromConnection(connection);

    } catch (MalformedURLException e) {
        throw e;
    } catch (ProtocolException e) {
        throw e;
    } catch (UnsupportedEncodingException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } catch (SecurityException e) {
        throw e;
    } catch (IllegalArgumentException e) {
        throw e;
    } finally {
        assert connection != null;
        connection.disconnect();
    }
    Object newEntity = gson.fromJson(result, tClass);
    objectCache.addUri(url, newEntity);
    return (T) newEntity;
}

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_departments);
    // Show the Up button in the action bar.
    // getActionBar().setDisplayHomeAsUpEnabled(false);
    this.getActionBar().setHomeButtonEnabled(true);
    final Bundle b = this.getIntent().getExtras();
    map_item = new HashMap<String, Department>();
    map = new ArrayList<String>();
    Bundle args = this.getIntent().getExtras();
    this.setTitle(args.getCharSequence("from"));
    try {/*from ww  w . j  av  a  2s .c  om*/
        JSONObject jso = new JSONObject(args.get("args").toString());
        JSONArray jsa = new JSONArray(jso.getString("departments"));
        ListView lv = (ListView) this.findViewById(R.id.department_list);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, map);
        for (int i = 0; i < jsa.length(); ++i) {
            String s = jsa.getString(i);
            JSONObject obj = new JSONObject(s);
            Department dept = new Department(obj.getString("title"), obj.getString("id"),
                    obj.getString("code"));
            addItem(dept);
            Log.v("Added", dept.toString());
        }
        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 Department department = map_item.get(s);
                new AsyncTask<String, String, String>() {
                    ProgressDialog p;

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

                    protected String doInBackground(String... dep) {
                        String params = "action=getCourses&department=" + dep[0] + "&quarter="
                                + b.getString("qCode");
                        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();
                            p.dismiss();
                            return null;
                        }
                        return back;
                    }

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

                        try {
                            JSONObject jso = new JSONObject(s);
                            JSONArray jsa = new JSONArray(jso.getString("courses"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                            new AlertError(DepartmentActivity.this, "Invalid JSON From Server").show();
                            p.dismiss();
                            return;
                        }
                        Intent intent = new Intent(DepartmentActivity.this, CourseActivity.class);
                        intent.putExtra("title", department.title);
                        intent.putExtra("id", department.id);
                        intent.putExtra("code", department.code);
                        intent.putExtra("args", s);
                        startActivity(intent);
                        p.dismiss();
                    }
                }.execute(department.id);
            }

        });

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        new AlertError(this, "Invalid JSON");
        e.printStackTrace();
    }

}

From source file:com.extrahardmode.config.EHMConfig.java

private void writeHeader() {
    if (mHeader == null)
        return;//from  ww w. ja  v  a  2 s. c om
    ByteArrayOutputStream memHeaderStream = null;
    OutputStreamWriter memWriter = null;
    try {
        //Write Header to a temporary file
        memHeaderStream = new ByteArrayOutputStream();
        memWriter = new OutputStreamWriter(memHeaderStream, Charset.forName("UTF-8").newEncoder());
        memWriter.write(String.format(mHeader.toString()));
        memWriter.close();
        //Copy Header to the beginning of the config file
        IoHelper.writeHeader(mConfigFile, memHeaderStream);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (memHeaderStream != null)
                memHeaderStream.close();
            if (memWriter != null)
                memWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:UploadTest.java

@Test
public void test_with_javaLib() {
    httpCon.disconnect();/*from   w  w w.  j a  v a  2  s . co m*/
    try {
        // readStream(httpCon.getInputStream());
    } catch (Exception e) {
        e.printStackTrace();
    }
    httpCon.setRequestProperty("Content-Type", "application/json");
    httpCon.setRequestProperty("Accept", "application/json");
    httpCon.setDoOutput(true);
    try {
        httpCon.setRequestMethod("PUT");
    } catch (ProtocolException e) {
        e.printStackTrace();
    }
    try {
        httpCon.connect();
    } catch (Exception e) {
        e.printStackTrace();
    }
    String content = "{\"contentType\":\"monograph\",\"accessScheme\":\"public\",\"publishScheme\":\"public\"}";
    System.out.println(content);
    OutputStreamWriter out;
    try {
        out = new OutputStreamWriter(httpCon.getOutputStream());
        out.write(content);
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        System.out.println(httpCon.getResponseCode());
    } catch (IOException e) {
        e.printStackTrace();
    }
}