Ejemplo n.º 1
0
 private void logVersionInfo(Class<?> clazz, String title, Log log) {
   Package pack = clazz.getPackage();
   String version = null;
   if (pack != null) {
     if (pack.getImplementationTitle() != null) {
       title = pack.getImplementationTitle();
     }
     version = pack.getImplementationVersion();
   }
   if (version == null) {
     try {
       String classname = clazz.getName();
       Class<?> packinf =
           Class.forName(classname.substring(0, classname.lastIndexOf('.')) + ".PackageInfo");
       java.lang.reflect.Method mo = packinf.getMethod("getProductVersion");
       version = mo.invoke(null).toString();
     } catch (Exception pie) {
       log.info("PackageInfo not found");
     }
     if (version == null) {
       version = "<unknown>";
     }
   }
   log.info(title + " version " + version);
 }
Ejemplo n.º 2
0
 /** Destroys the TeaServlet and the user's application. */
 public void destroy() {
   if (mEngine != null) {
     mLog.info("Destroying Engine");
     mEngine.destroy();
   }
   mLog.info("Destroying TeaServlet");
   super.destroy();
 }
Ejemplo n.º 3
0
  private PluginContext loadPlugins(PropertyMap properties, Log log) {

    PluginContext plug = new PluginContext(mResourceFactory);
    PluginFactoryConfig config = new PluginFactoryConfigSupport(properties, log, plug);

    try {
      PluginFactory.createPlugins(config, mPluginListener);
    } catch (PluginFactoryException e) {
      log.warn("Error loading plugins.");
      log.warn(e);
    }

    return plug;
  }
Ejemplo n.º 4
0
 public synchronized void error(Throwable t) {
   TeaStackTraceLine[] lines = getTeaStackTraceLines(t);
   if (lines == null) {
     super.error(t);
   } else {
     if (isEnabled() && isErrorEnabled()) {
       dispatchLogTeaStackTrace(new TeaLogEvent(this, LogEvent.ERROR_TYPE, lines));
     }
   }
 }
Ejemplo n.º 5
0
 public synchronized void info(Throwable t) {
   TeaStackTraceLine[] lines = getTeaStackTraceLines(t);
   if (lines == null) {
     super.info(t);
   } else {
     if (isEnabled() && isInfoEnabled()) {
       dispatchLogTeaStackTrace(new TeaLogEvent(this, LogEvent.INFO_TYPE, lines));
     }
   }
 }
Ejemplo n.º 6
0
 public synchronized void debug(Throwable t) {
   TeaStackTraceLine[] lines = getTeaStackTraceLines(t);
   if (lines == null) {
     super.debug(t);
   } else {
     if (isEnabled() && isDebugEnabled()) {
       dispatchLogTeaStackTrace(new TeaLogEvent(this, LogEvent.DEBUG_TYPE, lines));
     }
   }
 }
Ejemplo n.º 7
0
 public synchronized void warn(Throwable t) {
   TeaStackTraceLine[] lines = getTeaStackTraceLines(t);
   if (lines == null) {
     super.warn(t);
   } else {
     if (isEnabled() && isWarnEnabled()) {
       dispatchLogTeaStackTrace(new TeaLogEvent(this, LogEvent.WARN_TYPE, lines));
     }
   }
 }
Ejemplo n.º 8
0
  private void createMemoryLog(Log log) {

    if (log != null) {

      // Create memory log listener.
      mLogEvents = Collections.synchronizedList(new LinkedList<LogEvent>());

      // The maximum number of log events to store in memory.
      final int logEventsMax = mProperties.getInt("log.max", 100);

      log.addRootLogListener(
          new TeaLogListener() {
            public void logMessage(LogEvent e) {
              checkSize();
              mLogEvents.add(e);
            }

            public void logException(LogEvent e) {
              checkSize();
              mLogEvents.add(e);
            }

            public void logTeaStackTrace(TeaLogEvent e) {
              checkSize();
              mLogEvents.add(e);
            }

            private void checkSize() {
              while (mLogEvents.size() >= logEventsMax) {
                mLogEvents.remove(0);
              }
            }
          });

      logVersionInfo(TeaServlet.class, "TeaServlet", log);
      log.info("Copyright (C) 1999-2012 TeaTrove http://teatrove.org");
      logVersionInfo(TemplateLoader.class, "Tea", log);
      log.info("Copyright (C) 1997-2012 TeaTrove http://teatrove.org");
    }
  }
Ejemplo n.º 9
0
  /**
   * Initializes the TeaServlet. Creates the logger and loads the user's application.
   *
   * @param config the servlet config
   */
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    mServletConfig = config;

    config.getServletContext().log("Initializing TeaServlet...");

    String ver = System.getProperty("java.version");
    if (ver.startsWith("0.") || ver.startsWith("1.2") || ver.startsWith("1.3")) {
      config.getServletContext().log("The TeaServlet requires Java 1.4 or higher to run properly");
    }

    mServletContext = setServletContext(config);
    mServletName = setServletName(config);

    mProperties = new PropertyMap();
    mSubstitutions = SubstitutionFactory.getDefaults();
    mResourceFactory = new TeaServletResourceFactory(config.getServletContext(), mSubstitutions);

    Enumeration<?> e = config.getInitParameterNames();
    while (e.hasMoreElements()) {
      String key = (String) e.nextElement();
      String value = SubstitutionFactory.substitute(config.getInitParameter(key));

      if (key.equals("debug")) {
        mDebugEnabled = Boolean.parseBoolean(value);
        continue;
      }

      mProperties.put(key, value);
    }

    loadDefaults();
    discoverProperties();
    createListeners();
    createLog(mServletContext);
    mLog.applyProperties(mProperties.subMap("log"));
    createMemoryLog(mLog);

    mInstrumentationEnabled = mProperties.getBoolean("instrumentation.enabled", true);

    Initializer initializer = new Initializer();
    if (mProperties.getBoolean("startup.background", false)) {
      mInitializer = Executors.newSingleThreadExecutor().submit(initializer);
    } else {
      initializer.call();
    }
  }
Ejemplo n.º 10
0
  private void createLog(final ServletContext context) {

    if (mLog == null) {
      try {
        mLog = (Log) context.getAttribute("org.teatrove.trove.log.Log");
      } catch (ClassCastException e) {
      }

      // Log instance may not be provided, so make a Log that passes
      // messages to standard ServletContext log.
      if (mLog == null) {
        mLog = new Log(getServletName(), null);

        mLog.addLogListener(
            new LogListener() {
              public void logMessage(LogEvent e) {
                String message = e.getMessage();
                if (message != null) {
                  context.log(message);
                }
              }

              public void logException(LogEvent e) {
                String message = e.getMessage();
                Throwable t = e.getException();
                if (t == null) {
                  context.log(message);
                } else {
                  context.log(message, t);
                }
              }
            });
      }
    }

    String fullStackTrace = mProperties.getString("log.fullStackTrace", "false");
    if (!fullStackTrace.equals("true")) {
      mLog = new TeaLog(mLog);
    }
  }
Ejemplo n.º 11
0
 /**
  * @param name
  * @param parent
  */
 public TeaLog(Log parent) {
   super(parent.getName(), parent);
 }
Ejemplo n.º 12
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;
  }
Ejemplo n.º 13
0
 TeaServletEngine getEngine() {
   if (mEngine == null) {
     mLog.debug("the engine aint there");
   }
   return mEngine;
 }