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.microsoft.windowsazure.mobileservices.zumoe2etestapp.MainActivity.java

private void runTests() {

    MobileServiceClient client = null;/*  w w w  . j  a v  a2 s  .c  om*/

    try {
        client = createMobileServiceClient();
    } catch (MalformedURLException e) {
        createAndShowDialog(e, "Error");
    }

    // getMobileServiceRuntimeFeatures(client);

    final TestGroup group = (TestGroup) mTestGroupSpinner.getSelectedItem();
    logWithTimestamp(new Date(), "Tests for group \'" + group.getName() + "\'");

    logSeparator();

    final MobileServiceClient currentClient = client;

    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1
            || Build.VERSION.SDK_INT == Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        // For android versions 4.0.x
        // Run a first Void AsyncTask on UI thread to enable the possibility
        // of running others on sub threads
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                return null;
            }
        }.execute();

    }

    Thread thread = new Thread() {

        @Override
        public void run() {
            group.runTests(currentClient, new TestExecutionCallback() {

                @Override
                public void onTestStart(TestCase test) {
                    final TestCaseAdapter adapter = (TestCaseAdapter) mTestCaseList.getAdapter();

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                        }

                    });

                    log("TEST START", test.getName());
                }

                @Override
                public void onTestGroupComplete(TestGroup group, List<TestResult> results) {
                    log("TEST GROUP COMPLETED", group.getName() + " - " + group.getStatus().toString());
                    logSeparator();

                    if (group.getName().startsWith(TestGroup.AllTestsGroupName)) {

                        List<TestCase> tests = new ArrayList<TestCase>();

                        for (TestResult result : results) {
                            tests.add(result.getTestCase());
                        }

                        DaylightLogger logger = new DaylightLogger(getDaylightURL(), getDaylightProject(),
                                getDaylightClientId(), getDaylightClientSecret(), getDaylightRuntime(),
                                getDaylightRunId());
                        try {
                            logger.reportResultsToDaylight(group.getFailedTestCount(), group.getStartTime(),
                                    group.getEndTime(), tests, group.getSourceMap());
                        } catch (Throwable e) {
                            log(e.getMessage());
                        }
                    }

                    if (shouldRunUnattended()) {
                        // String logContent = mLog.toString();
                        // postLogs(logContent, true);

                        boolean passed = true;
                        for (TestResult result : results) {
                            if (result.getStatus() != TestStatus.Passed) {
                                passed = false;
                                break;
                            }
                        }

                        try {
                            String sdCard = Environment.getExternalStorageDirectory().getPath();
                            FileOutputStream fos = new FileOutputStream(sdCard + "/done_android_e2e.txt");
                            OutputStreamWriter osw = new OutputStreamWriter(fos);
                            BufferedWriter bw = new BufferedWriter(osw);
                            bw.write("Completed successfully.\n");
                            bw.write(passed ? "PASSED" : "FAILED");
                            bw.write("\n");
                            bw.close();
                            osw.close();
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onTestComplete(TestCase test, TestResult result) {
                    Throwable e = result.getException();
                    if (e != null) {
                        StringBuilder sb = new StringBuilder();
                        while (e != null) {
                            sb.append(e.getClass().getSimpleName() + ": ");
                            sb.append(e.getMessage());
                            sb.append("\n");
                            sb.append(Log.getStackTraceString(e));
                            sb.append("\n\n");
                            e = e.getCause();
                        }

                        test.log("Exception: " + sb.toString());
                    }

                    final TestCaseAdapter adapter = (TestCaseAdapter) mTestCaseList.getAdapter();

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();

                        }

                    });
                    logWithTimestamp(test.getStartTime(),
                            "Logs for test " + test.getName() + " (" + result.getStatus().toString() + ")");
                    String testLogs = test.getLog();
                    if (testLogs.length() > 0) {
                        if (testLogs.endsWith("\n")) {
                            testLogs = testLogs.substring(0, testLogs.length() - 1);
                        }
                        log(testLogs);
                    }

                    logWithTimestamp(test.getEndTime(), "Test " + result.getStatus().toString());
                    logWithTimestamp(test.getEndTime(), "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-");
                    logSeparator();
                }
            });
        }
    };

    thread.start();
}

From source file:br.gov.frameworkdemoiselle.monitoring.internal.implementation.zabbix.ZabbixSender.java

/**
 * @param key/* ww  w  . ja v  a 2s  .  c  o m*/
 * @param value
 * @throws IOException
 */
private void send(final String key, final String value) throws IOException {

    final long start = System.currentTimeMillis();

    final StringBuilder message = new StringBuilder(head);
    message.append(encodeBase64(key));
    message.append(middle);
    message.append(encodeBase64(value == null ? "" : value));
    message.append(tail);

    logger.debug(bundle.getString("zabbix-sender-sending-message", this.zabbixHost, key, value));
    logger.trace(bundle.getString("zabbix-sender-detailed-message", message));

    Socket socket = null;
    OutputStreamWriter out = null;
    InputStream in = null;

    try {
        socket = new Socket(zabbixServer, zabbixPort);
        socket.setSoTimeout(TIMEOUT);

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

        in = socket.getInputStream();
        final int read = in.read(response);

        final String resp = new String(response);
        logger.debug(bundle.getString("zabbix-sender-received-response", resp));
        if (read != 2 || response[0] != 'O' || response[1] != 'K') {
            logger.warn(bundle.getString("zabbix-sender-unexpected-response", key, resp));
        }

    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
        if (socket != null) {
            socket.close();
        }
    }

    final long elapsed = System.currentTimeMillis() - start;
    logger.trace(bundle.getString("zabbix-sender-message-sent", elapsed));
}

From source file:com.denimgroup.threadfix.service.defects.RestUtils.java

public static InputStream postUrl(String urlString, String data, String username, String password) {
    URL url = null;//  ww  w . j ava 2  s  .  c o m
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        log.warn("URL used for POST was bad: '" + urlString + "'");
        return null;
    }

    HttpURLConnection httpConnection = null;
    OutputStreamWriter outputWriter = null;
    try {
        httpConnection = (HttpURLConnection) url.openConnection();

        setupAuthorization(httpConnection, username, password);

        httpConnection.addRequestProperty("Content-Type", "application/json");
        httpConnection.addRequestProperty("Accept", "application/json");

        httpConnection.setDoOutput(true);
        outputWriter = new OutputStreamWriter(httpConnection.getOutputStream());
        outputWriter.write(data);
        outputWriter.flush();

        InputStream is = httpConnection.getInputStream();

        return is;
    } catch (IOException e) {
        log.warn("IOException encountered trying to post to URL with message: " + e.getMessage());
        if (httpConnection == null) {
            log.warn(
                    "HTTP connection was null so we cannot do further debugging of why the HTTP request failed");
        } else {
            try {
                InputStream errorStream = httpConnection.getErrorStream();
                if (errorStream == null) {
                    log.warn("Error stream from HTTP connection was null");
                } else {
                    log.warn(
                            "Error stream from HTTP connection was not null. Attempting to get response text.");
                    String postErrorResponse = IOUtils.toString(errorStream);
                    log.warn("Error text in response was '" + postErrorResponse + "'");
                }
            } catch (IOException e2) {
                log.warn("IOException encountered trying to read the reason for the previous IOException: "
                        + e2.getMessage(), e2);
            }
        }
    } finally {
        if (outputWriter != null) {
            try {
                outputWriter.close();
            } catch (IOException e) {
                log.warn("Failed to close output stream in postUrl.", e);
            }
        }
    }

    return null;
}

From source file:com.akop.bach.parser.Parser.java

protected void writeToFile(String filename, String text) {
    java.io.OutputStreamWriter osw = null;

    try {//w  w w  . j  a  v a2s . c o  m
        java.io.FileOutputStream fOut = mContext.openFileOutput(filename, 0666);
        osw = new java.io.OutputStreamWriter(fOut);
        osw.write(text);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (osw != null) {
            try {
                osw.flush();
                osw.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:org.pegadi.server.article.ArticleServerImpl.java

/**
 * Backup an article as XML/*from   w  ww. j  a v a2 s. c  o m*/
 *
 * @param articleID The ID of the article.
 * @param text      The text of the article.
 * @return <code>true</code> if all parts of the save operation
 *         was successful.
 */
protected boolean doBackup(int articleID, String text) {
    // Dump the XML to file
    SimpleDateFormat df = new SimpleDateFormat("-yyyyy-MM-dd-HH-mm");
    String xmlFile = backupLocation + "/" + articleID + df.format(new Date()) + ".xml";

    FileOutputStream fos = null;
    OutputStreamWriter writer = null;
    try {
        fos = new FileOutputStream(xmlFile);
        writer = new OutputStreamWriter(fos, Charset.forName("utf-8"));
        writer.write(text);

    } catch (IOException e) {
        log.error("doBackup: Error writing XML file, aborting publish", e);
        log.info("saveArticleText: WARNING: backup failed for article {}!", articleID);
    } finally {
        try {
            if (writer != null)
                writer.close();
            if (fos != null)
                fos.close();
        } catch (IOException e) {
            log.error("Failed on stream close", e);
        }
    }
    log.info("doBackup: XML file saves as '{}'.", xmlFile);

    return true;
}

From source file:com.masse.mvn.plugin.BuildJsonFromPropertiesMojo.java

private void buidJsonTargetFile(File inputFile) throws MojoExecutionException {

    String inputFileString = inputFile.getAbsolutePath()
            .substring(inputFile.getAbsolutePath().lastIndexOf(SystemUtils.IS_OS_LINUX ? "/" : "\\") + 1);
    String outputFileString = jsonTargetPath + new String(SystemUtils.IS_OS_LINUX ? "/" : "\\")
            + inputFileString.substring(0, inputFileString.lastIndexOf(".")) + ".json";

    getLog().info("Process file " + inputFileString);

    if (!inputFile.exists()) {
        throw new MojoExecutionException("Properties file " + inputFile + " not found !");
    }//w  w  w  .  j  ava  2 s  .  co  m

    TreeMap<String, PropertiesToJson> propertiesJson = new TreeMap<String, PropertiesToJson>();
    Properties props = new Properties();

    try {
        FileInputStream inputFileStream = new FileInputStream(inputFile);
        BufferedReader inputFileBufferedReader = new BufferedReader(
                new InputStreamReader(inputFileStream, "UTF-8"));

        File outputTempFile = new File(inputFileString + "-temp");

        FileOutputStream outputTempFileStream = new FileOutputStream(outputTempFile);
        OutputStreamWriter outputTempFileStrWriter = new OutputStreamWriter(outputTempFileStream, "UTF-8");
        BufferedWriter writer = new BufferedWriter(outputTempFileStrWriter);

        String line = "";
        while ((line = inputFileBufferedReader.readLine()) != null) {
            if (!(line.isEmpty() || line.trim().equals("") || line.trim().equals("\n"))) {
                if (line.startsWith("#")) {
                    continue;
                }
                int equalsIndex = line.indexOf("=");
                if (equalsIndex < 0) {
                    continue;
                }
                line = line.replace("\"", "&quot;");
                line = line.replace("\\", "\\\\\\\\");
                line = line.replace("   ", "");
                writer.write(line + "\n");
            }
        }

        writer.close();
        outputTempFileStrWriter.close();
        outputTempFileStream.close();

        inputFileBufferedReader.close();
        inputFileStream.close();

        FileInputStream fis = new FileInputStream(outputTempFile);
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        props.load(isr);
        isr.close();
        fis.close();

        outputTempFile.delete();

        @SuppressWarnings("rawtypes")
        Enumeration e = props.propertyNames();

        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();

            String rootKey = key.split("=")[0];

            propertiesJson.put(rootKey, createMap(propertiesJson, key, props.getProperty(key), 1));

        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    StringBuffer sb = new StringBuffer();
    sb.append(PrintJsonTree(propertiesJson, 0, false));

    File outputFile = new File(outputFileString);

    try {
        FileOutputStream fos = new FileOutputStream(outputFile);
        OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
        BufferedWriter bwr = new BufferedWriter(osw);

        //write contents of StringBuffer to a file

        bwr.write(sb.toString());

        //flush the stream
        bwr.flush();

        //close the stream
        bwr.close();
        osw.close();
        fos.close();
    } catch (IOException e) {
        getLog().error(e);
        throw new MojoExecutionException("json file creation error", e);
    }
}

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

public void doUpdate() {
    showDialog(DIALOG_PROGRESS);/*from w  ww. ja  v  a2s  . c o m*/
    savePreferences();
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                URL uri = new URL(UPDATE_URL);
                URLConnection urlc = uri.openConnection();
                long lastModified = urlc.getLastModified();
                if ((lastModified == 0) || (lastModified != mPrefs.getLong(PREFS_UPDATE, 0))) {
                    FileOutputStream file = getApplicationContext().openFileOutput(UPDATE_FILE, MODE_PRIVATE);
                    OutputStreamWriter content = new OutputStreamWriter(file);

                    String tmp;
                    InputStream is = urlc.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    while ((tmp = br.readLine()) != null) {
                        content.write(tmp + "\n");
                    }

                    content.flush();
                    content.close();
                    file.close();

                    SharedPreferences.Editor prefsEditor = mPrefs.edit();
                    prefsEditor.putLong(PREFS_UPDATE, lastModified);
                    prefsEditor.commit();

                    Message message = mUpdateHandler.obtainMessage();
                    message.what = MESSAGE_UPDATE_FINISHED;
                    mUpdateHandler.sendMessage(message);
                } else {
                    Message message = mUpdateHandler.obtainMessage();
                    message.what = MESSAGE_UPDATE_UNNECESSARY;
                    mUpdateHandler.sendMessage(message);
                }
            } catch (MalformedURLException e) {
                System.out.println(e.getMessage());
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }).start();
}

From source file:com.akop.bach.parser.Parser.java

protected void writeToSd(String filename, String text) {
    java.io.OutputStreamWriter osw = null;
    File root = Environment.getExternalStorageDirectory();

    try {/*w  w w .  j a  v  a  2 s.  com*/
        java.io.FileOutputStream fOut = new FileOutputStream(root + "/" + filename);
        osw = new java.io.OutputStreamWriter(fOut);
        osw.write(text);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (osw != null) {
            try {
                osw.flush();
                osw.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:objective.taskboard.RequestBuilder.java

private RequestResponse doActualRequest(String method) {
    OutputStreamWriter writer = null;
    try {//from   w  w  w. j a  v a 2  s .c om
        conn.setRequestMethod(method);

        if (!StringUtils.isEmpty(body)) {
            conn.setDoOutput(true);
            writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            writer.write(body);
            writer.flush();
        }

        int responseCode = conn.getResponseCode();
        String content;

        try {
            content = IOUtils.toString(conn.getInputStream(), "UTF-8");
        } catch (IOException e) {
            content = e.getMessage();
        }

        if (responseCode < lowerAcceptableStatus || responseCode > upperAcceptableStatus)
            throw new IllegalStateException("Failed : HTTP error code : " + responseCode);

        return new RequestResponse(responseCode, content, conn.getHeaderFields());

    } catch (Exception e) {
        throw new IllegalStateException(e);
    } finally {
        try {
            if (writer != null)
                writer.close();
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }
}

From source file:net.sourceforge.ganttproject.io.GanttCSVExport.java

/**
 * Save the project as CSV on a stream//ww w .  j a  v a 2 s  . c  o  m
 *
 * @throws IOException
 */
public void save(OutputStream stream) throws IOException {
    OutputStreamWriter writer = new OutputStreamWriter(stream);
    CSVFormat format = CSVFormat.DEFAULT.withEscape('\\');
    if (csvOptions.sSeparatedChar.length() == 1) {
        format = format.withDelimiter(csvOptions.sSeparatedChar.charAt(0));
    }
    if (csvOptions.sSeparatedTextChar.length() == 1) {
        format = format.withEncapsulator(csvOptions.sSeparatedTextChar.charAt(0));
    }

    CSVPrinter csvPrinter = new CSVPrinter(writer, format);

    if (csvOptions.bFixedSize) {
        // TODO The CVS library we use is lacking support for fixed size
        getMaxSize();
    }

    writeTasks(csvPrinter);

    if (myProject.getHumanResourceManager().getResources().size() > 0) {
        csvPrinter.println();
        csvPrinter.println();
        writeResources(csvPrinter);
    }
    writer.flush();
    writer.close();
}