Example usage for java.io Writer append

List of usage examples for java.io Writer append

Introduction

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

Prototype

public Writer append(char c) throws IOException 

Source Link

Document

Appends the specified character to this writer.

Usage

From source file:com.indeema.emailcommon.internet.Rfc822Output.java

/**
 * Write a single attachment and its payload
 *//*from ww w . j ava  2s.c  o m*/
private static void writeOneAttachment(Context context, Writer writer, OutputStream out,
        EmailContent.Attachment attachment) throws IOException, MessagingException {
    writeHeader(writer, "Content-Type", attachment.mMimeType + ";\n name=\"" + attachment.mFileName + "\"");
    writeHeader(writer, "Content-Transfer-Encoding", "base64");
    // Most attachments (real files) will send Content-Disposition.  The suppression option
    // is used when sending calendar invites.
    if ((attachment.mFlags & EmailContent.Attachment.FLAG_ICS_ALTERNATIVE_PART) == 0) {
        writeHeader(writer, "Content-Disposition", "attachment;" + "\n filename=\"" + attachment.mFileName
                + "\";" + "\n size=" + Long.toString(attachment.mSize));
    }
    if (attachment.mContentId != null) {
        writeHeader(writer, "Content-ID", attachment.mContentId);
    }
    writer.append("\r\n");

    // Set up input stream and write it out via base64
    InputStream inStream = null;
    try {
        // Use content, if provided; otherwise, use the contentUri
        if (attachment.mContentBytes != null) {
            inStream = new ByteArrayInputStream(attachment.mContentBytes);
        } else {
            // First try the cached file
            final String cachedFile = attachment.getCachedFileUri();
            if (!TextUtils.isEmpty(cachedFile)) {
                final Uri cachedFileUri = Uri.parse(cachedFile);
                try {
                    inStream = context.getContentResolver().openInputStream(cachedFileUri);
                } catch (FileNotFoundException e) {
                    // Couldn't open the cached file, fall back to the original content uri
                    inStream = null;

                    LogUtils.d(TAG, "Rfc822Output#writeOneAttachment(), failed to load"
                            + "cached file, falling back to: %s", attachment.getContentUri());
                }
            }

            if (inStream == null) {
                // try to open the file
                final Uri fileUri = Uri.parse(attachment.getContentUri());
                inStream = context.getContentResolver().openInputStream(fileUri);
            }
        }
        // switch to output stream for base64 text output
        writer.flush();
        Base64OutputStream base64Out = new Base64OutputStream(out, Base64.CRLF | Base64.NO_CLOSE);
        // copy base64 data and close up
        IOUtils.copy(inStream, base64Out);
        base64Out.close();

        // The old Base64OutputStream wrote an extra CRLF after
        // the output.  It's not required by the base-64 spec; not
        // sure if it's required by RFC 822 or not.
        out.write('\r');
        out.write('\n');
        out.flush();
    } catch (FileNotFoundException fnfe) {
        // Ignore this - empty file is OK
        LogUtils.e(TAG, fnfe,
                "Rfc822Output#writeOneAttachment(), FileNotFoundException" + "when sending attachment");
    } catch (IOException ioe) {
        LogUtils.e(TAG, ioe, "Rfc822Output#writeOneAttachment(), IOException" + "when sending attachment");
        throw new MessagingException("Invalid attachment.", ioe);
    }
}

From source file:com.palantir.stash.stashbot.servlet.BuildSuccessReportingServlet.java

private void printOutput(HttpServletRequest req, HttpServletResponse res) throws IOException {
    res.reset();//  w  ww .j  av a2s.c  om
    res.setStatus(200);
    res.setContentType("text/plain;charset=UTF-8");
    Writer w = res.getWriter();
    w.append("Status Updated");
    w.close();
}

From source file:com.bstek.dorado.view.config.attachment.AttachedJavaScriptResourceManager.java

@Override
public void outputContent(OutputContext context, Object content) throws Exception {
    Map<String, Object> arguments = null;
    View view = context.getCurrentView();
    if (view != null) {
        ViewConfig viewConfig = view.getViewConfig();
        arguments = viewConfig.getArguments();
    }/*from  w w  w  .  j  a v a  2 s .  c  o  m*/

    JexlContext jexlContext = getExpressionHandler().getJexlContext();
    final String ARGUMENT = "argument";
    Object originArgumentsVar = jexlContext.get(ARGUMENT);
    jexlContext.set(ARGUMENT, arguments);
    try {
        JavaScriptContent javaScriptContent = (JavaScriptContent) content;
        if (javaScriptContent.getIsController()) {
            Writer writer = context.getWriter();
            JsonBuilder jsonBuilder = context.getJsonBuilder();
            writer.append("\n\n(function(view){\n");

            super.outputContent(context, javaScriptContent.getContent());

            if (javaScriptContent.getFunctionInfos() != null) {
                writer.append("\ndorado.widget.Controller.registerFunctions(view,");
                jsonBuilder.array();
                for (FunctionInfo functionInfo : javaScriptContent.getFunctionInfos()) {
                    jsonBuilder.object();
                    jsonBuilder.key("name").value(functionInfo.getFunctionName());

                    jsonBuilder.key("func").beginValue();
                    writer.append(functionInfo.getFunctionName());
                    jsonBuilder.endValue();

                    if (functionInfo.getShouldRegisterToGlobal()) {
                        jsonBuilder.key("global").value(true);
                    }
                    if (functionInfo.getShouldRegisterToView()) {
                        jsonBuilder.key("view").value(true);
                    }

                    BindingInfo bindingInfo = functionInfo.getBindingInfo();
                    if (bindingInfo != null) {
                        jsonBuilder.key("bindingInfos").array();
                        for (String expression : bindingInfo.getExpressions()) {
                            if (expression.charAt(0) == '@') {
                                registerIncludeDataType(context, expression);
                            }
                            jsonBuilder.value(expression);
                        }
                        jsonBuilder.endArray();
                    }
                    jsonBuilder.endObject();
                }
                jsonBuilder.endArray();
                writer.append(");\n");
            }
            writer.append("})(view);\n");
        } else {
            super.outputContent(context, javaScriptContent.getContent());
        }
    } finally {
        jexlContext.set(ARGUMENT, originArgumentsVar);
    }
}

From source file:org.apache.sshd.EchoCommand.java

@Override
protected Integer executeCommand(Environment env) throws Throwable {
    BufferedReader rdr = new BufferedReader(
            new InputStreamReader(new ExtendedCloseShieldInputStream(getInputStream()), "UTF-8"));
    try {//from  www  .ja  va  2s .  co  m
        Writer w = new OutputStreamWriter(new ExtendedCloseShieldOutputStream(getOutputStream()), "UTF-8");

        try {
            for (String line = rdr.readLine(); line != null; line = rdr.readLine()) {
                w.append(line).append(SystemUtils.LINE_SEPARATOR).flush();
                if (getExitCommand().equals(line.trim())) {
                    break;
                }
            }

            return EXIT_SUCCESS;
        } finally {
            w.close();
        }
    } finally {
        rdr.close();
    }
}

From source file:org.apache.blur.metrics.MetricInfo.java

private void writeMetricMap(Writer writer) throws IOException {
    boolean flag = false;
    for (Entry<String, ArrayWriter> entry : metricMap.entrySet()) {
        if (flag) {
            writer.append(',');
        }/*from  w  w w . j av a 2s  .c o m*/
        writer.append("\"");
        writer.append(entry.getKey());
        writer.append("\":");
        entry.getValue().writeArray(writer);
        flag = true;
    }
}

From source file:org.sonar.plugins.checkstyle.CheckstyleProfileExporter.java

private void appendModule(Writer writer, ActiveRule activeRule) throws IOException {
    String moduleName = StringUtils.substringAfterLast(activeRule.getConfigKey(), "/");
    writer.append("<module name=\"");
    StringEscapeUtils.escapeXml(writer, moduleName);
    writer.append("\">");
    if (activeRule.getRule().getParent() != null) {
        appendModuleProperty(writer, "id", activeRule.getRuleKey());
    }//from w  w  w . j a  v a  2  s .  com
    appendModuleProperty(writer, "severity", CheckstyleSeverityUtils.toSeverity(activeRule.getSeverity()));
    appendRuleParameters(writer, activeRule);
    writer.append("</module>");
}

From source file:tudarmstadt.lt.ABSentiment.training.util.ProblemBuilder.java

protected static void printFeatureStatistics(Vector<FeatureExtractor> features) {
    if (featureStatisticsFile != null) {
        try {//  w w  w  . j a v a2 s.c om
            Writer statisticsOut = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(featureStatisticsFile), "UTF-8"));
            statisticsOut.write("training set: " + trainFile + "\n");
            if (featureStatisticsFile != null) {
                int start;
                int end;
                for (FeatureExtractor feature : features) {
                    start = feature.getOffset();
                    end = feature.getOffset() + feature.getFeatureCount();
                    statisticsOut
                            .append(feature.getClass().getCanonicalName() + "\t" + start + "\t" + end + "\n");
                }
            }
            statisticsOut.close();
        } catch (UnsupportedEncodingException | FileNotFoundException e) {
            e.printStackTrace();
            System.exit(1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:ca.uhn.hl7v2.testpanel.model.MessagesList.java

/**
 * Save all files to work directory//from   w  ww.j  av  a  2  s.  c o m
 */
public void dumpToWorkDirectory(File theWorkfilesDir) throws IOException {
    ourLog.info("Flushing work files to directory: " + theWorkfilesDir.getAbsolutePath());

    IOUtils.deleteAllFromDirectory(theWorkfilesDir);

    int index = 0;
    for (Hl7V2MessageCollection next : myMessages) {
        index++;
        String seq = StringUtils.leftPad(Integer.toString(index), 10, '0');

        File nextFile = new File(theWorkfilesDir, next.getId() + "-" + seq + ".xml");
        nextFile.delete();
        Writer nextWriter = new OutputStreamWriter(new FileOutputStream(nextFile), Charset.forName("UTF-8"));
        nextWriter.append(next.exportConfigToXml());
        nextWriter.close();
    }

}

From source file:com.palantir.stash.stashbot.servlet.BuildStatusReportingServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {//from ww w  .j a v  a2  s .co  m
        // Look at JenkinsManager class if you change this:
        // final two arguments could be empty...
        final String URL_FORMAT = "BASE_URL/REPO_ID_OR_SLUG/PULLREQUEST_ID]";
        final String pathInfo = req.getPathInfo();
        final String[] parts = pathInfo.split("/");

        // need at *least* 3 parts to be correct
        if (parts.length < 3) {
            throw new IllegalArgumentException("The format of the URL is " + URL_FORMAT);
        }

        // Last part is always the PR
        String pullRequestPart = parts[parts.length - 1];

        // First part is always empty because string starts with '/', last is pr, the rest is the slug
        String slugOrId = StringUtils.join(Arrays.copyOfRange(parts, 1, parts.length - 1), "/");

        Repository repo;
        try {
            int repoId = Integer.valueOf(slugOrId);
            repo = rs.getById(repoId);
            if (repo == null) {
                throw new IllegalArgumentException("Unable to find repository for repo id " + repoId);
            }
        } catch (NumberFormatException e) {
            // we have a slug, try to get a repo ID from that
            // slug should look like this: projects/PROJECT_KEY/repos/REPO_SLUG/pull-requests
            String[] newParts = slugOrId.split("/");

            if (newParts.length != 5) {
                throw new IllegalArgumentException(
                        "The format of the REPO_ID_OR_SLUG is an ID, or projects/PROJECT_KEY/repos/REPO_SLUG/pull-requests");
            }
            Project p = ps.getByKey(newParts[1]);
            if (p == null) {
                throw new IllegalArgumentException("Unable to find project for project key" + newParts[1]);
            }
            repo = rs.getBySlug(p.getKey(), newParts[3]);
            if (repo == null) {
                throw new IllegalArgumentException("Unable to find repository for project key" + newParts[1]
                        + " and repo slug " + newParts[3]);
            }
        }

        final long pullRequestId;
        final PullRequest pullRequest;

        try {
            pullRequestId = Long.parseLong(pullRequestPart);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Unable to parse pull request id " + parts[7], e);
        }
        pullRequest = prs.getById(repo.getId(), pullRequestId);
        if (pullRequest == null) {
            throw new IllegalArgumentException("Unable to find pull request for repo id "
                    + repo.getId().toString() + " pr id " + pullRequestId);
        }

        PullRequestMergeability canMerge = prs.canMerge(repo.getId(), pullRequestId);

        JSONObject output = new JSONObject();
        output.put("repoId", repo.getId());
        output.put("prId", pullRequestId);
        output.put("url", nb.repo(repo).pullRequest(pullRequest.getId()).buildAbsolute());
        output.put("canMerge", canMerge.canMerge());
        if (!canMerge.canMerge()) {
            JSONArray vetoes = new JSONArray();
            for (PullRequestMergeVeto prmv : canMerge.getVetos()) {
                JSONObject prmvjs = new JSONObject();
                prmvjs.put("summary", prmv.getSummaryMessage());
                prmvjs.put("details", prmv.getDetailedMessage());
                vetoes.put(prmvjs);
            }
            // You might expect a conflict would be included in the list of merge blockers.  You'd be mistaken.
            if (canMerge.isConflicted()) {
                JSONObject prmvjs = new JSONObject();
                prmvjs.put("summary", "This pull request is unmergeable due to conflicts.");
                prmvjs.put("details", "You will need to resolve conflicts to be able to merge.");
                vetoes.put(prmvjs);
            }
            output.put("vetoes", vetoes);
        }

        log.debug("Serving build status: " + output.toString());
        printOutput(output, req, res);
    } catch (Exception e) {
        res.reset();
        res.setStatus(500);
        res.setContentType("application/json");
        Writer w = res.getWriter();
        try {
            w.append(new JSONObject().put("error", e.getMessage()).toString());
        } catch (JSONException e1) {
            throw new RuntimeException("Errorception!", e1);
        }
        w.close();
    }
}

From source file:com.android.emailcommon.internet.Rfc822Output.java

/**
 * Write a single attachment and its payload
 *///  www  . j  a v a2s . c o m
private static void writeOneAttachment(Context context, Writer writer, OutputStream out, Attachment attachment)
        throws IOException, MessagingException {
    writeHeader(writer, "Content-Type", attachment.mMimeType + ";\n name=\"" + attachment.mFileName + "\"");
    writeHeader(writer, "Content-Transfer-Encoding", "base64");
    // Most attachments (real files) will send Content-Disposition.  The suppression option
    // is used when sending calendar invites.
    if ((attachment.mFlags & Attachment.FLAG_ICS_ALTERNATIVE_PART) == 0) {
        writeHeader(writer, "Content-Disposition", "attachment;" + "\n filename=\"" + attachment.mFileName
                + "\";" + "\n size=" + Long.toString(attachment.mSize));
    }
    if (attachment.mContentId != null) {
        writeHeader(writer, "Content-ID", attachment.mContentId);
    }
    writer.append("\r\n");

    // Set up input stream and write it out via base64
    InputStream inStream = null;
    try {
        // Use content, if provided; otherwise, use the contentUri
        if (attachment.mContentBytes != null) {
            inStream = new ByteArrayInputStream(attachment.mContentBytes);
        } else {
            // try to open the file
            Uri fileUri = Uri.parse(attachment.mContentUri);
            inStream = context.getContentResolver().openInputStream(fileUri);
        }
        // switch to output stream for base64 text output
        writer.flush();
        Base64OutputStream base64Out = new Base64OutputStream(out, Base64.CRLF | Base64.NO_CLOSE);
        // copy base64 data and close up
        IOUtils.copy(inStream, base64Out);
        base64Out.close();

        // The old Base64OutputStream wrote an extra CRLF after
        // the output.  It's not required by the base-64 spec; not
        // sure if it's required by RFC 822 or not.
        out.write('\r');
        out.write('\n');
        out.flush();
    } catch (FileNotFoundException fnfe) {
        // Ignore this - empty file is OK
    } catch (IOException ioe) {
        throw new MessagingException("Invalid attachment.", ioe);
    }
}