/**
   * Looks up and returns a repository bound in the servlet context of the given filter.
   *
   * @return repository from servlet context
   * @throws RepositoryException if the repository is not available
   */
  public Repository getRepository() throws RepositoryException {
    String name = config.getInitParameter(Repository.class.getName());
    if (name == null) {
      name = Repository.class.getName();
    }

    ServletContext context = config.getServletContext();
    Object repository = context.getAttribute(name);
    if (repository instanceof Repository) {
      return (Repository) repository;
    } else if (repository != null) {
      throw new RepositoryException(
          "Invalid repository: Attribute "
              + name
              + " in servlet context "
              + context.getServletContextName()
              + " is an instance of "
              + repository.getClass().getName());
    } else {
      throw new RepositoryException(
          "Repository not found: Attribute "
              + name
              + " does not exist in servlet context "
              + context.getServletContextName());
    }
  }
예제 #2
0
  protected final void logServerInfo(@Nonnull final ServletContext aSC) {
    // Print Java and Server (e.g. Tomcat) info
    s_aLogger.info(
        "Java "
            + SystemProperties.getJavaVersion()
            + " running '"
            + aSC.getServletContextName()
            + "' on "
            + aSC.getServerInfo()
            + " with "
            + (Runtime.getRuntime().maxMemory() / CGlobal.BYTES_PER_MEGABYTE)
            + "MB max RAM and Servlet API "
            + aSC.getMajorVersion()
            + "."
            + aSC.getMinorVersion());

    // Tell them to use the server VM if possible:
    final EJVMVendor eJVMVendor = EJVMVendor.getCurrentVendor();
    if (eJVMVendor.isSun() && eJVMVendor != EJVMVendor.SUN_SERVER)
      s_aLogger.warn(
          "Consider using the Sun Server Runtime by specifiying '-server' on the commandline!");

    if (SystemProperties.getJavaVersion().startsWith("1.6.0_14"))
      s_aLogger.warn(
          "This Java version is bad for development - breakpoints don't work in the debugger!");

    if (getClass().desiredAssertionStatus())
      s_aLogger.warn("Java assertions are enabled - this should be disabled in production!");
  }
  protected void installExt(ServletContext servletContext, ClassLoader portletClassLoader)
      throws Exception {

    String servletContextName = servletContext.getServletContextName();

    String globalLibDir = PortalUtil.getGlobalLibDir();
    String portalWebDir = PortalUtil.getPortalWebDir();
    String portalLibDir = PortalUtil.getPortalLibDir();
    String pluginWebDir = WebDirDetector.getRootDir(portletClassLoader);

    copyJar(servletContext, globalLibDir, "ext-service");
    copyJar(servletContext, portalLibDir, "ext-impl");
    copyJar(servletContext, portalLibDir, "ext-util-bridges");
    copyJar(servletContext, portalLibDir, "ext-util-java");
    copyJar(servletContext, portalLibDir, "ext-util-taglib");

    mergeWebXml(portalWebDir, pluginWebDir);

    CopyTask.copyDirectory(
        pluginWebDir + "WEB-INF/ext-web/docroot",
        portalWebDir,
        StringPool.BLANK,
        "**/WEB-INF/web.xml",
        true,
        false);

    FileUtil.copyFile(
        pluginWebDir + "WEB-INF/ext-" + servletContextName + ".xml",
        portalWebDir + "WEB-INF/ext-" + servletContextName + ".xml");

    ExtRegistry.registerExt(servletContext);
  }
예제 #4
0
 private static String getServletContextIdentifier(ServletContext context) {
   if (context.getMajorVersion() == 2 && context.getMinorVersion() < 5) {
     return context.getServletContextName();
   } else {
     return context.getContextPath();
   }
 }
예제 #5
0
  /** @return the name of this application */
  public String getServletContextName() {

    if (servletContext.getMajorVersion() == 2 && servletContext.getMinorVersion() <= 4) {
      return servletContext.getServletContextName();
    } else {
      return servletContext.getContextPath();
    }
  }
  /**
   * Called on web application add event if the application contains {@value
   * #GATEIN_CONFIG_RESOURCE} file.
   *
   * @param webApp
   * @param url
   */
  protected void add(final WebApp webApp, final URL url) {

    ServletContext scontext = webApp.getServletContext();
    try {
      /* Validate straight away here before creating the PortalContainerPostInitTask */
      final Document document = GateInResourcesSchemaValidator.validate(url);
      /* Also parse both js and skin resources before creating the PortalContainerPostInitTask */
      final ScriptResources scriptResources =
          new JavascriptConfigParser(scontext, document).parse();
      final List<SkinConfigTask> skinTasks = SkinConfigParser.parse(document);

      /* No exceptions at this point */
      final PortalContainerPostInitTask task =
          new PortalContainerPostInitTask() {
            public void execute(ServletContext scontext, PortalContainer portalContainer) {

              try {

                if (!scriptResources.isEmpty()) {
                  javascriptConfigService.add(scriptResources);
                  scontext.setAttribute(SCRIPT_RESOURCES_ATTR, scriptResources.toImmutable());
                }
                javascriptConfigService.registerContext(webApp);

                if (skinTasks != null && !skinTasks.isEmpty()) {
                  skinService.addSkins(skinTasks, scontext);
                }
                skinService.registerContext(webApp);

              } catch (Exception e) {
                log.error(
                    "Could not register script and skin resources from the context '"
                        + (scontext == null ? "unknown" : scontext.getServletContextName())
                        + "'",
                    e);

                /* try to cleanup if anything went wrong */
                try {
                  remove(webApp);
                } catch (Exception e1) {
                  log.error(
                      "Could not cleanup script and skin resources from the context '"
                          + (scontext == null ? "unknown" : scontext.getServletContextName())
                          + "' after a registration failure",
                      e);
                }
              }
            }
          };
      PortalContainer.addInitTask(scontext, task, portalContainerName);
    } catch (Exception ex) {
      log.error(
          "Could not parse or validate gatein-resources.xml in context '"
              + (scontext == null ? "unknown" : scontext.getServletContextName())
              + "'",
          ex);
    }
  }
  public void throwHotDeployException(HotDeployEvent event, String msg, Throwable t)
      throws HotDeployException {

    ServletContext servletContext = event.getServletContext();

    String servletContextName = servletContext.getServletContextName();

    throw new HotDeployException(msg + servletContextName, t);
  }
  public ContainerConfiguration buildContainerConfiguration(ServletContext servletContext) {
    ContainerConfiguration cc =
        new DefaultContainerConfiguration()
            .setName(servletContext.getServletContextName())
            .setContainerConfigurationURL(buildConfigurationURL(servletContext))
            .setContext(buildContext(servletContext));

    return cc;
  }
예제 #9
0
  @Override
  public void contextInitialized(ServletContextEvent servletContextEvent) {
    ServletContext servletContext = servletContextEvent.getServletContext();
    File homeDir = null;
    if (servletContext.getAttribute("homedir") != null) {
      homeDir = new File((String) servletContext.getAttribute("homedir"));
    }
    if (homeDir == null && servletContext.getInitParameter("homedir") != null) {
      homeDir = new File(servletContext.getInitParameter("homedir"));
    }

    boolean autoMigrate = false;
    if (servletContext.getAttribute("autoMigrate") != null) {
      autoMigrate = (boolean) servletContext.getAttribute("autoMigrate");
    }
    if (autoMigrate == false && servletContext.getInitParameter("autoMigrate") != null) {
      autoMigrate = Boolean.valueOf(servletContext.getInitParameter("autoMigrate"));
    }

    String realPath = servletContext.getRealPath("/");
    if (!realPath.endsWith("/")) {
      realPath = realPath + "/";
    }
    File baseDir = new File(realPath + "www/WEB-INF");
    if (homeDir == null) {
      homeDir = baseDir;
    }
    ResourceFetcher resourceFetcher = new WarResourceFetcher(servletContext, homeDir);
    BimServerConfig config = new BimServerConfig();
    config.setAutoMigrate(autoMigrate);
    config.setHomeDir(homeDir);
    config.setResourceFetcher(resourceFetcher);
    config.setClassPath(makeClassPath(resourceFetcher.getFile("lib")));
    config.setStartEmbeddedWebServer(false);
    bimServer = new BimServer(config);

    Logger LOGGER = LoggerFactory.getLogger(WarServerInitializer.class);
    LOGGER.info("Servlet Context Name: " + servletContext.getServletContextName());

    File file = resourceFetcher.getFile("plugins");
    try {
      bimServer.getPluginManager().loadAllPluginsFromDirectoryOfJars(file);
      bimServer.start();
    } catch (ServerException e) {
      LOGGER.error("", e);
    } catch (DatabaseInitException e) {
      LOGGER.error("", e);
    } catch (BimserverDatabaseException e) {
      LOGGER.error("", e);
    } catch (PluginException e) {
      LOGGER.error("", e);
    } catch (DatabaseRestartRequiredException e) {
      LOGGER.error("", e);
    }
    servletContext.setAttribute("bimserver", bimServer);
  }
예제 #10
0
  /** @see javax.faces.context.ExternalContext#getContextName() */
  public String getContextName() {

    if (servletContext.getMajorVersion() >= 3
        || (servletContext.getMajorVersion() == 2 && servletContext.getMinorVersion() == 5)) {
      return this.servletContext.getServletContextName();
    } else {
      // for servlet 2.4 support
      return servletContext.getServletContextName();
    }
  }
예제 #11
0
  public void contextDestroyed(ServletContextEvent sce) {
    ServletContext context = sce.getServletContext();
    InitFacesContext initContext = null;
    try {
      initContext = new InitFacesContext(context);

      if (webAppListener != null) {
        webAppListener.contextDestroyed(sce);
        webAppListener = null;
      }
      if (webResourcePool != null) {
        webResourcePool.shutdownNow();
      }
      if (!ConfigManager.getInstance().hasBeenInitialized(context)) {
        return;
      }
      GroovyHelper helper = GroovyHelper.getCurrentInstance(context);
      if (helper != null) {
        helper.setClassLoader();
      }
      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(
            Level.FINE, "ConfigureListener.contextDestroyed({0})", context.getServletContextName());
      }

      ELContext elctx = new ELContextImpl(initContext.getApplication().getELResolver());
      elctx.putContext(FacesContext.class, initContext);
      initContext.setELContext(elctx);
      Application app = initContext.getApplication();
      app.publishEvent(initContext, PreDestroyApplicationEvent.class, Application.class, app);

      Util.setNonFacesContextApplicationMap(null);

    } catch (Exception e) {
      if (LOGGER.isLoggable(Level.SEVERE)) {
        LOGGER.log(
            Level.SEVERE,
            "Unexpected exception when attempting to tear down the Mojarra runtime",
            e);
      }
    } finally {
      ApplicationAssociate.clearInstance(initContext.getExternalContext());
      ApplicationAssociate.setCurrentInstance(null);
      com.sun.faces.application.ApplicationImpl.clearInstance(initContext.getExternalContext());
      com.sun.faces.application.InjectionApplicationFactory.clearInstance(
          initContext.getExternalContext());
      // Release the initialization mark on this web application
      ConfigManager.getInstance().destory(context);
      if (initContext != null) {
        initContext.release();
      }
      ReflectionUtils.clearCache(Thread.currentThread().getContextClassLoader());
      WebConfiguration.clear(context);
    }
  }
 /**
  * Show class name and some details that are useful in template-not-found errors.
  *
  * @since 2.3.21
  */
 @Override
 public String toString() {
   return TemplateLoaderUtils.getClassNameForToString(this)
       + "(subdirPath="
       + StringUtil.jQuote(subdirPath)
       + ", servletContext={contextPath="
       + StringUtil.jQuote(getContextPath())
       + ", displayName="
       + StringUtil.jQuote(servletContext.getServletContextName())
       + "})";
 }
  public void contextInitialized(final ServletContextEvent sce) {
    final ServletContext context = sce.getServletContext();

    // create a container if there is none yet
    if (context.getAttribute(PlexusConstants.PLEXUS_KEY) == null) {
      try {
        appContext =
            createContainerContext(
                context, (AppContext) context.getAttribute(AppContext.APPCONTEXT_KEY));

        final ContainerConfiguration plexusConfiguration =
            new DefaultContainerConfiguration()
                .setName(context.getServletContextName())
                .setContainerConfigurationURL(plexusXmlFile.toURI().toURL())
                .setContext((Map) appContext.flatten())
                .setAutoWiring(true)
                .setClassPathScanning(PlexusConstants.SCANNING_INDEX)
                .setComponentVisibility(PlexusConstants.GLOBAL_VISIBILITY);

        final ArrayList<Module> modules = new ArrayList<Module>(2);
        modules.add(new NexusWebModule(sce.getServletContext()));
        modules.add(new AppContextModule(appContext));

        // Add support for @Timed
        modules.add(new TimingModule());

        final Module[] customModules = (Module[]) context.getAttribute(CUSTOM_MODULES);

        if (customModules != null) {
          modules.addAll(Arrays.asList(customModules));
        }

        plexusContainer =
            new DefaultPlexusContainer(
                plexusConfiguration, modules.toArray(new Module[modules.size()]));

        context.setAttribute(PlexusConstants.PLEXUS_KEY, plexusContainer);

        context.setAttribute(AppContext.APPCONTEXT_KEY, appContext);
      } catch (PlexusContainerException e) {
        sce.getServletContext().log("Could not start Plexus container!", e);

        throw new IllegalStateException("Could not start Plexus container!", e);
      } catch (IOException e) {
        sce.getServletContext().log("Could not start Plexus container!", e);

        throw new IllegalStateException("Could not start Plexus container!", e);
      }

      // fire startable
      appContext.getLifecycleManager().invokeHandler(Startable.class);
    }
  }
예제 #14
0
 @GET
 @Path("injection")
 public String getInjection(
     @Context HttpServletRequest request,
     @Context HttpServletResponse response,
     @Context WebConfig webConfig,
     @Context ServletConfig servletConfig,
     @Context ServletContext servletContext) {
   return request.getMethod()
       + (response != null)
       + webConfig.getName()
       + servletConfig.getServletName()
       + servletContext.getServletContextName();
 }
예제 #15
0
  public final void contextDestroyed(@Nonnull final ServletContextEvent aSCE) {
    final ServletContext aSC = aSCE.getServletContext();

    final StopWatch aSW = StopWatch.createdStarted();
    if (s_aLogger.isInfoEnabled())
      s_aLogger.info("Servlet context '" + aSC.getServletContextName() + "' is being destroyed");

    // Callback before global scope end
    beforeContextDestroyed(aSC);

    // Shutdown global scope and destroy all singletons
    WebScopeManager.onGlobalEnd();

    // Callback after global scope end
    afterContextDestroyed(aSC);

    // Handle statistics
    if (isHandleStatisticsOnEnd()) handleStatisticsOnEnd();

    // Reset base path - mainly for testing
    WebFileIO.resetPaths();

    // Clear commons cache also manually - but after destroy because it
    // is used in equals and hashCode implementations
    CommonsCleanup.cleanup();

    // De-init
    s_aInited.set(false);

    if (s_aLogger.isInfoEnabled())
      s_aLogger.info(
          "Servlet context '"
              + aSC.getServletContextName()
              + "' was destroyed in "
              + aSW.stopAndGetMillis()
              + " milli seconds");
  }
 @Override
 public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
     throws IOException, ServletException {
   HttpServletRequest request = (HttpServletRequest) arg0;
   // HttpServletResponse response = (HttpServletResponse) arg1;
   ServletContext servletContext = getServletContext();
   @SuppressWarnings("unused")
   String ctx = servletContext.getServletContextName();
   // TODO Auto-generated method stub
   request.setAttribute("imageDomain", imageDomain);
   request.setAttribute("cssDomain", cssDomain);
   request.setAttribute("jsDomain", jsDomain);
   request.setAttribute("sbglpath", sbglpath);
   request.setAttribute("webbaseurl", webbaseurl);
   request.setAttribute("strutsaction", strutsaction);
   super.doFilter(request, arg1, arg2);
 }
  protected void copyJar(ServletContext servletContext, String dir, String jarName)
      throws Exception {

    String servletContextName = servletContext.getServletContextName();

    String jarFullName = "/WEB-INF/" + jarName + "/" + jarName + ".jar";

    InputStream is = servletContext.getResourceAsStream(jarFullName);

    if (is == null) {
      throw new HotDeployException(jarFullName + " does not exist");
    }

    String newJarFullName = dir + "ext-" + servletContextName + jarName.substring(3) + ".jar";

    StreamUtil.transfer(is, new FileOutputStream(new File(newJarFullName)));
  }
예제 #18
0
  /** Initialisation. */
  @Before
  public void setUp() {
    Utils.initialize();
    try {
      final Field field = MonitoringFilter.class.getDeclaredField("instanceCreated");
      field.setAccessible(true);
      field.set(null, false);
    } catch (final IllegalAccessException e) {
      throw new IllegalStateException(e);
    } catch (final NoSuchFieldException e) {
      throw new IllegalStateException(e);
    }
    final ServletContext parametersContext = createNiceMock(ServletContext.class);
    expect(parametersContext.getMajorVersion()).andReturn(2).anyTimes();
    expect(parametersContext.getMinorVersion()).andReturn(5).anyTimes();
    expect(parametersContext.getContextPath()).andReturn(CONTEXT_PATH).anyTimes();
    expect(parametersContext.getServletContextName()).andReturn("test webapp").anyTimes();
    expect(parametersContext.getServerInfo()).andReturn("mock").anyTimes();
    replay(parametersContext);
    Parameters.initialize(parametersContext);
    verify(parametersContext);

    final ServletConfig config = createNiceMock(ServletConfig.class);
    final ServletContext context = createNiceMock(ServletContext.class);
    expect(config.getServletContext()).andReturn(context).anyTimes();
    // anyTimes sur getInitParameter car TestJdbcDriver a pu fixer la propriété système à false
    expect(
            context.getInitParameter(
                Parameters.PARAMETER_SYSTEM_PREFIX + Parameter.DISABLED.getCode()))
        .andReturn(null)
        .anyTimes();
    expect(config.getInitParameter(Parameter.DISABLED.getCode())).andReturn(null).anyTimes();
    expect(context.getMajorVersion()).andReturn(2).anyTimes();
    expect(context.getMinorVersion()).andReturn(5).anyTimes();
    expect(context.getContextPath()).andReturn(CONTEXT_PATH).anyTimes();
    expect(context.getAttribute(ReportServlet.FILTER_CONTEXT_KEY))
        .andReturn(new FilterContext())
        .anyTimes();
    reportServlet = new ReportServlet();
    replay(config);
    replay(context);
    reportServlet.init(config);
    verify(config);
    verify(context);
  }
  /**
   * Constructs an instance of a PortletWebApplicationImpl from a supplied ui application name and
   * corresponding <code>ServletContext</code>
   *
   * @param webApplicationName the the web application name
   * @param context the <code>ServletContext</code>
   */
  public PortletWebApplicationImpl(String webApplicationName, ServletContext context)
      throws PortletException {
    super(context);
    this.webApplicationName = webApplicationName;
    // get the servlet context for the coreportlets webapp
    String contextURIPath;
    if (webApplicationName.startsWith("/")) {
      contextURIPath = webApplicationName;
      this.webApplicationName = webApplicationName.substring(1);
    } else {
      contextURIPath = "/" + webApplicationName;
    }

    // Get the cross context servlet context
    ServletContext ctx = context.getContext(contextURIPath);
    // System.err.println("contextURIPath: " + contextURIPath);
    // System.err.println("contextName: " + ctx.getServletContextName());
    // System.err.println("context path: " + ctx.getRealPath(""));

    // System.err.println("testing example portlets");
    // ServletContext testsc = context.getContext("/exampleportlets");
    // System.err.println("description: " + ctx.getServletContextName());
    // System.err.println("testing core portlets");
    // testsc = context.getContext("/coreportlets");
    // System.err.println("description: " + testsc.getServletContextName());
    // System.err.println("context path: " + te.getRealPath(""));

    if (ctx == null) {
      log.error(webApplicationName + ": Unable to get ServletContext for: " + contextURIPath);
      throw new PortletException(
          webApplicationName + ": Unable to get ServletContext for: " + contextURIPath);
    }
    log.debug("context path: " + ctx.getRealPath(""));
    this.webAppDescription = ctx.getServletContextName();

    // load portlet.xml
    loadPortlets(ctx, Thread.currentThread().getContextClassLoader());
    // load services xml
    if (!isJSR) loadServices(ctx, Thread.currentThread().getContextClassLoader());
    // load roles.xml
    if (!isJSR) loadRoles(ctx);
    // load group.xml (and if found load layout.xml)
    if (!isJSR) loadGroup(ctx);
  }
예제 #20
0
  private void servletEnv() {
    if (!log.isDebugEnabled()) return;

    try {
      java.net.URL url = servletContext.getResource("/");
      log.trace("Joseki base directory: " + url);
    } catch (Exception ex) {
    }

    if (servletConfig != null) {
      String tmp = servletConfig.getServletName();
      log.trace("Servlet = " + (tmp != null ? tmp : "<null>"));
      @SuppressWarnings("unchecked")
      Enumeration<String> en = servletConfig.getInitParameterNames();

      for (; en.hasMoreElements(); ) {
        String s = en.nextElement();
        log.trace("Servlet parameter: " + s + " = " + servletConfig.getInitParameter(s));
      }
    }
    if (servletContext != null) {
      // Name of webapp
      String tmp = servletContext.getServletContextName();
      // msg(Level.FINE, "Webapp = " + (tmp != null ? tmp : "<null>"));
      log.debug("Webapp = " + (tmp != null ? tmp : "<null>"));

      // NB This servlet may not have been loaded as part of a web app
      @SuppressWarnings("unchecked")
      Enumeration<String> en = servletContext.getInitParameterNames();
      for (; en.hasMoreElements(); ) {
        String s = en.nextElement();
        log.debug("Webapp parameter: " + s + " = " + servletContext.getInitParameter(s));
      }
    }
    /*
    for ( Enumeration enum = servletContext.getAttributeNames() ;  enum.hasMoreElements() ; )
    {
        String s = (String)enum.nextElement() ;
        logger.log(LEVEL, "Webapp attribute: "+s+" = "+context.getAttribute(s)) ;
    }
     */
  }
  @Override
  public String getProperty(String key) {
    String prefix = extractPrefix(key);

    if (!knownParams.contains(prefix == null ? key : prefix)) return null;

    if (prefix == null) {
      if (CONTEXT_ROOT.equals(key)) return servletContext.getRealPath("");
      if (CONTEXT_PATH.equals(key)) return servletContext.getContextPath();
      if (SERVER_INFO.equals(key)) return servletContext.getServerInfo();
      if (SERVLET_CONTEXT_NAME.equals(key)) return servletContext.getServletContextName();
    } else if (CONTEXT_PREFIX.equals(prefix)) {
      key = removePrefix(key);
      String selector = extractPrefix(key);
      key = removePrefix(key);
      if (ATTRIBUTE.equals(selector)) return String.valueOf(servletContext.getAttribute(key));
      if (INIT_PARAM.equals(selector)) return servletContext.getInitParameter(key);
      if (MIME_TYPE.equals(selector)) return servletContext.getMimeType(key);
    }
    return null;
  }
  protected void doInvokeUndeploy(HotDeployEvent hotDeployEvent) throws Exception {

    ServletContext servletContext = hotDeployEvent.getServletContext();

    String servletContextName = servletContext.getServletContextName();

    if (_log.isDebugEnabled()) {
      _log.debug("Invoking undeploy for " + servletContextName);
    }

    String xml =
        HttpUtil.URLtoString(
            servletContext.getResource("/WEB-INF/ext-" + servletContextName + ".xml"));

    if (xml == null) {
      return;
    }

    if (_log.isInfoEnabled()) {
      _log.info("Extension environment for " + servletContextName + " will not be undeployed");
    }
  }
  protected void registerClpMessageListeners(
      ServletContext servletContext, ClassLoader portletClassLoader) throws Exception {

    List<MessageListener> clpMessageListeners =
        (List<MessageListener>) servletContext.getAttribute(WebKeys.CLP_MESSAGE_LISTENERS);

    if (clpMessageListeners != null) {
      return;
    }

    clpMessageListeners = new ArrayList<MessageListener>();

    Set<String> classNames = ServletContextUtil.getClassNames(servletContext);

    for (String className : classNames) {
      if (className.endsWith(".ClpMessageListener")) {
        Class<?> clpMessageListenerClass = portletClassLoader.loadClass(className);

        MessageListener clpMessageListener =
            (MessageListener) clpMessageListenerClass.newInstance();

        String clpServletContextName =
            getClpServletContextName(clpMessageListenerClass, clpMessageListener);

        if (clpServletContextName.equals(servletContext.getServletContextName())) {

          continue;
        }

        clpMessageListeners.add(clpMessageListener);

        MessageBusUtil.registerMessageListener(DestinationNames.HOT_DEPLOY, clpMessageListener);
      }
    }

    servletContext.setAttribute(WebKeys.CLP_MESSAGE_LISTENERS, clpMessageListeners);
  }
예제 #24
0
 /**
  * Prepare text.
  *
  * @param request The HTTP request
  * @return Builder of text
  */
 private StringBuilder text(final HttpServletRequest request) {
   final StringBuilder text = new StringBuilder();
   text.append(Logger.format("date: %s\n", new Date()));
   this.append(text, request, "code");
   this.append(text, request, "message");
   this.append(text, request, "exception_type");
   this.append(text, request, "request_uri");
   final ServletContext ctx = this.getServletContext();
   text.append(Logger.format("servlet context path: \"%s\"\n", request.getContextPath()));
   text.append(
       Logger.format(
           "requested: %s (%s) at %s:%d\n",
           request.getRequestURL().toString(),
           request.getMethod(),
           request.getServerName(),
           request.getServerPort()));
   text.append(
       Logger.format(
           "request: %s, %d bytes\n", request.getContentType(), request.getContentLength()));
   text.append(
       Logger.format(
           "remote: %s:%d (%s)\n",
           request.getRemoteAddr(), request.getRemotePort(), request.getRemoteHost()));
   text.append(
       Logger.format(
           "servlet: \"%s\" (API %d.%d) at \"%s\"\n",
           ctx.getServletContextName(),
           ctx.getMajorVersion(),
           ctx.getMinorVersion(),
           ctx.getServerInfo()));
   text.append("headers:\n").append(ExceptionTrap.headers(request)).append('\n');
   text.append(
       Logger.format(
           "exception: %[exception]s\n", request.getAttribute("javax.servlet.error.exception")));
   return text;
 }
예제 #25
0
  public final void contextInitialized(@Nonnull final ServletContextEvent aSCE) {
    final ServletContext aSC = aSCE.getServletContext();

    if (s_aInited.getAndSet(true))
      throw new IllegalStateException("WebAppListener was already instantiated!");

    final StopWatch aSW = StopWatch.createdStarted();
    m_aInitializationStartDT = PDTFactory.getCurrentLocalDateTime();

    // set global debug/trace mode
    final boolean bDebugMode = StringParser.parseBool(getInitParameterDebug(aSC));
    final boolean bProductionMode = StringParser.parseBool(getInitParameterProduction(aSC));
    GlobalDebug.setDebugModeDirect(bDebugMode);
    GlobalDebug.setProductionModeDirect(bProductionMode);

    final boolean bNoStartupInfo = StringParser.parseBool(getInitParameterNoStartupInfo(aSC));
    if (!bNoStartupInfo) {
      // Requires the global debug things to be present
      logStartupInfo(aSC);
    }

    // StaticServerInfo
    {
      final String sInitParameter = getInitParameterServerURL(aSC, bProductionMode);
      if (StringHelper.hasText(sInitParameter)) {
        final URL aURL = URLHelper.getAsURL(sInitParameter);
        if (aURL != null) {
          StaticServerInfo.init(
              aURL.getProtocol(), aURL.getHost(), aURL.getPort(), aSC.getContextPath());
        } else
          s_aLogger.error(
              "The init-parameter for the server URL"
                  + (bProductionMode ? " (production mode)" : " (non-production mode)")
                  + "contains the non-URL value '"
                  + sInitParameter
                  + "'");
      }
    }

    // Call callback
    beforeContextInitialized(aSC);

    // begin global context
    WebScopeManager.onGlobalBegin(aSC);

    // Init IO
    initPaths(aSC);

    // Set persistent ID provider - must be done after IO is setup
    initGlobalIDFactory();

    // Callback
    afterContextInitialized(aSC);

    // Remember end time
    m_aInitializationEndDT = PDTFactory.getCurrentLocalDateTime();

    // Finally
    if (s_aLogger.isInfoEnabled())
      s_aLogger.info(
          "Servlet context '"
              + aSC.getServletContextName()
              + "' was initialized in "
              + aSW.stopAndGetMillis()
              + " milli seconds");
  }
예제 #26
0
 public String getContextName() {
   return servletContext.getServletContextName();
 }
예제 #27
0
 @Override
 public String getServletContextName() {
   return proxy.getServletContextName();
 }
예제 #28
0
  /**
   * Place this filter into service.
   *
   * @param filterConfig The filter configuration object
   */
  public void init(FilterConfig filterConfig) throws ServletException {
    // capture the servlet context for later user
    m_servletContext = filterConfig.getServletContext();

    if (filterConfig.getInitParameter(CONFIG_SESSION) != null) {
      String s = filterConfig.getInitParameter(CONFIG_SESSION);
      if ("container".equalsIgnoreCase(s)) {
        m_sakaiHttpSession = CONTAINER_SESSION;
      } else if ("sakai".equalsIgnoreCase(s)) {
        m_sakaiHttpSession = SAKAI_SESSION;
      } else if ("context".equalsIgnoreCase(s)) {
        m_sakaiHttpSession = CONTEXT_SESSION;
      } else if ("tool".equalsIgnoreCase(s)) {
        m_sakaiHttpSession = TOOL_SESSION;
      } else {
        M_log.warn(
            "invalid "
                + CONFIG_SESSION
                + " setting ("
                + s
                + "): not one of container, sakai, context, tool");
      }
    }

    if (filterConfig.getInitParameter(CONFIG_REMOTE_USER) != null) {
      m_sakaiRemoteUser =
          Boolean.valueOf(filterConfig.getInitParameter(CONFIG_REMOTE_USER)).booleanValue();
    }

    if (filterConfig.getInitParameter(CONFIG_TOOL_PLACEMENT) != null) {
      m_toolPlacement =
          Boolean.valueOf(filterConfig.getInitParameter(CONFIG_TOOL_PLACEMENT)).booleanValue();
    }

    if (filterConfig.getInitParameter(CONFIG_CONTEXT) != null) {
      m_contextId = filterConfig.getInitParameter(CONFIG_CONTEXT);
    } else {
      m_contextId = m_servletContext.getServletContextName();
      if (m_contextId == null) {
        m_contextId = toString();
      }
    }

    if (filterConfig.getInitParameter(CONFIG_CHARACTER_ENCODING) != null) {
      m_characterEncoding = filterConfig.getInitParameter(CONFIG_CHARACTER_ENCODING);
    }

    if (filterConfig.getInitParameter(CONFIG_CHARACTER_ENCODING_ENABLED) != null) {
      m_characterEncodingEnabled =
          Boolean.valueOf(filterConfig.getInitParameter(CONFIG_CHARACTER_ENCODING_ENABLED))
              .booleanValue();
    }

    if (filterConfig.getInitParameter(CONFIG_UPLOAD_ENABLED) != null) {
      m_uploadEnabled =
          Boolean.valueOf(filterConfig.getInitParameter(CONFIG_UPLOAD_ENABLED)).booleanValue();
    }

    // get the maximum allowed upload size from the system property - use if not overriden, and also
    // use as the ceiling if that
    // is not defined.
    if (System.getProperty(SYSTEM_UPLOAD_MAX) != null) {
      m_uploadMaxSize =
          Long.valueOf(System.getProperty(SYSTEM_UPLOAD_MAX)).longValue() * 1024L * 1024L;
      m_uploadCeiling = m_uploadMaxSize;
    }

    // if the maximum allowed upload size is configured on the filter, it overrides the system
    // property
    if (filterConfig.getInitParameter(CONFIG_UPLOAD_MAX) != null) {
      m_uploadMaxSize =
          Long.valueOf(filterConfig.getInitParameter(CONFIG_UPLOAD_MAX)).longValue()
              * 1024L
              * 1024L;
    }

    // get the upload max ceiling that limits any other upload max, if defined
    if (System.getProperty(SYSTEM_UPLOAD_CEILING) != null) {
      m_uploadCeiling =
          Long.valueOf(System.getProperty(SYSTEM_UPLOAD_CEILING)).longValue() * 1024L * 1024L;
    }

    // get the system wide settin, if present, for the temp dir
    if (System.getProperty(SYSTEM_UPLOAD_DIR) != null) {
      m_uploadTempDir = System.getProperty(SYSTEM_UPLOAD_DIR);
    }

    // override with our configuration for temp dir, if set
    if (filterConfig.getInitParameter(CONFIG_UPLOAD_DIR) != null) {
      m_uploadTempDir = filterConfig.getInitParameter(CONFIG_UPLOAD_DIR);
    }

    if (filterConfig.getInitParameter(CONFIG_UPLOAD_THRESHOLD) != null) {
      m_uploadThreshold =
          Integer.valueOf(filterConfig.getInitParameter(CONFIG_UPLOAD_THRESHOLD)).intValue();
    }

    if (filterConfig.getInitParameter(CONFIG_CONTINUE) != null) {
      m_uploadContinue =
          Boolean.valueOf(filterConfig.getInitParameter(CONFIG_CONTINUE)).booleanValue();
    }

    if (filterConfig.getInitParameter(CONFIG_MAX_PER_FILE) != null) {
      m_uploadMaxPerFile =
          Boolean.valueOf(filterConfig.getInitParameter(CONFIG_MAX_PER_FILE)).booleanValue();
    }

    // Note: if set to continue processing max exceeded uploads, we only support per-file max, not
    // overall max
    if (m_uploadContinue && !m_uploadMaxPerFile) {
      M_log.warn(
          "overridding "
              + CONFIG_MAX_PER_FILE
              + " setting: must be 'true' with "
              + CONFIG_CONTINUE
              + " ='true'");
      m_uploadMaxPerFile = true;
    }
  }
예제 #29
0
  public void afterPropertiesSet() {

    // ToDo Instead of stdout, use servletContext.log( "...") [NOTE: it writes to localhost.*.log
    // rather than catalina.out].
    if (servletContext == null)
      throw new IllegalArgumentException("ServletContext must not be null.");

    // ToDo LOOK - Are we still using this.
    ServletUtil.initDebugging(servletContext);

    // Set the webapp name.
    this.webappName = servletContext.getServletContextName();

    // Set the context path.
    // Servlet 2.5 allows the following.
    // contextPath = servletContext.getContextPath();
    String tmpContextPath =
        servletContext.getInitParameter(
            "ContextPath"); // cannot be overridden in the ThreddsConfig file
    if (tmpContextPath == null) tmpContextPath = "thredds";
    contextPath = "/" + tmpContextPath;
    // ToDo LOOK - Get rid of need for setting contextPath in ServletUtil.
    ServletUtil.setContextPath(contextPath);

    // Set the root directory and source.
    String rootPath = servletContext.getRealPath("/");
    if (rootPath == null) {
      String msg =
          "Webapp ["
              + this.webappName
              + "] must run with exploded deployment directory (not from .war).";
      System.out.println("ERROR - TdsContext.init(): " + msg);
      // logServerStartup.error( "TdsContext.init(): " + msg );
      throw new IllegalStateException(msg);
    }
    this.rootDirectory = new File(rootPath);
    this.rootDirSource = new BasicDescendantFileSource(this.rootDirectory);
    this.rootDirectory = this.rootDirSource.getRootDirectory();
    // ToDo LOOK - Get rid of need for setting rootPath in ServletUtil.
    ServletUtil.setRootPath(this.rootDirSource.getRootDirectoryPath());

    // Set the startup (initial install) content directory and source.
    this.startupContentDirectory = new File(this.rootDirectory, this.startupContentPath);
    this.startupContentDirSource = new BasicDescendantFileSource(this.startupContentDirectory);
    this.startupContentDirectory = this.startupContentDirSource.getRootDirectory();

    this.webinfPath = this.rootDirectory + "/WEB-INF";

    // set the tomcat logging directory
    try {
      String base = System.getProperty("catalina.base");
      if (base != null) {
        this.tomcatLogDir = new File(base, "logs").getCanonicalFile();
        if (!this.tomcatLogDir.exists()) {
          String msg = "'catalina.base' directory not found";
          System.out.println("WARN - TdsContext.init(): " + msg);
          // logServerStartup.error( "TdsContext.init(): " + msg );
        }
      } else {
        String msg = "'catalina.base' property not found - probably not a tomcat server";
        System.out.println("WARN - TdsContext.init(): " + msg);
        // logServerStartup.warn( "TdsContext.init(): " + msg );
      }

    } catch (IOException e) {
      String msg = "tomcatLogDir could not be created";
      System.out.println("WARN - TdsContext.init(): " + msg);
      // logServerStartup.error( "TdsContext.init(): " + msg );
    }

    // Set the content directory and source.
    File contentRootDir = new File(this.contentRootPath);
    if (!contentRootDir.isAbsolute())
      this.contentDirectory =
          new File(new File(this.rootDirectory, this.contentRootPath), this.contentPath);
    else {
      if (contentRootDir.isDirectory())
        this.contentDirectory = new File(contentRootDir, this.contentPath);
      else {
        String msg = "Content root directory [" + this.contentRootPath + "] not a directory.";
        System.out.println("ERROR - TdsContext.init(): " + msg);
        // logServerStartup.error( "TdsContext.init(): " + msg );
        throw new IllegalStateException(msg);
      }
    }
    // If the content directory doesn't exist, try to copy startup content directory.
    if (!this.contentDirectory.exists()) {
      try {
        IO.copyDirTree(this.startupContentDirectory.getPath(), this.contentDirectory.getPath());
      } catch (IOException e) {
        String tmpMsg = "Content directory does not exist and could not be created";
        System.out.println(
            "ERROR - TdsContext.init(): "
                + tmpMsg
                + " ["
                + this.contentDirectory.getAbsolutePath()
                + "].");
        // logServerStartup.error( "TdsContext.init(): " + tmpMsg + " [" +
        // this.contentDirectory.getAbsolutePath() + "]" );
        throw new IllegalStateException(tmpMsg);
      }
    }

    // If content directory exists, make sure it is a directory.
    if (this.contentDirectory.isDirectory()) {
      this.contentDirSource =
          new BasicDescendantFileSource(
              StringUtils.cleanPath(this.contentDirectory.getAbsolutePath()));
      this.contentDirectory = this.contentDirSource.getRootDirectory();
    } else {
      String tmpMsg = "Content directory not a directory";
      System.out.println(
          "ERROR - TdsContext.init(): "
              + tmpMsg
              + " ["
              + this.contentDirectory.getAbsolutePath()
              + "].");
      // logServerStartup.error( "TdsContext.init(): " + tmpMsg + " [" +
      // this.contentDirectory.getAbsolutePath() + "]" );
      throw new IllegalStateException(tmpMsg);
    }
    ServletUtil.setContentPath(this.contentDirSource.getRootDirectoryPath());

    File logDir = new File(this.contentDirectory, "logs");
    if (!logDir.exists()) {
      if (!logDir.mkdirs()) {
        String msg = "Couldn't create TDS log directory [" + logDir.getPath() + "].";
        // System.out.println( "ERROR - TdsContext.init(): " + msg);
        logServerStartup.error("TdsContext.init(): " + msg);
        throw new IllegalStateException(msg);
      }
    }
    String loggingDirectory = StringUtil2.substitute(logDir.getPath(), "\\", "/");
    System.setProperty("tds.log.dir", loggingDirectory); // variable substitution

    // LOOK Remove log4j init JC 6/13/2012
    // which is used in log4j.xml file loaded here.
    Log4jWebConfigurer.initLogging(servletContext);
    logServerStartup.info("TdsConfigContextListener.contextInitialized() start[2]: ");
    logServerStartup.info("TdsContext.init()  intializating logging...");

    // read in persistent user-defined params from threddsConfig.xml
    File tdsConfigFile = this.contentDirSource.getFile(this.getTdsConfigFileName());
    String tdsConfigFilename = tdsConfigFile != null ? tdsConfigFile.getPath() : "";
    ThreddsConfig.init(tdsConfigFilename);

    this.publicContentDirectory = new File(this.contentDirectory, "public");
    if (!publicContentDirectory.exists()) {
      if (!publicContentDirectory.mkdirs()) {
        String msg =
            "Couldn't create TDS public directory [" + publicContentDirectory.getPath() + "].";
        // System.out.println( "ERROR - TdsContext.init(): " + msg);
        logServerStartup.error("TdsContext.init(): " + msg);
        throw new IllegalStateException(msg);
      }
    }
    this.publicContentDirSource = new BasicDescendantFileSource(this.publicContentDirectory);

    this.iddContentDirectory = new File(this.rootDirectory, this.iddContentPath);
    this.iddContentPublicDirSource = new BasicDescendantFileSource(this.iddContentDirectory);

    this.motherlodeContentDirectory = new File(this.rootDirectory, this.motherlodeContentPath);
    this.motherlodeContentPublicDirSource =
        new BasicDescendantFileSource(this.motherlodeContentDirectory);

    List<DescendantFileSource> chain = new ArrayList<DescendantFileSource>();
    DescendantFileSource contentMinusPublicSource =
        new BasicWithExclusionsDescendantFileSource(
            this.contentDirectory, Collections.singletonList("public"));
    chain.add(contentMinusPublicSource);
    for (String curContentRoot : ThreddsConfig.getContentRootList()) {
      if (curContentRoot.equalsIgnoreCase("idd")) chain.add(this.iddContentPublicDirSource);
      else if (curContentRoot.equalsIgnoreCase("motherlode"))
        chain.add(this.motherlodeContentPublicDirSource);
      else {
        try {
          chain.add(new BasicDescendantFileSource(StringUtils.cleanPath(curContentRoot)));
        } catch (IllegalArgumentException e) {
          String msg = "Couldn't add content root [" + curContentRoot + "]: " + e.getMessage();
          // System.out.println( "WARN - TdsContext.init(): " + msg );
          logServerStartup.warn("TdsContext.init(): " + msg, e);
        }
      }
    }
    this.configSource = new ChainedFileSource(chain);
    this.publicDocSource = this.publicContentDirSource;

    // ToDo LOOK Find a better way once thredds.catalog2 is used.
    InvDatasetScan.setContext(contextPath);
    InvDatasetScan.setCatalogServletName("/catalog");
    InvDatasetFeatureCollection.setContext(contextPath);
    // GridServlet.setContextPath( contextPath ); // Won't need when switch GridServlet to use Swing
    // MVC and TdsContext

    jspRequestDispatcher = servletContext.getNamedDispatcher("jsp");
    defaultRequestDispatcher = servletContext.getNamedDispatcher("default");

    TdsConfigMapper tdsConfigMapper = new TdsConfigMapper();
    tdsConfigMapper.setTdsServerInfo(this.serverInfo);
    tdsConfigMapper.setHtmlConfig(this.htmlConfig);
    tdsConfigMapper.setWmsConfig(this.wmsConfig);
    tdsConfigMapper.init(this);
  }
  protected void doInvokeDeploy(HotDeployEvent hotDeployEvent) throws Exception {

    ServletContext servletContext = hotDeployEvent.getServletContext();

    String servletContextName = servletContext.getServletContextName();

    if (_log.isDebugEnabled()) {
      _log.debug("Invoking deploy for " + servletContextName);
    }

    String xml =
        HttpUtil.URLtoString(
            servletContext.getResource("/WEB-INF/ext-" + servletContextName + ".xml"));

    if (xml == null) {
      return;
    }

    if (_log.isInfoEnabled()) {
      _log.info("Registering extension environment for " + servletContextName);
    }

    if (ExtRegistry.isRegistered(servletContextName)) {
      if (_log.isInfoEnabled()) {
        _log.info("Extension environment for " + servletContextName + " has been applied.");
      }

      return;
    }

    Map<String, Set<String>> conflicts = ExtRegistry.getConflicts(servletContext);

    if (!conflicts.isEmpty()) {
      StringBundler sb = new StringBundler();

      sb.append(
          "Extension environment for "
              + servletContextName
              + " cannot be applied because of detected conflicts:");

      for (Map.Entry<String, Set<String>> entry : conflicts.entrySet()) {
        String conflictServletContextName = entry.getKey();
        Set<String> conflictFiles = entry.getValue();

        sb.append("\n\t");
        sb.append(conflictServletContextName);
        sb.append(":");

        for (String conflictFile : conflictFiles) {
          sb.append("\n\t\t");
          sb.append(conflictFile);
        }
      }

      _log.error(sb.toString());

      return;
    }

    installExt(servletContext, hotDeployEvent.getContextClassLoader());

    FileAvailabilityUtil.reset();

    if (_log.isInfoEnabled()) {
      _log.info(
          "Extension environment for "
              + servletContextName
              + " has been applied. You must reboot the server and "
              + "redeploy all other plugins.");
    }
  }