List of usage examples for org.springframework.web.context.support WebApplicationContextUtils getRequiredWebApplicationContext
public static WebApplicationContext getRequiredWebApplicationContext(ServletContext sc) throws IllegalStateException
From source file:org.apache.nifi.web.server.JettyServer.java
@Override public void start() { try {/*from w w w .ja va 2s .c om*/ // start the server server.start(); // ensure everything started successfully for (Handler handler : server.getChildHandlers()) { // see if the handler is a web app if (handler instanceof WebAppContext) { WebAppContext context = (WebAppContext) handler; // see if this webapp had any exceptions that would // cause it to be unavailable if (context.getUnavailableException() != null) { startUpFailure(context.getUnavailableException()); } } } // ensure the appropriate wars deployed successfully before injecting the NiFi context and security filters // this must be done after starting the server (and ensuring there were no start up failures) if (webApiContext != null) { // give the web api the component ui extensions final ServletContext webApiServletContext = webApiContext.getServletHandler().getServletContext(); webApiServletContext.setAttribute("nifi-ui-extensions", componentUiExtensions); // get the application context final WebApplicationContext webApplicationContext = WebApplicationContextUtils .getRequiredWebApplicationContext(webApiServletContext); // component ui extensions if (CollectionUtils.isNotEmpty(componentUiExtensionWebContexts)) { final NiFiWebConfigurationContext configurationContext = webApplicationContext .getBean("nifiWebConfigurationContext", NiFiWebConfigurationContext.class); for (final WebAppContext customUiContext : componentUiExtensionWebContexts) { // set the NiFi context in each custom ui servlet context final ServletContext customUiServletContext = customUiContext.getServletHandler() .getServletContext(); customUiServletContext.setAttribute("nifi-web-configuration-context", configurationContext); // add the security filter to any ui extensions wars final FilterHolder securityFilter = webApiContext.getServletHandler() .getFilter("springSecurityFilterChain"); if (securityFilter != null) { customUiContext.addFilter(securityFilter, "/*", EnumSet.allOf(DispatcherType.class)); } } } // content viewer extensions if (CollectionUtils.isNotEmpty(contentViewerWebContexts)) { for (final WebAppContext contentViewerContext : contentViewerWebContexts) { // add the security filter to any content viewer wars final FilterHolder securityFilter = webApiContext.getServletHandler() .getFilter("springSecurityFilterChain"); if (securityFilter != null) { contentViewerContext.addFilter(securityFilter, "/*", EnumSet.allOf(DispatcherType.class)); } } } // content viewer controller if (webContentViewerContext != null) { final ContentAccess contentAccess = webApplicationContext.getBean("contentAccess", ContentAccess.class); // add the content access final ServletContext webContentViewerServletContext = webContentViewerContext .getServletHandler().getServletContext(); webContentViewerServletContext.setAttribute("nifi-content-access", contentAccess); final FilterHolder securityFilter = webApiContext.getServletHandler() .getFilter("springSecurityFilterChain"); if (securityFilter != null) { webContentViewerContext.addFilter(securityFilter, "/*", EnumSet.allOf(DispatcherType.class)); } } } // ensure the web document war was loaded and provide the extension mapping if (webDocsContext != null) { final ServletContext webDocsServletContext = webDocsContext.getServletHandler().getServletContext(); webDocsServletContext.setAttribute("nifi-extension-mapping", extensionMapping); } // if this nifi is a node in a cluster, start the flow service and load the flow - the // flow service is loaded here for clustered nodes because the loading of the flow will // initialize the connection between the node and the NCM. if the node connects (starts // heartbeating, etc), the NCM may issue web requests before the application (wars) have // finished loading. this results in the node being disconnected since its unable to // successfully respond to the requests. to resolve this, flow loading was moved to here // (after the wars have been successfully deployed) when this nifi instance is a node // in a cluster if (props.isNode()) { FlowService flowService = null; try { logger.info("Loading Flow..."); ApplicationContext ctx = WebApplicationContextUtils .getWebApplicationContext(webApiContext.getServletContext()); flowService = ctx.getBean("flowService", FlowService.class); // start and load the flow flowService.start(); flowService.load(null); logger.info("Flow loaded successfully."); } catch (BeansException | LifeCycleStartException | IOException | FlowSerializationException | FlowSynchronizationException | UninheritableFlowException e) { // ensure the flow service is terminated if (flowService != null && flowService.isRunning()) { flowService.stop(false); } throw new Exception("Unable to load flow due to: " + e, e); } } // dump the application url after confirming everything started successfully dumpUrls(); } catch (Exception ex) { startUpFailure(ex); } }
From source file:org.apache.roller.weblogger.ui.core.RollerContext.java
/** * Setup Spring Security security features. */// w w w. j a v a 2 s . co m protected void initializeSecurityFeatures(ServletContext context) { ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context); /*String[] beanNames = ctx.getBeanDefinitionNames(); for (String name : beanNames) System.out.println(name);*/ String rememberMe = WebloggerConfig.getProperty("rememberme.enabled"); boolean rememberMeEnabled = Boolean.valueOf(rememberMe).booleanValue(); log.info("Remember Me enabled: " + rememberMeEnabled); context.setAttribute("rememberMeEnabled", rememberMe); if (!rememberMeEnabled) { ProviderManager provider = (ProviderManager) ctx.getBean("_authenticationManager"); for (Iterator it = provider.getProviders().iterator(); it.hasNext();) { AuthenticationProvider authProvider = (AuthenticationProvider) it.next(); if (authProvider instanceof RememberMeAuthenticationProvider) { provider.getProviders().remove(authProvider); } } } String encryptPasswords = WebloggerConfig.getProperty("passwds.encryption.enabled"); boolean doEncrypt = Boolean.valueOf(encryptPasswords).booleanValue(); if (doEncrypt) { DaoAuthenticationProvider provider = (DaoAuthenticationProvider) ctx .getBean("org.springframework.security.providers.dao.DaoAuthenticationProvider#0"); String algorithm = WebloggerConfig.getProperty("passwds.encryption.algorithm"); PasswordEncoder encoder = null; if (algorithm.equalsIgnoreCase("SHA")) { encoder = new ShaPasswordEncoder(); } else if (algorithm.equalsIgnoreCase("MD5")) { encoder = new Md5PasswordEncoder(); } else { log.error("Encryption algorithm '" + algorithm + "' not supported, disabling encryption."); } if (encoder != null) { provider.setPasswordEncoder(encoder); log.info("Password Encryption Algorithm set to '" + algorithm + "'"); } } if (WebloggerConfig.getBooleanProperty("securelogin.enabled")) { AuthenticationProcessingFilterEntryPoint entryPoint = (AuthenticationProcessingFilterEntryPoint) ctx .getBean("_formLoginEntryPoint"); entryPoint.setForceHttps(true); } /* if (WebloggerConfig.getBooleanProperty("schemeenforcement.enabled")) { ChannelProcessingFilter procfilter = (ChannelProcessingFilter)ctx.getBean("channelProcessingFilter"); ConfigAttributeDefinition secureDef = new ConfigAttributeDefinition(); secureDef.addConfigAttribute(new SecurityConfig("REQUIRES_SECURE_CHANNEL")); ConfigAttributeDefinition insecureDef = new ConfigAttributeDefinition(); insecureDef.addConfigAttribute(new SecurityConfig("REQUIRES_INSECURE_CHANNEL")); PathBasedFilterInvocationDefinitionMap defmap = (PathBasedFilterInvocationDefinitionMap)procfilter.getFilterInvocationDefinitionSource(); // add HTTPS URL path patterns to Acegi config String httpsUrlsProp = WebloggerConfig.getProperty("schemeenforcement.https.urls"); if (httpsUrlsProp != null) { String[] httpsUrls = StringUtils.stripAll(StringUtils.split(httpsUrlsProp, ",") ); for (int i=0; i<httpsUrls.length; i++) { defmap.addSecureUrl(httpsUrls[i], secureDef); } } // all other action URLs are non-HTTPS defmap.addSecureUrl("/**<!-- need to remove this when uncommenting -->/*.do*", insecureDef); } */ }
From source file:org.apache.roller.weblogger.ui.core.RollerContext.java
/** * Flush user from any caches maintained by security system. *//* ww w .j a va 2 s.c om*/ public static void flushAuthenticationUserCache(String userName) { ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); try { UserCache userCache = (UserCache) ctx.getBean("userCache"); if (userCache != null) { userCache.removeUserFromCache(userName); } } catch (NoSuchBeanDefinitionException exc) { log.debug("No userCache bean in context", exc); } }
From source file:org.atricore.idbus.kernel.main.mediation.camel.component.http.OsgiIDBusServlet.java
protected IdentityMediationUnitRegistry lookupIdentityMediationUnitRegistry() throws ServletException { org.springframework.osgi.web.context.support.OsgiBundleXmlWebApplicationContext wac = (org.springframework.osgi.web.context.support.OsgiBundleXmlWebApplicationContext) WebApplicationContextUtils .getRequiredWebApplicationContext(getServletContext()); if (wac == null) { logger.error("Spring application context not found in servlet context"); throw new ServletException("Spring application context not found in servlet context"); }/* ww w . ja v a 2s .c o m*/ BundleContext bc = wac.getBundleContext(); for (Bundle b : bc.getBundles()) { if (b.getRegisteredServices() != null) { if (logger.isTraceEnabled()) logger.trace("(" + b.getBundleId() + ") " + b.getSymbolicName() + " serviceReferences:" + b.getRegisteredServices().length); for (ServiceReference r : b.getRegisteredServices()) { String props = ""; for (String key : r.getPropertyKeys()) { props += "\n\t\t" + key + "=" + r.getProperty(key); if (r.getProperty(key) instanceof String[]) { String[] v = (String[]) r.getProperty(key); props += "["; String prefix = ""; for (String aV : v) { props += prefix + aV; prefix = ","; } props += "]"; } } if (logger.isTraceEnabled()) logger.trace( "ServiceReference:<<" + r + ">> [" + r.getProperty("service.id") + "]" + props); } } else { if (logger.isTraceEnabled()) logger.trace("(" + b.getBundleId() + ") " + b.getSymbolicName() + "services:<null>"); } } Map<String, IdentityMediationUnitRegistry> imuRegistryMap = wac .getBeansOfType(IdentityMediationUnitRegistry.class); if (imuRegistryMap == null) { logger.warn("No identity mediation unit registry configured"); return null; } if (imuRegistryMap.size() > 1) { logger.warn("More than one identity mediation unit registry configured"); return null; } IdentityMediationUnitRegistry r = imuRegistryMap.values().iterator().next(); if (logger.isDebugEnabled()) logger.debug("Found Identity Mediation Unit Registry " + r); return r; }
From source file:org.codehaus.groovy.grails.web.errors.GrailsWrappedRuntimeException.java
/** * @param servletContext The ServletContext instance * @param t The exception that was thrown *///from w w w . j av a 2 s . co m public GrailsWrappedRuntimeException(ServletContext servletContext, Throwable t) { super(t.getMessage(), t); cause = t; FastStringPrintWriter pw = FastStringPrintWriter.newInstance(); cause.printStackTrace(pw); stackTrace = pw.toString(); while (cause.getCause() != cause) { if (cause.getCause() == null) { break; } cause = cause.getCause(); } stackTraceLines = stackTrace.split("\\n"); if (cause instanceof MultipleCompilationErrorsException) { MultipleCompilationErrorsException mcee = (MultipleCompilationErrorsException) cause; Object message = mcee.getErrorCollector().getErrors().iterator().next(); if (message instanceof SyntaxErrorMessage) { SyntaxErrorMessage sem = (SyntaxErrorMessage) message; lineNumber = sem.getCause().getLine(); className = sem.getCause().getSourceLocator(); sem.write(pw); } } else { Matcher m1 = PARSE_DETAILS_STEP1.matcher(stackTrace); Matcher m2 = PARSE_DETAILS_STEP2.matcher(stackTrace); Matcher gsp = PARSE_GSP_DETAILS_STEP1.matcher(stackTrace); try { if (gsp.find()) { className = gsp.group(2); lineNumber = Integer.parseInt(gsp.group(3)); gspFile = URL_PREFIX + "views/" + gsp.group(1) + '/' + className; } else { if (m1.find()) { do { className = m1.group(1); lineNumber = Integer.parseInt(m1.group(2)); } while (m1.find()); } else { while (m2.find()) { className = m2.group(1); lineNumber = Integer.parseInt(m2.group(2)); } } } } catch (NumberFormatException nfex) { // ignore } } LineNumberReader reader = null; try { checkIfSourceCodeAware(t); checkIfSourceCodeAware(cause); if (getLineNumber() > -1) { String fileLocation; String url = null; if (fileName != null) { fileLocation = fileName; } else { String urlPrefix = ""; if (gspFile == null) { fileName = className.replace('.', '/') + ".groovy"; GrailsApplication application = WebApplicationContextUtils .getRequiredWebApplicationContext(servletContext) .getBean(GrailsApplication.APPLICATION_ID, GrailsApplication.class); // @todo Refactor this to get the urlPrefix from the ArtefactHandler if (application.isArtefactOfType(ControllerArtefactHandler.TYPE, className)) { urlPrefix += "/controllers/"; } else if (application.isArtefactOfType(TagLibArtefactHandler.TYPE, className)) { urlPrefix += "/taglib/"; } else if (application.isArtefactOfType(ServiceArtefactHandler.TYPE, className)) { urlPrefix += "/services/"; } url = URL_PREFIX + urlPrefix + fileName; } else { url = gspFile; GrailsApplicationAttributes attrs = new DefaultGrailsApplicationAttributes(servletContext); GroovyPagesTemplateEngine engine = attrs.getPagesTemplateEngine(); int[] lineNumbers = engine.calculateLineNumbersForPage(servletContext, url); if (lineNumber < lineNumbers.length) { lineNumber = lineNumbers[lineNumber - 1]; } } fileLocation = "grails-app" + urlPrefix + fileName; } InputStream in = null; if (!StringUtils.isBlank(url)) { in = servletContext.getResourceAsStream(url); LOG.debug("Attempting to display code snippet found in url " + url); } if (in == null) { Resource r = null; try { r = resolver.getResource(fileLocation); in = r.getInputStream(); } catch (Throwable e) { r = resolver.getResource("file:" + fileLocation); if (r.exists()) { try { in = r.getInputStream(); } catch (IOException e1) { // ignore } } } } if (in != null) { reader = new LineNumberReader(new InputStreamReader(in)); String currentLine = reader.readLine(); StringBuilder buf = new StringBuilder(); while (currentLine != null) { int currentLineNumber = reader.getLineNumber(); if ((lineNumber > 0 && currentLineNumber == lineNumber - 1) || (currentLineNumber == lineNumber)) { buf.append(currentLineNumber).append(": ").append(currentLine).append("\n"); } else if (currentLineNumber == lineNumber + 1) { buf.append(currentLineNumber).append(": ").append(currentLine); break; } currentLine = reader.readLine(); } codeSnippet = buf.toString().split("\n"); } } } catch (IOException e) { LOG.warn("[GrailsWrappedRuntimeException] I/O error reading line diagnostics: " + e.getMessage(), e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // ignore } } } }
From source file:org.codehaus.groovy.grails.web.mapping.filter.UrlMappingsFilter.java
@Override protected void initFilterBean() throws ServletException { super.initFilterBean(); urlHelper.setUrlDecode(false);/*from ww w.ja v a2 s . c o m*/ final ServletContext servletContext = getServletContext(); final WebApplicationContext applicationContext = WebApplicationContextUtils .getRequiredWebApplicationContext(servletContext); handlerInterceptors = WebUtils.lookupHandlerInterceptors(servletContext); application = WebUtils.lookupApplication(servletContext); viewResolver = WebUtils.lookupViewResolver(servletContext); ApplicationContext mainContext = application.getMainContext(); urlConverter = mainContext.getBean(UrlConverter.BEAN_NAME, UrlConverter.class); if (application != null) { grailsConfig = new GrailsConfig(application); } Map<String, MimeTypeResolver> mimeTypeResolvers = applicationContext.getBeansOfType(MimeTypeResolver.class); if (!mimeTypeResolvers.isEmpty()) { mimeTypeResolver = mimeTypeResolvers.values().iterator().next(); } this.allowHeaderForWrongHttpMethod = grailsConfig.get(WebUtils.SEND_ALLOW_HEADER_FOR_INVALID_HTTP_METHOD, Boolean.TRUE); createStackTraceFilterer(); }
From source file:org.codehaus.groovy.grails.web.sitemesh.GrailsLayoutDecoratorMapper.java
@Override public void init(Config c, Properties properties, DecoratorMapper parentMapper) throws InstantiationException { super.init(c, properties, parentMapper); servletContext = c.getServletContext(); applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); if (applicationContext.containsBean(GrailsPluginManager.BEAN_NAME)) { pluginManager = applicationContext.getBean(GrailsPluginManager.BEAN_NAME, GrailsPluginManager.class); }//from www . jav a 2s.c o m if (applicationContext.containsBean(GrailsApplication.APPLICATION_ID)) { GrailsApplication grailsApplication = applicationContext.getBean(GrailsApplication.APPLICATION_ID, GrailsApplication.class); Map conf = grailsApplication.getFlatConfig(); if (conf != null && conf.containsKey("grails.sitemesh.default.layout")) { defaultDecoratorName = conf.get("grails.sitemesh.default.layout").toString(); } else { defaultDecoratorName = "application"; } } }
From source file:org.codehaus.groovy.grails.web.sitemesh.GrailsLayoutDecoratorMapper.java
private ResourceLoader establishResourceLoader() { ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); GrailsApplication application = null; if (ctx.containsBean(GrailsApplication.APPLICATION_ID)) { application = (GrailsApplication) ctx.getBean(GrailsApplication.APPLICATION_ID); }// w ww .jav a2 s . c o m if (application == null) { return ctx; } if (ctx.containsBean(GroovyPageResourceLoader.BEAN_ID) && !application.isWarDeployed()) { return (ResourceLoader) ctx.getBean(GroovyPageResourceLoader.BEAN_ID); } return ctx; }
From source file:org.codehaus.groovy.grails.web.sitemesh.GrailsPageFilter.java
public void init(FilterConfig filterConfig) { super.init(filterConfig); this.filterConfig = filterConfig; this.containerTweaks = new ContainerTweaks(); Config config = new Config(filterConfig); DefaultFactory defaultFactory = new DefaultFactory(config); config.getServletContext().setAttribute("sitemesh.factory", defaultFactory); defaultFactory.refresh();/*from ww w . ja va2 s . c o m*/ FactoryHolder.setFactory(defaultFactory); this.applicationContext = WebApplicationContextUtils .getRequiredWebApplicationContext(filterConfig.getServletContext()); Map interceptors = applicationContext.getBeansOfType(PersistenceContextInterceptor.class); if (!interceptors.isEmpty()) { persistenceInterceptor = (PersistenceContextInterceptor) interceptors.values().iterator().next(); } }
From source file:org.codehaus.groovy.grails.web.util.WebUtils.java
public static ViewResolver lookupViewResolver(ServletContext servletContext) { WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); return lookupViewResolver(wac); }