Example #1
0
 private void loadHeaderAndFooter(PDFDocument doc, Map<String, Object> args)
     throws TemplateNotFoundException {
   Options options = doc.options;
   if (options == null) return;
   if (!StringUtils.isEmpty(options.HEADER_TEMPLATE)) {
     Template template = TemplateLoader.load(options.HEADER_TEMPLATE);
     options.HEADER = template.render(new HashMap<String, Object>(args));
   }
   if (!StringUtils.isEmpty(options.FOOTER_TEMPLATE)) {
     Template template = TemplateLoader.load(options.FOOTER_TEMPLATE);
     options.FOOTER = template.render(new HashMap<String, Object>(args));
   }
   if (!StringUtils.isEmpty(options.HEADER))
     doc.headerFooterList.add(
         new IHtmlToPdfTransformer.CHeaderFooter(
             options.HEADER, IHtmlToPdfTransformer.CHeaderFooter.HEADER));
   if (!StringUtils.isEmpty(options.ALL_PAGES))
     doc.headerFooterList.add(
         new IHtmlToPdfTransformer.CHeaderFooter(
             options.ALL_PAGES, IHtmlToPdfTransformer.CHeaderFooter.ALL_PAGES));
   if (!StringUtils.isEmpty(options.EVEN_PAGES))
     doc.headerFooterList.add(
         new IHtmlToPdfTransformer.CHeaderFooter(
             options.EVEN_PAGES, IHtmlToPdfTransformer.CHeaderFooter.EVEN_PAGES));
   if (!StringUtils.isEmpty(options.FOOTER))
     doc.headerFooterList.add(
         new IHtmlToPdfTransformer.CHeaderFooter(
             options.FOOTER, IHtmlToPdfTransformer.CHeaderFooter.FOOTER));
   if (!StringUtils.isEmpty(options.ODD_PAGES))
     doc.headerFooterList.add(
         new IHtmlToPdfTransformer.CHeaderFooter(
             options.ODD_PAGES, IHtmlToPdfTransformer.CHeaderFooter.ODD_PAGES));
 }
Example #2
0
  public static void serve404(
      NotFound e, ChannelHandlerContext ctx, Request request, HttpRequest nettyRequest) {
    Logger.trace("serve404: begin");
    HttpResponse nettyResponse =
        new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
    nettyResponse.setHeader(SERVER, signature);

    nettyResponse.setHeader(CONTENT_TYPE, "text/html");
    Map<String, Object> binding = getBindingForErrors(e, false);

    String format = Request.current().format;
    if (format == null) {
      format = "txt";
    }
    nettyResponse.setHeader(
        CONTENT_TYPE, (MimeTypes.getContentType("404." + format, "text/plain")));

    String errorHtml = TemplateLoader.load("errors/404." + format).render(binding);
    try {
      ChannelBuffer buf = ChannelBuffers.copiedBuffer(errorHtml.getBytes("utf-8"));
      nettyResponse.setContent(buf);
      ChannelFuture writeFuture = ctx.getChannel().write(nettyResponse);
      writeFuture.addListener(ChannelFutureListener.CLOSE);
    } catch (UnsupportedEncodingException fex) {
      Logger.error(fex, "(utf-8 ?)");
    }
    Logger.trace("serve404: end");
  }
Example #3
0
 /**
  * Parse a route file. If an action starts with <i>"plugin:name"</i>, replace that route by the
  * ones declared in the plugin route file denoted by that <i>name</i>, if found.
  *
  * @param routeFile
  * @param prefix The prefix that the path of all routes in this route file start with. This prefix
  *     should not end with a '/' character.
  */
 static void parse(VirtualFile routeFile, String prefix) {
   String fileAbsolutePath = routeFile.getRealFile().getAbsolutePath();
   String content = routeFile.contentAsString();
   if (content.indexOf("${") > -1 || content.indexOf("#{") > -1 || content.indexOf("%{") > -1) {
     // Mutable map needs to be passed in.
     content = TemplateLoader.load(routeFile).render(new HashMap<String, Object>(16));
   }
   parse(content, prefix, fileAbsolutePath);
 }
Example #4
0
 private void renderDocuments(Map<String, Object> args) {
   for (PDFDocument doc : docs.documents) {
     Request request = Http.Request.current();
     String templateName = PDF.resolveTemplateName(doc.template, request, request.format);
     Template template = TemplateLoader.load(templateName);
     doc.content = template.render(new HashMap<String, Object>(args));
     loadHeaderAndFooter(doc, args);
   }
 }
Example #5
0
 public void serve404(
     HttpServletRequest servletRequest, HttpServletResponse servletResponse, NotFound e) {
   Logger.warn(
       "404 -> %s %s (%s)",
       servletRequest.getMethod(), servletRequest.getRequestURI(), e.getMessage());
   servletResponse.setStatus(404);
   servletResponse.setContentType("text/html");
   Map<String, Object> binding = new HashMap<String, Object>();
   binding.put("result", e);
   binding.put("session", Scope.Session.current());
   binding.put("request", Http.Request.current());
   binding.put("flash", Scope.Flash.current());
   binding.put("params", Scope.Params.current());
   binding.put("play", new Play());
   try {
     binding.put("errors", Validation.errors());
   } catch (Exception ex) {
     //
   }
   String format = Request.current().format;
   servletResponse.setStatus(404);
   // Do we have an ajax request? If we have then we want to display some text even if it is html
   // that is requested
   if ("XMLHttpRequest".equals(servletRequest.getHeader("X-Requested-With"))
       && (format == null || format.equals("html"))) {
     format = "txt";
   }
   if (format == null) {
     format = "txt";
   }
   servletResponse.setContentType(MimeTypes.getContentType("404." + format, "text/plain"));
   String errorHtml = TemplateLoader.load("errors/404." + format).render(binding);
   try {
     servletResponse.getOutputStream().write(errorHtml.getBytes(Response.current().encoding));
   } catch (Exception fex) {
     Logger.error(fex, "(encoding ?)");
   }
 }
Example #6
0
  /**
   * Force all java source and template compilation.
   *
   * @return success ?
   */
  static boolean preCompile() {
    if (usePrecompiled) {
      if (Play.getFile("precompiled").exists()) {
        classloader.getAllClasses();
        Logger.info("Application is precompiled");
        return true;
      }
      Logger.error("Precompiled classes are missing!!");
      fatalServerErrorOccurred();
      return false;
    }
    try {
      Logger.info("Precompiling ...");
      Thread.currentThread().setContextClassLoader(Play.classloader);
      long start = System.currentTimeMillis();
      classloader.getAllClasses();

      if (Logger.isTraceEnabled()) {
        Logger.trace("%sms to precompile the Java stuff", System.currentTimeMillis() - start);
      }

      if (!lazyLoadTemplates) {
        start = System.currentTimeMillis();
        TemplateLoader.getAllTemplate();

        if (Logger.isTraceEnabled()) {
          Logger.trace("%sms to precompile the templates", System.currentTimeMillis() - start);
        }
      }
      return true;
    } catch (Throwable e) {
      Logger.error(e, "Cannot start in PROD mode with errors");
      fatalServerErrorOccurred();
      return false;
    }
  }
Example #7
0
 public static void getTemplateSource(String name) {
   VirtualFile vf = VirtualFile.fromRelativePath(name);
   renderText(TemplateLoader.load(vf).source);
 }
Example #8
0
 public void serve500(Exception e, HttpServletRequest request, HttpServletResponse response) {
   try {
     Map<String, Object> binding = new HashMap<String, Object>();
     if (!(e instanceof PlayException)) {
       e = new play.exceptions.UnexpectedException(e);
     }
     // Flush some cookies
     try {
       Map<String, Http.Cookie> cookies = Response.current().cookies;
       for (Http.Cookie cookie : cookies.values()) {
         if (cookie.sendOnError) {
           Cookie c = new Cookie(cookie.name, cookie.value);
           c.setSecure(cookie.secure);
           c.setPath(cookie.path);
           if (cookie.domain != null) {
             c.setDomain(cookie.domain);
           }
           response.addCookie(c);
         }
       }
     } catch (Exception exx) {
       // humm ?
     }
     binding.put("exception", e);
     binding.put("session", Scope.Session.current());
     binding.put("request", Http.Request.current());
     binding.put("flash", Scope.Flash.current());
     binding.put("params", Scope.Params.current());
     binding.put("play", new Play());
     try {
       binding.put("errors", Validation.errors());
     } catch (Exception ex) {
       //
     }
     response.setStatus(500);
     String format = "html";
     if (Request.current() != null) {
       format = Request.current().format;
     }
     // Do we have an ajax request? If we have then we want to display some text even if it is html
     // that is requested
     if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))
         && (format == null || format.equals("html"))) {
       format = "txt";
     }
     if (format == null) {
       format = "txt";
     }
     response.setContentType(MimeTypes.getContentType("500." + format, "text/plain"));
     try {
       String errorHtml = TemplateLoader.load("errors/500." + format).render(binding);
       response.getOutputStream().write(errorHtml.getBytes(Response.current().encoding));
       Logger.error(e, "Internal Server Error (500)");
     } catch (Throwable ex) {
       Logger.error(e, "Internal Server Error (500)");
       Logger.error(ex, "Error during the 500 response generation");
       throw ex;
     }
   } catch (Throwable exxx) {
     if (exxx instanceof RuntimeException) {
       throw (RuntimeException) exxx;
     }
     throw new RuntimeException(exxx);
   }
 }
Example #9
0
  // TODO: add request and response as parameter
  public static void serve500(Exception e, ChannelHandlerContext ctx, HttpRequest nettyRequest) {
    Logger.trace("serve500: begin");
    HttpResponse nettyResponse =
        new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
    if (exposePlayServer) {
      nettyResponse.setHeader(SERVER, signature);
    }

    Request request = Request.current();
    Response response = Response.current();

    try {
      if (!(e instanceof PlayException)) {
        e = new play.exceptions.UnexpectedException(e);
      }

      // Flush some cookies
      try {

        Map<String, Http.Cookie> cookies = response.cookies;
        for (Http.Cookie cookie : cookies.values()) {
          CookieEncoder encoder = new CookieEncoder(true);
          Cookie c = new DefaultCookie(cookie.name, cookie.value);
          c.setSecure(cookie.secure);
          c.setPath(cookie.path);
          if (cookie.domain != null) {
            c.setDomain(cookie.domain);
          }
          if (cookie.maxAge != null) {
            c.setMaxAge(cookie.maxAge);
          }
          c.setHttpOnly(cookie.httpOnly);
          encoder.addCookie(c);
          nettyResponse.addHeader(SET_COOKIE, encoder.encode());
        }

      } catch (Exception exx) {
        Logger.error(e, "Trying to flush cookies");
        // humm ?
      }
      Map<String, Object> binding = getBindingForErrors(e, true);

      String format = request.format;
      if (format == null) {
        format = "txt";
      }

      nettyResponse.setHeader(
          "Content-Type", (MimeTypes.getContentType("500." + format, "text/plain")));
      try {
        String errorHtml = TemplateLoader.load("errors/500." + format).render(binding);

        ChannelBuffer buf = ChannelBuffers.copiedBuffer(errorHtml.getBytes("utf-8"));
        nettyResponse.setContent(buf);
        ChannelFuture writeFuture = ctx.getChannel().write(nettyResponse);
        writeFuture.addListener(ChannelFutureListener.CLOSE);
        Logger.error(
            e, "Internal Server Error (500) for request %s", request.method + " " + request.url);
      } catch (Throwable ex) {
        Logger.error(
            e, "Internal Server Error (500) for request %s", request.method + " " + request.url);
        Logger.error(ex, "Error during the 500 response generation");
        try {
          ChannelBuffer buf =
              ChannelBuffers.copiedBuffer("Internal Error (check logs)".getBytes("utf-8"));
          nettyResponse.setContent(buf);
          ChannelFuture writeFuture = ctx.getChannel().write(nettyResponse);
          writeFuture.addListener(ChannelFutureListener.CLOSE);
        } catch (UnsupportedEncodingException fex) {
          Logger.error(fex, "(utf-8 ?)");
        }
      }
    } catch (Throwable exxx) {
      try {
        ChannelBuffer buf =
            ChannelBuffers.copiedBuffer("Internal Error (check logs)".getBytes("utf-8"));
        nettyResponse.setContent(buf);
        ChannelFuture writeFuture = ctx.getChannel().write(nettyResponse);
        writeFuture.addListener(ChannelFutureListener.CLOSE);
      } catch (Exception fex) {
        Logger.error(fex, "(utf-8 ?)");
      }
      if (exxx instanceof RuntimeException) {
        throw (RuntimeException) exxx;
      }
      throw new RuntimeException(exxx);
    }
    Logger.trace("serve500: end");
  }
Example #10
0
  private static void load_(VirtualFile yamlFile) {
    Logger.info(msg_("loading menu from yaml file: %s", yamlFile.relativePath()));
    String renderedYaml = TemplateLoader.load(yamlFile).render();
    Yaml yaml = new Yaml();
    try {
      startTx_();
      Object o = yaml.load(renderedYaml);
      if (o instanceof LinkedHashMap<?, ?>) {
        Map<String, IMenu> all = new HashMap<String, IMenu>();
        @SuppressWarnings("unchecked")
        Map<Object, Map<?, ?>> objects = (Map<Object, Map<?, ?>>) o;
        Map<Object, String> parents = new HashMap<Object, String>();
        for (Object key : objects.keySet()) {
          String id = key.toString().trim();
          Matcher matcher = P_K.matcher(id);
          if (matcher.matches()) {
            id = matcher.group(2);
          }
          Map<?, ?> mm = objects.get(key);
          String name = (String) mm.get("name");
          String url = (String) mm.get("url");
          String cssClass = (String) mm.get("cssClass");
          String title = (String) mm.get("title");
          List<String> labels = (List<String>) mm.get("labels");
          String parent = (String) mm.get("parent");

          IMenu menu = menuInstance();
          menu.setName(name);
          menu.setUrl(url);
          menu.setCssClass(cssClass);
          menu.setTitle(title);
          if (null != labels) {
            menu.setLabels(labels);
          }
          menu._save();
          if (null != parent) parents.put(menu._getId(), parent);
          all.put(id, menu);
        }
        for (IMenu menu : all.values()) {
          String parent = (String) parents.get(menu._getId());
          if (null != parent) {
            if (all.containsKey(parent)) {
              menu.setParent(all.get(parent));
              menu._save();
            } else {
              throw new RuntimeException(
                  "cannot find parent["
                      + parent
                      + "] in men yaml file : "
                      + yamlFile.relativePath());
            }
          }
        }
      } else {
        throw new RuntimeException("menu yml format not reconized: " + yamlFile.relativePath());
      }
      commitTx_();
    } catch (Exception e) {
      rollbackTx_();
      throw new RuntimeException(e);
    }
  }
Example #11
0
  /** Start the application. Recall to restart ! */
  public static synchronized void start() {
    try {

      if (started) {
        stop();
      }

      if (standalonePlayServer) {
        // Can only register shutdown-hook if running as standalone server
        if (!shutdownHookEnabled) {
          // registers shutdown hook - Now there's a good chance that we can notify
          // our plugins that we're going down when some calls ctrl+c or just kills our process..
          shutdownHookEnabled = true;
          Runtime.getRuntime()
              .addShutdownHook(
                  new Thread() {
                    public void run() {
                      Play.stop();
                    }
                  });
        }
      }

      if (mode == Mode.DEV) {
        // Need a new classloader
        classloader = new ApplicationClassloader();
        // Put it in the current context for any code that relies on having it there
        Thread.currentThread().setContextClassLoader(classloader);
        // Reload plugins
        pluginCollection.reloadApplicationPlugins();
      }

      // Reload configuration
      readConfiguration();

      // Configure logs
      String logLevel = configuration.getProperty("application.log", "INFO");
      // only override log-level if Logger was not configured manually
      if (!Logger.configuredManually) {
        Logger.setUp(logLevel);
      }
      Logger.recordCaller =
          Boolean.parseBoolean(configuration.getProperty("application.log.recordCaller", "false"));

      // Locales
      langs =
          new ArrayList<String>(
              Arrays.asList(configuration.getProperty("application.langs", "").split(",")));
      if (langs.size() == 1 && langs.get(0).trim().length() == 0) {
        langs = new ArrayList<String>(16);
      }

      // Clean templates
      TemplateLoader.cleanCompiledCache();

      // SecretKey
      secretKey = configuration.getProperty("application.secret", "").trim();
      if (secretKey.length() == 0) {
        Logger.warn("No secret key defined. Sessions will not be encrypted");
      }

      // Default web encoding
      String _defaultWebEncoding = configuration.getProperty("application.web_encoding");
      if (_defaultWebEncoding != null) {
        Logger.info("Using custom default web encoding: " + _defaultWebEncoding);
        defaultWebEncoding = _defaultWebEncoding;
        // Must update current response also, since the request/response triggering
        // this configuration-loading in dev-mode have already been
        // set up with the previous encoding
        if (Http.Response.current() != null) {
          Http.Response.current().encoding = _defaultWebEncoding;
        }
      }

      // Try to load all classes
      Play.classloader.getAllClasses();

      // Routes
      Router.detectChanges(ctxPath);

      // Cache
      Cache.init();

      // Plugins
      try {
        pluginCollection.onApplicationStart();
      } catch (Exception e) {
        if (Play.mode.isProd()) {
          Logger.error(e, "Can't start in PROD mode with errors");
        }
        if (e instanceof RuntimeException) {
          throw (RuntimeException) e;
        }
        throw new UnexpectedException(e);
      }

      if (firstStart) {
        Logger.info(
            "Application '%s' is now started !", configuration.getProperty("application.name", ""));
        firstStart = false;
      }

      // We made it
      started = true;
      startedAt = System.currentTimeMillis();

      // Plugins
      pluginCollection.afterApplicationStart();

    } catch (PlayException e) {
      started = false;
      try {
        Cache.stop();
      } catch (Exception ignored) {
      }
      throw e;
    } catch (Exception e) {
      started = false;
      try {
        Cache.stop();
      } catch (Exception ignored) {
      }
      throw new UnexpectedException(e);
    }
  }