Example #1
0
  /**
   * Process the user's http get request. Process the template that maps to the URI that was hit.
   *
   * @param request the user's http request
   * @param response the user's http response
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (processStatus(request, response)) {
      return;
    }

    if (!isRunning()) {
      int errorCode = mProperties.getInt("startup.codes.error", 503);
      response.sendError(errorCode);
      return;
    }

    if (mUseSpiderableRequest) {
      request =
          new SpiderableRequest(request, mQuerySeparator, mParameterSeparator, mValueSeparator);
    }

    // start transaction
    TeaServletTransaction tsTrans = getEngine().createTransaction(request, response, true);

    // load associated request/response
    ApplicationRequest appRequest = tsTrans.getRequest();
    ApplicationResponse appResponse = tsTrans.getResponse();

    // process template
    processTemplate(appRequest, appResponse);
    appResponse.finish();

    // flush the output
    response.flushBuffer();
  }
Example #2
0
  /**
   * Inserts a plugin to expose parts of the teaservlet via the EngineAccess interface.
   *
   * <p>private void createEngineAccessPlugin(PluginContext context) {
   *
   * <p>Plugin engineAccess = new EngineAccessPlugin(this); context.addPlugin(engineAccess);
   * context.addPluginListener(engineAccess); }
   */
  private boolean processResource(ApplicationRequest appRequest, ApplicationResponse appResponse)
      throws IOException {

    // get the associated system path
    String requestURI = null;
    if ((requestURI = appRequest.getPathInfo()) == null) {
      String context = appRequest.getContextPath();

      requestURI = appRequest.getRequestURI();
      if (requestURI.startsWith(context)) {
        requestURI = requestURI.substring(context.length());
      }
    }

    // check for valid asset
    Asset asset = getEngine().getAssetEngine().getAsset(requestURI);
    if (asset == null) {
      return false;
    }

    // set mime type
    appResponse.setContentType(asset.getMimeType());

    // write contents
    int read = -1;
    byte[] contents = new byte[1024];
    InputStream input = asset.getInputStream();
    ServletOutputStream output = appResponse.getOutputStream();
    while ((read = input.read(contents)) >= 0) {
      output.write(contents, 0, read);
    }

    // complete response
    appResponse.finish();

    // success
    return true;
  }
Example #3
0
  /**
   * Creates a transaction from the provided request and response and then processes that
   * transaction by executing the target template.
   *
   * @param request the user's http request
   * @param response the user's http response
   */
  private boolean processTemplate(ApplicationRequest appRequest, ApplicationResponse appResponse)
      throws IOException {

    // check if redirect or erroring out
    if (appResponse.isRedirectOrError()) {
      return false;
    }

    // set initial content type and helper attributes
    appResponse.setContentType("text/html");
    appRequest.setAttribute(this.getClass().getName(), this);

    // lookup template
    Template template = (Template) appRequest.getTemplate();

    // process as resource if no template available
    if (template == null) {
      if (!processResource(appRequest, appResponse)) {
        appResponse.sendError(404);
        return false;
      }
      return true;
    }

    long endTime = 0L;
    long startTime = 0L;
    long contentLength = 0;

    TemplateStats templateStats = null;
    if (mInstrumentationEnabled) {
      templateStats = mTeaServletRequestStats.getStats(template.getName());
    }

    try {
      Object[] params = null;
      try {
        if (templateStats != null) {
          templateStats.incrementServicing();
        }

        // Fill in the parameters to pass to the template.
        Class<?>[] paramTypes = template.getParameterTypes();
        if (paramTypes.length == 0) {
          params = NO_PARAMS;
        } else {
          params = new Object[paramTypes.length];
          String[] paramNames = template.getParameterNames();
          for (int i = 0; i < paramNames.length; i++) {
            String paramName = paramNames[i];
            if (paramName == null) {
              continue;
            }

            Class<?> paramType = paramTypes[i];

            if (!paramType.isArray()) {
              String value = appRequest.getParameter(paramName);
              if (value == null || paramType == String.class) {
                params[i] = value;
              } else {
                params[i] = convertParameter(value, paramType);
              }
            } else {
              String[] values = appRequest.getParameterValues(paramName);
              if (values == null || paramType == String[].class) {
                params[i] = values;
              } else {
                paramType = paramType.getComponentType();
                Object converted = Array.newInstance(paramType, values.length);
                params[i] = converted;
                for (int j = 0; j < values.length; j++) {
                  Array.set(converted, j, convertParameter(values[j], paramType));
                }
              }
            }
          }
        }

        startTime = System.currentTimeMillis();
        try {
          try {
            appRequest.getTemplate().execute(appResponse.getHttpContext(), params);
          } catch (ContextCreationException cce) {
            // unwrap the inner exception
            throw (Exception) cce.getUndeclaredThrowable();
          }
        } catch (AbortTemplateException e) {
          if (DEBUG) {
            mLog.debug("Template execution aborted!");
            mLog.debug(e);
          }
        } catch (RuntimeException e) {
          if (getEngine().getTemplateSource().isExceptionGuardianEnabled()) {
            // Just log the error and use what the template wrote out.
            mLog.error(e);
          } else {
            throw new ServletException(e);
          }
        } catch (IOException e) {
          // TODO: shouldn't we be throwing this as a ServletException?
          //       otherwise its not logged to the TeaLog.
          throw e;
        } catch (ServletException e) {
          throw e;
        } catch (Exception e) {
          throw new ServletException(e);
        }
        // TODO: shouldn't we be catching errors and not just exceptions?
        //       otherwise its not logged to the TeaLog.
        finally {
          endTime = System.currentTimeMillis();
          if (appRequest instanceof TeaServletStats) {
            long duration = endTime - startTime;
            ((TeaServletStats) appRequest).setTemplateDuration(duration);
          }
        }

        if (DEBUG) {
          mLog.debug("Finished executing template");
        }
      } catch (ServletException e) {
        // Log exception
        StringBuffer msg = new StringBuffer();
        msg.append("Error processing request for ");
        msg.append(appRequest.getRequestURI());
        if (appRequest.getQueryString() != null) {
          msg.append('?');
          msg.append(appRequest.getQueryString());
        }
        mLog.error(msg.toString());

        Throwable t = e;
        while (t instanceof ServletException) {
          e = (ServletException) t;
          if (e.getRootCause() != null) {
            String message = e.getMessage();
            if (message != null && message.length() > 0) {
              mLog.error(message);
            }
            mLog.error(t = e.getRootCause());
          } else {
            mLog.error(e);
            break;
          }
        }

        // Internal server error unless header is already set
        if (!appResponse.isRedirectOrError()) {
          String displayMessage = e.getLocalizedMessage();
          if (displayMessage == null || displayMessage.length() == 0) {
            appResponse.sendError(ApplicationResponse.SC_INTERNAL_SERVER_ERROR);
          } else {
            appResponse.sendError(ApplicationResponse.SC_INTERNAL_SERVER_ERROR, displayMessage);
          }
        }
      }
      contentLength = appResponse.getResponseBuffer().getByteCount();
      appResponse.finish();
      if (templateStats != null) {
        templateStats.decrementServicing();
        templateStats.log(startTime, endTime, contentLength, params);
      }
    } catch (Exception e) {
      if (templateStats != null) {
        templateStats.decrementServicing();
      }
    }
    return true;
  }