Example usage for java.io StringWriter append

List of usage examples for java.io StringWriter append

Introduction

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

Prototype

public StringWriter append(char c) 

Source Link

Document

Appends the specified character to this writer.

Usage

From source file:Main.java

public static String getSetMethod(Class<?> c, String prefix, String postfix) {
    StringWriter sw = new StringWriter();
    if (prefix == null)
        prefix = "";
    if (postfix == null)
        postfix = "";
    Method[] ms = c.getDeclaredMethods();
    if (ms != null && ms.length > 0) {
        for (Method m : ms) {
            String name = m.getName();
            if (name.startsWith("set") && isPublicNoStatic(m.getModifiers())) {
                sw.append(prefix).append(name).append("(").append(postfix).append(");\r\n");
            }//w ww  .j a v a2s .co m
        }
    }
    return sw.toString();
}

From source file:com.cloudbees.jenkins.support.impl.RootCAs.java

public static void getRootCAList(StringWriter writer) {
    KeyStore instance = null;//from   www . j  a  va 2s  .c  o  m
    try {
        instance = KeyStore.getInstance(KeyStore.getDefaultType());
        Enumeration<String> aliases = instance.aliases();
        while (aliases.hasMoreElements()) {
            String s = aliases.nextElement();
            writer.append("========");
            writer.append("Alias: " + s);
            writer.append(instance.getCertificate(s).getPublicKey().toString());
            writer.append("Trusted certificate: " + instance.isCertificateEntry(s));
        }
    } catch (KeyStoreException e) {
        writer.write(Functions.printThrowable(e));
    }
}

From source file:com.espertech.esper.epl.parse.ExceptionConvertor.java

/**
 * Converts from a syntax error to a nice exception.
 * @param e is the syntax error/*from ww  w  .  j a  v  a2  s  .c o m*/
 * @param expression is the expression text
 * @param parser the parser that parsed the expression
 * @param addPleaseCheck indicates to add "please check" paraphrases
 * @return syntax exception
 */
public static UniformPair<String> convert(RecognitionException e, String expression, boolean addPleaseCheck,
        EsperEPL2GrammarParser parser) {
    if (expression.trim().length() == 0) {
        String message = "Unexpected " + END_OF_INPUT_TEXT;
        return new UniformPair<String>(message, expression);
    }

    Token t;
    Token tBeforeBefore = null;
    Token tBefore = null;
    Token tAfter = null;

    int tIndex = e.getOffendingToken() != null ? e.getOffendingToken().getTokenIndex() : Integer.MAX_VALUE;
    if (tIndex < parser.getTokenStream().size()) {
        t = parser.getTokenStream().get(tIndex);
        if ((tIndex + 1) < parser.getTokenStream().size()) {
            tAfter = parser.getTokenStream().get(tIndex + 1);
        }
        if (tIndex - 1 >= 0) {
            tBefore = parser.getTokenStream().get(tIndex - 1);
        }
        if (tIndex - 2 >= 0) {
            tBeforeBefore = parser.getTokenStream().get(tIndex - 2);
        }
    } else {
        if (parser.getTokenStream().size() >= 1) {
            tBeforeBefore = parser.getTokenStream().get(parser.getTokenStream().size() - 1);
        }
        if (parser.getTokenStream().size() >= 2) {
            tBefore = parser.getTokenStream().get(parser.getTokenStream().size() - 2);
        }
        t = parser.getTokenStream().get(parser.getTokenStream().size() - 1);
    }

    Token tEnd = null;
    if (parser.getTokenStream().size() > 0) {
        tEnd = parser.getTokenStream().get(parser.getTokenStream().size() - 1);
    }

    String positionInfo = getPositionInfo(t);
    String token = t.getType() == EsperEPL2GrammarParser.EOF ? "end-of-input" : "'" + t.getText() + "'";

    Stack stack = parser.getParaphrases();
    String check = "";
    boolean isSelect = stack.size() == 1 && stack.get(0).equals("select clause");
    if ((stack.size() > 0) && addPleaseCheck) {
        String delimiter = "";
        StringBuilder checkList = new StringBuilder();
        checkList.append(", please check the ");
        while (stack.size() != 0) {
            checkList.append(delimiter);
            checkList.append(stack.pop());
            delimiter = " within the ";
        }
        check = checkList.toString();
    }

    // check if token is a reserved keyword
    Set<String> keywords = parser.getKeywords();
    boolean reservedKeyword = false;
    if (keywords.contains(token.toLowerCase())) {
        token += " (a reserved keyword)";
        reservedKeyword = true;
    } else if (tAfter != null && keywords.contains("'" + tAfter.getText().toLowerCase() + "'")) {
        token += " ('" + tAfter.getText() + "' is a reserved keyword)";
        reservedKeyword = true;
    } else {
        if ((tBefore != null) && (tAfter != null)
                && (keywords.contains("'" + tBefore.getText().toLowerCase() + "'"))
                && (keywords.contains("'" + tAfter.getText().toLowerCase() + "'"))) {
            token += " ('" + tBefore.getText() + "' and '" + tAfter.getText() + "' are a reserved keyword)";
            reservedKeyword = true;
        } else if ((tBefore != null) && (keywords.contains("'" + tBefore.getText().toLowerCase() + "'"))) {
            token += " ('" + tBefore.getText() + "' is a reserved keyword)";
            reservedKeyword = true;
        } else if (tEnd != null && keywords.contains("'" + tEnd.getText().toLowerCase() + "'")) {
            token += " ('" + tEnd.getText() + "' is a reserved keyword)";
            reservedKeyword = true;
        }
    }

    // special handling for the select-clause "as" keyword, which is required
    if (isSelect && !reservedKeyword) {
        check += getSelectClauseAsText(tBeforeBefore, t);
    }

    String message = "Incorrect syntax near " + token + positionInfo + check;
    if (e instanceof NoViableAltException || e instanceof LexerNoViableAltException
            || checkForInputMismatchWithNoExpected(e)) {
        Token nvaeToken = e.getOffendingToken();
        int nvaeTokenType = nvaeToken != null ? nvaeToken.getType() : EsperEPL2GrammarLexer.EOF;

        if (nvaeTokenType == EsperEPL2GrammarLexer.EOF) {
            if (token.equals(END_OF_INPUT_TEXT)) {
                message = "Unexpected " + END_OF_INPUT_TEXT + positionInfo + check;
            } else {
                if (ParseHelper.hasControlCharacters(expression)) {
                    message = "Unrecognized control characters found in text" + positionInfo;
                } else {
                    message = "Unexpected " + END_OF_INPUT_TEXT + " near " + token + positionInfo + check;
                }
            }
        } else {
            if (parser.getParserTokenParaphrases().get(nvaeTokenType) != null) {
                message = "Incorrect syntax near " + token + positionInfo + check;
            } else {
                // find next keyword in the next 3 tokens
                int currentIndex = tIndex + 1;
                while ((currentIndex > 0) && (currentIndex < parser.getTokenStream().size() - 1)
                        && (currentIndex < tIndex + 3)) {
                    Token next = parser.getTokenStream().get(currentIndex);
                    currentIndex++;

                    String quotedToken = "'" + next.getText() + "'";
                    if (parser.getKeywords().contains(quotedToken)) {
                        check += " near reserved keyword '" + next.getText() + "'";
                        break;
                    }
                }
                message = "Incorrect syntax near " + token + positionInfo + check;
            }
        }
    } else if (e instanceof InputMismatchException) {
        InputMismatchException mismatched = (InputMismatchException) e;

        String expected;
        if (mismatched.getExpectedTokens().size() > 1) {
            StringWriter writer = new StringWriter();
            writer.append("any of the following tokens {");
            String delimiter = "";
            for (int i = 0; i < mismatched.getExpectedTokens().size(); i++) {
                writer.append(delimiter);
                if (i > 5) {
                    writer.append("...");
                    writer.append(Integer.toString(mismatched.getExpectedTokens().size() - 5));
                    writer.append(" more");
                    break;
                }
                delimiter = ", ";
                writer.append(getTokenText(parser, mismatched.getExpectedTokens().get(i)));
            }
            writer.append("}");
            expected = writer.toString();
        } else {
            expected = getTokenText(parser, mismatched.getExpectedTokens().get(0));
        }

        int offendingTokenType = mismatched.getOffendingToken().getType();
        String unexpected = getTokenText(parser, offendingTokenType);

        String expecting = " expecting " + expected.trim() + " but found " + unexpected.trim();
        message = "Incorrect syntax near " + token + expecting + positionInfo + check;
    }

    return new UniformPair<String>(message, expression);
}

From source file:io.fabric8.tooling.archetype.generator.ArchetypeTest.java

@AfterClass
public static void afterAll() throws Exception {
    // now let invoke the projects
    final int[] resultPointer = new int[1];
    StringWriter sw = new StringWriter();
    Set<String> modules = new HashSet<String>();
    for (final String outDir : outDirs) {
        String module = new File(outDir).getName();
        if (modules.add(module)) {
            sw.append(String.format("        <module>%s</module>\n", module));
        }//from w w  w .  j  a v  a 2  s  . c o  m
    }
    sw.close();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOUtils.copy(ArchetypeTest.class.getResourceAsStream("/archetypes-test-pom.xml"), baos);
    String pom = new String(baos.toByteArray()).replace("        <!-- to be replaced -->", sw.toString());
    FileWriter modulePom = new FileWriter("target/archetypes-test-pom.xml");
    IOUtils.copy(new StringReader(pom), modulePom);
    modulePom.close();

    final String outDir = new File("target").getCanonicalPath();
    // thread locals are evil (I'm talking to you - org.codehaus.plexus.DefaultPlexusContainer#lookupRealm!)
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("Invoking projects in " + outDir);
            MavenCli maven = new MavenCli();
            resultPointer[0] = maven.doMain(
                    new String[] { "clean", "package", "-f", "archetypes-test-pom.xml" }, outDir, System.out,
                    System.out);
            System.out.println("result: " + resultPointer[0]);
        }
    });
    t.start();
    t.join();

    assertEquals("Build of project " + outDir + " failed. Result = " + resultPointer[0], 0, resultPointer[0]);
}

From source file:org.qipki.site.plugin.WebsiteMojo.java

public static String extractRange(String source, int firstline, int lastline) {
    String[] lines = source.split("\n");
    int idx = firstline - 1;
    StringWriter sw = new StringWriter();
    while (idx < lines.length && idx < lastline) {
        sw.append(lines[idx]).append("\n");
        idx++;//w w  w . j  av a2  s.  com
    }
    return sw.toString();
}

From source file:com.espertech.esper.epl.parse.ASTUtil.java

private static String unescapeEscapableStr(List<EsperEPL2GrammarParser.EscapableStrContext> ctxs,
        String delimiterConst) {//from   w ww. j av  a 2  s.c  om
    if (ctxs.size() == 1) {
        return unescapeBacktick(unescapeDot(ctxs.get(0).getText()));
    }

    StringWriter writer = new StringWriter();
    String delimiter = "";
    for (EsperEPL2GrammarParser.EscapableStrContext ctx : ctxs) {
        writer.append(delimiter);
        writer.append(unescapeBacktick(unescapeDot(ctx.getText())));
        delimiter = delimiterConst;
    }

    return writer.toString();
}

From source file:org.commonjava.indy.bind.jaxrs.util.ResponseUtils.java

public static CharSequence formatEntity(final String id, final Throwable error, final String message) {
    final StringWriter sw = new StringWriter();
    sw.append("Id: ").append(id).append("\n");
    if (message != null) {
        sw.append("Message: ").append(message).append("\n");
    }/* ww  w  . j  a v  a 2 s  . com*/

    if (error != null) {
        sw.append(error.getMessage());

        final Throwable cause = error.getCause();
        if (cause != null) {
            sw.append("Error:\n\n");
            cause.printStackTrace(new PrintWriter(sw));
        }

        sw.write('\n');
    }

    return sw.toString();
}

From source file:dk.statsbiblioteket.util.Logs.java

protected static void expand(StringWriter writer, Set set, int maxLength, int maxDepth) {
    writer.append(Integer.toString(set.size()));
    if (maxDepth == 0) {
        writer.append("(...)");
        return;//  ww w  . j  av  a2 s  .  c  o  m
    }
    int num = set.size() <= maxLength + 1 ? set.size() : Math.max(1, maxLength);
    writer.append("(");
    int counter = 0;
    for (Object object : set) {
        expand(writer, object, maxLength, maxDepth - 1);
        if (counter++ < num - 1) {
            writer.append(", ");
        } else {
            break;
        }
    }
    if (num < set.size()) {
        writer.append(", ...");
    }
    writer.append(")");
}

From source file:com.espertech.esper.epl.parse.ParseHelper.java

private static ScriptResult rewriteTokensScript(TokenRewriteStream tokens) {
    List<String> scripts = new ArrayList<String>();

    for (int i = 0; i < tokens.size(); i++) {
        if (tokens.get(i).getType() == EsperEPL2Ast.EXPRESSIONDECL) {
            Token tokenBefore = getTokenBefore(i, tokens);
            boolean isCreateExpressionClause = tokenBefore != null
                    && tokenBefore.getType() == EsperEPL2Ast.CREATE;
            Pair<String, Integer> nameAndNameStart = findScriptName(i + 1, tokens);

            int startIndex = findStartTokenScript(nameAndNameStart.getSecond(), tokens, EsperEPL2Ast.LBRACK);
            if (startIndex != -1) {
                int endIndex = findEndTokenScript(startIndex + 1, tokens, EsperEPL2Ast.RBRACK,
                        EsperEPL2GrammarParser.getAfterScriptTokens(), !isCreateExpressionClause);
                if (endIndex != -1) {

                    StringWriter writer = new StringWriter();
                    for (int j = startIndex + 1; j < endIndex; j++) {
                        writer.append(tokens.get(j).getText());
                    }//ww  w .ja v a2s. c o  m
                    scripts.add(writer.toString());

                    rewriteScript(startIndex, endIndex, tokens);
                }
            }
        }
    }

    String rewrittenEPL = tokens.toString();
    return new ScriptResult(rewrittenEPL, scripts);
}

From source file:dk.statsbiblioteket.util.Logs.java

protected static void expand(StringWriter writer, Map map, int maxLength, int maxDepth) {
    writer.append(Integer.toString(map.size()));
    if (maxDepth == 0) {
        writer.append("(...)");
        return;/*from  ww w .  ja v a  2s.c o  m*/
    }
    int num = map.size() <= maxLength + 1 ? map.size() : Math.max(1, maxLength);
    writer.append("(");
    int counter = 0;
    for (Object oEntry : map.entrySet()) {
        Map.Entry entry = (Map.Entry) oEntry;
        writer.append("{");
        expand(writer, entry.getKey(), maxLength, maxDepth - 1);
        writer.append(", ");
        expand(writer, entry.getValue(), maxLength, maxDepth - 1);
        writer.append("}");
        if (counter++ < num - 1) {
            writer.append(", ");
        } else {
            break;
        }
    }
    if (num < map.size()) {
        writer.append(", ...");
    }
    writer.append(")");
}