@Override
  protected void processTemplates(List<TemplateResource> templateResources, Writer writer)
      throws Exception {

    try {
      String namespace = GetterUtil.getString(get(TemplateConstants.NAMESPACE));

      if (Validator.isNull(namespace)) {
        throw new TemplateException("No namespace specified.");
      }

      SoyFileSet soyFileSet = getSoyFileSet(templateResources);

      SoyTofu soyTofu = soyFileSet.compileToTofu();

      Renderer renderer = soyTofu.newRenderer(namespace);

      renderer.setData(getSoyMapData());

      boolean renderStrict = GetterUtil.getBoolean(get(TemplateConstants.RENDER_STRICT), true);

      if (renderStrict) {
        SanitizedContent sanitizedContent = renderer.renderStrict();

        writer.write(sanitizedContent.stringValue());
      } else {
        writer.write(renderer.render());
      }
    } catch (PrivilegedActionException pae) {
      throw pae.getException();
    }
  }
示例#2
0
  @Override
  protected void doGet(HttpExchange exchange, QueryData data, Config config) throws IOException {
    Compilation compilation = getCompilation(exchange, data, config);
    if (compilation == null) {
      return;
    }
    if (!compilation.usesModules()) {
      HttpUtil.writeErrorMessageResponse(exchange, "This configuration does not use modules");
      return;
    }

    // Get the size of each module.
    ModuleConfig moduleConfig = config.getModuleConfig();
    Map<String, List<String>> invertedDependencyTree = moduleConfig.getInvertedDependencyTree();
    Function<String, String> moduleNameToUri = moduleConfig.createModuleNameToUriFunction();
    ImmutableMap.Builder<String, Pair<Integer, Integer>> builder = ImmutableMap.builder();
    final boolean isDebugMode = false;
    for (String module : invertedDependencyTree.keySet()) {
      // The file size is in bytes, assuming UTF-8 input.
      String compiledCode = compilation.getCodeForModule(module, isDebugMode, moduleNameToUri);
      int uncompressedSize = compiledCode.getBytes(Charsets.UTF_8).length;
      int gzippedSize = GzipUtil.getGzipSize(compiledCode);
      builder.put(module, Pair.of(uncompressedSize, gzippedSize));
    }
    Map<String, Pair<Integer, Integer>> moduleSizes = builder.build();

    // Construct the SVG.
    SetMultimap<Integer, String> moduleDepths =
        calculateModuleDepths(moduleConfig.getRootModule(), invertedDependencyTree);
    Map<String, List<JsInput>> moduleToInputs;
    try {
      moduleToInputs = moduleConfig.partitionInputsIntoModules(config.getManifest());
    } catch (CompilationException e) {
      throw new RuntimeException(e);
    }
    Pair<String, Dimension> svg =
        generateSvg(
            config.getId(), moduleDepths, invertedDependencyTree, moduleSizes, moduleToInputs);

    // Populate Soy template.
    Dimension svgDimension = svg.getSecond();
    SoyMapData mapData =
        new SoyMapData(
            ImmutableMap.<String, Object>builder()
                .put("configId", config.getId())
                .put("svg", svg.getFirst())
                .put("svgWidth", svgDimension.width)
                .put("svgHeight", svgDimension.height)
                .build());
    String xhtml = TOFU.newRenderer("org.plovr.modules").setData(mapData).render();

    // Write the response.
    Headers responseHeaders = exchange.getResponseHeaders();
    responseHeaders.set("Content-Type", "text/xml");
    exchange.sendResponseHeaders(200, xhtml.length());
    Writer responseBody = new OutputStreamWriter(exchange.getResponseBody());
    responseBody.write(xhtml);
    responseBody.close();
  }
示例#3
0
  @Override
  protected void doGet(HttpExchange exchange, QueryData data, Config config) throws IOException {
    Compilation compilation = getCompilation(exchange, data, config);
    if (compilation == null) {
      return;
    }

    String configId = config.getId();
    List<JsInput> inputs;
    if (compilation.usesModules()) {
      ModuleConfig moduleConfig = config.getModuleConfig();
      Map<String, List<JsInput>> moduleToInputs;
      try {
        moduleToInputs = moduleConfig.partitionInputsIntoModules(config.getManifest());
      } catch (CompilationException e) {
        throw new RuntimeException(e);
      }

      String module = data.getParam("module");
      inputs = moduleToInputs.get(module);
    } else {
      try {
        inputs = config.getManifest().getInputsInCompilationOrder();
      } catch (CompilationException e) {
        HttpUtil.writeErrorMessageResponse(exchange, e.getMessage());
        return;
      }
    }

    // Build up the list of hyperlinks.
    Function<JsInput, String> converter =
        InputFileHandler.createInputNameToUriConverter(server, exchange, configId);
    SoyListData inputData = new SoyListData();
    for (JsInput input : inputs) {
      SoyMapData inputDatum = new SoyMapData();
      inputDatum.put("href", converter.apply(input));
      inputDatum.put("name", input.getName());
      inputData.add(inputDatum);
    }
    SoyMapData soyData = new SoyMapData();
    soyData.put("inputs", inputData);
    soyData.put("configId", configId);

    // Write the response.
    Headers responseHeaders = exchange.getResponseHeaders();
    responseHeaders.set("Content-Type", "text/html");
    String html = TOFU.newRenderer("org.plovr.list").setData(soyData).render();
    exchange.sendResponseHeaders(200, html.length());
    Writer responseBody = new OutputStreamWriter(exchange.getResponseBody());
    responseBody.write(html);
    responseBody.close();
  }
  /** @param exchange */
  @Override
  public void handle(HttpExchange exchange) throws IOException {
    File staticContentDirectory =
        RequestHandlerSelector.getCorrespondingFileForRequest(config, exchange);
    if (staticContentDirectory == null) {
      // A 403 response was already written.
      return;
    }

    Preconditions.checkArgument(
        staticContentDirectory.isDirectory(), "This handler only processes directory listings.");

    // If the URI does not end in "/" (and is not "/"), then redirect. This will
    // ensure that all of the hyperlinks in the page work correctly.
    final String path = exchange.getRequestURI().getPath();
    if (!path.endsWith("/") && !path.equals("/")) {
      Responses.redirect(exchange, path + "/");
      return;
    }

    // Split the files into directories and files.
    List<File> directories = Lists.newArrayList();
    List<File> files = Lists.newArrayList();
    for (File f : staticContentDirectory.listFiles()) {
      if (f.isDirectory()) {
        directories.add(f);
      } else {
        files.add(f);
        String name = f.getName();
        if (name.endsWith(".soy")) {
          name = name.replaceAll("\\.soy$", ".html");
          File htmlFile = new File(f.getParentFile(), name);
          if (!htmlFile.exists()) {
            // If the HTML already exists, then it will already be added by this
            // loop.
            files.add(htmlFile);
          }
        }
      }
    }

    // Sort each list alphabetically.
    Collections.sort(directories);
    Collections.sort(files);

    List<String> directoryNames = Lists.transform(directories, fileToName);
    List<String> fileNames = Lists.transform(files, fileToName);

    List<Map<String, String>> directoryParts = Lists.newArrayList();
    String href = "/";
    directoryParts.add(ImmutableMap.of("href", href, "name", "Root"));
    for (String name : path.split("/")) {
      if (!name.isEmpty()) {
        href += name + "/";
        directoryParts.add(ImmutableMap.of("href", href, "name", name));
      }
    }

    // Write out the HTML using a template.
    Map<String, ?> data =
        ImmutableMap.<String, Object>of(
            "directory", path,
            "directoryParts", directoryParts,
            "directories", directoryNames,
            "files", fileNames);
    String html = soyWebTemplate.newRenderer("org.plovr.soyweb.directory").setData(data).render();
    Responses.writeHtml(html, exchange);
  }