Package com.google.caja.reporting

Examples of com.google.caja.reporting.MessageQueue


    // 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 = handle(args, mq);
    if (result == null) {
      closeBadRequest(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, mq);
      return;
    }
View Full Code Here


    // Using a simple regex is possible if we reject anything but 7-bit ASCII.
    // However, this implementation ensures Caja has a single point of truth
    // regarding what constitutes a JS identifier.
    // TODO(kpreid): Reevaluate whether this is worth the complexity and the
    // runtime dependency on the JS parser now that there is no cajoler.
    MessageQueue mq = new SimpleMessageQueue();
    Parser parser = new Parser(
        new JsTokenQueue(
            new JsLexer(
                CharProducer.Factory.fromString(
                    "var " + candidate + ";",
                    InputSource.UNKNOWN)),
            InputSource.UNKNOWN),
        mq);
    ParseTreeNode node;
    try { node = parser.parse(); } catch (ParseException e) { return false; }
    if (node == null || !mq.getMessages().isEmpty()) { return false; }
    Map<String, ParseTreeNode> bindings = Maps.newHashMap();
    if (!QuasiBuilder.match("{ var @p; }", node, bindings)) { return false; }
    if (bindings.size() != 1) { return false; }
    if (bindings.get("p") == null) { return false; }
    if (!(bindings.get("p") instanceof Identifier)) { return false; }
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;
    if ("caja".equals(language)) {
      throw new IllegalArgumentException("language=caja no longer supported");
    } 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();
    } 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

      Map<String, Object> options, File output) throws IOException {
    Set<?> ignores = (Set<?>)options.get("toIgnore");
    if (ignores == null) { ignores = Collections.emptySet(); }
    MessageContext mc = new MessageContext();
    Map<InputSource, CharSequence> contentMap = Maps.newLinkedHashMap();
    MessageQueue mq = new SimpleMessageQueue();
    List<LintJob> lintJobs = parseInputs(inputs, contentMap, mc, mq);
    lint(lintJobs, env, mq);
    if (!ignores.isEmpty()) {
      for (Iterator<Message> it = mq.getMessages().iterator(); it.hasNext();) {
        if (ignores.contains(it.next().getMessageType().name())) {
          it.remove();
        }
      }
    }
View Full Code Here

          attrsFile.getAbsoluteFile().toURI()));

      MessageContext mc = new MessageContext();
      mc.addInputSource(elements.source());
      mc.addInputSource(attrs.source());
      MessageQueue mq = new EchoingMessageQueue(
          new PrintWriter(new OutputStreamWriter(System.err), true), mc, false);

      Set<File> inputsAndDeps = new HashSet<File>();
      for (File f : inputs) { inputsAndDeps.add(f.getAbsoluteFile()); }
      for (File f : deps) { inputsAndDeps.add(f.getAbsoluteFile()); }
View Full Code Here

      if (p != null) {
        mq.getMessages().addAll(p.b);
        return p.a;
      }
    }
    MessageQueue origMq = mq;
    SimpleMessageQueue cacheMq = new SimpleMessageQueue();
    this.mq = cacheMq;
    try {
      WhiteListSkeleton skel = loadSkeleton(
          expectJSONObject(JSONValue.parse(in), "whitelist"));
      if (in instanceof UriReader) {
        cache.put(
            ((UriReader) in).getUri(),
            Pair.pair(skel, cacheMq.getMessages()));
      }
      return skel;
    } finally {
      this.mq = origMq;
      origMq.getMessages().addAll(cacheMq.getMessages());
    }
  }
View Full Code Here

          functionsFile.getAbsoluteFile().toURI()));

      MessageContext mc = new MessageContext();
      mc.addInputSource(sps.source());
      mc.addInputSource(fns.source());
      MessageQueue mq = new EchoingMessageQueue(
          new PrintWriter(new OutputStreamWriter(System.err), true), mc, false);

      Set<File> inputsAndDeps = Sets.newHashSet();
      for (File f : inputs) { inputsAndDeps.add(f.getAbsoluteFile()); }
      for (File f : deps) { inputsAndDeps.add(f.getAbsoluteFile()); }
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);
          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));
View Full Code Here

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

    boolean isHtml = codeSnippet.trim().startsWith("<");
    return key(codeSnippet, isHtml);
  }

  private ModuleCacheKey key(String codeSnippet, boolean isHtml) throws Exception {
    MessageQueue mq = new EchoingMessageQueue(
        new PrintWriter(System.err, true), new MessageContext());
    InputSource is = new InputSource(new URI("test:///" + getName()));
    ParseTreeNode node = CajaContentRewriter.parse(
        is, CharProducer.Factory.fromString(codeSnippet, is),
        isHtml ? "text/html" : "text/javascript",
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.