Package com.google.caja.reporting

Examples of com.google.caja.reporting.MessageQueue


    Block program = (Block) QuasiBuilder.substV(
        "{ (function (@formals*) { @f; }); }",
        "formals", new ParseTreeNodeContainer(
            Lists.newArrayList(rewrittenNames.values())),
        "f", new ExpressionStmt(f));
    MessageQueue sanityCheckMq = DevNullMessageQueue.singleton();
    Set<String> freeIdents = Sets.newLinkedHashSet();
    Scope programScope = Scope.fromProgram(
        program,
        new Rewriter(sanityCheckMq, false, false));
    checkScope(program, programScope, freeIdents);

    if (!freeIdents.isEmpty()) {
      List<MessagePart> freeVarParts = Lists.newArrayList();
      for (String freeIdent : freeIdents) {
        freeVarParts.add(MessagePart.Factory.valueOf(freeIdent));
      }
      mq.addMessage(
          RewriterMessageType.ALPHA_RENAMING_FAILURE, e.getFilePosition(),
          MessagePart.Factory.valueOf(freeVarParts));
      mq.getMessages().addAll(sanityCheckMq.getMessages());
      // Substitute a safe value.  Errors have already been reported on mq.
      return new NullLiteral(e.getFilePosition());
    }
    return f;
  }
View Full Code Here


    // URL path parameters can trick IE into misinterpreting responses as HTML
    if (req.getRequestURI().contains(";")) {
      throw new ServletException("Invalid URL path parameter");
    }

    MessageQueue mq = new SimpleMessageQueue();
    FetchedData result = service.handle(inputFetchedData, args, mq);
    if (result == null) {
      closeBadRequest(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, mq);
      return;
    }
View Full Code Here

    this.mgr = mgr;
    this.baseUri = baseUri;
  }

  public ParseTreeNode sanitize(ParseTreeNode input) {
    MessageQueue mq = mgr.getMessageQueue();
    ParseTreeNode result = null;
    if (input instanceof UncajoledModule) {
      Block body = ((UncajoledModule) input).getModuleBody();
      if (body.children().size() == 2
          && body.children().get(0) instanceof DirectivePrologue
          && ((DirectivePrologue) body.children().get(0))
              .hasDirective("use strict")
          && body.children().get(1) instanceof TranslatedCode) {
        result = input;
      }
    }
    result = newES53Rewriter(mgr).expand(input);
    if (mq.hasMessageAtLevel(MessageLevel.ERROR)) {
      return null;
    }

    result = new IllegalReferenceCheckRewriter(mq, false).expand(result);
    if (mq.hasMessageAtLevel(MessageLevel.ERROR)) {
      return null;
    }

    result.visitPreOrder(new NonAsciiCheckVisitor(mq));
    if (mq.hasMessageAtLevel(MessageLevel.ERROR)) {
      return null;
    }

    return result;
  }
View Full Code Here

    // being cajoled at once since this can be mis-used for modularity
    // and we set up expectations on the part of our users to
    // maintain this behavior, regardless of whatever complexity that
    // might entail.

    MessageQueue mq = jobs.getMessageQueue();

    TemplateSanitizer ts = new TemplateSanitizer(htmlSchema, mq);
    for (IhtmlRoot ihtmlRoot : html) {
      ts.sanitize(ihtmlRoot.root);
    }
View Full Code Here

    return elapsed.doubleValue();
  }

  private double runCajoledES53(String filename) throws Exception {
    PluginMeta meta = new PluginMeta();
    MessageQueue mq = new SimpleMessageQueue();
    PluginCompiler pc = new PluginCompiler(new TestBuildInfo(), meta, mq);
    CharProducer src = fromString(plain(fromResource(filename)));
    pc.addInput(js(src), is.getUri());

    if (!pc.run()) {
View Full Code Here

  }

  public CajoledModule es53(Block plain) {
    CajoledModule result = null;
    PluginMeta meta = new PluginMeta();
    MessageQueue mq = TestUtil.createTestMessageQueue(this.mc);
    PluginCompiler pc = new PluginCompiler(
        TestBuildInfo.getInstance(), meta, mq);
    pc.addInput(plain, null);
    if (pc.run()) {
      result = pc.getJavascript();
View Full Code Here

          node.getFilePosition().source(), requires, provides, overrides, node);
    }
  }

  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);
View Full Code Here

  }

  private int benchmark(int nRuns) throws IOException, ParseException {
    CharProducer testInput = fromResource("amazon.com.html");
    InputSource is = testInput.getSourceBreaks(0).source();
    MessageQueue mq = DevNullMessageQueue.singleton();
    long t0 = System.nanoTime();
    for (int i = nRuns; --i >= 0;) {
      HtmlLexer lexer = new HtmlLexer(testInput.clone());
      lexer.setTreatedAsXml(false);
      TokenQueue<HtmlTokenType> tq = new TokenQueue<HtmlTokenType>(
View Full Code Here

    // where it will make things shorter.
    return (Statement) StatementSimplifier.optimize(block, mq);
  }

  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);
          opt.setEnvJson((ObjectConstructor) jsExpr(fromFile(jsonfile), mq));
        } else {
          if ("--".equals(arg)) { ++i; }
          for (;i < n; ++i) {
            CharProducer cp = fromFile(args[i]);
            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));
View Full Code Here

      for (File f : inputs) { canonFiles.add(f.getCanonicalFile()); }
    } catch (IOException ex) {
      logger.println(ex.toString());
      return false;
    }
    final MessageQueue mq = new SimpleMessageQueue();

    UriFetcher fetcher = new UriFetcher() {
        public FetchedData fetch(ExternalReference ref, String mimeType)
            throws UriFetchException {
          URI uri = ref.getUri();
          uri = ref.getReferencePosition().source().getUri().resolve(uri);
          InputSource is = new InputSource(uri);

          try {
            if (!canonFiles.contains(new File(uri).getCanonicalFile())) {
              throw new UriFetchException(ref, mimeType);
            }
          } catch (IllegalArgumentException ex) {
            throw new UriFetchException(ref, mimeType, ex);
          } catch (IOException ex) {
            throw new UriFetchException(ref, mimeType, ex);
          }

          try {
            String content = getSourceContent(is);
            if (content == null) {
              throw new UriFetchException(ref, mimeType);
            }
            return FetchedData.fromCharProducer(
                CharProducer.Factory.fromString(content, is),
                mimeType, Charsets.UTF_8.name());
          } catch (IOException ex) {
            throw new UriFetchException(ref, mimeType, ex);
          }
        }
      };

    UriPolicy policy;
    final UriPolicy prePolicy = new UriPolicy() {
      public String rewriteUri(
          ExternalReference u, UriEffect effect, LoaderType loader,
          Map<String, ?> hints) {
        // TODO(ihab.awad): Need to pass in the URI rewriter from the build
        // file somehow (as a Cajita program?). The below is a stub.
        return URI.create(
            "http://example.com/"
            + "?effect=" + effect + "&loader=" + loader
            + "&uri=" + UriUtil.encode("" + u.getUri()))
            .toString();
      }
    };
    final Set<?> lUrls = (Set<?>) options.get("canLink");
    if (!lUrls.isEmpty()) {
      policy = new UriPolicy() {
        public String rewriteUri(
            ExternalReference u, UriEffect effect,
            LoaderType loader, Map<String, ?> hints) {
          String uri = u.getUri().toString();
          if (lUrls.contains(uri)) { return uri; }
          return prePolicy.rewriteUri(u, effect, loader, hints);
        }
      };
    } else {
      policy = prePolicy;
    }

    MessageContext mc = new MessageContext();

    String language = (String) options.get("language");
    String rendererType = (String) options.get("renderer");

    if ("javascript".equals(language) && "concat".equals(rendererType)) {
      return concat(inputs, output, logger);
    }

    boolean passed = true;
    ParseTreeNode outputJs;
    Node outputHtml;
    if ("caja".equals(language)) {
      PluginMeta meta = new PluginMeta(fetcher, policy);
      meta.setPrecajoleMinify("minify".equals(rendererType));
      PluginCompiler compiler = new PluginCompiler(
          BuildInfo.getInstance(), meta, mq);
      compiler.setMessageContext(mc);
      if (Boolean.TRUE.equals(options.get("debug"))) {
        compiler.setGoals(compiler.getGoals()
            .without(PipelineMaker.ONE_CAJOLED_MODULE)
            .with(PipelineMaker.ONE_CAJOLED_MODULE_DEBUG));
      }
      if (Boolean.TRUE.equals(options.get("onlyJsEmitted"))) {
        compiler.setGoals(
            compiler.getGoals().without(PipelineMaker.HTML_SAFE_STATIC));
      }

      // Parse inputs
      for (File f : inputs) {
        try {
          URI fileUri = f.getCanonicalFile().toURI();
          ParseTreeNode parsedInput = new ParserContext(mq)
              .withInput(new InputSource(fileUri))
              .withConfig(meta)
              .build();
          if (parsedInput == null) {
            passed = false;
          } else {
            compiler.addInput(parsedInput, fileUri);
          }
        } catch (IOException ex) {
          logger.println("Failed to read " + f);
          passed = false;
        } catch (ParseException ex) {
          logger.println("Failed to parse " + f);
          ex.toMessageQueue(mq);
          passed = false;
        } catch (IllegalStateException e) {
          logger.println("Failed to configure parser " + e.getMessage());
          passed = false;
        }
      }

      // Cajole
      passed = passed && compiler.run();

      outputJs = passed ? compiler.getJavascript() : null;
      outputHtml = passed ? compiler.getStaticHtml() : null;
    } else if ("javascript".equals(language)) {
      PluginMeta meta = new PluginMeta(fetcher, policy);
      passed = true;
      JsOptimizer optimizer = new JsOptimizer(mq);
      for (File f : inputs) {
        try {
          if (f.getName().endsWith(".env.json")) {
            loadEnvJsonFile(f, optimizer, mq);
          } else {
            ParseTreeNode parsedInput = new ParserContext(mq)
            .withInput(new InputSource(f.getCanonicalFile().toURI()))
            .withConfig(meta)
            .build();
            if (parsedInput != null) {
              optimizer.addInput((Statement) parsedInput);
            }
          }
        } catch (IOException ex) {
          logger.println("Failed to read " + f);
          passed = false;
        } catch (ParseException ex) {
          logger.println("Failed to parse " + f);
          ex.toMessageQueue(mq);
          passed = false;
        } catch (IllegalStateException e) {
          logger.println("Failed to configure parser " + e.getMessage());
          passed = false;
        }
      }
      outputJs = optimizer.optimize();
      outputHtml = null;
    } else {
      throw new RuntimeException("Unrecognized language: " + language);
    }
    passed = passed && !hasErrors(mq);

    // From the ignore attribute to the <transform> element.
    Set<?> toIgnore = (Set<?>) options.get("toIgnore");
    if (toIgnore == null) { toIgnore = Collections.emptySet(); }

    // Log messages
    SnippetProducer snippetProducer = new SnippetProducer(originalSources, mc);
    for (Message msg : mq.getMessages()) {
      if (passed && MessageLevel.LOG.compareTo(msg.getMessageLevel()) >= 0) {
        continue;
      }
      String snippet = snippetProducer.getSnippet(msg);
      if (!"".equals(snippet)) { snippet = "\n" + snippet; }
View Full Code Here

TOP

Related Classes of com.google.caja.reporting.MessageQueue

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.