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.github.pemapmodder.pocketminegui.gui.startup.installer.cards.ServerSetupCard.java

@SuppressWarnings("unchecked")
public ServerSetupCard(InstallServerActivity activity) {
    JButton serverPropertiesButton = new JButton("General server properties");
    serverPropertiesButton.addActionListener(e -> new ServerOptionsActivity("Server properties editor",
            activity, new HashMap<>(SERVER_PROPERTIES_MAP), new HashMap<>(SERVER_PROPERTIES_DESC_MAP)) {
        @Override/*from  www. java 2s  .c om*/
        protected void onResult(Map<String, Object> opts) {
            try {
                OutputStreamWriter writer = new OutputStreamWriter(
                        new FileOutputStream(new File(activity.getSelectedHome(), "server.properties")));
                writer.append("#Properties Config file\r\n").append("#Generated by PocketMine-GUI\r\n");
                for (Map.Entry<String, Object> entry : opts.entrySet()) {
                    writer.append(entry.getKey()).append('=').append(entry.getValue().toString())
                            .append("\r\n");
                }
                writer.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }.init());
    JButton pocketmineOpts = new JButton("PocketMine-specific settings");
    pocketmineOpts.addActionListener(e -> new ServerOptionsActivity("PocketMine settings editor", activity,
            new HashMap<>(POCKETMINE_YML_MAP), new HashMap<>(POCKETMINE_YML_DESC_MAP)) {
        @Override
        protected void onResult(Map<String, Object> opts) {
            Yaml yaml = new Yaml();
            try {
                Writer writer = new OutputStreamWriter(
                        new FileOutputStream(new File(activity.getSelectedHome(), "pocketmine.yml")));
                yaml.dump(convertPlainToNested(opts), writer);
                writer.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }.init());
    add(serverPropertiesButton);
    add(pocketmineOpts);
}

From source file:org.apache.olingo.fit.tecsvc.http.PreferHeaderForGetAndDeleteITCase.java

private HttpURLConnection postRequest(final URL url, final String content, final Map<String, String> headers)
        throws IOException {
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.POST.toString());

    for (Map.Entry<String, String> header : headers.entrySet()) {
        connection.setRequestProperty(header.getKey(), header.getValue());
    }//from   w  w  w. j ava 2 s  .  c  o  m

    connection.setDoOutput(true);
    final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    writer.append(content);
    writer.close();
    connection.connect();
    return connection;
}

From source file:com.alta189.commons.yaml.YAMLProcessor.java

/**
 * Saves the configuration to disk. All errors are clobbered.
 *
 * @return true if it was successful/*ww w. j a  v  a  2 s  .c  om*/
 */
public boolean save() {
    OutputStream stream = null;

    File parent = file.getParentFile();

    if (parent != null) {
        parent.mkdirs();
    }

    try {
        stream = getOutputStream();
        if (stream == null)
            return false;
        OutputStreamWriter writer = new OutputStreamWriter(stream, "UTF-8");
        if (header != null) {
            writer.append(header);
            writer.append(LINE_BREAK);
        }
        if (comments.size() == 0 || format != YAMLFormat.EXTENDED) {
            yaml.dump(root, writer);
        } else {
            // Iterate over each root-level property and dump
            for (Iterator<Map.Entry<String, Object>> i = root.entrySet().iterator(); i.hasNext();) {
                Map.Entry<String, Object> entry = i.next();

                // Output comment, if present
                String comment = comments.get(entry.getKey());
                if (comment != null) {
                    writer.append(LINE_BREAK);
                    writer.append(comment);
                    writer.append(LINE_BREAK);
                }

                // Dump property
                yaml.dump(Collections.singletonMap(entry.getKey(), entry.getValue()), writer);
            }
        }
        return true;
    } catch (IOException e) {
    } finally {
        try {
            if (stream != null) {
                stream.close();
            }
        } catch (IOException e) {
        }
    }

    return false;
}

From source file:org.superfuntime.chatty.yml.YAMLProcessor.java

/**
 * Saves the configuration to disk. All errors are clobbered.
 *
 * @return true if it was successful//from   w w w.j  a  v  a  2 s.c om
 */
public boolean save() {
    OutputStream stream = null;

    File parent = file.getParentFile();

    if (parent != null) {
        parent.mkdirs();
    }

    try {
        stream = getOutputStream();
        if (stream == null)
            return false;
        OutputStreamWriter writer = new OutputStreamWriter(stream, "UTF-8");
        if (header != null) {
            writer.append(header);
            writer.append(LINE_BREAK);
        }
        if (comments.size() == 0 || format != YAMLFormat.EXTENDED) {
            yaml.dump(root, writer);
        } else {
            // Iterate over each root-level property and dump
            for (Map.Entry<String, Object> entry : root.entrySet()) {
                // Output comment, if present
                String comment = comments.get(entry.getKey());
                if (comment != null) {
                    writer.append(LINE_BREAK);
                    writer.append(comment);
                    writer.append(LINE_BREAK);
                }

                // Dump property
                yaml.dump(Collections.singletonMap(entry.getKey(), entry.getValue()), writer);
            }
        }
        return true;
    } catch (IOException ignored) {
    } finally {
        try {
            if (stream != null) {
                stream.close();
            }
        } catch (IOException ignored) {
        }
    }

    return false;
}

From source file:be.solidx.hot.test.TestScriptExecutors.java

@Test
public void testScriptEncodingGroovy() throws Exception {
    Script<CompiledScript> script = new Script<CompiledScript>(
            IOUtils.toByteArray(getClass().getResourceAsStream("/frenchScript.groovy")), "french");
    FileOutputStream fileOutputStream = new FileOutputStream(new File("testiso.txt"));
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(bos, "ISO8859-1");

    groovyScriptExecutor.execute(script, outputStreamWriter);
    outputStreamWriter.flush();//from w w  w .  ja v  a2  s.  c  o  m
    bos.flush();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    OutputStreamWriter writer = new OutputStreamWriter(outputStream, "ISO8859-1");
    writer.append(new String(bos.toByteArray(), "iso8859-1"));
    writer.flush();
    writer.close();
    fileOutputStream.write(outputStream.toByteArray());
    fileOutputStream.close();
    new File("testiso.txt").delete();
}

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

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

    // web view/* w  ww. j a va2s .co m*/
    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:org.molgenis.util.GsonHttpMessageConverter.java

@Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {

    OutputStreamWriter writer = new OutputStreamWriter(outputMessage.getBody(),
            getCharset(outputMessage.getHeaders()));

    String callback = getCallbackParam();
    if (callback != null) {
        // this is a JSONP (JSON with padding) request
        writer.append(callback).append('(');
    }/*from w  w  w.  j a v  a 2 s  .c o m*/

    try {
        Type typeOfSrc = getType();

        if (LOG.isTraceEnabled()) {
            StringBuilder sb = new StringBuilder();
            if (this.prefixJson) {
                sb.append("{} && ");
            }

            if (typeOfSrc != null) {
                sb.append(gson.toJson(o, typeOfSrc));
            } else {
                sb.append(gson.toJson(o));
            }

            LOG.debug("Json response:\n" + sb.toString());
            writer.write(sb.toString());
        } else {
            if (this.prefixJson) {
                writer.append("{} && ");
            }

            if (typeOfSrc != null) {
                this.gson.toJson(o, typeOfSrc, writer);
            } else {
                this.gson.toJson(o, writer);
            }
        }

        if (callback != null) {
            // this is a JSONP (JSON with padding) request
            writer.append(')');
        }
    } catch (JsonIOException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    } finally {
        IOUtils.closeQuietly(writer);
    }

}

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

/**
 * {@inheritDoc}/*from  ww w . j  av a  2  s.  c o m*/
 */
@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {

    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>URL</th><th>MTBF (ms)</th><th>Timespan</th><th>XML Duration Value</th></tr>");

    for (int i = 0; i < urls.size(); i++) {
        if (!isPolicyTypeOf(urls.get(i), PolicyType.TRANSACTIONAL)) {
            continue;
        }
        //https://github.com/mil-oss/fgsms/issues/112
        if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) {
            continue;
        }
        String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i)));
        try {
            long mtbf = meanTimeBetweenFailures(urls.get(i), range);
            Duration newDuration = df.newDuration(mtbf);
            data.append("<tr><td>").append(url).append("</td><td>");
            if (mtbf == -1 || mtbf == 0) {
                data.append("Never</td><td>0</td><td>0</d></tr>");
            } else {
                data.append(mtbf + "").append("ms</td><td>").append(Utility.durationToString(newDuration))
                        .append("</td><td>").append(newDuration.toString()).append("</td></tr>");
            }
            if (mtbf > 0) {
                set.addValue(mtbf, url, url);
            }

        } catch (Exception ex) {
            data.append("0 bytes</td></tr>");
            log.log(Level.ERROR, "Error opening or querying the database.", ex);
        }
    }
    chart = org.jfree.chart.ChartFactory.createBarChart(GetDisplayName(), "Service URL", "", set,
            PlotOrientation.HORIZONTAL, true, false, false);
    data.append("</table>");
    try {
        if (set.getRowCount() != 0) {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, pixelHeightCalc(set.getRowCount()));
            data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
            files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");
        }
    } catch (IOException ex) {
        log.log(Level.ERROR, "Error saving chart image for request", ex);
    }

}

From source file:org.gephi.ui.components.ReportSelection.java

private boolean saveReport(String html, File destinationFolder) throws IOException {
    if (!destinationFolder.exists()) {
        destinationFolder.mkdir();//from  w ww.  j av  a 2  s  .  co m
    } else {
        if (!destinationFolder.isDirectory()) {
            return false;
        }
    }

    //Find images location
    String imgRegex = "<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>";
    Pattern pattern = Pattern.compile(imgRegex, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(html);
    StringBuffer replaceBuffer = new StringBuffer();
    while (matcher.find()) {
        String fileAbsolutePath = matcher.group(1);
        if (fileAbsolutePath.startsWith("file:")) {
            fileAbsolutePath = fileAbsolutePath.replaceFirst("file:", "");
        }
        File file = new File(fileAbsolutePath);
        if (file.exists()) {
            copy(file, destinationFolder);
        }

        //Replace temp path
        matcher.appendReplacement(replaceBuffer, "<IMG SRC=\"" + file.getName() + "\">");
    }
    matcher.appendTail(replaceBuffer);

    //Write HTML file
    File htmlFile = new File(destinationFolder, "report.html");
    FileOutputStream outputStream = new FileOutputStream(htmlFile);
    OutputStreamWriter out = new OutputStreamWriter(outputStream, "UTF-8");
    out.append(replaceBuffer.toString());
    out.flush();
    out.close();
    outputStream.close();

    return true;
}

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

/**
 * {@inheritDoc}//from  ww w.j a  va2  s  . co  m
 */
@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)) {
        data.append("<h2>Access for " + GetDisplayName() + " was denied for non-global admin users</h2>");
        return;
    }
    int itemcount = 0;
    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("This represents Web Application Server utilization (host) by invocations.<br />");
        data.append("<table class=\"table table-hover\"><tr><th>Host</th><th>Invocations</th></tr>");
        List<String> dcs = new ArrayList<String>();
        try {
            cmd = con.prepareStatement("select hostingsource from RawData group by hostingsource;");
            rs = cmd.executeQuery();
            while (rs.next()) {
                dcs.add(rs.getString(1));
            }
        } catch (Exception ex) {
        } finally {
            DBUtils.safeClose(rs);
            DBUtils.safeClose(cmd);
        }
        try {

            itemcount = dcs.size();
            for (int i = 0; i < dcs.size(); i++) {
                data.append("<tr><td>").append(Utility.encodeHTML(dcs.get(i))).append("</td><td>");
                int success = 0;
                try {
                    cmd = con.prepareStatement(
                            "select count(*) from RawData where hostingsource=? and UTCdatetime > ? and UTCdatetime < ?;");
                    cmd.setString(1, dcs.get(i));
                    cmd.setLong(2, range.getStart().getTimeInMillis());
                    cmd.setLong(3, range.getEnd().getTimeInMillis());
                    rs = cmd.executeQuery();
                    try {
                        if (rs.next()) {
                            success = rs.getInt(1);
                        }
                    } catch (Exception ex) {
                        log.log(Level.DEBUG, null, ex);
                    }
                } catch (Exception ex) {
                    log.log(Level.WARN, null, ex);
                } finally {
                    DBUtils.safeClose(rs);
                    DBUtils.safeClose(cmd);
                }

                data.append(success + "").append("</td></tr>");

                set.addValue(success, dcs.get(i), dcs.get(i));
            }

        } catch (Exception ex) {
            log.log(Level.ERROR, "Error generating chart information.", ex);
        }
        chart = org.jfree.chart.ChartFactory.createBarChart(GetDisplayName(), "Hosting Servers", "", set,
                PlotOrientation.HORIZONTAL, true, false, false);
        data.append("</table>");
        try {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, pixelHeightCalc(itemcount));
        } 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);
    }
}