List of usage examples for javax.servlet FilterConfig getServletContext
public ServletContext getServletContext();
From source file:com.sfwl.framework.web.casclient.AbstractTicketValidationFilter.java
protected void initInternal(final FilterConfig filterConfig) throws ServletException { setExceptionOnValidationFailure(//from w ww. j a v a 2s . c om parseBoolean(getPropertyFromInitParams(filterConfig, "exceptionOnValidationFailure", "false"))); logger.trace("Setting exceptionOnValidationFailure parameter: {}", this.exceptionOnValidationFailure); setRedirectAfterValidation( parseBoolean(getPropertyFromInitParams(filterConfig, "redirectAfterValidation", "true"))); logger.trace("Setting redirectAfterValidation parameter: {}", this.redirectAfterValidation); setUseSession(parseBoolean(getPropertyFromInitParams(filterConfig, "useSession", "true"))); logger.trace("Setting useSession parameter: {}", this.useSession); if (!this.useSession && this.redirectAfterValidation) { logger.warn( "redirectAfterValidation parameter may not be true when useSession parameter is false. Resetting it to false in order to prevent infinite redirects."); setRedirectAfterValidation(false); } setTicketValidator(getTicketValidator(filterConfig)); super.initInternal(filterConfig); // URL String casExcepUrlRegex = filterConfig.getServletContext().getInitParameter("casExcepUrlRegex"); if (StringUtils.isNotBlank(casExcepUrlRegex)) { excepUrlPattern = Pattern.compile(casExcepUrlRegex); } }
From source file:org.infoscoop.web.OpenIDFilter.java
public void init(FilterConfig config) throws ServletException { String excludePathStr = config.getInitParameter("excludePath"); if (excludePathStr != null) { String[] pathArray = excludePathStr.split(","); for (int i = 0; i < pathArray.length; i++) { String path = pathArray[i].trim(); if (path.endsWith("*")) { excludePaths.add(path.substring(0, path.length() - 1)); } else { excludePaths.add(path);/*from w w w . j a v a2 s . c om*/ } } } String opIdentifierParam = config.getInitParameter("opIdentifier"); if (opIdentifierParam != null) { if (log.isInfoEnabled()) log.info("loginUrl is set to " + opIdentifierParam); this.opIdentifier = opIdentifierParam; } int socketTimeout = 30 * 1000; String socketTimeoutParam = config.getInitParameter("socketTimeout"); if (socketTimeoutParam != null) { if (log.isInfoEnabled()) log.info("socketTimeout is set to " + socketTimeoutParam); socketTimeout = Integer.parseInt(socketTimeoutParam); } try { ConsumerManager newmgr = (ConsumerManager) config.getServletContext() .getAttribute("openid-consumermanager"); if (newmgr == null) { newmgr = new ConsumerManager(); newmgr.setAssociations(new InMemoryConsumerAssociationStore()); newmgr.setNonceVerifier(new InMemoryNonceVerifier(5000)); newmgr.setSocketTimeout(socketTimeout); config.getServletContext().setAttribute("openid-consumermanager", newmgr); } this.consumerMgr = newmgr; } catch (Exception e) { log.error(e.getMessage(), e); } }
From source file:com.sfwl.framework.web.casclient.SingleSignOutFilter.java
public void init(final FilterConfig filterConfig) throws ServletException { if (!isIgnoreInitConfiguration()) { HANDLER.setArtifactParameterName(getPropertyFromInitParams(filterConfig, "artifactParameterName", SingleSignOutHandler.DEFAULT_ARTIFACT_PARAMETER_NAME)); HANDLER.setLogoutParameterName(getPropertyFromInitParams(filterConfig, "logoutParameterName", SingleSignOutHandler.DEFAULT_LOGOUT_PARAMETER_NAME)); HANDLER.setFrontLogoutParameterName(getPropertyFromInitParams(filterConfig, "frontLogoutParameterName", SingleSignOutHandler.DEFAULT_FRONT_LOGOUT_PARAMETER_NAME)); HANDLER.setRelayStateParameterName(getPropertyFromInitParams(filterConfig, "relayStateParameterName", SingleSignOutHandler.DEFAULT_RELAY_STATE_PARAMETER_NAME)); HANDLER.setCasServerUrlPrefix(getPropertyFromInitParams(filterConfig, "casServerUrlPrefix", "")); HANDLER.setArtifactParameterOverPost( parseBoolean(getPropertyFromInitParams(filterConfig, "artifactParameterOverPost", "false"))); HANDLER.setEagerlyCreateSessions( parseBoolean(getPropertyFromInitParams(filterConfig, "eagerlyCreateSessions", "true"))); }// www.ja v a 2 s. c o m HANDLER.init(); handlerInitialized.set(true); // URL String casExcepUrlRegex = filterConfig.getServletContext().getInitParameter("casExcepUrlRegex"); if (StringUtils.isNotBlank(casExcepUrlRegex)) { excepUrlPattern = Pattern.compile(casExcepUrlRegex); } }
From source file:org.seasar.extension.filter.RequestDumpFilter.java
public void init(final FilterConfig filterConfig) throws ServletException { this.config = filterConfig; beforeRequestParameter = getBooleanParameter(filterConfig, "beforeRequestParameter", true); afterRequestParameter = getBooleanParameter(filterConfig, "afterRequestParameter", false); beforeRequestAttribute = getBooleanParameter(filterConfig, "beforeRequestAttribute", true); afterRequestAttribute = getBooleanParameter(filterConfig, "afterRequestAttribute", true); beforeRequestHeader = getBooleanParameter(filterConfig, "beforeRequestHeader", true); afterRequestHeader = getBooleanParameter(filterConfig, "afterRequestHeader", false); beforeContextAttribute = getBooleanParameter(filterConfig, "beforeContextAttribute", true); afterContextAttribute = getBooleanParameter(filterConfig, "afterContextAttribute", true); beforeCookies = getBooleanParameter(filterConfig, "beforeCookies", true); afterCookies = getBooleanParameter(filterConfig, "afterCookies", true); beforeSessionAttribute = getBooleanParameter(filterConfig, "beforeSessionAttribute", true); afterSessionAttribute = getBooleanParameter(filterConfig, "afterSessionAttribute", true); afterResponse = getBooleanParameter(filterConfig, "afterResponse", true); final StringBuffer sb = new StringBuffer(); RequestDumpUtil.dumpContextProperties(sb, filterConfig.getServletContext(), LF, INDENT); log.debug(sb.toString());//from ww w . java 2 s . c om }
From source file:org.apache.solr.servlet.SolrDispatchFilter.java
@Override public void init(FilterConfig config) throws ServletException { log.trace("SolrDispatchFilter.init(): {}", this.getClass().getClassLoader()); SolrRequestParsers.fileCleaningTracker = new SolrFileCleaningTracker(); StartupLoggingUtils.checkLogDir();//from ww w. ja va 2s . c o m logWelcomeBanner(); String muteConsole = System.getProperty(SOLR_LOG_MUTECONSOLE); if (muteConsole != null && !Arrays.asList("false", "0", "off", "no").contains(muteConsole.toLowerCase(Locale.ROOT))) { StartupLoggingUtils.muteConsole(); } String logLevel = System.getProperty(SOLR_LOG_LEVEL); if (logLevel != null) { StartupLoggingUtils.changeLogLevel(logLevel); } String exclude = config.getInitParameter("excludePatterns"); if (exclude != null) { String[] excludeArray = exclude.split(","); excludePatterns = new ArrayList<>(); for (String element : excludeArray) { excludePatterns.add(Pattern.compile(element)); } } try { Properties extraProperties = (Properties) config.getServletContext().getAttribute(PROPERTIES_ATTRIBUTE); if (extraProperties == null) extraProperties = new Properties(); String solrHome = (String) config.getServletContext().getAttribute(SOLRHOME_ATTRIBUTE); ExecutorUtil.addThreadLocalProvider(SolrRequestInfo.getInheritableThreadLocalProvider()); this.cores = createCoreContainer( solrHome == null ? SolrResourceLoader.locateSolrHome() : Paths.get(solrHome), extraProperties); this.httpClient = cores.getUpdateShardHandler().getHttpClient(); setupJvmMetrics(); log.debug("user.dir=" + System.getProperty("user.dir")); } catch (Throwable t) { // catch this so our filter still works log.error("Could not start Solr. Check solr/home property and the logs"); SolrCore.log(t); if (t instanceof Error) { throw (Error) t; } } log.trace("SolrDispatchFilter.init() done"); }
From source file:org.alfresco.web.site.servlet.SSOAuthenticationFilter.java
/** * Initialize the filter/*from ww w.j av a 2s.c o m*/ */ public void init(FilterConfig args) throws ServletException { if (logger.isDebugEnabled()) logger.debug("Initializing the SSOAuthenticationFilter."); // get reference to our ServletContext this.servletContext = args.getServletContext(); ApplicationContext context = getApplicationContext(); this.loginController = (SlingshotLoginController) context.getBean("loginController"); // retrieve the connector service this.connectorService = (ConnectorService) context.getBean("connector.service"); ConfigService configService = (ConfigService) context.getBean("web.config"); // Retrieve the remote configuration RemoteConfigElement remoteConfig = (RemoteConfigElement) configService.getConfig("Remote") .getConfigElement("remote"); if (remoteConfig == null) { logger.error( "There is no Remote configuration element. This is required to use SSOAuthenticationFilter."); return; } // get the endpoint id to use String endpoint = args.getInitParameter("endpoint"); if (endpoint == null) { logger.error( "There is no 'endpoint' id in the SSOAuthenticationFilter init parameters. Cannot initialise filter."); return; } // Get the endpoint descriptor and check if external auth is enabled EndpointDescriptor endpointDescriptor = remoteConfig.getEndpointDescriptor(endpoint); if (endpointDescriptor == null || !endpointDescriptor.getExternalAuth()) { if (logger.isDebugEnabled()) logger.debug("No External Auth endpoint configured for " + endpoint); return; } try { Connector conn = this.connectorService.getConnector(endpoint); // Save the endpoint, activating the filter this.endpoint = endpoint; if (logger.isDebugEnabled()) logger.debug("Endpoint is " + endpoint); // Obtain the userHeader (if configured) from the alfresco connector this.userHeader = conn.getConnectorSession() .getParameter(SlingshotAlfrescoConnector.CS_PARAM_USER_HEADER); String userIdPattern = conn.getConnectorSession() .getParameter(SlingshotAlfrescoConnector.CS_PARAM_USER_ID_PATTERN); if (userIdPattern != null) { this.userIdPattern = Pattern.compile(userIdPattern); } if (logger.isDebugEnabled()) { logger.debug("userHeader is " + userHeader); logger.debug("userIdPattern is " + userIdPattern); } } catch (ConnectorServiceException e) { logger.error("Unable to find connector " + endpointDescriptor.getConnectorId() + " for the endpoint " + endpoint, e); } // retrieve the optional kerberos configuration KerberosConfigElement krbConfig = (KerberosConfigElement) configService.getConfig("Kerberos") .getConfigElement("kerberos"); if (krbConfig != null) { if (logger.isDebugEnabled()) logger.debug("Found configuration for Kerberos authentication."); // Get the Kerberos realm String krbRealm = krbConfig.getRealm(); if (krbRealm != null && krbRealm.length() > 0) { if (logger.isDebugEnabled()) logger.debug("Found Kerberos realm: " + krbRealm); // Set the Kerberos realm this.krbRealm = krbRealm; } else throw new ServletException("Kerberos realm not specified"); // Get the HTTP service account password String srvPassword = krbConfig.getPassword(); if (srvPassword != null && srvPassword.length() > 0) { // Set the HTTP service account password this.krbPassword = srvPassword; } else throw new ServletException("HTTP service account password not specified"); String krbEndpointSPN = krbConfig.getEndpointSPN(); if (krbEndpointSPN != null && krbEndpointSPN.length() > 0) { // Set the Service Principal Name to use on the endpoint if (logger.isDebugEnabled()) logger.debug("The Service Principal Name to use on the endpoint: " + krbEndpointSPN); this.krbEndpointSPN = krbEndpointSPN; } else throw new ServletException("endpoint service principal name not specified"); // Get the login configuration entry name String loginEntry = krbConfig.getLoginEntryName(); if (loginEntry != null) { if (loginEntry.length() > 0) { // Set the login configuration entry name to use if (logger.isDebugEnabled()) logger.debug("The login configuration entry name to use: " + loginEntry); jaasLoginEntryName = loginEntry; } else throw new ServletException("Invalid login entry specified"); } // Get the login stripUserNameSuffix property boolean stripUserNameSuffix = krbConfig.getStripUserNameSuffix(); // Set the login configuration entry name to use if (logger.isDebugEnabled()) logger.debug("The stripUserNameSuffix property is set to: " + stripUserNameSuffix); this.stripUserNameSuffix = stripUserNameSuffix; // Create a login context for the HTTP server service try { // Login the HTTP server service jaasLoginContext = new LoginContext(jaasLoginEntryName, this); jaasLoginContext.login(); // DEBUG if (logger.isDebugEnabled()) logger.debug("HTTP Kerberos login successful"); } catch (LoginException ex) { // Debug if (logger.isErrorEnabled()) logger.error("HTTP Kerberos web filter error", ex); throw new ServletException("Failed to login HTTP server service"); } // Get the HTTP service account name from the subject Subject subj = jaasLoginContext.getSubject(); Principal princ = subj.getPrincipals().iterator().next(); krbAccountName = princ.getName(); // DEBUG if (logger.isDebugEnabled()) logger.debug("Logged on using principal " + krbAccountName); } if (logger.isInfoEnabled()) logger.info("SSOAuthenticationFilter initialised."); }
From source file:org.apache.ranger.security.web.filter.RangerKRBAuthenticationFilter.java
@Override public void init(FilterConfig conf) throws ServletException { final FilterConfig globalConf = conf; final Map<String, String> params = new HashMap<String, String>(); params.put(AUTH_TYPE, PropertiesUtil.getProperty(RANGER_AUTH_TYPE, "simple")); params.put(NAME_RULES_PARAM, PropertiesUtil.getProperty(NAME_RULES, "DEFAULT")); params.put(TOKEN_VALID_PARAM, PropertiesUtil.getProperty(TOKEN_VALID, "30")); params.put(COOKIE_DOMAIN_PARAM,//from w ww. j av a 2 s .com PropertiesUtil.getProperty(COOKIE_DOMAIN, PropertiesUtil.getProperty(HOST_NAME, "localhost"))); params.put(COOKIE_PATH_PARAM, PropertiesUtil.getProperty(COOKIE_PATH, "/")); try { params.put(PRINCIPAL_PARAM, SecureClientLogin.getPrincipal(PropertiesUtil.getProperty(PRINCIPAL, ""), PropertiesUtil.getProperty(HOST_NAME))); } catch (IOException ignored) { // do nothing } params.put(KEYTAB_PARAM, PropertiesUtil.getProperty(KEYTAB, "")); FilterConfig myConf = new FilterConfig() { @Override public ServletContext getServletContext() { if (globalConf != null) { return globalConf.getServletContext(); } else { return noContext; } } @SuppressWarnings("unchecked") @Override public Enumeration<String> getInitParameterNames() { return new IteratorEnumeration(params.keySet().iterator()); } @Override public String getInitParameter(String param) { return params.get(param); } @Override public String getFilterName() { return "KerberosFilter"; } }; super.init(myConf); }
From source file:org.ambraproject.struts2.AmbraStruts2Dispatcher.java
@Override public void init(FilterConfig filterConfig) { // Copied the init function of the StrutsPrepareAndExecuteFilter class // and modified how the Dispatcher object is getting created by passing our own configuration values. // There should be a better way to do this than what we are doing here. InitOperations init = new InitOperations(); Dispatcher dispatcher = null;/*w ww .j ava 2 s . co m*/ try { FilterHostConfig config = new FilterHostConfig(filterConfig); init.initLogging(config); // initDispatcher is the function we really want to override // dispatcher = init.initDispatcher(config); Map<String, String> params = new HashMap<String, String>(); for (Iterator e = config.getInitParameterNames(); e.hasNext();) { String name = (String) e.next(); String value = filterConfig.getInitParameter(name); params.put(name, value); } // adding our own configuration values Configuration conf = ConfigurationStore.getInstance().getConfiguration(); for (String name : keys) { String val = conf.getString(name); if (val != null) { log.info("Setting struts constant: " + name + "=" + val); params.put(name, val); } } dispatcher = new Dispatcher(config.getServletContext(), params); dispatcher.init(); init.initStaticContentLoader(config, dispatcher); prepare = new PrepareOperations(filterConfig.getServletContext(), dispatcher); execute = new ExecuteOperations(filterConfig.getServletContext(), dispatcher); this.excludedPatterns = init.buildExcludedPatternsList(dispatcher); postInit(dispatcher, filterConfig); } finally { if (dispatcher != null) { dispatcher.cleanUpAfterInit(); } init.cleanup(); } }
From source file:org.apache.myfaces.webapp.filter.ExtensionsFilter.java
/** * Init method for this filter.//from w ww . j av a 2 s . co m * <p> * The following filter init parameters can be configured in the web.xml file * for this filter: * <ul> * <li>uploadMaxFileSize</li> * <li>uploadThresholdSize</li> * <li>uploadRepositoryPath</li> * <li>uploadMaxSize</li> * <li>cacheFileSizeErrors</li> * </ul> * </p> * <p> * All size parameters may have the suffix "g" (gigabytes), "m" (megabytes) or "k" (kilobytes). * </p> * * <h2>uploadMaxFileSize</h2> * * Sets the maximum allowable size for uploaded files. * <p> * If the user attempts to upload a file which is larger than this, then the data <i>is</i> * transmitted from the browser to the server (this cannot be prevented with standard HTML * functionality). However the file will not be saved in memory or on disk. An error message * will be added to the standard JSF error messages, and the page re-rendered (as for a * validation failure). * </p> * <p> * The default value is 100 Megabytes. * </p> * * <h2>uploadThresholdSize</h2> * * Sets the size threshold beyond which files are written directly to disk. Files which are * smaller than this are simply held in memory. The default is 1 Megabyte. * * <h2>uploadRepositoryPath</h2> * * Sets the directory in which temporary files (ie caches for those uploaded files that * are larger than uploadThresholdSize) are to be stored. * * <h2>uploadMaxSize</h2> * * Sets the maximum allowable size for the current request. If not set, its value is the * value set on uploadMaxFileSize param. * * <h2>cacheFileSizeErrors</h2> * * Catch and swallow FileSizeLimitExceededExceptions in order to return as * many usable items as possible. * */ public void init(FilterConfig filterConfig) { // Note that the code here to extract FileUpload configuration params is not actually used. // The handling of multipart requests was moved from this Filter into a custom FacesContext // (TomahawkFacesContextWrapper) so that Portlets could be supported (Portlets cannot use // servlet filters). // // For backwards compatibility, the TomahawkFacesContextWrapper class *parses* the // web.xml to retrieve these same filter config params. That is IMO seriously ugly // and hopefully will be fixed. String param = filterConfig.getInitParameter("uploadMaxFileSize"); _uploadMaxFileSize = resolveSize(param, _uploadMaxFileSize); param = filterConfig.getInitParameter("uploadMaxSize"); if (param != null) { _uploadMaxSize = resolveSize(param, _uploadMaxSize); } else { //If not set, default to uploadMaxFileSize _uploadMaxSize = resolveSize(param, _uploadMaxFileSize); } param = filterConfig.getInitParameter("uploadThresholdSize"); _uploadThresholdSize = resolveSize(param, _uploadThresholdSize); _uploadRepositoryPath = filterConfig.getInitParameter("uploadRepositoryPath"); _cacheFileSizeErrors = getBooleanValue(filterConfig.getInitParameter("cacheFileSizeErrors"), false); _servletContext = filterConfig.getServletContext(); filterConfig.getServletContext().setAttribute(EXTENSIONS_FILTER_INITIALIZED, true); }