com.google.caja.reporting.Message

Here are the examples of the java api class com.google.caja.reporting.Message taken from open source projects.

1. CajaTestCase#assertMessage()

Project: caja
Source File: CajaTestCase.java
View license
protected void assertMessage(boolean consume, Function<Message, Integer> scorer, String description) {
    Message closest = null;
    int closestScore = Integer.MIN_VALUE;
    for (Message msg : mq.getMessages()) {
        final int score = scorer.apply(msg);
        if (score == Integer.MAX_VALUE) {
            if (consume) {
                mq.getMessages().remove(msg);
            }
            return;
        }
        if (score > closestScore) {
            closest = msg;
            closestScore = score;
        }
    }
    if (closest == null) {
        fail("No message found like " + description);
    } else {
        fail("Failed to find message.  Closest match was " + closest.format(mc) + " with parts " + closest.getMessageParts());
    }
}

2. CajaTestCase#render()

Project: caja
Source File: CajaTestCase.java
View license
public static String render(MessageQueue mq) {
    StringBuilder sb = new StringBuilder();
    for (Message m : mq.getMessages()) {
        try {
            m.format(new MessageContext(), sb);
        } catch (IOException e) {
            sb.append(e.toString());
        }
        sb.append("\n");
    }
    return sb.toString();
}

3. LinterTest#runLinterTest()

Project: caja
Source File: LinterTest.java
View license
private void runLinterTest(List<Linter.LintJob> inputs, String... messages) {
    MessageQueue mq = new SimpleMessageQueue();
    Linter.lint(inputs, new Linter.Environment(Sets.<String>newHashSet()), mq);
    List<String> actualMessageStrs = Lists.newArrayList();
    for (Message msg : mq.getMessages()) {
        actualMessageStrs.add(msg.getMessageLevel().name() + ": " + msg.format(mc));
    }
    List<String> goldenMessageStrs = Lists.newArrayList(messages);
    Collections.sort(actualMessageStrs);
    Collections.sort(goldenMessageStrs);
    MoreAsserts.assertListsEqual(goldenMessageStrs, actualMessageStrs);
}

4. ParserTest#assertNextMessage()

Project: caja
Source File: ParserTest.java
View license
private void assertNextMessage(Iterator<Message> msgs, MessageType type, String filePositionString, Object... otherMessageParts) throws Exception {
    assertTrue(msgs.hasNext());
    Message m = msgs.next();
    assertEquals(type, m.getMessageType());
    assertFilePosition(filePositionString, (FilePosition) m.getMessageParts().get(0), mc);
    for (int i = 0; i < otherMessageParts.length; i++) {
        assertEquals(otherMessageParts[i], m.getMessageParts().get(i + 1));
    }
}

5. ParserTest#assertParseFails()

Project: caja
Source File: ParserTest.java
View license
private void assertParseFails(String code) {
    mq.getMessages().clear();
    try {
        js(fromString(code));
    } catch (ParseException e) {
        e.toMessageQueue(mq);
    }
    for (Message msg : mq.getMessages()) {
        if (msg.getMessageLevel().compareTo(MessageLevel.ERROR) >= 0) {
            return;
        }
    }
    log("assertParseFails", code);
    fail("expected failure");
}

6. ErrorReporterTest#testMessageSorting()

Project: caja
Source File: ErrorReporterTest.java
View license
public final void testMessageSorting() {
    InputSource a = new InputSource(URI.create("test:///a"));
    InputSource b = new InputSource(URI.create("test:///b"));
    InputSource c = new InputSource(URI.create("test:///c"));
    FilePosition a1 = FilePosition.instance(a, 1, 10, 10);
    FilePosition a2 = FilePosition.instance(a, 2, 20, 10);
    FilePosition a12 = FilePosition.span(a1, a2);
    FilePosition b2 = FilePosition.instance(b, 2, 20, 10);
    FilePosition c1 = FilePosition.instance(c, 1, 10, 10);
    FilePosition c2 = FilePosition.instance(c, 2, 20, 10);
    FilePosition c12 = FilePosition.span(c1, c2);
    Message ma12 = new Message(TestMessageType.MT, a12);
    Message mc2 = new Message(TestMessageType.MT, c2);
    Message mc12 = new Message(TestMessageType.MT, c12);
    Message mb2 = new Message(TestMessageType.MT, b2);
    Message ma = new Message(TestMessageType.MT, a);
    Message mb = new Message(TestMessageType.MT, b);
    Message mc1 = new Message(TestMessageType.MT, c1);
    Message ma1 = new Message(TestMessageType.MT, a1);
    Message ma2 = new Message(TestMessageType.MT, a2);
    Message mhi = new Message(TestMessageType.MT, MessagePart.Factory.valueOf("hi"));
    Message mhithere = new Message(TestMessageType.MT, MessagePart.Factory.valueOf("hi there"));
    List<Message> messages = Arrays.asList(ma12, mhithere, mc2, mc12, mb2, ma, mb, mc1, ma1, ma2, mhi);
    MoreAsserts.assertListsEqual(Arrays.asList(ma, ma1, ma12, ma2, mb, mb2, mc1, mc12, mc2, mhi, mhithere), ErrorReporter.sortMessages(messages));
}

7. DomParserTest#assertParsedMarkup()

Project: caja
Source File: DomParserTest.java
View license
private void assertParsedMarkup(List<String> htmlInput, List<String> expectedParseTree, List<String> expectedMessages, List<String> expectedOutputHtml, Boolean asXml, boolean fragment, boolean wantsComments) throws ParseException {
    System.err.println("\n\nStarting " + getName() + "\n===================");
    mq.getMessages().clear();
    DomParser p;
    if (asXml != null) {
        // specified
        TokenQueue<HtmlTokenType> tq = tokenizeTestInput(Join.join("\n", htmlInput), asXml, wantsComments);
        p = new DomParser(tq, asXml, mq);
    } else {
        HtmlLexer lexer = new HtmlLexer(fromString(Join.join("\n", htmlInput)));
        p = new DomParser(lexer, wantsComments, is, mq);
        asXml = lexer.getTreatedAsXml();
    }
    Node tree = fragment ? p.parseFragment() : p.parseDocument();
    List<String> actualParseTree = formatLines(tree);
    MoreAsserts.assertListsEqual(expectedParseTree, actualParseTree);
    List<String> actualMessages = Lists.newArrayList();
    for (Message message : mq.getMessages()) {
        String messageText = (message.getMessageLevel().name() + " " + message.format(mc));
        actualMessages.add(messageText);
    }
    MoreAsserts.assertListsEqual(expectedMessages, actualMessages, 0);
    MarkupRenderMode rm = asXml ? MarkupRenderMode.XML : MarkupRenderMode.HTML;
    MoreAsserts.assertListsEqual(expectedOutputHtml, Arrays.asList(Nodes.render(tree, rm).split("\n")));
    Node clone = tree.cloneNode(true);
    MoreAsserts.assertListsEqual(expectedOutputHtml, Arrays.asList(Nodes.render(clone, rm).split("\n")));
    // Make sure that parsing with and without debug data return the same tree
    // structure.
    Node treeWithoutDebugData;
    {
        TokenQueue<HtmlTokenType> tq = tokenizeTestInput(Join.join("\n", htmlInput), asXml, wantsComments);
        DomParser noDebugParser = new DomParser(tq, p.asXml(), DevNullMessageQueue.singleton());
        treeWithoutDebugData = fragment ? noDebugParser.parseFragment() : noDebugParser.parseDocument();
    }
    assertEquals("Comparing parse with and without debug data", formatToString(tree, false), formatToString(treeWithoutDebugData, false));
}

8. TestUtil#maxMessageLevel()

Project: caja
Source File: TestUtil.java
View license
public static MessageLevel maxMessageLevel(MessageQueue mq) {
    MessageLevel max = MessageLevel.values()[0];
    for (Message msg : mq.getMessages()) {
        MessageLevel lvl = msg.getMessageLevel();
        if (max.compareTo(lvl) < 0) {
            max = lvl;
        }
    }
    return max;
}

9. CajaTestCase#assertNoMessage()

Project: caja
Source File: CajaTestCase.java
View license
protected void assertNoMessage(MessageTypeInt type) {
    for (Message msg : mq.getMessages()) {
        if (msg.getMessageType() == type) {
            fail(msg.format(mc));
        }
    }
}

10. CajaTestCase#assertMessagesLessSevereThan()

Project: caja
Source File: CajaTestCase.java
View license
protected void assertMessagesLessSevereThan(MessageLevel level) {
    for (Message msg : mq.getMessages()) {
        if (level.compareTo(msg.getMessageLevel()) <= 0) {
            fail(msg.format(mc));
        }
    }
}

11. ParserTest#runParseTest()

Project: caja
Source File: ParserTest.java
View license
private void runParseTest(String testFile, String goldenFile, String... errors) throws Exception {
    Statement parseTree = js(fromResource(testFile));
    assertCloneable(parseTree);
    checkFilePositionInvariants(parseTree);
    StringBuilder output = new StringBuilder();
    parseTree.format(mc, output);
    output.append('\n');
    // Check that parse tree matches.
    String golden = TestUtil.readResource(getClass(), goldenFile);
    assertEquals(golden, output.toString());
    // Clone the parse tree, and check that it, too, matches
    Statement cloneParseTree = (Statement) parseTree.clone();
    StringBuilder cloneOutput = new StringBuilder();
    cloneParseTree.format(mc, cloneOutput);
    cloneOutput.append('\n');
    assertEquals(golden, cloneOutput.toString());
    List<String> actualErrors = new ArrayList<String>();
    for (Message m : mq.getMessages()) {
        if (MessageLevel.ERROR.compareTo(m.getMessageLevel()) <= 0) {
            String error = m.toString();
            actualErrors.add(error.substring(error.indexOf(": ") + 2));
        }
    }
    List<String> expectedErrors = Arrays.asList(errors);
    MoreAsserts.assertListsEqual(expectedErrors, actualErrors);
}

12. ErrorReporter#reportErrors()

Project: caja
Source File: ErrorReporter.java
View license
/** Dumps error messages to the output stream. */
static MessageLevel reportErrors(Map<InputSource, CharSequence> inputs, MessageContext mc, MessageQueue mq, Appendable out) throws IOException {
    MessageLevel max = MessageLevel.values()[0];
    SnippetProducer sp = new SnippetProducer(inputs, mc);
    // HACK: do not commit
    Map<MessageTypeInt, Integer> counts = Maps.newHashMap();
    for (Message msg : sortMessages(mq.getMessages())) {
        counts.put(msg.getMessageType(), Integer.valueOf(counts.containsKey(msg.getMessageType()) ? counts.get(msg.getMessageType()) + 1 : 1));
        MessageLevel level = msg.getMessageLevel();
        if (level.compareTo(max) > 0) {
            max = level;
        }
        String snippet = sp.getSnippet(msg);
        out.append(level.name() + " : " + msg.format(mc) + ("".equals(snippet) ? "" : "\n" + snippet) + "\n");
    }
    List<Map.Entry<MessageTypeInt, Integer>> countsInOrder = Lists.newArrayList(counts.entrySet());
    Collections.sort(countsInOrder, new Comparator<Map.Entry<MessageTypeInt, Integer>>() {

        public int compare(Map.Entry<MessageTypeInt, Integer> a, Map.Entry<MessageTypeInt, Integer> b) {
            int delta = a.getValue() - b.getValue();
            if (delta != 0) {
                return delta;
            }
            return a.getKey().name().compareTo(b.getKey().name());
        }
    });
    for (Map.Entry<MessageTypeInt, Integer> e : countsInOrder) {
        out.append(String.format("%3d %s\n", e.getValue(), e.getKey().name()));
    }
    return max;
}

13. ConfigUtilTest#assertMessages()

Project: caja
Source File: ConfigUtilTest.java
View license
private void assertMessages(String... golden) {
    List<String> actual = new ArrayList<String>();
    for (Message msg : mq.getMessages()) {
        // Simple JSON doesn't preserve key ordering.
        String msgText = msg.format(mc).replaceAll(JSON_FLAT_OBJECT, "{@}");
        actual.add(msg.getMessageLevel() + ": " + msgText);
    }
    MoreAsserts.assertListsEqual(Arrays.asList(golden), actual);
}

14. ProxyServlet#renderAsJSON()

Project: caja
Source File: ProxyServlet.java
View license
private static void renderAsJSON(String staticHtml, String javascript, String jsonpCallback, MessageQueue mq, Writer output, boolean pretty) throws IOException {
    if (jsonpCallback != null && !checkIdentifier(jsonpCallback)) {
        throw new RuntimeException("Detected XSS attempt; aborting request");
    }
    JSONObject o = new JSONObject();
    JSONArray messages = new JSONArray();
    if (staticHtml != null) {
        Json.put(o, "html", staticHtml);
    }
    if (javascript != null) {
        Json.put(o, "js", javascript);
    }
    Json.put(o, "messages", messages);
    for (Message m : mq.getMessages()) {
        JSONObject msg = new JSONObject();
        Json.put(msg, "level", m.getMessageLevel().ordinal());
        Json.put(msg, "name", m.getMessageLevel().name());
        Json.put(msg, "type", m.getMessageType().name());
        Json.put(msg, "message", m.toString());
        Json.push(messages, msg);
    }
    String rendered = o.toJSONString();
    output.append((jsonpCallback != null) ? "/**/" + jsonpCallback + "(" + rendered + ");" : rendered);
    output.flush();
}

15. ProxyServlet#serializeMessageQueue()

Project: caja
Source File: ProxyServlet.java
View license
// TODO(jasvir): The service like the gwt version should accumulate
// input sources and use html snippet producer to produce messages
private static String serializeMessageQueue(MessageQueue mq) {
    StringBuilder sb = new StringBuilder();
    MessageContext mc = new MessageContext();
    for (Message m : mq.getMessages()) {
        sb.append(m.getMessageLevel().name()).append(": ");
        Escaping.escapeXml(m.format(mc), false, sb);
        sb.append("\n");
    }
    return sb.toString();
}

16. BuildServiceImplementation#hasErrors()

View license
private static boolean hasErrors(MessageQueue mq) {
    for (Message msg : mq.getMessages()) {
        if (MessageLevel.ERROR.compareTo(msg.getMessageLevel()) <= 0) {
            return true;
        }
    }
    return false;
}

17. Minify#minify()

Project: caja
Source File: Minify.java
View license
public static boolean minify(Iterable<Pair<InputSource, File>> inputs, Writer out, PrintWriter err) throws IOException {
    MessageContext mc = new MessageContext();
    for (Pair<InputSource, File> input : inputs) {
        mc.addInputSource(input.a);
    }
    final MessageQueue errs = new EchoingMessageQueue(err, mc, false);
    RenderContext rc = new RenderContext(new JsMinimalPrinter(new Concatenator(out, new Callback<IOException>() {

        public void handle(IOException ex) {
            errs.addMessage(MessageType.IO_ERROR, MessagePart.Factory.valueOf(ex.getMessage()));
        }
    })));
    for (Pair<InputSource, File> input : inputs) {
        CharProducer cp = CharProducer.Factory.fromFile(input.b, Charsets.UTF_8.name());
        JsLexer lexer = new JsLexer(cp);
        JsTokenQueue tq = new JsTokenQueue(lexer, input.a);
        Parser p = new Parser(tq, errs);
        try {
            while (!tq.isEmpty()) {
                Block b = p.parse();
                for (Statement topLevelStmt : b.children()) {
                    topLevelStmt.render(rc);
                    if (!topLevelStmt.isTerminal()) {
                        rc.getOut().consume(";");
                    }
                }
            }
        } catch (ParseException ex) {
            ex.toMessageQueue(errs);
        }
    }
    rc.getOut().noMoreTokens();
    out.flush();
    MessageLevel maxMessageLevel = MessageLevel.values()[0];
    for (Message msg : errs.getMessages()) {
        if (msg.getMessageLevel().compareTo(maxMessageLevel) >= 0) {
            maxMessageLevel = msg.getMessageLevel();
        }
    }
    return maxMessageLevel.compareTo(MessageLevel.ERROR) < 0;
}

18. JsOptimizer#main()

Project: caja
Source File: JsOptimizer.java
View license
public static void main(String... args) throws IOException {
    MessageQueue mq = new SimpleMessageQueue();
    MessageContext mc = new MessageContext();
    JsOptimizer opt = new JsOptimizer(mq);
    opt.setRename(true);
    opt.setEnvJson(new ObjectConstructor(FilePosition.UNKNOWN));
    try {
        for (int i = 0, n = args.length; i < n; ++i) {
            String arg = args[i];
            if ("--norename".equals(arg)) {
                opt.setRename(false);
            } else if (arg.startsWith("--envjson=")) {
                String jsonfile = arg.substring(arg.indexOf('=') + 1);
                CharProducer json = CharProducer.Factory.fromFile(new File(jsonfile), "UTF-8");
                opt.setEnvJson((ObjectConstructor) jsExpr(json, mq));
            } else {
                if ("--".equals(arg)) {
                    ++i;
                }
                for (; i < n; ++i) {
                    CharProducer cp = CharProducer.Factory.fromFile(new File(args[i]), "UTF-8");
                    mc.addInputSource(cp.getCurrentPosition().source());
                    opt.addInput(js(cp, mq));
                }
            }
        }
    } catch (ParseException ex) {
        ex.toMessageQueue(mq);
    }
    Statement out = opt.optimize();
    for (Message msg : mq.getMessages()) {
        msg.format(mc, System.err);
        System.err.println();
    }
    JsMinimalPrinter printer = new JsMinimalPrinter(new Concatenator(System.out, null));
    RenderContext rc = new RenderContext(printer).withPropertyNameQuotingMode(PropertyNameQuotingMode.NO_QUOTES);
    if (out instanceof Block) {
        ((Block) out).renderBody(rc);
    } else {
        out.render(rc);
    }
    printer.noMoreTokens();
}