@Override
  protected ModelAndView handleRequestInternal(
      HttpServletRequest request, HttpServletResponse response) throws Exception {
    SiteContext siteContext = SiteContext.getCurrent();
    ScriptFactory scriptFactory = siteContext.getScriptFactory();

    if (scriptFactory == null) {
      throw new IllegalStateException(
          "No script factory associate to current site context '"
              + siteContext.getSiteName()
              + "'");
    }

    String serviceUrl = getServiceUrl(request);
    String scriptUrl = getScriptUrl(scriptFactory, siteContext, request, serviceUrl);
    Object responseBody = executeScript(scriptFactory, request, response, scriptUrl);

    if (response.isCommitted()) {
      // If response has been already committed by the script, just return null
      logger.debug("Response already committed by script " + scriptUrl);

      return null;
    }

    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject(responseBodyModelAttributeName, responseBody);

    return modelAndView;
  }
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    SiteContext siteContext = contextResolver.getContext((HttpServletRequest) request);
    if (siteContext == null) {
      throw new CrafterException("No site context was resolved for the current request");
    }

    SiteContext.setCurrent(siteContext);
    try {
      chain.doFilter(request, response);
    } finally {
      SiteContext.clear();
    }
  }
  @Override
  public Object findTemplateSource(String name) throws IOException {
    SiteContext context = AbstractSiteContextResolvingFilter.getCurrentContext();

    String path = getTemplatePath(context, name);

    if (logger.isDebugEnabled()) {
      logger.debug(
          "Looking for FreeMarker template at [context=" + context + ", path='" + path + "']");
    }

    try {
      return contentStoreService.getContent(context.getContext(), path);
    } catch (PathNotFoundException e) {
      if (logger.isDebugEnabled()) {
        logger.debug(
            "Unable to find FreeMarker template at [context=" + context + ", path='" + path + "']");
      }

      return null;
    }
  }
  protected String getScriptUrl(
      ScriptFactory scriptFactory,
      SiteContext siteContext,
      HttpServletRequest request,
      String serviceUrl) {
    String baseUrl =
        UrlUtils.appendUrl(
            siteContext.getRestScriptsPath(), FilenameUtils.removeExtension(serviceUrl));

    return String.format(
        SCRIPT_URL_FORMAT,
        baseUrl,
        request.getMethod().toLowerCase(),
        scriptFactory.getScriptFileExtension());
  }
 @Override
 public String[] getTenants() {
   return new String[] {SiteContext.getCurrent().getSiteName()};
 }
 protected String getTemplatePath(SiteContext context, String name) {
   return UrlUtils.appendUrl(context.getTemplatesPath(), name);
 }