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.syncedsynapse.kore2.jsonrpc.HostConnection.java

/**
 * Send an HTTP POST request/*  ww w.j a  v a2 s . c o m*/
 * @param connection Open connection
 * @param request Request to send
 * @throws ApiException
 */
private void sendHttpRequest(HttpURLConnection connection, String request) throws ApiException {
    try {
        LogUtils.LOGD(TAG, "Sending request via HTTP: " + request);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(request);
        out.flush();
        out.close();
    } catch (IOException e) {
        LogUtils.LOGW(TAG, "Failed to send HTTP request.", e);
        throw new ApiException(ApiException.IO_EXCEPTION_WHILE_SENDING_REQUEST, e);
    }

}

From source file:com.googlecode.CallerLookup.Main.java

public void saveUserLookupEntries() {
    try {/* w  w w . ja  v a 2  s.  c o  m*/
        FileOutputStream file = getApplicationContext().openFileOutput(SAVED_FILE, MODE_PRIVATE);
        JSONArray userLookupEntries = new JSONArray();
        for (String lookupEntryName : mUserLookupEntries.keySet()) {
            try {
                userLookupEntries.put(mUserLookupEntries.get(lookupEntryName).toJSONObject());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        OutputStreamWriter content = new OutputStreamWriter(file);
        content.write(userLookupEntries.toString());
        content.flush();
        content.close();
        file.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.csounds.examples.tests.MultiTouchXYActivity.java

private void writeToFile(String data) {
    try {/*from  www  .j a  va2  s  . c o  m*/
        if (!txtfile.exists()) {
            Log.d("txtfile", "txtfile doesn't exist");
            ContextWrapper cw = new ContextWrapper(this);
            File directory = cw.getExternalFilesDir(null);
            txtfile = new File(directory, "temp.txt");
        }
        System.out.println("zz" + txtfile);
        FileOutputStream outStream = new FileOutputStream(txtfile, true);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outStream);

        String output = String.format(data);
        //        BufferedWriter oFile = new BufferedWriter(new OutputStreamWriter(
        //            new FileOutputStream("test.txt"), "UTF-16"));
        outputStreamWriter.append("\r\n");
        outputStreamWriter.append(output);
        outputStreamWriter.close();

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

From source file:org.pixmob.appengine.client.AppEngineClient.java

private void writeAuthenticationCookie() {
    OutputStreamWriter out = null;
    try {/*from  w ww  .  j av  a2s  .  co  m*/
        out = new OutputStreamWriter(
                context.openFileOutput(AUTH_COOKIE_FILE + account.name, Context.MODE_PRIVATE), "UTF-8");

        if (authenticationCookie != null) {
            out.write(authenticationCookie);
        }
        out.write("\n");
    } catch (IOException e) {
        Log.i(TAG, "Failed to store authentication cookie", e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException ignore) {
            }
        }
    }
}

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

public void logOldAlerts() {
    try {/*from w  w w  .  j  ava  2  s. c om*/
        // check for old alerts
        File oldAlerts = new File(ctx.getFilesDir() + "/oldAlerts.dat");

        if (oldAlerts.length() > 0) {

            alertFTPClient.changeWorkingDirectory("/data");
            OutputStream os = alertFTPClient
                    .storeFileStream(airport + "_" + System.currentTimeMillis() + ".dat");
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedReader br = new BufferedReader(new FileReader(oldAlerts));
            String line;
            while ((line = br.readLine()) != null) {
                osw.write(line);
                osw.write("\n");
            }

            // clear oldAlerts.dat
            FileWriter clearOldAlerts = new FileWriter(oldAlerts, false);
            clearOldAlerts.write("");
            clearOldAlerts.close();
            osw.close();
        }

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.tomcat.monitor.zabbix.ZabbixSender.java

public void send(final String zabbixServer, final int zabbixPort, int zabbixTimeout, final String host,
        final String key, final String value) throws IOException {

    final byte[] response = new byte[1024];

    final long start = System.currentTimeMillis();

    final int TIMEOUT = zabbixTimeout * 1000;

    final StringBuilder message = new StringBuilder("<req><host>");
    message.append(new String(Base64.encodeBase64(host.getBytes())));
    message.append("</host><key>");
    message.append(new String(Base64.encodeBase64(key.getBytes())));
    message.append("</key><data>");
    message.append(new String(Base64.encodeBase64(value.getBytes())));
    message.append("</data></req>");

    if (log.isDebugEnabled()) {
        log.debug("sending " + message);
    }/* w  w  w. j  a v  a2 s .c o  m*/

    Socket zabbix = null;
    OutputStreamWriter out = null;
    InputStream in = null;
    try {
        zabbix = new Socket(zabbixServer, zabbixPort);
        zabbix.setSoTimeout(TIMEOUT);

        out = new OutputStreamWriter(zabbix.getOutputStream());
        out.write(message.toString());
        out.flush();

        in = zabbix.getInputStream();
        final int read = in.read(response);
        if (log.isDebugEnabled()) {
            log.debug("received " + new String(response));
        }
        if (read != 2 || response[0] != 'O' || response[1] != 'K') {
            log.warn("received unexpected response '" + new String(response) + "' for key '" + key + "'");
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
        if (zabbix != null) {
            zabbix.close();
        }
    }
    log.info("send() " + (System.currentTimeMillis() - start) + " ms");
}

From source file:markson.visuals.sitapp.settingActivity.java

public void WriteSettings(Context context, String data) {

    FileOutputStream fOut = null;

    OutputStreamWriter osw = null;

    try {//from w w  w .  j a  v a  2 s  . co  m

        fOut = openFileOutput("settings.dat", MODE_PRIVATE);

        osw = new OutputStreamWriter(fOut);

        osw.write(data);

        osw.flush();

        //Toast.makeText(context, "Classes Saved",Toast.LENGTH_SHORT).show();

    }

    catch (Exception e) {

        e.printStackTrace();

        Toast.makeText(context, "Settings not saved", Toast.LENGTH_SHORT).show();

    }

    finally {

        try {

            osw.close();

            fOut.close();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

From source file:it.infn.ct.ToscaIDCInterface.java

/**
 * Submit template to the orchestrator a template.
 * @return TOSCA UUID/* w  w w. j a  v a  2  s  . co  m*/
 */
public final String submitOrchestrator() {

    StringBuilder orchestratorResult = new StringBuilder("");
    StringBuilder postData = new StringBuilder();
    String toscParametersValues = "";
    String toscaParametersJson = "";
    String tUUID = "";
    String[] toscaParams = toscaParameters.split("&");
    String tParams = "";
    for (int i = 0; i < toscaParams.length; i++) {
        String[] paramArgs = toscaParams[i].split("=");
        if (paramArgs[0].trim().equals("params")) {
            toscaParametersJson = toscaCommand.getActionInfo() + FS + paramArgs[1].trim();
            LOG.debug("Loading params json file: '" + toscaParametersJson + "'");
            try {
                String paramsJson = new String(Files.readAllBytes(Paths.get(toscaParametersJson)));
                LOG.debug("params JSON: '" + paramsJson + "'");
                toscParametersValues = getDocumentValue(paramsJson, "parameters");
                LOG.debug("extracted parameters: '" + tParams + "'");
            } catch (IOException ex) {
                LOG.error("Parameters json file '" + toscaParametersJson + "' is not readable");
                LOG.error(ex);
            } catch (ParseException ex) {
                LOG.error("Parameters json file '" + toscaParametersJson + "' is not parseable");
                LOG.error(ex);
            }
            LOG.debug("Parameters json file '" + toscaParametersJson + "' successfully parsed");
            break;
        }
    }
    if (toscParametersValues.length() > 0) {
        tParams = "\"parameters\": " + toscParametersValues + ", ";
    }
    postData.append("{ " + tParams + "\"template\": \"");
    String toscaTemplateContent = "";
    LOG.debug("Escaping toscaTemplate file '" + toscaTemplate + "'");
    try {
        toscaTemplateContent = new String(Files.readAllBytes(Paths.get(toscaTemplate))).replace("\n", "\\n");
    } catch (IOException ex) {
        LOG.error("Template '" + toscaTemplate + "'is not readable");
        LOG.error(ex);
    }
    postData.append(toscaTemplateContent);
    postData.append("\" }");
    LOG.debug("JSON Data (begin):\n" + postData + "\nJSON Data (end)");

    HttpURLConnection conn;
    String orchestratorDoc = "";
    try {
        conn = (HttpURLConnection) toscaEndPoint.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Bearer " + toscaToken);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("charset", "utf-8");
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(postData.toString());
        wr.flush();
        wr.close();
        LOG.debug("Orchestrator status code: " + conn.getResponseCode());
        LOG.debug("Orchestrator status message: " + conn.getResponseMessage());
        if (conn.getResponseCode() == HTTP_201) {
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            orchestratorResult = new StringBuilder();
            String ln;
            while ((ln = br.readLine()) != null) {
                orchestratorResult.append(ln);
            }
            LOG.debug("Orchestrator result: " + orchestratorResult);
            orchestratorDoc = orchestratorResult.toString();
            tUUID = getDocumentValue(orchestratorDoc, "uuid");
            LOG.debug("Created resource has UUID: '" + tUUID + "'");
        } else {
            LOG.warn("Orchestrator return code is: " + conn.getResponseCode());
        }
    } catch (IOException ex) {
        LOG.error("Connection error with the service at " + toscaEndPoint.toString());
        LOG.error(ex);
    } catch (ParseException ex) {
        LOG.error("Error parsing JSON:" + orchestratorDoc);
        LOG.error(ex);
    }
    return tUUID;
}

From source file:net.nicholaswilliams.java.licensing.licensor.interfaces.cli.ConsoleLicenseGenerator.java

private void printHelp(HelpFormatter formatter, Options options) {
    OutputStreamWriter streamWriter = new OutputStreamWriter(this.device.out(), LicensingCharsets.UTF_8);
    PrintWriter printWriter = new PrintWriter(streamWriter);
    formatter.printHelp(printWriter, CLI_WIDTH, USAGE, null, options, 1, 3, null, false);
    printWriter.close();//  www  .  j av a2 s.co m
    try {
        streamWriter.close();
    } catch (IOException e) {
        e.printStackTrace(this.device.err());
    }
}

From source file:debrepo.teamcity.web.DebDownloadController.java

/**
 * Creates a new {@link GZIPOutputStream} and streams the stringToGzip through it to the provided {@link OutputStream}
 * @param stringToGzip - String of text which needs gzipping.
 * @param outputStream - {@link OutputStream} to write gzip'd string to.
 * @throws IOException// w  w w  .j  ava2s .c  o m
 */
private void gzip(String stringToGzip, OutputStream outputStream) throws IOException {
    GZIPOutputStream gzip = new GZIPOutputStream(outputStream);
    OutputStreamWriter osw = new OutputStreamWriter(gzip, StandardCharsets.UTF_8);
    osw.write(stringToGzip);
    osw.flush();
    osw.close();
}