Example usage for java.io OutputStreamWriter append

List of usage examples for java.io OutputStreamWriter append

Introduction

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

Prototype

@Override
    public Writer append(CharSequence csq) throws IOException 

Source Link

Usage

From source file:com.androidaq.AndroiDAQMain.java

public void writeToFile(String data) {

    File myFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/log.txt");

    try {/*from  www.  j a  va  2 s .co m*/
        if (!myFile.exists()) {
            myFile.createNewFile();
            Toast.makeText(getBaseContext(), "Created new 'log.txt'", Toast.LENGTH_SHORT).show();
        }
    } catch (IOException e) {
        Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
    }

    try {

        FileOutputStream fOut = new FileOutputStream(myFile, true);
        OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
        myOutWriter.append(data);
        myOutWriter.close();
        fOut.close();
        Toast.makeText(getBaseContext(), "Done writing to SD 'log.txt'", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
    }

}

From source file:org.kuali.rice.krad.theme.postprocessor.ThemeFilesProcessor.java

/**
 * Merges the content from the list of files into the given merge file
 *
 * <p>/* w ww . j a  v  a2 s.  c  o m*/
 * Contents are read for each file in the order they appear in the files list. Before adding the contents
 * to the merged file, the method {@link #processMergeFileContents(java.lang.String, java.io.File, java.io.File)}
 * is invoked to allow subclasses to alter the contents
 * </p>
 *
 * @param filesToMerge list of files whose content should be merged
 * @param mergedFile file that should receive the merged content
 * @throws IOException
 */
protected void mergeFiles(List<File> filesToMerge, File mergedFile) throws IOException {
    OutputStream out = null;
    OutputStreamWriter outWriter = null;
    InputStreamReader reader = null;

    LOG.info("Creating merged file: " + mergedFile.getPath());

    try {
        out = new FileOutputStream(mergedFile);
        outWriter = new OutputStreamWriter(out);

        for (File fileToMerge : filesToMerge) {
            reader = new FileReader(fileToMerge);

            String fileContents = IOUtils.toString(reader);
            if ((fileContents == null) || "".equals(fileContents)) {
                continue;
            }

            fileContents = processMergeFileContents(fileContents, fileToMerge, mergedFile);

            outWriter.append(fileContents);
            outWriter.flush();
        }
    } finally {
        if (out != null) {
            out.close();
        }

        if (reader != null) {
            reader.close();
        }
    }
}

From source file:org.apache.zeppelin.interpreter.InterpreterSettingManager.java

public void saveToFile() throws IOException {
    String jsonString;/*  w w w .  j a  v  a2s.c  om*/

    synchronized (interpreterSettings) {
        InterpreterInfoSaving info = new InterpreterInfoSaving();
        info.interpreterBindings = interpreterBindings;
        info.interpreterSettings = interpreterSettings;
        info.interpreterRepositories = interpreterRepositories;

        jsonString = gson.toJson(info);
    }

    if (!Files.exists(interpreterBindingPath)) {
        Files.createFile(interpreterBindingPath);

        Set<PosixFilePermission> permissions = EnumSet.of(OWNER_READ, OWNER_WRITE);
        Files.setPosixFilePermissions(interpreterBindingPath, permissions);
    }

    FileOutputStream fos = new FileOutputStream(interpreterBindingPath.toFile(), false);
    OutputStreamWriter out = new OutputStreamWriter(fos);
    out.append(jsonString);
    out.close();
    fos.close();
}

From source file:com.wyp.module.controller.LicenseController.java

/**
 * wslicense//  w w  w  . jav  a2  s .c o m
 * 
 * @param properties
 * @return
 */
private String getCitrixLicense(String requestJson) {
    String licenses = "";
    OutputStreamWriter out = null;
    InputStream is = null;
    long start = System.currentTimeMillis();
    try {
        // ws url
        URL url = new URL(map.get("address"));
        // ws connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", " application/json");
        connection.setRequestMethod("POST");
        connection.connect();
        out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        out.append(requestJson);
        out.flush();
        // response string
        is = connection.getInputStream();
        int length = is.available();
        if (0 < length) {
            long end = System.currentTimeMillis();
            System.out.println("?" + (end - start));
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuilder tempStr = new StringBuilder();
            String temp = "";
            while ((temp = reader.readLine()) != null) {
                tempStr.append(temp);
            }
            licenses = tempStr.toString(); // utf-8?
            System.out.println(licenses);
        }
    } catch (IOException e) {
        String eMsg = e.getMessage();
        if ("Read timed out".equals(eMsg) || "Connection timed out: connect".equals(eMsg)
                || "Software caused connection abort: recv failed".equals(eMsg)) {
            long end = System.currentTimeMillis();
            System.out.println(eMsg + (end - start));
            licenses = "TIMEOUT";
        }
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
            if (is != null) {
                is.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    System.out.println(licenses);
    return licenses;
}

From source file:org.miloss.fgsms.services.rs.impl.reports.ws.ThroughputByHostingServer.java

@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {

    if (!UserIdentityUtil.hasGlobalAdministratorRole(currentuser, "INVOCATIONS_BY_HOSTING_SERVER",
            classification, ctx)) {/*  www.j ava2 s.  c o m*/
        data.write("<h2>Access for " + GetDisplayName() + " was denied for non-global admin users</h2>");
        return;
    }
    double d = range.getEnd().getTimeInMillis() - range.getStart().getTimeInMillis();
    double day = d / 86400000;
    double hours = d / 3600000;
    double min = d / 60000;
    double sec = d / 1000;
    Connection con = Utility.getPerformanceDBConnection();
    try {
        PreparedStatement cmd = null;
        ResultSet rs = null;
        DefaultCategoryDataset set = new DefaultCategoryDataset();
        JFreeChart chart = null;
        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append(GetHtmlFormattedHelp() + "<br />");
        data.append(
                "<table  class=\"table table-hover\"><tr><th>Service Hostname</th><th>Invocations</th><th>Msg/Day</th><th>Msg/Hour</th><th>Msg/Min</th><th>Msg/Sec</th></tr>");

        // for (int i = 0; i < urls.size(); i++) {
        List<String> hosts = new ArrayList<String>();
        try {
            cmd = con.prepareStatement(
                    "select hostingsource from rawdata where (UTCdatetime > ?) and (UTCdatetime < ?) group by hostingsource ;");
            cmd.setLong(1, range.getStart().getTimeInMillis());
            cmd.setLong(2, range.getEnd().getTimeInMillis());
            rs = cmd.executeQuery();
            while (rs.next()) {
                String s = rs.getString(1);
                if (!Utility.stringIsNullOrEmpty(s)) {
                    s = s.trim();
                }
                if (!Utility.stringIsNullOrEmpty(s)) {
                    hosts.add(s);
                }
            }
        } catch (Exception ex) {
        } finally {
            DBUtils.safeClose(rs);
            DBUtils.safeClose(cmd);
        }

        for (int i = 0; i < hosts.size(); i++) {
            long count = 0;
            try {
                cmd = con.prepareStatement("select count(*) from RawData where hostingsource=? and "
                        + "(UTCdatetime > ?) and (UTCdatetime < ?) ;");
                cmd.setString(1, hosts.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                try {
                    if (rs.next()) {
                        count = rs.getLong(1);
                    }
                } catch (Exception ex) {
                    log.log(Level.DEBUG, null, ex);
                }
            } catch (Exception ex) {
                log.log(Level.ERROR, "Error opening or querying the database.", ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }
            data.append("<tr><td>").append(Utility.encodeHTML(hosts.get(i))).append("</td><td>");
            data.append(count + "");
            data.append("</td><td>").append(format.format((double) ((double) count / day))).append("</td><td>")
                    .append(format.format((double) ((double) count / hours))).append("</td><td>")
                    .append(format.format((double) ((double) count / min))).append("</td><td>")
                    .append(format.format((double) ((double) count / sec))).append("</td></tr>");
            if (count > 0) {
                set.addValue((double) ((double) count / day), hosts.get(i), hosts.get(i));
            }
        }

        chart = org.jfree.chart.ChartFactory.createBarChart(GetDisplayName(), "Service URL", "", set,
                PlotOrientation.HORIZONTAL, true, false, false);
        data.append("</table>");
        try {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, pixelHeightCalc(hosts.size()));
        } catch (IOException ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }

        data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
        files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");
    } catch (Exception ex) {
        log.log(Level.ERROR, null, ex);
    } finally {
        DBUtils.safeClose(con);
    }
}

From source file:org.kuali.rice.krad.theme.postprocessor.ThemeJsFilesProcessor.java

/**
 * Minifies the JS contents from the given merged file into the minified file
 *
 * <p>//from   w w  w  .j av  a  2 s  .c  o  m
 * Minification is performed using the Google Closure compiler, using
 * com.google.javascript.jscomp.CompilationLevel#WHITESPACE_ONLY and EcmaScript5 language level
 * </p>
 *
 * @see ThemeFilesProcessor#minify(java.io.File, java.io.File)
 * @see com.google.javascript.jscomp.Compiler
 */
@Override
protected void minify(File mergedFile, File minifiedFile) throws IOException {
    InputStream in = null;
    OutputStream out = null;
    OutputStreamWriter writer = null;
    InputStreamReader reader = null;

    LOG.info("Populating minified JS file: " + minifiedFile.getPath());

    try {
        out = new FileOutputStream(minifiedFile);
        writer = new OutputStreamWriter(out);

        in = new FileInputStream(mergedFile);
        reader = new InputStreamReader(in);

        CompilerOptions options = new CompilerOptions();
        CompilationLevel.WHITESPACE_ONLY.setOptionsForCompilationLevel(options);
        options.setLanguageIn(CompilerOptions.LanguageMode.ECMASCRIPT5);
        options.setExtraAnnotationNames(ignoredAnnotations());

        SourceFile input = SourceFile.fromInputStream(mergedFile.getName(), in);
        List<SourceFile> externs = Collections.emptyList();

        Compiler compiler = new Compiler();
        compiler.compile(externs, Arrays.asList(input), options);

        writer.append(compiler.toSource());
        writer.flush();
    } finally {
        if (in != null) {
            in.close();
        }

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

From source file:org.opendatakit.briefcase.util.ExportToCsv.java

private void processRepeatingGroupDefinition(TreeElement group, TreeElement primarySet, boolean emitCsvHeaders)
        throws IOException {
    String formName = baseFilename + "-" + getFullName(group, primarySet);
    File topLevelCsv = new File(outputDir, safeFilename(formName) + ".csv");
    FileOutputStream os = new FileOutputStream(topLevelCsv, !overwrite);
    OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
    fileMap.put(group, osw);//  www . jav  a  2s  .  co  m
    if (emitCsvHeaders) {
        boolean first = true;
        first = emitCsvHeaders(osw, group, group, first);
        emitString(osw, first, "PARENT_KEY");
        emitString(osw, false, "KEY");
        emitString(osw, false, "SET-OF-" + group.getName());
        osw.append("\n");
    } else {
        populateRepeatGroupsIntoFileMap(group, group);
    }
}

From source file:com.roamprocess1.roaming4world.syncadapter.SyncAdapter.java

public void sendContacts(File contactFile) throws IOException {
    Log.d("sendContacts", "called");

    Log.d("sendContacts", "1");
    FileOutputStream fOut = new FileOutputStream(contactFile);
    Log.d("sendContacts", "2");
    OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
    Log.d("sendContacts", "3");
    String lastContacts = getAllContacts[getAllContacts.length - 1];

    Log.d("sendContacts", "4");

    for (int x = 0; x <= getAllContacts.length; x++) {
        if (x == 0) {
            myOutWriter.append(selfNumber);
        } else if (getAllContacts[x - 1] != null) {
            if (getAllContacts[x - 1].contains(",")) {
                getAllContacts[x - 1] = getAllContacts[x - 1].substring(0, getAllContacts[x - 1].length() - 1);
            }/*from w w w. j ava2 s  . com*/
            myOutWriter.append("," + getAllContacts[x - 1]);
        }

    }

    myOutWriter.close();
    fOut.close();
    int response = 0;

    String imagePathUri = defaultPath + "/" + selfNumber + ".txt";
    if (!imagePathUri.equals("")) {
        Log.d("sendContacts", "if (!imagePathUri.equals())");
        response = uploadFile(imagePathUri);
        Log.d("response ", response + "  d");
        if (response == 200) {
            Log.d("doInBackgroud", "doInBackground");
            contactFile.delete();

            if (websericeR4WContacts()) {
                try {
                    CharSequence constraint = "str";
                    if (RContactlist.r4wCompleteContactList.length != 0) {
                        ContactsWrapper.getInstance().getContactsPhonesR4W(mcontext, constraint);
                        //c1.close();

                    }
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }

        }

    }

}

From source file:org.opendatakit.briefcase.util.ExportToCsv.java

private void emitRepeatingGroupCsv(EncryptionInformation ei, List<Element> groupElementList, TreeElement group,
        String uniqueParentPath, String uniqueGroupPath, File instanceDir) throws IOException {
    OutputStreamWriter osw = fileMap.get(group);
    int trueOrdinal = 1;
    for (Element groupElement : groupElementList) {
        String uniqueGroupInstancePath = uniqueGroupPath + "[" + trueOrdinal + "]";
        boolean first = true;
        first = emitSubmissionCsv(osw, ei, groupElement, group, group, first, uniqueGroupInstancePath,
                instanceDir);/*from  ww  w .  java 2 s  .  c  o m*/
        emitString(osw, first, uniqueParentPath);
        emitString(osw, false, uniqueGroupInstancePath);
        emitString(osw, false, uniqueGroupPath);
        osw.append("\n");
        ++trueOrdinal;
    }
}

From source file:org.opendatakit.briefcase.util.ExportToCsv.java

private boolean processFormDefinition() {

    TreeElement submission = briefcaseLfd.getSubmissionElement();

    String formName = baseFilename;
    File topLevelCsv = new File(outputDir, safeFilename(formName) + ".csv");
    boolean exists = topLevelCsv.exists();
    FileOutputStream os;// www .j  a  va  2s.  c  om
    try {
        os = new FileOutputStream(topLevelCsv, !overwrite);
        OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
        fileMap.put(submission, osw);
        // only write headers if overwrite is set, or creating file for the first time
        if (overwrite || !exists) {
            emitString(osw, true, "SubmissionDate");
            emitCsvHeaders(osw, submission, submission, false);
            emitString(osw, false, "KEY");
            if (briefcaseLfd.isFileEncryptedForm()) {
                emitString(osw, false, "isValidated");
            }
            osw.append("\n");
        } else {
            populateRepeatGroupsIntoFileMap(submission, submission);
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
        EventBus.publish(new ExportProgressEvent("Unable to create csv file: " + topLevelCsv.getPath()));
        for (OutputStreamWriter w : fileMap.values()) {
            try {
                w.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        fileMap.clear();
        return false;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        EventBus.publish(new ExportProgressEvent("Unable to create csv file: " + topLevelCsv.getPath()));
        for (OutputStreamWriter w : fileMap.values()) {
            try {
                w.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        fileMap.clear();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        EventBus.publish(new ExportProgressEvent("Unable to create csv file: " + topLevelCsv.getPath()));
        for (OutputStreamWriter w : fileMap.values()) {
            try {
                w.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        fileMap.clear();
        return false;
    }
    return true;
}