List of usage examples for javax.servlet ServletConfig getServletContext
public ServletContext getServletContext();
From source file:net.sf.appstatus.web.StatusServlet.java
/** * Init the AppStatus Web UI./*from w w w . jav a 2 s . c om*/ * <p> * Read <b>bean</> init parameter. If defined, switch to Spring-enabled * behavior. */ @Override public void init(ServletConfig config) throws ServletException { super.init(config); super.init(); SpringObjectInstantiationListener instantiation = null; String beanName = getInitParameter("bean"); String[] pagesBeanNames = StringUtils.split(getInitParameter("custom-pages"), ", "); Map<String, IPage> pages = new LinkedHashMap<String, IPage>(); ; AppStatus status; if (beanName != null) { // Using Spring instantiation = new SpringObjectInstantiationListener(this.getServletContext()); // Status status = (AppStatus) instantiation.getInstance(beanName); } else { status = AppStatusStatic.getInstance(); } status.setServletContextProvider(new IServletContextProvider() { public ServletContext getServletContext() { return StatusServlet.this.getServletContext(); } }); // // Pages addPage(pages, new StatusPage()); if (status.getServiceManager() != null) { addPage(pages, new ServicesPage()); } if (status.getBatchManager() != null) { addPage(pages, new BatchPage()); } if (status.getLoggersManager() != null) { addPage(pages, new LoggersPage()); } // Custom pages if (pagesBeanNames != null) { for (String pageBean : pagesBeanNames) { IPage newPage = null; if (instantiation != null) { newPage = (IPage) instantiation.getInstance(pageBean); if (newPage == null) { try { newPage = (IPage) Thread.currentThread().getContextClassLoader().loadClass(pageBean) .newInstance(); } catch (ClassNotFoundException e) { logger.warn("Class {} not found ", pageBean, e); } catch (InstantiationException e) { logger.warn("Cannot instanciate {} ", pageBean, e); } catch (IllegalAccessException e) { logger.warn("Cannot access class {} for instantiation ", pageBean, e); } } } addPage(pages, newPage); } } // Radiator at the end. addPage(pages, new RadiatorPage()); // Init statusWeb = new StatusWebHandler(); statusWeb.setAppStatus(status); statusWeb.setApplicationName( StringUtils.defaultString(config.getServletContext().getServletContextName(), "No name")); statusWeb.setPages(pages); statusWeb.init(); }
From source file:org.sakaiproject.blti.ProviderServlet.java
@Override public void init(ServletConfig config) throws ServletException { super.init(config); siteEmailPreferenceSetter = (SiteEmailPreferenceSetter) ComponentManager.getInstance() .get("org.sakaiproject.lti.api.SiteEmailPreferenceSetter"); if (siteEmailPreferenceSetter == null) { throw new ServletException("Failed to set siteEmailPreferenceSetter."); }/*www . j av a 2 s . c o m*/ siteMembershipUpdater = (SiteMembershipUpdater) ComponentManager.getInstance() .get("org.sakaiproject.lti.api.SiteMembershipUpdater"); if (siteMembershipUpdater == null) { throw new ServletException("Failed to set siteMembershipUpdater."); } siteMembershipsSynchroniser = (SiteMembershipsSynchroniser) ComponentManager.getInstance() .get("org.sakaiproject.lti.api.SiteMembershipsSynchroniser"); if (siteMembershipsSynchroniser == null) { throw new ServletException("Failed to set siteMembershipsSynchroniser."); } userFinderOrCreator = (UserFinderOrCreator) ComponentManager.getInstance() .get("org.sakaiproject.lti.api.UserFinderOrCreator"); if (userFinderOrCreator == null) { throw new ServletException("Failed to set userFinderOrCreator."); } userPictureSetter = (UserPictureSetter) ComponentManager.getInstance() .get("org.sakaiproject.lti.api.UserPictureSetter"); if (userPictureSetter == null) { throw new ServletException("Failed to set userPictureSettter."); } userLocaleSetter = (UserLocaleSetter) ComponentManager.getInstance() .get("org.sakaiproject.lti.api.UserLocaleSetter"); if (userLocaleSetter == null) { throw new ServletException("Failed to set userLocaleSettter."); } ltiService = (LTIService) ComponentManager.getInstance().get("org.sakaiproject.lti.api.LTIService"); if (ltiService == null) { throw new ServletException("Failed to set ltiService."); } ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext()); // load all instance of BLTIProcessor in component mgr by type detection Collection processors = ac.getParent().getBeansOfType(BLTIProcessor.class).values(); bltiProcessors = new ArrayList(processors); // sort in using getOrder() method // sort them so the execution order is determined consistenly - by getOrder() Collections.sort(bltiProcessors, new Comparator() { public int compare(Object o1, Object o2) { return ((Comparable) ((BLTIProcessor) (o1)).getOrder()) .compareTo(((BLTIProcessor) (o2)).getOrder()); } }); }
From source file:com.acciente.induction.dispatcher.HttpDispatcher.java
/** * This method is called by the webcontainer to initialize this servlet * * @param oServletConfig web container-provided access to this servlet's configuration * @throws javax.servlet.ServletException *//*from w w w . j a v a 2 s . c om*/ public void init(ServletConfig oServletConfig) throws ServletException { super.init(oServletConfig); // first setup a logger _oLog = LogFactory.getLog(HttpDispatcher.class); Config oConfig; // load the configuration for the dispatcher try { oConfig = ConfigLoaderInitializer.getConfigLoader(oServletConfig).getConfig(); //System.out.println( "config: \n" + oConfig ); } catch (ClassNotFoundException e) { throw new ServletException("init-error: config-loader-initializer", e); } catch (InvocationTargetException e) { throw new ServletException("init-error: config-loader-initializer", e); } catch (IllegalAccessException e) { throw new ServletException("init-error: config-loader-initializer", e); } catch (InstantiationException e) { throw new ServletException("init-error: config-loader-initializer", e); } catch (ConstructorNotFoundException e) { throw new ServletException("init-error: config-loader-initializer", e); } catch (ParameterProviderException e) { throw new ServletException("init-error: config-loader-initializer", e); } catch (ConfigLoaderException e) { throw new ServletException("init-error: config-loader", e); } // setup up our classloader ClassLoader oClassLoader; try { oClassLoader = ClassLoaderInitializer.getClassLoader(oConfig.getJavaClassPath(), getClass().getClassLoader()); } catch (ClassNotFoundException e) { throw new ServletException("init-error: class-loader-initializer", e); } // we setup the model factory and pool managers early since we now support inject models // into the initializers for the templating engine, controller resolver, view resolver and // redirect resolver ModelFactory oModelFactory = new ModelFactory(oClassLoader, oServletConfig, oConfig.getFileUpload()); ModelPool oModelPool; try { oModelPool = new ModelPool(oConfig.getModelDefs(), oModelFactory, oServletConfig.getServletContext()); } catch (MethodNotFoundException e) { throw new ServletException("init-error: model-pool", e); } catch (InvocationTargetException e) { throw new ServletException("init-error: model-pool", e); } catch (ClassNotFoundException e) { throw new ServletException("init-error: model-pool", e); } catch (ConstructorNotFoundException e) { throw new ServletException("init-error: model-pool", e); } catch (ParameterProviderException e) { throw new ServletException("init-error: model-pool", e); } catch (IllegalAccessException e) { throw new ServletException("init-error: model-pool", e); } catch (InstantiationException e) { throw new ServletException("init-error: model-pool", e); } // now set the pool for the model factory to use in model-to-model injection oModelFactory.setModelPool(oModelPool); // we instantiate the templating engine early since we now support injecting the // TemplatingEngine instance into models TemplatingEngine oTemplatingEngine; try { oTemplatingEngine = TemplatingEngineInitializer.getTemplatingEngine(oConfig.getTemplating(), oModelPool, oClassLoader, oServletConfig); } catch (IOException e) { throw new ServletException("init-error: templating-engine-initializer", e); } catch (ClassNotFoundException e) { throw new ServletException("init-error: templating-engine-initializer", e); } catch (InvocationTargetException e) { throw new ServletException("init-error: templating-engine-initializer", e); } catch (IllegalAccessException e) { throw new ServletException("init-error: templating-engine-initializer", e); } catch (InstantiationException e) { throw new ServletException("init-error: templating-engine-initializer", e); } catch (ConstructorNotFoundException e) { throw new ServletException("init-error: templating-engine-initializer", e); } catch (ParameterProviderException e) { throw new ServletException("init-error: templating-engine-initializer", e); } // after the templating engine is setup is we set the templating engine in the model factory, // to make it available to models or any of the other classes that can request it oModelFactory.setTemplatingEngine(oTemplatingEngine); // pre-initialize any app scope models that requested it Log oLog = LogFactory.getLog(ModelPool.class); for (Iterator oIter = oConfig.getModelDefs().getModelDefList().iterator(); oIter.hasNext();) { Config.ModelDefs.ModelDef oModelDef = (Config.ModelDefs.ModelDef) oIter.next(); if (oModelDef.isApplicationScope() && oModelDef.isInitOnStartUp()) { oLog.info("model-pool: initializing model: " + oModelDef.getModelClassName()); try { oModelPool.initAppModel(oModelDef.getModelClassName()); } catch (MethodNotFoundException e) { throw new ServletException("init-error: model-init-on-startup", e); } catch (InvocationTargetException e) { throw new ServletException("init-error: model-init-on-startup", e); } catch (ClassNotFoundException e) { throw new ServletException("init-error: model-init-on-startup", e); } catch (ConstructorNotFoundException e) { throw new ServletException("init-error: model-init-on-startup", e); } catch (ParameterProviderException e) { throw new ServletException("init-error: model-init-on-startup", e); } catch (IllegalAccessException e) { throw new ServletException("init-error: model-init-on-startup", e); } catch (InstantiationException e) { throw new ServletException("init-error: model-init-on-startup", e); } } } // setup the interceptor chain try { RequestInterceptor[] oRequestInterceptorArray; oRequestInterceptorArray = RequestInterceptorInitializer.getRequestInterceptor( oConfig.getRequestInterceptors(), oModelPool, oClassLoader, oServletConfig); _oRequestInterceptorExecutor = new RequestInterceptorExecutor(oRequestInterceptorArray, new RequestInterceptorParameterProviderFactory(oModelPool, oConfig.getFileUpload(), oTemplatingEngine, oClassLoader)); } catch (ClassNotFoundException e) { throw new ServletException("init-error: request-interceptor-initializer", e); } catch (InvocationTargetException e) { throw new ServletException("init-error: request-interceptor-initializer", e); } catch (IllegalAccessException e) { throw new ServletException("init-error: request-interceptor-initializer", e); } catch (InstantiationException e) { throw new ServletException("init-error: request-interceptor-initializer", e); } catch (ConstructorNotFoundException e) { throw new ServletException("init-error: request-interceptor-initializer", e); } catch (ParameterProviderException e) { throw new ServletException("init-error: request-interceptor-initializer", e); } // setup a resolver that maps a request to a controller try { ControllerResolver oControllerResolver; oControllerResolver = ControllerResolverInitializer.getControllerResolver( oConfig.getControllerResolver(), oConfig.getControllerMapping(), oModelPool, oClassLoader, oServletConfig); _oControllerResolverExecutor = new ControllerResolverExecutor(oControllerResolver, new ControllerResolverParameterProviderFactory(oModelPool, oConfig.getFileUpload(), oClassLoader)); } catch (ClassNotFoundException e) { throw new ServletException("init-error: controller-resolver-initializer", e); } catch (InvocationTargetException e) { throw new ServletException("init-error: controller-resolver-initializer", e); } catch (IllegalAccessException e) { throw new ServletException("init-error: controller-resolver-initializer", e); } catch (InstantiationException e) { throw new ServletException("init-error: controller-resolver-initializer", e); } catch (ConstructorNotFoundException e) { throw new ServletException("init-error: controller-resolver-initializer", e); } catch (ParameterProviderException e) { throw new ServletException("init-error: controller-resolver-initializer", e); } catch (IOException e) { throw new ServletException("init-error: controller-resolver-initializer", e); } catch (MethodNotFoundException e) { throw new ServletException("init-error: controller-resolver-initializer", e); } // setup a resolver that maps a request to a view try { ViewResolver oViewResolver; oViewResolver = ViewResolverInitializer.getViewResolver(oConfig.getViewResolver(), oConfig.getViewMapping(), oModelPool, oClassLoader, oServletConfig); _oViewResolverExecutor = new ViewResolverExecutor(oViewResolver, new ViewResolverParameterProviderFactory(oModelPool, oConfig.getFileUpload(), oClassLoader)); } catch (ClassNotFoundException e) { throw new ServletException("init-error: view-resolver-initializer", e); } catch (InvocationTargetException e) { throw new ServletException("init-error: view-resolver-initializer", e); } catch (IllegalAccessException e) { throw new ServletException("init-error: view-resolver-initializer", e); } catch (InstantiationException e) { throw new ServletException("init-error: view-resolver-initializer", e); } catch (ConstructorNotFoundException e) { throw new ServletException("init-error: view-resolver-initializer", e); } catch (ParameterProviderException e) { throw new ServletException("init-error: view-resolver-initializer", e); } catch (IOException e) { throw new ServletException("init-error: view-resolver-initializer", e); } catch (MethodNotFoundException e) { throw new ServletException("init-error: view-resolver-initializer", e); } // setup a resolver that maps a redirect to a URL try { RedirectResolver oRedirectResolver; oRedirectResolver = RedirectResolverInitializer.getRedirectResolver(oConfig.getRedirectResolver(), oConfig.getRedirectMapping(), oModelPool, oClassLoader, oServletConfig); _oRedirectResolverExecutor = new RedirectResolverExecutor(oRedirectResolver, new RedirectResolverParameterProviderFactory(oModelPool, oConfig.getFileUpload(), oClassLoader)); } catch (ClassNotFoundException e) { throw new ServletException("init-error: redirect-resolver-initializer", e); } catch (InvocationTargetException e) { throw new ServletException("init-error: redirect-resolver-initializer", e); } catch (IllegalAccessException e) { throw new ServletException("init-error: redirect-resolver-initializer", e); } catch (InstantiationException e) { throw new ServletException("init-error: redirect-resolver-initializer", e); } catch (ConstructorNotFoundException e) { throw new ServletException("init-error: redirect-resolver-initializer", e); } catch (ParameterProviderException e) { throw new ServletException("init-error: redirect-resolver-initializer", e); } catch (IOException e) { throw new ServletException("init-error: redirect-resolver-initializer", e); } catch (MethodNotFoundException e) { throw new ServletException("init-error: redirect-resolver-initializer", e); } // tell the model pool of the redirect resolver, so that models can now request it oModelFactory.setRedirectResolver(_oRedirectResolverExecutor); // the ControllerPool manages a pool of controllers, reloading if the underlying controller def changes ControllerPool oControllerPool = new ControllerPool(oClassLoader, oServletConfig); // the ControllerExecutor manages the execution of controllers _oControllerExecutor = new ControllerExecutor(oControllerPool, new ControllerParameterProviderFactory( oModelPool, oConfig.getFileUpload(), oTemplatingEngine, _oRedirectResolverExecutor, oClassLoader)); // the ViewExecutor manages the loading (when needed) and processing of views ViewParameterProviderFactory oViewParameterProviderFactory = new ViewParameterProviderFactory(oModelPool, oConfig.getFileUpload(), oTemplatingEngine, _oRedirectResolverExecutor, oClassLoader); ViewFactory oViewFactory = new ViewFactory(oClassLoader, oViewParameterProviderFactory); // we have to delay setting this until here, since ViewParameterProviderFactory and // ViewFactory have a cyclical relationship oViewParameterProviderFactory.setViewFactory(oViewFactory); // finally create the view executor _oViewExecutor = new ViewExecutor(oViewFactory, oTemplatingEngine); }
From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java
public void testServletContextUnsupportedOperations() { final AtomicReference<ServletContext> contextHolder = new AtomicReference<ServletContext>(); Servlet unsupportedServlet = new HttpServlet() { private static final long serialVersionUID = 1L; @Override// www. jav a 2 s . co m public void init(ServletConfig config) throws ServletException { contextHolder.set(config.getServletContext()); } }; ServiceRegistration<Servlet> servletReg = null; Dictionary<String, Object> servletProps = new Hashtable<String, Object>(); servletProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/sessions"); try { servletReg = getBundleContext().registerService(Servlet.class, unsupportedServlet, servletProps); } catch (Exception e) { fail("Unexpected exception: " + e); } finally { if (servletReg != null) { servletReg.unregister(); } } ServletContext context = contextHolder.get(); assertNotNull("Null context.", context); for (Method m : getUnsupportedMethods()) { checkMethod(m, context); } }
From source file:com.cloud.bridge.service.EC2RestServlet.java
/** * We build the path to where the keystore holding the WS-Security X509 certificates * are stored.//from w w w . j a v a 2s . c o m */ @Override public void init(ServletConfig config) throws ServletException { File propertiesFile = ConfigurationHelper.findConfigurationFile("ec2-service.properties"); Properties EC2Prop = null; if (null != propertiesFile) { logger.info("Use EC2 properties file: " + propertiesFile.getAbsolutePath()); EC2Prop = new Properties(); try { EC2Prop.load(new FileInputStream(propertiesFile)); } catch (FileNotFoundException e) { logger.warn("Unable to open properties file: " + propertiesFile.getAbsolutePath(), e); } catch (IOException e) { logger.warn("Unable to read properties file: " + propertiesFile.getAbsolutePath(), e); } String keystore = EC2Prop.getProperty("keystore"); keystorePassword = EC2Prop.getProperty("keystorePass"); wsdlVersion = EC2Prop.getProperty("WSDLVersion", "2010-11-15"); version = EC2Prop.getProperty("cloudbridgeVersion", "UNKNOWN VERSION"); String installedPath = System.getenv("CATALINA_HOME"); if (installedPath == null) installedPath = System.getenv("CATALINA_BASE"); if (installedPath == null) installedPath = System.getProperty("catalina.home"); String webappPath = config.getServletContext().getRealPath("/"); //pathToKeystore = new String( installedPath + File.separator + "webapps" + File.separator + webappName + File.separator + "WEB-INF" + File.separator + "classes" + File.separator + keystore ); pathToKeystore = new String( webappPath + "WEB-INF" + File.separator + "classes" + File.separator + keystore); } }
From source file:org.apache.cocoon.servlet.CocoonServlet.java
/** * Initialize this <code>CocoonServlet</code> instance. You will * notice that I have broken the init into sub methods to make it * easier to maintain (BL). The context is passed to a couple of * the subroutines. This is also because it is better to explicitly * pass variables than implicitely. It is both more maintainable, * and more elegant./* ww w. ja v a 2s .c om*/ * * @param conf The ServletConfig object from the servlet engine. * * @throws ServletException */ public void init(ServletConfig conf) throws ServletException { super.init(conf); // Check the init-classloader parameter only if it's not already true. // This is useful for subclasses of this servlet that override the value // initially set by this class (i.e. false). if (!this.initClassLoader) { this.initClassLoader = getInitParameterAsBoolean("init-classloader", false); } if (this.initClassLoader) { // Force context classloader so that JAXP can work correctly // (see javax.xml.parsers.FactoryFinder.findClassLoader()) try { Thread.currentThread().setContextClassLoader(this.classLoader); } catch (Exception e) { // ignore this } } try { // FIXME (VG): We shouldn't have to specify these. Need to override // jaxp implementation of weblogic before initializing logger. // This piece of code is also required in the Cocoon class. String value = System.getProperty("javax.xml.parsers.SAXParserFactory"); if (value != null && value.startsWith("weblogic")) { System.setProperty("javax.xml.parsers.SAXParserFactory", "org.apache.xerces.jaxp.SAXParserFactoryImpl"); System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"); } } catch (Exception e) { // Ignore security exception System.out.println("CocoonServlet: Could not check system properties, got: " + e); } this.servletContext = conf.getServletContext(); this.appContext.put(Constants.CONTEXT_ENVIRONMENT_CONTEXT, new HttpContext(this.servletContext)); this.servletContextPath = this.servletContext.getRealPath("/"); // first init the work-directory for the logger. // this is required if we are running inside a war file! final String workDirParam = getInitParameter("work-directory"); if (workDirParam != null) { if (this.servletContextPath == null) { // No context path : consider work-directory as absolute this.workDir = new File(workDirParam); } else { // Context path exists : is work-directory absolute ? File workDirParamFile = new File(workDirParam); if (workDirParamFile.isAbsolute()) { // Yes : keep it as is this.workDir = workDirParamFile; } else { // No : consider it relative to context path this.workDir = new File(servletContextPath, workDirParam); } } } else { this.workDir = (File) this.servletContext.getAttribute("javax.servlet.context.tempdir"); this.workDir = new File(workDir, "cocoon-files"); } this.workDir.mkdirs(); this.appContext.put(Constants.CONTEXT_WORK_DIR, workDir); String path = this.servletContextPath; // these two variables are just for debugging. We can't log at this point // as the logger isn't initialized yet. String debugPathOne = null, debugPathTwo = null; if (path == null) { // Try to figure out the path of the root from that of WEB-INF try { path = this.servletContext.getResource("/WEB-INF").toString(); } catch (MalformedURLException me) { throw new ServletException("Unable to get resource 'WEB-INF'.", me); } debugPathOne = path; path = path.substring(0, path.length() - "WEB-INF".length()); debugPathTwo = path; } try { if (path.indexOf(':') > 1) { this.servletContextURL = path; } else { this.servletContextURL = new File(path).toURL().toExternalForm(); } } catch (MalformedURLException me) { // VG: Novell has absolute file names starting with the // volume name which is easily more then one letter. // Examples: sys:/apache/cocoon or sys:\apache\cocoon try { this.servletContextURL = new File(path).toURL().toExternalForm(); } catch (MalformedURLException ignored) { throw new ServletException("Unable to determine servlet context URL.", me); } } try { this.appContext.put("context-root", new URL(this.servletContextURL)); } catch (MalformedURLException ignore) { // we simply ignore this } // Init logger initLogger(); if (getLogger().isDebugEnabled()) { getLogger().debug("getRealPath for /: " + this.servletContextPath); if (this.servletContextPath == null) { getLogger().debug("getResource for /WEB-INF: " + debugPathOne); getLogger().debug("Path for Root: " + debugPathTwo); } } this.forceLoadParameter = getInitParameter("load-class", null); this.forceSystemProperty = getInitParameter("force-property", null); // Output some debug info if (getLogger().isDebugEnabled()) { getLogger().debug("Servlet Context URL: " + this.servletContextURL); if (workDirParam != null) { getLogger().debug("Using work-directory " + this.workDir); } else { getLogger().debug("Using default work-directory " + this.workDir); } } final String uploadDirParam = conf.getInitParameter("upload-directory"); if (uploadDirParam != null) { if (this.servletContextPath == null) { this.uploadDir = new File(uploadDirParam); } else { // Context path exists : is upload-directory absolute ? File uploadDirParamFile = new File(uploadDirParam); if (uploadDirParamFile.isAbsolute()) { // Yes : keep it as is this.uploadDir = uploadDirParamFile; } else { // No : consider it relative to context path this.uploadDir = new File(servletContextPath, uploadDirParam); } } if (getLogger().isDebugEnabled()) { getLogger().debug("Using upload-directory " + this.uploadDir); } } else { this.uploadDir = new File(workDir, "upload-dir" + File.separator); if (getLogger().isDebugEnabled()) { getLogger().debug("Using default upload-directory " + this.uploadDir); } } this.uploadDir.mkdirs(); this.appContext.put(Constants.CONTEXT_UPLOAD_DIR, this.uploadDir); this.enableUploads = getInitParameterAsBoolean("enable-uploads", ENABLE_UPLOADS); this.autoSaveUploads = getInitParameterAsBoolean("autosave-uploads", SAVE_UPLOADS_TO_DISK); String overwriteParam = getInitParameter("overwrite-uploads", "rename"); // accepted values are deny|allow|rename - rename is default. if ("deny".equalsIgnoreCase(overwriteParam)) { this.allowOverwrite = false; this.silentlyRename = false; } else if ("allow".equalsIgnoreCase(overwriteParam)) { this.allowOverwrite = true; this.silentlyRename = false; // ignored in this case } else { // either rename is specified or unsupported value - default to rename. this.allowOverwrite = false; this.silentlyRename = true; } this.maxUploadSize = getInitParameterAsInteger("upload-max-size", MAX_UPLOAD_SIZE); String cacheDirParam = conf.getInitParameter("cache-directory"); if (cacheDirParam != null) { if (this.servletContextPath == null) { this.cacheDir = new File(cacheDirParam); } else { // Context path exists : is cache-directory absolute ? File cacheDirParamFile = new File(cacheDirParam); if (cacheDirParamFile.isAbsolute()) { // Yes : keep it as is this.cacheDir = cacheDirParamFile; } else { // No : consider it relative to context path this.cacheDir = new File(servletContextPath, cacheDirParam); } } if (getLogger().isDebugEnabled()) { getLogger().debug("Using cache-directory " + this.cacheDir); } } else { this.cacheDir = IOUtils.createFile(workDir, "cache-dir" + File.separator); if (getLogger().isDebugEnabled()) { getLogger().debug("cache-directory was not set - defaulting to " + this.cacheDir); } } this.cacheDir.mkdirs(); this.appContext.put(Constants.CONTEXT_CACHE_DIR, this.cacheDir); this.appContext.put(Constants.CONTEXT_CONFIG_URL, getConfigFile(conf.getInitParameter("configurations"))); if (conf.getInitParameter("configurations") == null) { if (getLogger().isDebugEnabled()) { getLogger().debug("configurations was not set - defaulting to... ?"); } } // get allow reload parameter, default is true this.allowReload = getInitParameterAsBoolean("allow-reload", ALLOW_RELOAD); String value = conf.getInitParameter("show-time"); this.showTime = BooleanUtils.toBoolean(value) || (this.hiddenShowTime = "hide".equals(value)); if (value == null) { if (getLogger().isDebugEnabled()) { getLogger().debug("show-time was not set - defaulting to false"); } } this.showCocoonVersion = getInitParameterAsBoolean("show-cocoon-version", true); parentComponentManagerClass = getInitParameter("parent-component-manager", null); if (parentComponentManagerClass != null) { int dividerPos = parentComponentManagerClass.indexOf('/'); if (dividerPos != -1) { parentComponentManagerInitParam = parentComponentManagerClass.substring(dividerPos + 1); parentComponentManagerClass = parentComponentManagerClass.substring(0, dividerPos); } } this.containerEncoding = getInitParameter("container-encoding", "ISO-8859-1"); this.defaultFormEncoding = getInitParameter("form-encoding", "ISO-8859-1"); this.appContext.put(Constants.CONTEXT_DEFAULT_ENCODING, this.defaultFormEncoding); this.manageExceptions = getInitParameterAsBoolean("manage-exceptions", true); this.enableInstrumentation = getInitParameterAsBoolean("enable-instrumentation", false); this.requestFactory = new RequestFactory(this.autoSaveUploads, this.uploadDir, this.allowOverwrite, this.silentlyRename, this.maxUploadSize, this.containerEncoding); // Add the servlet configuration this.appContext.put(CONTEXT_SERVLET_CONFIG, conf); this.createCocoon(); }
From source file:org.wyona.yanel.servlet.YanelServlet.java
/** * @see javax.servlet.GenericServlet#init(ServletConfig) *//* ww w . j a v a 2s . com*/ @Override public void init(ServletConfig config) throws ServletException { servletContextRealPath = config.getServletContext().getRealPath("/"); if (config.getInitParameter("memory.growth.threshold") != null) { MEMORY_GROWTH_THRESHOLD = new Long(config.getInitParameter("memory.growth.threshold")).longValue(); } defaultXsltInfoAndException = config.getInitParameter("exception-and-info-screen-xslt"); xsltLoginScreenDefault = config.getInitParameter("login-screen-xslt"); displayMostRecentVersion = new Boolean(config.getInitParameter("workflow.not-live.most-recent-version")) .booleanValue(); try { yanelInstance = Yanel.getInstance(); yanelInstance.init(); // TODO: Tell Yanel about alternative directory to look for configuration files, e.g. (File) getServletContext().getAttribute("javax.servlet.context.tempdir") map = yanelInstance.getMapImpl("map"); sitetree = yanelInstance.getSitetreeImpl("repo-navigation"); sslPort = config.getInitParameter("ssl-port"); toolbarMasterSwitch = config.getInitParameter("toolbar-master-switch"); reservedPrefix = yanelInstance.getReservedPrefix(); String expires = config.getInitParameter("static-content-cache-expires"); if (expires != null) { this.cacheExpires = Integer.parseInt(expires); } yanelUI = new YanelHTMLUI(map, reservedPrefix); // TODO: Make this value configurable also per realm or per individual user! logAccessEnabled = new Boolean(config.getInitParameter("log-access")).booleanValue(); String TAG_SEP_PARAM_NAME = "access-log-tag-separator"; if (config.getInitParameter(TAG_SEP_PARAM_NAME) != null) { if (config.getInitParameter(TAG_SEP_PARAM_NAME).equals("SPACE")) { // Note that the leading and trailing space around the parameter value is trimmed, hence we denote the space sign by SPACE. ACCESS_LOG_TAG_SEPARATOR = " "; } else { ACCESS_LOG_TAG_SEPARATOR = config.getInitParameter(TAG_SEP_PARAM_NAME); } } else { ACCESS_LOG_TAG_SEPARATOR = ","; log.warn("No access log tag separator parameter '" + TAG_SEP_PARAM_NAME + "' configured, hence use default: " + ACCESS_LOG_TAG_SEPARATOR); } // TODO: Make this value configurable also per realm or per individual user! if (config.getInitParameter("detect-mobile-per-request") != null) { detectMobilePerRequest = new Boolean(config.getInitParameter("detect-mobile-per-request")) .booleanValue(); } if (config.getInitParameter("mobile-devices") != null) { mobileDevices = org.springframework.util.StringUtils .tokenizeToStringArray(config.getInitParameter("mobile-devices"), ",", true, true); } else { mobileDevices = new String[] { "iPhone", "Android" }; log.error( "No mobile devices configured! Please make sure to update your web.xml configuration file accordingly. Fallback to hard-coded list: " + mobileDevices); } if (yanelInstance.isSchedulerEnabled()) { try { log.debug("Startup scheduler ..."); scheduler = StdSchedulerFactory.getDefaultScheduler(); Realm[] realms = yanelInstance.getRealmConfiguration().getRealms(); for (int i = 0; i < realms.length; i++) { if (realms[i] instanceof org.wyona.yanel.core.map.RealmWithConfigurationExceptionImpl) { String eMessage = ((org.wyona.yanel.core.map.RealmWithConfigurationExceptionImpl) realms[i]) .getConfigurationException().getMessage(); log.error("Realm '" + realms[i].getID() + "' has thrown a configuration exception: " + eMessage); } else { String schedulerJobsPath = "/scheduler-jobs.xml"; if (realms[i].getRepository().existsNode(schedulerJobsPath)) { log.debug("Scheduler jobs config found for realm: " + realms[i].getRepository().getID()); try { // Get and filter scheduler config InputStream istream = realms[i].getRepository().getNode(schedulerJobsPath) .getInputStream(); log.debug("Filter scheduler configuration of realm '" + realms[i].getID() + "' by target environment '" + yanelInstance.getTargetEnvironment() + "'..."); istream = ConfigurationUtil.filterEnvironment(istream, yanelInstance.getTargetEnvironment()); Document filteredConfiguration = XMLHelper.readDocument(istream); // INFO: Debug filtered scheduler configuration if (log.isDebugEnabled()) { org.wyona.yarep.core.Node filteredConfigDebugNode = null; if (realms[i].getRepository().existsNode(schedulerJobsPath + ".DEBUG")) { filteredConfigDebugNode = realms[i].getRepository() .getNode(schedulerJobsPath + ".DEBUG"); } else { filteredConfigDebugNode = org.wyona.yarep.util.YarepUtil.addNodes( realms[i].getRepository(), schedulerJobsPath + ".DEBUG", org.wyona.yarep.core.NodeType.RESOURCE); } XMLHelper.writeDocument(filteredConfiguration, filteredConfigDebugNode.getOutputStream()); } // INFO: Run scheduler util org.wyona.yanel.impl.scheduler.QuartzSchedulerUtil.schedule(scheduler, filteredConfiguration, realms[i]); } catch (Exception e) { log.error(e, e); // INFO: Log error, but otherwise ignore and keep going ... } } } } /* TODO: Make global scheduler jobs configurable String groupName = "yanel"; JobDetail jobDetail = new JobDetail("heartbeatJob", groupName, org.wyona.yanel.servlet.HeartbeatJob.class); Date startDate = new Date(); Date endDate = null; Trigger trigger = new SimpleTrigger("heartbeatTrigger", groupName, startDate, endDate, SimpleTrigger.REPEAT_INDEFINITELY, 60L * 1000L); scheduler.scheduleJob(jobDetail, trigger); */ scheduler.start(); } catch (Exception e) { log.error(e, e); // INFO: Let's be fault tolerant in case the scheduler should not start } } else { log.info("The scheduler is currently disabled."); } } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } }
From source file:lucee.runtime.config.ConfigWebFactory.java
/** * creates a new ServletConfig Impl Object * //from ww w .j a v a 2s . c o m * @param configServer * @param configDir * @param servletConfig * @return new Instance * @throws SAXException * @throws ClassNotFoundException * @throws PageException * @throws IOException * @throws TagLibException * @throws FunctionLibException * @throws NoSuchAlgorithmException */ public static ConfigWebImpl newInstance(CFMLFactoryImpl factory, ConfigServerImpl configServer, Resource configDir, boolean isConfigDirACustomSetting, ServletConfig servletConfig) throws SAXException, ClassException, PageException, IOException, TagLibException, FunctionLibException, NoSuchAlgorithmException { // DO NOT REMOVE!!!! try { new LabelBlockImpl("aa"); } catch (Throwable t) { } String hash = SystemUtil.hash(servletConfig.getServletContext()); Map<String, String> labels = configServer.getLabels(); String label = null; if (labels != null) { label = labels.get(hash); } if (label == null) label = hash; SystemOut.print(SystemUtil.getPrintWriter(SystemUtil.OUT), "===================================================================\n" + "WEB CONTEXT (" + label + ")\n" + "-------------------------------------------------------------------\n" + "- config:" + configDir + (isConfigDirACustomSetting ? " (custom setting)" : "") + "\n" + "- webroot:" + ReqRspUtil.getRootPath(servletConfig.getServletContext()) + "\n" + "- hash:" + hash + "\n" + "- label:" + label + "\n" + "===================================================================\n" ); boolean doNew = doNew(configDir); Resource configFile = configDir.getRealResource("lucee-web.xml.cfm"); Resource configFileOld = configDir.getRealResource("lucee-web.xml"); String strPath = servletConfig.getServletContext().getRealPath("/WEB-INF"); Resource path = ResourcesImpl.getFileResourceProvider().getResource(strPath); // get config file if (!configFile.exists()) { if (configFileOld.exists()) { // if(!configFileOld.renameTo(configFile)) configFile = configFileOld; } else createConfigFile("web", configFile); } Document doc = null; Resource bugFile; int count = 1; // rename old bugfiles while ((bugFile = configDir.getRealResource("lucee-web." + (count++) + ".buggy.cfm")).exists()) { bugFile.renameTo(configDir.getRealResource("lucee-web." + (count) + ".buggy")); } try { doc = loadDocument(configFile); } catch (Exception e) { // rename buggy config files if (configFile.exists()) { SystemOut.printDate(SystemUtil.getPrintWriter(SystemUtil.OUT), "config file " + configFile + " was not valid and has been replaced"); count = 1; while ((bugFile = configDir.getRealResource("lucee-web." + (count++) + ".buggy")).exists()) { } IOUtil.copy(configFile, bugFile); configFile.delete(); } createConfigFile("web", configFile); doc = loadDocument(configFile); } // htaccess if (path.exists()) createHtAccess(path.getRealResource(".htaccess")); if (configDir.exists()) createHtAccess(configDir.getRealResource(".htaccess")); createContextFiles(configDir, servletConfig, doNew); ConfigWebImpl configWeb = new ConfigWebImpl(factory, configServer, servletConfig, configDir, configFile); load(configServer, configWeb, doc, false, doNew); createContextFilesPost(configDir, configWeb, servletConfig, false, doNew); return configWeb; }
From source file:lucee.runtime.config.XMLConfigWebFactory.java
/** * creates a new ServletConfig Impl Object * /*from ww w. ja v a2s . c o m*/ * @param configServer * @param configDir * @param servletConfig * @return new Instance * @throws SAXException * @throws ClassNotFoundException * @throws PageException * @throws IOException * @throws TagLibException * @throws FunctionLibException * @throws NoSuchAlgorithmException * @throws BundleException */ public static ConfigWebImpl newInstance(CFMLFactoryImpl factory, ConfigServerImpl configServer, Resource configDir, boolean isConfigDirACustomSetting, ServletConfig servletConfig) throws SAXException, ClassException, PageException, IOException, TagLibException, FunctionLibException, NoSuchAlgorithmException, BundleException { // DO NOT REMOVE!!!! try { new LabelBlockImpl("aa"); } catch (Throwable t) { } String hash = SystemUtil.hash(servletConfig.getServletContext()); Map<String, String> labels = configServer.getLabels(); String label = null; if (labels != null) { label = labels.get(hash); } if (label == null) label = hash; SystemOut.print(SystemUtil.getPrintWriter(SystemUtil.OUT), "===================================================================\n" + "WEB CONTEXT (" + label + ")\n" + "-------------------------------------------------------------------\n" + "- config:" + configDir + (isConfigDirACustomSetting ? " (custom setting)" : "") + "\n" + "- webroot:" + ReqRspUtil.getRootPath(servletConfig.getServletContext()) + "\n" + "- hash:" + hash + "\n" + "- label:" + label + "\n" + "===================================================================\n" ); boolean doNew = doNew(configDir); Resource configFile = configDir.getRealResource("lucee-web.xml." + TEMPLATE_EXTENSION); String strPath = servletConfig.getServletContext().getRealPath("/WEB-INF"); Resource path = ResourcesImpl.getFileResourceProvider().getResource(strPath); // get config file if (!configFile.exists()) { createConfigFile("web", configFile); } Document doc = null; Resource bugFile; int count = 1; doc = loadDocumentCreateIfFails(configFile, "web"); // htaccess if (path.exists()) createHtAccess(path.getRealResource(".htaccess")); if (configDir.exists()) createHtAccess(configDir.getRealResource(".htaccess")); createContextFiles(configDir, servletConfig, doNew); ConfigWebImpl configWeb = new ConfigWebImpl(factory, configServer, servletConfig, configDir, configFile); load(configServer, configWeb, doc, false, doNew); createContextFilesPost(configDir, configWeb, servletConfig, false, doNew); return configWeb; }
From source file:edu.ucsd.library.dams.api.DAMSAPIServlet.java
public void init(ServletConfig config) throws ServletException { ServletContext ctx = config.getServletContext(); config(ctx);//w w w . ja v a 2 s.c om appVersion = ctx.getInitParameter("app-version"); srcVersion = ctx.getInitParameter("src-version"); buildTimestamp = ctx.getInitParameter("build-timestamp"); super.init(config); }