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.laxser.blitz.web.portal.impl.DefaultPipeRender.java

@Override
public void render(Writer out, Window window) throws IOException {

    JSONObject json = new JSONObject();
    json.put("content", window.getContent());
    json.put("id", window.getName());

    // javascript
    JSONArray js = getAttributeAsArray(window, PipeImpl.WINDIW_JS);
    if (js != null && js.length() > 0) {
        json.put("js", js);
    }/*from   w w w .  j  a va  2 s. c o m*/
    // css
    JSONArray css = getAttributeAsArray(window, PipeImpl.WINDOW_CSS);
    if (css != null && css.length() > 0) {
        json.put("css", css);
    }
    out.append("<script type=\"text/javascript\">");
    out.append("blitzpipe.addWindow(");
    out.append(json.toString());
    out.append(");");
    out.append("</script>");
    out.append('\n');
}

From source file:org.structr.rest.RestMethodResult.java

public void commitResponse(final Gson gson, final HttpServletResponse response) {

    // set headers
    for (Entry<String, String> header : headers.entrySet()) {
        response.setHeader(header.getKey(), header.getValue());
    }/*from   w  ww.j  a  v a  2  s .c om*/

    // set  response code
    response.setStatus(responseCode);

    try {

        Writer writer = response.getWriter();
        if (content != null) {

            // create result set
            Result result = new Result(this.content, this.content.size(),
                    this.content.size() > 1 || serializeSingleObjectAsCollection, serializeAsPrimitiveArray);

            // serialize result set
            gson.toJson(result, writer);
        }

        if (content == null) {

            writer.append(jsonMessage(responseCode, message));

        }

        // add newline
        writer.append("\n");

        //writer.flush();
        //writer.close();
    } catch (JsonIOException | IOException t) {

        logger.log(Level.WARNING, "Unable to commit HttpServletResponse", t);
    }
}

From source file:com.github.rvesse.airline.help.html.HtmlCommandUsageGenerator.java

/**
 * Outputs a documentation section detailing an allowed value for an option
 * //  w ww .  j a va  2 s .  com
 * @param writer
 *            Writer
 * @param option
 *            Option meta-data
 * @param restriction
 *            Restriction
 * @param hint
 *            Help hint
 * @throws IOException
 */
protected void outputOptionRestriction(Writer writer, OptionMetadata option, OptionRestriction restriction,
        HelpHint hint) throws IOException {
    writer.append("<div class=\"row\">\n");
    writer.append("<div class=\"span8 offset3\">\n");

    // Append preamble if present
    if (!StringUtils.isEmpty(hint.getPreamble())) {
        writer.append(htmlize(hint.getPreamble()));
        writer.append(NEWLINE);
    }

    if (hint.numContentBlocks() > 0) {
        // Append help content
        switch (hint.getFormat()) {
        case EXAMPLES:
            // Treat as code examples
            String[] examples = hint.getContentBlock(0);
            for (int i = 0; i < examples.length; i++) {
                writer.append("<pre>");
                writer.append(examples[i]);
                writer.append("</pre>").append(NEWLINE);

                for (int j = 1; j < hint.numContentBlocks(); j++) {
                    String[] explanations = hint.getContentBlock(j);
                    if (i < explanations.length) {
                        writer.append("<p>").append(NEWLINE);
                        writer.append(htmlize(explanations[i]));
                        writer.append("</p>").append(NEWLINE);
                    }
                }
            }
            break;
        case LIST:
            // Treat as a list
            writer.append("<ul>").append(NEWLINE);
            for (String item : hint.getContentBlock(0)) {
                writer.append("<li>");
                writer.append(htmlize(item));
                writer.append("</li>").append(NEWLINE);
            }
            writer.append("</ul>");
            break;
        case TABLE:
        case TABLE_WITH_HEADERS:
            // Find max rows
            boolean useHeaders = hint.getFormat() == HelpFormat.TABLE_WITH_HEADERS;
            int maxRows = 0;
            for (int col = 0; col < hint.numContentBlocks(); col++) {
                maxRows = Math.max(maxRows, hint.getContentBlock(col).length);
            }
            writer.append("<table>").append(NEWLINE);

            // Output table rows
            for (int row = 0; row < maxRows; row++) {
                writer.append("<tr>").append(NEWLINE);
                for (int col = 0; col < hint.numContentBlocks(); col++) {
                    String[] colData = hint.getContentBlock(col);
                    writer.append(useHeaders ? "<th>" : "<td>");
                    if (row < colData.length) {
                        writer.append(htmlize(colData[row]));
                    }
                    writer.append(useHeaders ? "</th>" : "</td>");
                    writer.append(NEWLINE);
                }
                useHeaders = false;
                writer.append("</tr>").append(NEWLINE);
            }

            writer.append("</table>").append(NEWLINE);
            break;
        default:
            // Treat as paragraphs of text
            for (int i = 0; i < hint.numContentBlocks(); i++) {
                for (String para : hint.getContentBlock(i)) {
                    writer.append("<p>").append(NEWLINE);
                    writer.append(htmlize(para));
                    writer.append("</p>").append(NEWLINE);
                }
            }
            break;
        }
    }

    writer.append("</div>\n");
    writer.append("</div>\n");
}

From source file:org.genedb.web.mvc.controller.SequenceDistributorController.java

@RequestMapping(method = RequestMethod.GET, value = "/{name}/{type}/{destination}")
public void process(HttpServletResponse response, @PathVariable(value = "name") String uniqueName,
        @PathVariable(value = "destination") String destination,
        @PathVariable(value = "type") String sequenceType) throws IOException {

    Writer writer = response.getWriter();
    response.setContentType("text/html");

    Feature feature = sequenceDao.getFeatureByUniqueName(uniqueName, Feature.class);
    if (feature == null) {
        writer.append(String.format("Failed to find feature '%s'", uniqueName));
        //be.reject("no.results");
        //return showForm(request, response, be);
        return; // FIXME
    }/*from  w w  w .  j  a  v a 2  s.co  m*/
    Transcript transcript = modelBuilder.findTranscriptForFeature(feature);

    String sequence = null;
    String sequence2 = null;
    boolean nucleotide = true;
    String program = "wublastn";

    SequenceType st = SequenceType.valueOf(sequenceType);
    switch (st) {
    case GENE_SEQUENCE:
        sequence = transcript.getGene().getResidues();
        sequence2 = getSequence(transcript, GeneSection.TRANSCRIPTIONAL_START, 0, GeneSection.POLY_A, 0, true,
                true);
        compareSequences(sequence, sequence2);
        break;
    case TRANSCRIPT:
        sequence = transcript.getResidues();
        sequence2 = getSequence(transcript, GeneSection.TRANSCRIPTIONAL_START, 0, GeneSection.POLY_A, 0, true,
                false);
        compareSequences(sequence, sequence2);
        break;
    case CDS:
        sequence = transcript.getResidues();
        sequence2 = getSequence(transcript, GeneSection.START_CODON, 0, GeneSection.STOP_CODON, 0, true, false);
        compareSequences(sequence, sequence2);
        break;
    case PROTEIN:
        if (transcript instanceof ProductiveTranscript) {
            Polypeptide pp = ((ProductiveTranscript) transcript).getProtein();
            if (pp != null) {
                sequence = pp.getResidues();
                if (sequence.endsWith("*")) {
                    sequence = sequence.substring(0, sequence.length() - 1);
                }
                nucleotide = false;
            }
        }
        program = "wublastx";
    }

    String unsplitSequence = sequence;

    //   sequence = splitSequenceIntoLines(sequence);

    SequenceDestination sd = SequenceDestination.valueOf(destination);

    switch (sd) {
    case BLAST:

        String uri = String.format("%s/%s", LOCAL_BLAST, "GeneDB_" + transcript.getOrganism().getCommonName());
        Map<String, String> parameters = new Hashtable<String, String>();
        parameters.put("sequence", sequence);
        parameters.put("blast_type", program);

        writer.append(postForm(uri, parameters));
        break;

    //           String returnable = String.format("redirect:%s/%s?sequence=%s&blast_type=%s",
    //                    LOCAL_BLAST,
    //                    "GeneDB_" + transcript.getOrganism().getCommonName(),
    //                    sequence,
    //                    program
    //                );
    //           
    //           

    //           logger.error(returnable);
    //            return returnable;

    case OMNIBLAST:

        String uri2 = String.format("%s/%s", LOCAL_BLAST,
                nucleotide ? "GeneDB_transcripts/omni" : "GeneDB_proteins/omni");
        Map<String, String> parameters2 = new Hashtable<String, String>();
        parameters2.put("sequence", sequence);
        parameters2.put("blast_type", program);

        writer.append(postForm(uri2, parameters2));
        break;

    //            return String.format("redirect:%s/%s?sequence=%s&blast_type=%s",
    //                LOCAL_BLAST,
    //                nucleotide ? "GeneDB_transcripts/omni" : "GeneDB_proteins/omni",
    //                sequence,
    //                program
    //            );

    case NCBI_BLAST:

        String uri3 = "http://blast.ncbi.nlm.nih.gov/Blast.cgi";

        Map<String, String> parameters3 = new Hashtable<String, String>();
        parameters3.put("PAGE_TYPE", "BlastSearch");
        parameters3.put("SHOW_DEFAULTS", "on");
        parameters3.put("LINK_LOC", "blasthome");

        if (nucleotide) {
            parameters3.put("PROGRAM", "blastn");
            parameters3.put("BLAST_PROGRAMS", "megaBlast");
            parameters3.put("DBTYPE", "gc");
            parameters3.put("DATABASE", "nr");
        } else {
            parameters3.put("PROGRAM", "blastp");
            parameters3.put("BLAST_PROGRAMS", "blastp");
        }

        parameters3.put("QUERY", unsplitSequence);

        writer.append(postForm(uri3, parameters3));
        break;

    //            return String.format("redirect:%s&%s&QUERY=%s",
    //                "http://blast.ncbi.nlm.nih.gov/Blast.cgi?PAGE_TYPE=BlastSearch&SHOW_DEFAULTS=on&LINK_LOC=blasthome",
    //                nucleotide ?
    //                    "PROGRAM=blastn&BLAST_PROGRAMS=megaBlast&DBTYPE=gc&DATABASE=nr"
    //                    : "PROGRAM=blastp&BLAST_PROGRAMS=blastp",
    //                sequence
    //            );

    default:
        throw new RuntimeException("Unknown sequence destination");
    }
}

From source file:com.github.rvesse.airline.help.html.HtmlCommandUsageGenerator.java

/**
 * Outputs a documentation section detailing the options
 * /*from  ww w . j  a v a2s .c o  m*/
 * @param writer
 *            Writer
 * @param options
 *            Option meta-data
 * @throws IOException
 */
protected <T> void outputOptions(Writer writer, List<OptionMetadata> options, ArgumentsMetadata arguments,
        ParserMetadata<T> parserConfig) throws IOException {
    writer.append(NEWLINE);
    writer.append("<h1 class=\"text-info\">OPTIONS</h1>\n").append(NEWLINE);

    for (OptionMetadata option : options) {
        // skip hidden options
        if (option.isHidden() && !this.includeHidden()) {
            continue;
        }

        // Option names
        writer.append("<div class=\"row\">\n");
        writer.append("<div class=\"span8 offset1\">\n");
        writer.append(htmlize(toDescription(option)));
        writer.append("</div>\n");
        writer.append("</div>\n");

        // Description
        writer.append("<div class=\"row\">\n");
        writer.append("<div class=\"span8 offset2\">\n");
        writer.append(htmlize(option.getDescription()));
        writer.append("</div>\n");
        writer.append("</div>\n");

        // Allowed values
        for (OptionRestriction restriction : option.getRestrictions()) {
            if (restriction instanceof HelpHint) {
                outputOptionRestriction(writer, option, restriction, (HelpHint) restriction);
            }
        }
    }

    if (arguments != null) {
        // Arguments separator
        writer.append("<div class=\"row\">\n");
        writer.append("<div class=\"span8 offset1\">\n");

        writer.append(parserConfig.getArgumentsSeparator()).append("\n");

        writer.append("</div>\n");
        writer.append("</div>\n");

        // description
        writer.append("<div class=\"row\">\n");
        writer.append("<div class=\"span8 offset2\">\n");

        writer.append("This option can be used to separate command-line options from the "
                + "list of argument, (useful when arguments might be mistaken for command-line options)\n");

        writer.append("</div>\n");
        writer.append("</div>\n");

        // arguments name
        writer.append("<div class=\"row\">\n");
        writer.append("<div class=\"span8 offset1\">\n");

        writer.append(htmlize(toDescription(arguments)));

        writer.append("</div>\n");
        writer.append("</div>\n");

        // description
        writer.append("<div class=\"row\">\n");
        writer.append("<div class=\"span8 offset2\">\n");

        writer.append(htmlize(arguments.getDescription()));

        writer.append("</div>\n");
        writer.append("</div>\n");
    }
}

From source file:org.apache.mahout.utils.SequenceFileDumper.java

@Override
public int run(String[] args) throws Exception {

    addInputOption();//  w w w.ja  va  2s.  co  m
    addOutputOption();
    addOption("substring", "b", "The number of chars to print out per value", false);
    addOption(buildOption("count", "c", "Report the count only", false, false, null));
    addOption("numItems", "n", "Output at most <n> key value pairs", false);
    addOption(
            buildOption("facets", "fa", "Output the counts per key.  Note, if there are a lot of unique keys, "
                    + "this can take up a fair amount of memory", false, false, null));
    addOption(buildOption("quiet", "q", "Print only file contents.", false, false, null));

    if (parseArguments(args, false, true) == null) {
        return -1;
    }

    Path[] pathArr;
    Configuration conf = new Configuration();
    Path input = getInputPath();
    FileSystem fs = input.getFileSystem(conf);
    if (fs.getFileStatus(input).isDir()) {
        pathArr = FileUtil.stat2Paths(fs.listStatus(input, PathFilters.logsCRCFilter()));
    } else {
        pathArr = new Path[1];
        pathArr[0] = input;
    }

    Writer writer;
    boolean shouldClose;
    if (hasOption("output")) {
        shouldClose = true;
        writer = Files.newWriter(new File(getOption("output")), Charsets.UTF_8);
    } else {
        shouldClose = false;
        writer = new OutputStreamWriter(System.out, Charsets.UTF_8);
    }
    try {
        for (Path path : pathArr) {
            if (!hasOption("quiet")) {
                writer.append("Input Path: ").append(String.valueOf(path)).append('\n');
            }

            int sub = Integer.MAX_VALUE;
            if (hasOption("substring")) {
                sub = Integer.parseInt(getOption("substring"));
            }
            boolean countOnly = hasOption("count");
            SequenceFileIterator<?, ?> iterator = new SequenceFileIterator<>(path, true, conf);
            if (!hasOption("quiet")) {
                writer.append("Key class: ").append(iterator.getKeyClass().toString());
                writer.append(" Value Class: ").append(iterator.getValueClass().toString()).append('\n');
            }
            OpenObjectIntHashMap<String> facets = null;
            if (hasOption("facets")) {
                facets = new OpenObjectIntHashMap<>();
            }
            long count = 0;
            if (countOnly) {
                while (iterator.hasNext()) {
                    Pair<?, ?> record = iterator.next();
                    String key = record.getFirst().toString();
                    if (facets != null) {
                        facets.adjustOrPutValue(key, 1, 1); //either insert or add 1
                    }
                    count++;
                }
                writer.append("Count: ").append(String.valueOf(count)).append('\n');
            } else {
                long numItems = Long.MAX_VALUE;
                if (hasOption("numItems")) {
                    numItems = Long.parseLong(getOption("numItems"));
                    if (!hasOption("quiet")) {
                        writer.append("Max Items to dump: ").append(String.valueOf(numItems)).append("\n");
                    }
                }
                while (iterator.hasNext() && count < numItems) {
                    Pair<?, ?> record = iterator.next();
                    String key = record.getFirst().toString();
                    writer.append("Key: ").append(key);
                    String str = record.getSecond().toString();
                    writer.append(": Value: ").append(str.length() > sub ? str.substring(0, sub) : str);
                    writer.write('\n');
                    if (facets != null) {
                        facets.adjustOrPutValue(key, 1, 1); //either insert or add 1
                    }
                    count++;
                }
                if (!hasOption("quiet")) {
                    writer.append("Count: ").append(String.valueOf(count)).append('\n');
                }
            }
            if (facets != null) {
                List<String> keyList = new ArrayList<>(facets.size());

                IntArrayList valueList = new IntArrayList(facets.size());
                facets.pairsSortedByKey(keyList, valueList);
                writer.append("-----Facets---\n");
                writer.append("Key\t\tCount\n");
                int i = 0;
                for (String key : keyList) {
                    writer.append(key).append("\t\t").append(String.valueOf(valueList.get(i++))).append('\n');
                }
            }
        }
        writer.flush();

    } finally {
        if (shouldClose) {
            Closeables.close(writer, false);
        }
    }

    return 0;
}

From source file:com.serphacker.serposcope.db.base.ExportDB.java

public boolean export(Writer writer) throws IOException {
    for (String resource : MigrationDB.DB_SCHEMA_FILES) {
        String sql = new String(ByteStreams.toByteArray(MigrationDB.class.getResourceAsStream(resource)));
        sql = sql.replaceAll("--.*\n", "\n");
        sql = sql.replaceAll("\\s+", " ");
        sql = sql.replaceAll(";\\s*", ";\n");
        writer.append(sql);
        writer.append("\n");
    }/*from  w ww .  jav  a2  s  .  c o  m*/

    writer.append("\nSET FOREIGN_KEY_CHECKS=0;\n");
    try (Connection con = ds.getConnection()) {
        for (String table : TABLES) {
            writer.flush();
            try (Statement stmt = con.createStatement()) {
                LOG.info("exporting table {}", table);
                long _start = System.currentTimeMillis();

                stmt.setQueryTimeout(3600 * 24);
                ResultSet rs = stmt.executeQuery("SELECT * FROM `" + table + "`");
                ResultSetMetaData metaData = rs.getMetaData();
                int columns = metaData.getColumnCount();

                String insertStatement = "INSERT INTO `" + table + "` VALUES ";

                StringBuilder stmtBuilder = new StringBuilder(insertStatement);
                while (rs.next()) {

                    StringBuilder entryBuilder = new StringBuilder("(");
                    for (int colIndex = 1; colIndex <= columns; colIndex++) {
                        Object object = rs.getObject(colIndex);
                        String colName = metaData.getColumnName(colIndex);
                        String colClassName = metaData.getColumnClassName(colIndex);
                        String escaped = escape(object, colClassName, colName);
                        entryBuilder.append(escaped);
                        if (colIndex < columns) {
                            entryBuilder.append(',');
                        }
                    }
                    entryBuilder.append("),");

                    if (stmtBuilder.length() != insertStatement.length()
                            && stmtBuilder.length() + entryBuilder.length() > DEFAULT_MAX_ALLOWED_PACKET) {
                        stmtBuilder.setCharAt(stmtBuilder.length() - 1, ';');
                        writer.append(stmtBuilder).append('\n');
                        stmtBuilder = new StringBuilder(insertStatement);
                    }

                    stmtBuilder.append(entryBuilder);
                }

                if (stmtBuilder.length() != insertStatement.length()) {
                    stmtBuilder.setCharAt(stmtBuilder.length() - 1, ';');
                    writer.append(stmtBuilder).append('\n');
                }

                LOG.info("exported table {} in {}", table,
                        DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - _start));
            }
        }
        writer.append("SET FOREIGN_KEY_CHECKS=1;\n");
    } catch (Exception ex) {
        LOG.error("SQL error", ex);
        return false;
    }

    return true;
}

From source file:org.openqa.selenium.firefox.FirefoxProfile.java

protected void writeNewPrefs(File userPrefs, Map<String, String> prefs) {
    Writer writer = null;
    try {/* ww  w  . j  a  v  a 2 s .c  om*/
        writer = new FileWriter(userPrefs);
        for (Map.Entry<String, String> entry : prefs.entrySet()) {
            writer.append(String.format("user_pref(\"%s\", %s);\n", entry.getKey(), entry.getValue()));
        }
    } catch (IOException e) {
        throw new WebDriverException(e);
    } finally {
        Cleanly.close(writer);
    }
}

From source file:org.sonar.plugins.csharp.gendarme.profiles.GendarmeProfileExporter.java

private void appendRuleParams(Writer writer, List<ActiveRule> assemblyRules) throws IOException {
    for (ActiveRule activeRule : assemblyRules) {
        List<ActiveRuleParam> params = activeRule.getActiveRuleParams();
        for (ActiveRuleParam param : params) {
            String key = activeRule.getConfigKey();
            String ruleName = StringUtils.substringBefore(key, "@");
            String propertyName = param.getRuleParam().getKey();
            String propertyValue = param.getValue();
            writer.append("            <parameter rule=\"");
            writer.append(ruleName);//from  w w w . j  a v  a2  s.c om
            writer.append("\" property=\"");
            writer.append(propertyName);
            writer.append("\" value=\"");
            writer.append(propertyValue);
            writer.append("\" />\n");
        }
    }
}

From source file:org.sablo.IndexPageEnhancer.java

/**
 * Enhance the provided index.html//from   w  w w. j a  v  a  2s.  c  om
 * @param resource url to index.html
 * @param contextPath the path to express in base tag
 * @param cssContributions possible css contributions
 * @param jsContributions possible js contributions
 * @param variableSubstitution replace variables
 * @param writer the writer to write to
 * @throws IOException
 */
public static void enhance(URL resource, String contextPath, Collection<String> cssContributions,
        Collection<String> jsContributions, Map<String, String> variableSubstitution, Writer writer,
        IContributionFilter contributionFilter) throws IOException {
    String index_file = IOUtils.toString(resource);
    String lowercase_index_file = index_file.toLowerCase();
    int headstart = lowercase_index_file.indexOf("<head>");
    int headend = lowercase_index_file.indexOf(COMPONENT_CONTRIBUTIONS);

    //use real html parser here instead?
    if (variableSubstitution != null) {
        for (String variableName : variableSubstitution.keySet()) {
            String variableReplace = VAR_START + variableName + VAR_END;
            index_file = index_file.replaceAll(Matcher.quoteReplacement(variableReplace),
                    variableSubstitution.get(variableName));
        }
    }

    StringBuilder sb = new StringBuilder(index_file);
    if (headend < 0) {
        log.warn("Could not find marker for component contributions: " + COMPONENT_CONTRIBUTIONS
                + " for resource " + resource);
    } else {
        sb.insert(headend + COMPONENT_CONTRIBUTIONS.length(),
                getAllContributions(cssContributions, jsContributions, contributionFilter));
    }
    if (headstart < 0) {
        log.warn("Could not find empty head tag for base tag for resource " + resource);
    } else {
        sb.insert(headstart + 6, getBaseTag(contextPath));
    }
    writer.append(sb);
}