Package com.google.caja.lexer

Examples of com.google.caja.lexer.InputSource


          return null;
        }
      } else {
        try {
          inputFetchedData = FetchedData.fromReader(new StringReader(content),
              new InputSource(inputUri), expectedInputContentType,
              Charsets.UTF_8.displayName());
        } catch (IOException e) {
          return null;
        }
      }
    }

    if (!typeCheck.check(
            expectedInputContentType,
            inputFetchedData.getContentType())) {
      mq.addMessage(
          ServiceMessageType.UNEXPECTED_INPUT_MIME_TYPE,
          MessagePart.Factory.valueOf(expectedInputContentType),
          MessagePart.Factory.valueOf(inputFetchedData.getContentType()));
      return null;
    }

    String transformName = CajaArguments.TRANSFORM.get(args);
    Transform transform = null;
    if (transformName != null) {
      try {
        transform = Transform.valueOf(transformName);
      } catch (Exception e) {
        mq.addMessage(
            ServiceMessageType.INVALID_ARGUMENT,
            MessagePart.Factory.valueOf(transformName),
            MessagePart.Factory.valueOf(CajaArguments.TRANSFORM.toString()));
        return null;
      }
    }

    // TODO(jasvir): Change CajaArguments to handle >1 occurrence of arg
    String directiveName = CajaArguments.DIRECTIVE.get(args);
    List<Directive> directive = Lists.newArrayList();
    if (directiveName != null) {
      try {
        directive.add(Directive.valueOf(directiveName));
      } catch (Exception e) {
        mq.addMessage(
            ServiceMessageType.INVALID_ARGUMENT,
            MessagePart.Factory.valueOf(directiveName),
            MessagePart.Factory.valueOf(CajaArguments.DIRECTIVE.toString()));
        return null;
      }
    }

    ByteArrayOutputStream intermediateResponse = new ByteArrayOutputStream();
    Pair<String, String> contentInfo;
    try {
      contentInfo = applyHandler(
          inputUri,
          transform,
          directive,
          args,
          inputFetchedData.getContentType(),
          inputFetchedData,
          intermediateResponse,
          mq);
    } catch (UnsupportedContentTypeException e) {
      mq.addMessage(ServiceMessageType.UNSUPPORTED_CONTENT_TYPES);
      return null;
    } catch (RuntimeException e) {
      mq.addMessage(
          ServiceMessageType.EXCEPTION_IN_SERVICE,
          MessagePart.Factory.valueOf(e.toString()));
      return null;
    }

    return FetchedData.fromBytes(
        intermediateResponse.toByteArray(),
        contentInfo.a,
        contentInfo.b,
        new InputSource(inputUri));
  }
View Full Code Here


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

      Map<String, Object> options) {
    try {
      List<Pair<InputSource, File>> inputSources = Lists.newArrayList();
      for (File f : inputs) {
        inputSources.add(
            Pair.pair(new InputSource(f.getAbsoluteFile().toURI()), f));
      }
      Writer outputWriter = new OutputStreamWriter(
          new FileOutputStream(output), Charsets.UTF_8);
      try {
        return Minify.minify(inputSources, outputWriter, logger);
View Full Code Here

    }
    op.setEnvJson(envJson);
  }

  private static CharProducer read(File f) throws IOException {
    InputSource is = new InputSource(f.toURI());
    return CharProducer.Factory.create(
        new InputStreamReader(new FileInputStream(f), Charsets.UTF_8), is);
  }
View Full Code Here

      }
      if (attrsFile == null) {
        throw new IOException("No JSON whitelist for HTML attributes");
      }

      FilePosition elements = FilePosition.startOfFile(new InputSource(
          elementsFile.getAbsoluteFile().toURI()));
      FilePosition attrs = FilePosition.startOfFile(new InputSource(
          attrsFile.getAbsoluteFile().toURI()));

      MessageContext mc = new MessageContext();
      mc.addInputSource(elements.source());
      mc.addInputSource(attrs.source());
View Full Code Here

              } catch (UriFetcher.UriFetchException ex) {
                cp = null// Handled below.
              } catch (UnsupportedEncodingException ex) {
                cp = null// Handled below.
              }
              mc.addInputSource(new InputSource(toLoad.getUri()));
              loaded = true;
            }
            if (cp == null) {
              URI srcUri = extRef.getUri();
              String errUri = srcUri.isAbsolute()
                  ? mc.abbreviate(new InputSource(srcUri)) : srcUri.toString();
              mq.addMessage(
                  PluginMessageType.FAILED_TO_LOAD_EXTERNAL_URL,
                  extRef.getReferencePosition(),
                  MessagePart.Factory.valueOf(errUri));
              switch (t) {
View Full Code Here

       *            .without(PipelineMaker.ONE_CAJOLED_MODULE)
       *            .with(PipelineMaker.ONE_CAJOLED_MODULE_DEBUG));
       *      }
       */
     
      InputSource is = new InputSource(javaGadgetUri);
      boolean safe = false;

      compiler.addInput(new Dom(root), javaGadgetUri);

      try {
View Full Code Here

            new HttpRequest(resourceUri).setContainer(container).setGadget(gadgetUri);
        try {
          HttpResponse response = requestPipeline.execute(request);
          byte[] responseBytes = IOUtils.toByteArray(response.getResponse());
          return FetchedData.fromBytes(responseBytes, mimeType, response.getEncoding(),
              new InputSource(ref.getUri()));
        } catch (GadgetException e) {
          LOG.info("Failed to retrieve: " + ref.toString());
          return null;
        } catch (IOException e) {
          LOG.info("Failed to read: " + ref.toString());
View Full Code Here

* @author ihab.awad@gmail.com
*/
public class QuasiBuilderTest extends CajaTestCase {
  public final void testParseDoesNotFail() throws Exception {
    QuasiNode n = QuasiBuilder.parseQuasiNode(
        new InputSource(URI.create("built-in:///js-quasi-literals")),
        "function @a() { @b.@c = @d; @e = @f; }");
    assertTrue(n instanceof SimpleQuasiNode);
  }
View Full Code Here

      String specimenText,
      String matchPatternText,
      String substPatternText) throws Exception {
    ParseTreeNode specimen = parse(specimenText);
    QuasiNode matchPattern = QuasiBuilder.parseQuasiNode(
        new InputSource(URI.create("built-in:///js-quasi-literals")),
        matchPatternText);
    QuasiNode substPattern = QuasiBuilder.parseQuasiNode(
        new InputSource(URI.create("built-in:///js-quasi-literals")),
        substPatternText);

    System.out.println("specimen = " + format(specimen));
    System.out.println("matchPattern = " + format(matchPattern));
    System.out.println("substPattern = " + format(substPattern));
View Full Code Here

TOP

Related Classes of com.google.caja.lexer.InputSource

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.