List of usage examples for org.springframework.web.context.support WebApplicationContextUtils getWebApplicationContext
@Nullable public static WebApplicationContext getWebApplicationContext(ServletContext sc)
From source file:org.alfresco.web.app.ContextListener.java
/** * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent) */// w ww .ja v a 2s. c om public void contextInitialized(ServletContextEvent event) { // make sure that the spaces store in the repository exists this.servletContext = event.getServletContext(); WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext); // If no context has been initialised, exit silently so config changes can be made if (ctx == null) { return; } ServiceRegistry registry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY); TransactionService transactionService = registry.getTransactionService(); NodeService nodeService = registry.getNodeService(); SearchService searchService = registry.getSearchService(); NamespaceService namespaceService = registry.getNamespaceService(); AuthenticationContext authenticationContext = (AuthenticationContext) ctx.getBean("authenticationContext"); // repo bootstrap code for our client UserTransaction tx = null; NodeRef companySpaceNodeRef = null; try { tx = transactionService.getUserTransaction(); tx.begin(); authenticationContext.setSystemUserAsCurrentUser(); // get and setup the initial store ref and root path from config StoreRef storeRef = Repository.getStoreRef(servletContext); // get root path String rootPath = Application.getRootPath(servletContext); // Extract company space id and store it in the Application object companySpaceNodeRef = Repository.getCompanyRoot(nodeService, searchService, namespaceService, storeRef, rootPath); Application.setCompanyRootId(companySpaceNodeRef.getId()); // commit the transaction tx.commit(); } catch (Throwable e) { // rollback the transaction try { if (tx != null) { tx.rollback(); } } catch (Exception ex) { } logger.error("Failed to initialise ", e); throw new AlfrescoRuntimeException("Failed to initialise ", e); } finally { try { authenticationContext.clearCurrentSecurityContext(); } catch (Exception ex) { } } }
From source file:org.apache.axis2.extensions.spring.receivers.SpringServletContextObjectSupplier.java
/** * Method getServiceObject that is Spring aware via ServletContext. * * @param axisService/*from www. j a v a 2s . co m*/ * @return Returns Object. * @throws AxisFault */ public Object getServiceObject(AxisService axisService) throws AxisFault { try { // Name of spring aware bean to be injected, taken from services.xml // via 'SERVICE_SPRING_BEANNAME ' . The Bean and its properties are pre-configured // as normally done in a spring type of way and subsequently loaded by Spring. // Axis2 just assumes that the bean is configured and is in the classloader. Parameter implBeanParam = axisService.getParameter(SERVICE_SPRING_BEANNAME); String beanName = ((String) implBeanParam.getValue()).trim(); if (beanName != null) { Parameter servletConfigParam = axisService.getAxisConfiguration() .getParameter(HTTPConstants.HTTP_SERVLETCONFIG); if (servletConfigParam == null) { throw new Exception("Axis2 Can't find ServletConfigParameter"); } Object obj = servletConfigParam.getValue(); ServletContext servletContext; if (obj instanceof ServletConfig) { ServletConfig servletConfig = (ServletConfig) obj; servletContext = servletConfig.getServletContext(); } else { throw new Exception("Axis2 Can't find ServletConfig"); } ApplicationContext aCtx = WebApplicationContextUtils.getWebApplicationContext(servletContext); if (aCtx == null) { log.warn("Axis2 Can't find Spring's ApplicationContext"); return null; } else if (aCtx.getBean(beanName) == null) { throw new Exception("Axis2 Can't find Spring Bean: " + beanName); } return aCtx.getBean(beanName); } else { throw new AxisFault(Messages.getMessage("paramIsNotSpecified", "SERVICE_SPRING_BEANNAME")); } } catch (Exception e) { throw AxisFault.makeFault(e); } }
From source file:org.apache.nifi.web.filter.NodeRequestFilter.java
@Override public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain filterChain) throws IOException, ServletException { ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext()); NiFiProperties properties = ctx.getBean("nifiProperties", NiFiProperties.class); HttpServletRequest httpReq = (HttpServletRequest) req; HttpServletResponse httpResp = (HttpServletResponse) resp; /*//from w ww . j a v a 2s . c om * If we're the cluster manager or we're sent head requests, continue. * Head requests are included because there exists a AJAX/XHR race * condition between the following requests: * HEAD /nifi-api/cluster * GET /nifi-api/controller/config * If the head request finishes first, then the UI JavaScript will display * a default error message and not display the error message given in this * filter for directly accessing connected nodes. */ if (properties.isClusterManager() || "HEAD".equalsIgnoreCase(httpReq.getMethod())) { filterChain.doFilter(req, resp); } else { NiFiServiceFacade serviceFacade = ctx.getBean("serviceFacade", NiFiServiceFacade.class); if (!serviceFacade.isClustered()) { filterChain.doFilter(req, resp); } else { // get the cluster context from the request ClusterContext clusterContext = null; String clusterContextHeaderValue = httpReq.getHeader(WebClusterManager.CLUSTER_CONTEXT_HTTP_HEADER); if (StringUtils.isNotBlank(clusterContextHeaderValue)) { try { // deserialize object Serializable clusterContextObj = WebUtils.deserializeHexToObject(clusterContextHeaderValue); if (clusterContextObj instanceof ClusterContext) { clusterContext = (ClusterContext) clusterContextObj; } } catch (final ClassNotFoundException cnfe) { logger.warn("Failed to deserialize cluster context from request due to: " + cnfe, cnfe); } } // if don't have a cluster context or the context indicates if (clusterContext == null || !clusterContext.isRequestSentByClusterManager()) { // node is connected and request is not from cluster manager, so respond with error httpResp.setContentType("text/plain"); httpResp.setStatus(HttpServletResponse.SC_FORBIDDEN); httpResp.getWriter().print( "Direct access to Flow Controller node is only permissible if node is disconnected."); } else { ClusterContextThreadLocal.setContext(clusterContext); filterChain.doFilter(req, resp); } } } }
From source file:org.apache.nifi.web.security.authorization.NodeAuthorizedUserFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpServletRequest = (HttpServletRequest) request; // get the proxied user's authorities final String hexEncodedUserDetails = httpServletRequest.getHeader(PROXY_USER_DETAILS); // check if the request has the necessary header information and this instance is configured as a node if (StringUtils.isNotBlank(hexEncodedUserDetails) && properties.isNode()) { // get the flow controller from the Spring context final ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); final FlowController flowController = ctx.getBean("flowController", FlowController.class); // check that we are connected to the cluster if (flowController.getNodeId() != null) { try { // get the DN from the cert in the request final X509Certificate certificate = certificateExtractor .extractClientCertificate((HttpServletRequest) request); if (certificate != null) { // extract the principal from the certificate final Object certificatePrincipal = principalExtractor.extractPrincipal(certificate); final String dn = certificatePrincipal.toString(); // only consider the pre-authorized user when the request came from the NCM according to the DN in the certificate final String clusterManagerDN = flowController.getClusterManagerDN(); if (clusterManagerDN != null && clusterManagerDN.equals(dn)) { // deserialize hex encoded object final Serializable userDetailsObj = WebUtils .deserializeHexToObject(hexEncodedUserDetails); // if we have a valid object, set the authentication token and bypass the remaining authentication processing chain if (userDetailsObj instanceof NiFiUserDetails) { final NiFiUserDetails userDetails = (NiFiUserDetails) userDetailsObj; final NiFiUser user = userDetails.getNiFiUser(); // log the request attempt - response details will be logged later logger.info(String.format("Attempting request for (%s) %s %s (source ip: %s)", user.getDn(), httpServletRequest.getMethod(), httpServletRequest.getRequestURL().toString(), request.getRemoteAddr())); // we do not create the authentication token with the X509 certificate because the certificate is from the sending system, not the proxied user final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken( userDetails, null, userDetails.getAuthorities()); token.setDetails(authenticationDetailsSource.buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(token); }/* w w w .ja v a 2 s .c o m*/ } } } catch (final ClassNotFoundException cnfe) { LOGGER.warn( "Classpath issue detected because failed to deserialize authorized user in request header due to: " + cnfe, cnfe); } } } chain.doFilter(request, response); }
From source file:org.apache.nifi.web.security.node.NodeAuthorizedUserFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpServletRequest = (HttpServletRequest) request; // get the proxied user's authorities final String hexEncodedUserDetails = httpServletRequest.getHeader(PROXY_USER_DETAILS); // check if the request has the necessary header information and this instance is configured as a node if (StringUtils.isNotBlank(hexEncodedUserDetails) && properties.isNode()) { // get the flow controller from the Spring context final ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); final FlowController flowController = ctx.getBean("flowController", FlowController.class); // check that we are connected to the cluster if (flowController.getNodeId() != null) { try { // attempt to extract the client certificate final X509Certificate[] certificate = certificateExtractor .extractClientCertificate(httpServletRequest); if (certificate != null) { // authenticate the certificate final AuthenticationResponse authenticationResponse = certificateIdentityProvider .authenticate(certificate); // only consider the pre-authorized user when the request came directly from the NCM according to the DN in the certificate final String clusterManagerIdentity = flowController.getClusterManagerDN(); if (clusterManagerIdentity != null && clusterManagerIdentity.equals(authenticationResponse.getIdentity())) { // deserialize hex encoded object final Serializable userDetailsObj = WebUtils .deserializeHexToObject(hexEncodedUserDetails); // if we have a valid object, set the authentication token and bypass the remaining authentication processing chain if (userDetailsObj instanceof NiFiUserDetails) { final NiFiUserDetails userDetails = (NiFiUserDetails) userDetailsObj; final NiFiUser user = userDetails.getNiFiUser(); // log the request attempt - response details will be logged later logger.info(String.format("Attempting request for (%s) %s %s (source ip: %s)", user.getIdentity(), httpServletRequest.getMethod(), httpServletRequest.getRequestURL().toString(), request.getRemoteAddr())); // create the authorized nifi token final NiFiAuthorizationToken token = new NiFiAuthorizationToken(userDetails); SecurityContextHolder.getContext().setAuthentication(token); }//from w ww. j a v a 2 s . c om } } } catch (final ClassNotFoundException cnfe) { LOGGER.warn( "Classpath issue detected because failed to deserialize authorized user in request header due to: " + cnfe, cnfe); } catch (final IllegalArgumentException iae) { // unable to authenticate a serialized user from the incoming request } } } chain.doFilter(request, response); }
From source file:org.apache.nifi.web.server.JettyServer.java
@Override public void start() { try {// ww w . j a v a2 s . com // 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.struts2.showcase.chat.ChatSessionListener.java
public void sessionDestroyed(HttpSessionEvent event) { HttpSession session = event.getSession(); WebApplicationContext context = WebApplicationContextUtils .getWebApplicationContext(session.getServletContext()); if (context != null) { User user = (User) session.getAttribute(ChatInterceptor.CHAT_USER_SESSION_KEY); if (user != null) { ChatService service = (ChatService) context.getBean("chatService"); service.logout(user.getName()); _log.info("session expired, logged user [" + user.getName() + "] out"); }/* w w w . j av a2 s . com*/ } }
From source file:org.apache.syncope.client.console.SyncopeApplication.java
@Override protected void init() { super.init(); getComponentInstantiationListeners().add(new SpringComponentInjector(this)); getResourceSettings().setThrowExceptionOnMissingResource(true); getSecuritySettings().setAuthorizationStrategy(new RoleAuthorizationStrategy(this)); getSecuritySettings().setUnauthorizedComponentInstantiationListener(this); getMarkupSettings().setStripWicketTags(true); getMarkupSettings().setCompressWhitespace(true); getRequestCycleListeners().add(new SyncopeRequestCycleListener()); final String activitiModelerDirectory = WebApplicationContextUtils .getWebApplicationContext(WebApplication.get().getServletContext()) .getBean("activitiModelerDirectory", String.class); mountResource("/" + ACTIVITI_MODELER_CONTEXT, new ResourceReference(ACTIVITI_MODELER_CONTEXT) { private static final long serialVersionUID = -128426276529456602L; @Override//from w w w . j a v a 2 s . com public IResource getResource() { return new FilesystemResource(ACTIVITI_MODELER_CONTEXT, activitiModelerDirectory); } }); mountResource("/workflowDefGET", new ResourceReference("workflowDefGET") { private static final long serialVersionUID = -128426276529456602L; @Override public IResource getResource() { return new WorkflowDefGETResource(); } }); mountResource("/workflowDefPUT", new ResourceReference("workflowDefPUT") { private static final long serialVersionUID = -128426276529456602L; @Override public IResource getResource() { return new WorkflowDefPUTResource(); } }); }
From source file:org.apache.syncope.client.console.SyncopeSession.java
public SyncopeSession(final Request request) { super(request); final ApplicationContext ctx = WebApplicationContextUtils .getWebApplicationContext(WebApplication.get().getServletContext()); clientFactory = ctx.getBean(SyncopeClientFactoryBean.class) .setContentType(SyncopeClientFactoryBean.ContentType.JSON); anonymousUser = ctx.getBean("anonymousUser", String.class); anonymousKey = ctx.getBean("anonymousKey", String.class); syncopeTO = clientFactory.create(anonymousUser, anonymousKey).getService(SyncopeService.class).info(); }
From source file:org.apache.syncope.console.pages.Configuration.java
public Configuration() { super();//from ww w .ja v a 2 s . c o m setupSyncopeConf(); add(new PoliciesPanel("passwordPoliciesPanel", getPageReference(), PolicyType.PASSWORD)); add(new PoliciesPanel("accountPoliciesPanel", getPageReference(), PolicyType.ACCOUNT)); add(new PoliciesPanel("syncPoliciesPanel", getPageReference(), PolicyType.SYNC)); add(createNotificationWin = new ModalWindow("createNotificationWin")); add(editNotificationWin = new ModalWindow("editNotificationWin")); setupNotification(); // Workflow definition stuff WebMarkupContainer noActivitiEnabledForUsers = new WebMarkupContainer("noActivitiEnabledForUsers"); noActivitiEnabledForUsers.setOutputMarkupPlaceholderTag(true); add(noActivitiEnabledForUsers); WebMarkupContainer workflowDefContainer = new WebMarkupContainer("workflowDefContainer"); workflowDefContainer.setOutputMarkupPlaceholderTag(true); if (wfRestClient.isActivitiEnabledForUsers()) { noActivitiEnabledForUsers.setVisible(false); } else { workflowDefContainer.setVisible(false); } BookmarkablePageLink<Void> activitiModeler = new BookmarkablePageLink<Void>("activitiModeler", ActivitiModelerPopupPage.class); activitiModeler.setPopupSettings(new VeilPopupSettings().setHeight(600).setWidth(800)); MetaDataRoleAuthorizationStrategy.authorize(activitiModeler, ENABLE, xmlRolesReader.getAllAllowedRoles("Configuration", "workflowDefRead")); workflowDefContainer.add(activitiModeler); // Check if Activiti Modeler directory is found boolean activitiModelerEnabled = false; try { String activitiModelerDirectory = WebApplicationContextUtils .getWebApplicationContext(WebApplication.get().getServletContext()) .getBean("activitiModelerDirectory", String.class); File baseDir = new File(activitiModelerDirectory); activitiModelerEnabled = baseDir.exists() && baseDir.canRead() && baseDir.isDirectory(); } catch (Exception e) { LOG.error("Could not check for Activiti Modeler directory", e); } activitiModeler.setEnabled(activitiModelerEnabled); BookmarkablePageLink<Void> xmlEditor = new BookmarkablePageLink<Void>("xmlEditor", XMLEditorPopupPage.class); xmlEditor.setPopupSettings(new VeilPopupSettings().setHeight(480).setWidth(800)); MetaDataRoleAuthorizationStrategy.authorize(xmlEditor, ENABLE, xmlRolesReader.getAllAllowedRoles("Configuration", "workflowDefRead")); workflowDefContainer.add(xmlEditor); Image workflowDefDiagram = new Image("workflowDefDiagram", new Model()) { private static final long serialVersionUID = -8457850449086490660L; @Override protected IResource getImageResource() { return new DynamicImageResource() { private static final long serialVersionUID = 923201517955737928L; @Override protected byte[] getImageData(final IResource.Attributes attributes) { return wfRestClient.isActivitiEnabledForUsers() ? wfRestClient.getDiagram() : new byte[0]; } }; } }; workflowDefContainer.add(workflowDefDiagram); MetaDataRoleAuthorizationStrategy.authorize(workflowDefContainer, ENABLE, xmlRolesReader.getAllAllowedRoles("Configuration", "workflowDefRead")); add(workflowDefContainer); // Logger stuff PropertyListView<LoggerTO> coreLoggerList = new LoggerPropertyList(null, "corelogger", loggerRestClient.listLogs()); WebMarkupContainer coreLoggerContainer = new WebMarkupContainer("coreLoggerContainer"); coreLoggerContainer.add(coreLoggerList); coreLoggerContainer.setOutputMarkupId(true); MetaDataRoleAuthorizationStrategy.authorize(coreLoggerContainer, ENABLE, xmlRolesReader.getAllAllowedRoles("Configuration", "logList")); add(coreLoggerContainer); ConsoleLoggerController consoleLoggerController = new ConsoleLoggerController(); PropertyListView<LoggerTO> consoleLoggerList = new LoggerPropertyList(consoleLoggerController, "consolelogger", consoleLoggerController.getLoggers()); WebMarkupContainer consoleLoggerContainer = new WebMarkupContainer("consoleLoggerContainer"); consoleLoggerContainer.add(consoleLoggerList); consoleLoggerContainer.setOutputMarkupId(true); MetaDataRoleAuthorizationStrategy.authorize(consoleLoggerContainer, ENABLE, xmlRolesReader.getAllAllowedRoles("Configuration", "logList")); add(consoleLoggerContainer); }