List of usage examples for org.springframework.web.context.support WebApplicationContextUtils getRequiredWebApplicationContext
public static WebApplicationContext getRequiredWebApplicationContext(ServletContext sc) throws IllegalStateException
From source file:org.commonfarm.security.auth.DefaultAuthenticator.java
/** * Tries to authenticate a user (via OSUser). If successful, sets a session attribute and cookie indicating * their logged-in status./*from w w w . j av a2 s .c o m*/ * @return Whether the user was authenticated. This base implementation returns false if any errors occur, rather * than throw an exception. */ public boolean login(HttpServletRequest request, HttpServletResponse response, String username, String password, boolean cookie) throws AuthenticatorException { if (appContext == null) { appContext = WebApplicationContextUtils .getRequiredWebApplicationContext(request.getSession().getServletContext()); } //UserManager userManager = (UserManager) appContext.getBean("userManager"); UserService userService = (UserService) appContext.getBean("userService"); Principal user = null; try { user = userService.getUser(username); } catch (Exception e) { log.debug("Could not find user who tried to login: " + e); } // check that they can login (they have the USE permission or ADMINISTER permission) if (user == null) { log.info("Cannot login user '" + username + "' as they do not exist."); } else { boolean authenticated = authenticate(user, password); if (authenticated) { request.getSession().setAttribute(LOGGED_IN_KEY, user); request.getSession().setAttribute(LOGGED_OUT_KEY, null); if (getRoleMapper().canLogin(user, request)) { if (cookie && response != null) { CookieUtils.setCookie(request, response, getLoginCookieKey(), CookieUtils.encodePasswordCookie(username, password, getConfig().getCookieEncoding()), AUTOLOGIN_COOKIE_AGE, getCookiePath(request)); } return true; } else { request.getSession().removeAttribute(LOGGED_IN_KEY); } } else { log.info("Cannot login user '" + username + "' as they used an incorrect password"); } } if (response != null && CookieUtils.getCookie(request, getLoginCookieKey()) != null) { log.warn("LoginUser: " + username + " tried to login but they do not have USE permission or weren't found. Deleting cookie."); try { CookieUtils.invalidateCookie(request, response, getLoginCookieKey(), getCookiePath(request)); } catch (Exception e) { log.error("Could not invalidate cookie: " + e, e); } } return false; }
From source file:org.commonfarm.web.ECSideFilter.java
public Object getBean(HttpServletRequest request, String beanName) { Object bean = null;/*from w w w. ja v a 2 s . co m*/ if (appContext == null) { appContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); } if (appContext != null) { bean = appContext.getBean(beanName); } if (bean == null) { LogHandler.warnLog("Can't find DataAccess Bean named " + beanName, ECSideFilter.class.getName()); } return bean; }
From source file:org.craftercms.cstudio.share.forms.impl.submission.endpoint.WebscriptEndpointImpl.java
/** * post content to url//www . j av a 2 s .c o m */ protected Response call(String op, String url, InputStream model, Map<String, Object> parameters) { Response response = null; try { String endpointId = "alfresco"; SeamlessAppContext appContext = SeamlessAppContext.currentApplicationContext(); HttpServletRequest req = appContext.getRequest(); HttpServletResponse res = appContext.getResponse(); res = new BufferedResponseWrapper(res); /* dont need to do this every time, can cache config */ ApplicationContext alfAppContext = WebApplicationContextUtils .getRequiredWebApplicationContext(appContext.getServletContext()); ConfigService configService = (ConfigService) alfAppContext.getBean("web.config"); RemoteConfigElement config = (RemoteConfigElement) configService.getConfig("Remote") .getConfigElement("remote"); try { // retrieve the endpoint descriptor - do not allow proxy access // to // unsecure endpoints EndpointDescriptor descriptor = config.getEndpointDescriptor(endpointId); if (descriptor == null || descriptor.getUnsecure()) { // throw an exception if endpoint ID is does not exist or // invalid throw new AlfrescoRuntimeException("Invalid EndPoint Id: " + endpointId); } String ticket = req.getParameter(PARAM_ALF_TICKET); if (ticket == null) { ticket = appContext.getTicket(); } // user id from session NOTE: @see // org.alfresco.web.site.UserFactory Connector connector = null; String userId = (String) req.getSession().getAttribute(UserFactory.SESSION_ATTRIBUTE_KEY_USER_ID); if (userId != null) { // build an authenticated connector - as we have a userId connector = _connectorService.getConnector(endpointId, userId, req.getSession()); } else if (ticket != null || descriptor.getIdentity() == IdentityType.NONE || descriptor.getIdentity() == IdentityType.DECLARED || descriptor.getExternalAuth()) { connector = _connectorService.getConnector(endpointId, req.getSession()); } else if (descriptor.getBasicAuth()) { String authorization = req.getHeader("Authorization"); if (authorization == null || authorization.length() == 0) { res.setStatus(HttpServletResponse.SC_UNAUTHORIZED, "No user id found in session and requested endpoint requires authentication."); res.setHeader("WWW-Authenticate", "Basic realm=\"Alfresco\""); } else { String[] authParts = authorization.split(" "); if (!authParts[0].equalsIgnoreCase("basic")) { throw new AlfrescoRuntimeException( "Authorization '" + authParts[0] + "' not supported."); } String[] values = new String(Base64.decode(authParts[1])).split(":"); if (values.length == 2) { if (logger.isDebugEnabled()) logger.debug("Authenticating (BASIC HTTP) user " + values[0]); connector = _connectorService.getConnector(endpointId, values[0], req.getSession()); Credentials credentials = new CredentialsImpl(endpointId); credentials.setProperty(Credentials.CREDENTIAL_USERNAME, values[0]); credentials.setProperty(Credentials.CREDENTIAL_PASSWORD, values[1]); connector.setCredentials(credentials); } else { throw new AlfrescoRuntimeException("Authorization request did not provide user/pass."); } } } else { res.setStatus(HttpServletResponse.SC_UNAUTHORIZED, "No user id found in session and requested endpoint requires authentication."); } ConnectorContext context; if (ticket == null) { context = new ConnectorContext(); } else { // special case for some Flash apps - see above Map<String, String> params = new HashMap<String, String>(1, 1.0f); params.put(PARAM_ALF_TICKET, ticket); context = new ConnectorContext(params, null); } context.setContentType(req.getContentType()); HttpMethod httpMethod = HttpMethod.valueOf(op); context.setMethod(httpMethod); if (url.indexOf("?") != -1) { url += "&" + PARAM_ALF_TICKET + "=" + ticket; } else { url += "?" + PARAM_ALF_TICKET + "=" + ticket; } if (logger.isDebugEnabled()) { logger.debug("EndPointProxyServlet preparing to proxy:"); logger.debug(" - endpointId: " + endpointId); logger.debug(" - userId: " + userId); logger.debug(" - connector: " + connector); logger.debug(" - method: " + context.getMethod()); logger.debug(" - url: " + url); } if (model != null && "POST".equals(op)) { // set default content type for post if not provided if (StringUtils.isEmpty(context.getContentType())) { context.setContentType(POST_REQUEST_DEFAULT_CONTENT_TYPE); } response = connector.call(url, context, model); } else { response = connector.call(url, context); } String statusCode = "" + response.getStatus().getCode(); int statusCodeAsInt = Integer.parseInt(statusCode); if (statusCodeAsInt >= 400) { System.out.println("Submission handler: End point Return code: '" + statusCode + "'"); System.out.println(" - message: " + response.getStatus().getMessage()); System.out.println(" - message: " + response.getStatus().getException()); System.out.println(((BufferedResponseWrapper) res).getString()); System.out.println(" - endpointId: " + endpointId); System.out.println(" - userId: " + userId); System.out.println(" - connector: " + connector); System.out.println(" - method: " + context.getMethod()); System.out.println(" - url: " + url); } } catch (Throwable err) { System.out.println("error during proxy:" + err); throw new AlfrescoRuntimeException("Error during endpoint proxy processing: " + err.getMessage(), err); } } catch (Throwable err) { System.out.println("error during proxy:" + err); err.printStackTrace(); throw new AlfrescoRuntimeException("Error during endpoint proxy processing: " + err.getMessage(), err); } return response; }
From source file:org.craftercms.cstudio.share.servlet.ShareAuthenticationFilter.java
/** * Run the filter//from www . ja v a 2s . co m * * @param request * ServletRequest * @param response * ServletResponse * @param chain * FilterChain * @exception IOException * @exception ServletException */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) request; HttpServletResponse httpRes = (HttpServletResponse) response; // get ticket and username from cookies String ticket = getTicket(httpReq); String username = getUsername(httpReq); SeamlessAppContext seamlessAppContext = null; ConnectorSession connectionSession = null; try { if (ServletUtils.determineDispatchType(httpReq) == ServletUtils.REQUEST || ServletUtils.determineDispatchType(httpReq) == ServletUtils.FORWARD) { seamlessAppContext = new SeamlessAppContext(); seamlessAppContext.setRequest(httpReq); seamlessAppContext.setResponse(httpRes); seamlessAppContext.setServletContext(this.servletContext); SeamlessAppContext.setApplicationContextForThread(seamlessAppContext); if (ticket == null && username == null) { AuthenticationUtil.logout(httpReq, httpRes); } // Validate the ticket if retrieved from cookie and set it in // connection session if (ticket != null) { //////// // This is from http://forums1.man.alfresco.com/en/viewtopic.php?f=48&t=27872. // It was added to deal with the fact that FrameworkUtil.getServiceRegistry() returned null. /////// ApplicationContext applContext = WebApplicationContextUtils .getRequiredWebApplicationContext(this.servletContext); // initialize a new request context RequestContext context = FrameworkUtil.getCurrentRequestContext(); // This is probably always null in this case. if (context == null) { try { // perform a "silent" init - i.e. no user creation or remote connections context = RequestContextUtil.initRequestContext(applContext, httpReq, true); } catch (RequestContextException ex) { throw new ServletException(ex); } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Validating alfresco ticket: " + ticket); } connectionSession = validateTicket(request, response, ticket, username); } if (connectionSession != null) loadLastPages(httpReq, httpRes, username); } if (connectionSession != null) { if (connectionSession.getParameter(AlfrescoAuthenticator.CS_PARAM_ALF_TICKET) != null) { seamlessAppContext .setTicket(connectionSession.getParameter(AlfrescoAuthenticator.CS_PARAM_ALF_TICKET)); seamlessAppContext.setRequest(httpReq); seamlessAppContext.setResponse(httpRes); /* Chain to the next filter */ chain.doFilter(httpReq, httpRes); } } else { /* Chain to the next filter */ chain.doFilter(httpReq, httpRes); } } finally { if (ServletUtils.determineDispatchType(httpReq) == ServletUtils.REQUEST || ServletUtils.determineDispatchType(httpReq) == ServletUtils.FORWARD) { SeamlessAppContext.setApplicationContextForThread(null); } } }
From source file:org.craftercms.cstudio.share.servlet.ShareAuthenticationFilter.java
public void init(FilterConfig filterConfig) { this.servletContext = filterConfig.getServletContext(); ApplicationContext context = WebApplicationContextUtils .getRequiredWebApplicationContext(this.servletContext); /* retrieve the connector service */ this.connectorService = (ConnectorService) context.getBean("connector.service"); /* retrieve the cookie manager */ this.cookieManager = (CookieManager) context.getBean("rlCookieManager"); /* retrieve the user preference manager */ this.userPreferenceManager = (UserPreferenceManager) context.getBean("rlUserPreferenceManager"); this.enableRememberLastPage = new Boolean(filterConfig.getInitParameter("enableRememberLastPage")); this.defaultLastPage = filterConfig.getInitParameter("defaultRememberLastPage"); }
From source file:org.craftercms.cstudio.share.servlet.ShareLoginServlet.java
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = (String) request.getParameter("username"); String password = (String) request.getParameter("password"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Share Login Username " + username); LOGGER.debug("Share Login Password " + password); }/* w w w .j a v a2 s . c o m*/ String successPage = (String) request.getParameter("success"); String failurePage = (String) request.getParameter("failure"); ApplicationContext applContext = WebApplicationContextUtils .getRequiredWebApplicationContext(getServletContext()); /* retrieve the cookie manager */ this.cookieManager = (CookieManager) applContext.getBean("rlCookieManager"); /* retrieve the user preference manager */ this.userPreferenceManager = (UserPreferenceManager) applContext.getBean("rlUserPreferenceManager"); // See if we can load the user with this identity boolean success = false; try { //////// // This is from http://forums1.man.alfresco.com/en/viewtopic.php?f=48&t=27872. // It was added to deal with the fact that FrameworkUtil.getServiceRegistry() returned null. /////// // initialize a new request context RequestContext context = FrameworkUtil.getCurrentRequestContext(); // This is probably always null in this case. if (context == null) { try { // perform a "silent" init - i.e. no user creation or remote connections context = RequestContextUtil.initRequestContext(applContext, request, true); } catch (RequestContextException ex) { throw new ServletException(ex); } } //////// WebFrameworkServiceRegistry serviceRegistry = context.getServiceRegistry(); UserFactory userFactory = serviceRegistry.getUserFactory(); // see if we can authenticate the user boolean authenticated = userFactory.authenticate(request, username, password); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Is authenticated " + authenticated); } if (authenticated) { // this will fully reset all connector sessions AuthenticationUtil.login(request, response, username); ConnectorSession cs = FrameworkUtil.getConnectorSession(request.getSession(), ShareConstants.ENDPOINT_ALFRESCO); String alf_ticket = cs.getParameter(AlfrescoAuthenticator.CS_PARAM_ALF_TICKET); //protecting any unexpected situation, when ticket/username is null if ((StringUtils.isEmpty(alf_ticket)) || (StringUtils.isEmpty(username))) { success = false; } else { //set cookies when authenticated cookieManager.putCookieValue(request, response, ShareConstants.COOKIE_ALFRESCO_TICKET, COOKIE_AGE, alf_ticket); cookieManager.putCookieValue(request, response, ShareConstants.COOKIE_ALFRESCO_USERNAME, COOKIE_AGE, username); // mark the fact that we succeeded success = true; } } } catch (Throwable err) { throw new ServletException(err); // instead of throwing exception, we should have forwarded to login page; but later! } // If they succeeded in logging in, redirect to the success page // Otherwise, redirect to the failure page if (success) { if (successPage != null) { //check for recent dashboard and set the page to it Cookie cookies[] = request.getCookies(); String pageCookie = null; // if (cookies != null) { // pageCookie = userPreferenceManager.getMostRecentDashboard(username, request); // } // if(pageCookie != null) { // if(successPage.contains("/page") && ! successPage.contains("/site-index")) { // response.sendRedirect(successPage); // } else { // response.sendRedirect(pageCookie); // } // } else { response.sendRedirect(successPage); // } } else { response.sendRedirect(request.getContextPath()); } } else { if (failurePage != null) { response.sendRedirect(failurePage); } else { response.sendRedirect(request.getContextPath()); } } }
From source file:org.devproof.portal.core.app.PortalApplication.java
public ApplicationContext getSpringContext() { return WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); }
From source file:org.efs.openreports.dispatcher.FileDispatcher.java
public void init(ServletConfig servletConfig) throws ServletException { ORComponentManager.initializeObject(this); //If not using WebWork IOC try Spring... if (directoryProvider == null) { ApplicationContext appContext = WebApplicationContextUtils .getRequiredWebApplicationContext(servletConfig.getServletContext()); directoryProvider = (DirectoryProvider) appContext.getBean("directoryProvider", ReportService.class); }/* w ww. j av a2 s .c om*/ imageDirectory = directoryProvider.getReportImageDirectory(); imageTempDirectory = directoryProvider.getReportImageTempDirectory(); reportGenerationDirectory = directoryProvider.getReportGenerationDirectory(); super.init(servletConfig); log.info("Started..."); }
From source file:org.efs.openreports.services.servlet.ReportServiceServlet.java
public void init(ServletConfig servletConfig) throws ServletException { ApplicationContext appContext = WebApplicationContextUtils .getRequiredWebApplicationContext(servletConfig.getServletContext()); reportService = (ReportService) appContext.getBean("reportService", ReportService.class); //cache ServletReportServiceInput PropertyDescriptors descriptors = PropertyUtils.getPropertyDescriptors(ServletReportServiceInput.class); super.init(servletConfig); log.info("Started..."); }
From source file:org.egov.services.zuulproxy.filter.ZuulProxyFilter.java
@Override public Object run() { mapper = new ObjectMapper(); final RequestContext ctx = RequestContext.getCurrentContext(); final HttpServletRequest request = ctx.getRequest(); final WebApplicationContext springContext = WebApplicationContextUtils .getRequiredWebApplicationContext(request.getServletContext()); final HashMap<String, String> zuulProxyRoutingUrls; final ServicesApplicationProperties applicationProperties = (ServicesApplicationProperties) springContext .getBean(SERVICES_APPLICATION_PROPERTIES); try {/*from w w w .j a va 2s . c om*/ zuulProxyRoutingUrls = (HashMap<String, String>) applicationProperties.zuulProxyRoutingUrls(); if (log.isInfoEnabled()) log.info("Zuul Proxy Routing Mapping Urls... " + zuulProxyRoutingUrls); } catch (final Exception e) { throw new ApplicationRuntimeException("Could not get valid routing url mapping for mirco services", e); } try { final URL requestURL = new URL(request.getRequestURL().toString()); String endPointURI; if (requestURL.getPath().startsWith(SERVICES_CONTEXTROOT)) endPointURI = requestURL.getPath().split(SERVICES_CONTEXTROOT)[1]; else endPointURI = requestURL.getPath(); String mappingURL = ""; for (final Entry<String, String> entry : zuulProxyRoutingUrls.entrySet()) { final String key = entry.getKey(); if (endPointURI.contains(key)) { mappingURL = entry.getValue(); break; } } if (log.isInfoEnabled()) log.info(String.format("%s request to the url %s", request.getMethod(), request.getRequestURL().toString())); final String tenantId = getTanentId(springContext); final StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(endPointURI).append('?') .append(updateQueryString(request.getQueryString(), TENANT_ID, tenantId)); endPointURI = stringBuilder.toString(); if (log.isInfoEnabled()) log.info("endPointURI " + endPointURI); final URL routedHost = new URL(mappingURL + endPointURI); ctx.setRouteHost(routedHost); ctx.set(REQUEST_URI, routedHost.getPath()); Map<String, List<String>> map = HTTPRequestUtils.getInstance().getQueryParams(); if (map == null) { RequestContext.getCurrentContext().setRequestQueryParams(new HashMap<String, List<String>>()); map = HTTPRequestUtils.getInstance().getQueryParams(); } map.put(TENANT_ID, Arrays.asList(tenantId)); ctx.setRequestQueryParams(map); if (log.isInfoEnabled()) log.info("TenantId from getRequestQueryParams() " + ctx.getRequestQueryParams().get(TENANT_ID).toString()); final String userInfo = getUserInfo(request, springContext, tenantId); //Adding userInfo to Response header - to show or hide some of the UI components based on user roles ctx.addZuulResponseHeader(USER_INFO_FIELD_NAME, userInfo); if (log.isInfoEnabled()) if (request.getSession() != null) log.info("SESSION ID " + request.getSession().getId()); if (shouldPutUserInfoOnHeaders(ctx)) { ctx.addZuulRequestHeader(USER_INFO_FIELD_NAME, userInfo); if (request.getSession() != null) ctx.addZuulRequestHeader(SESSION_ID, request.getSession().getId()); } else { if (request.getSession() != null) ctx.addZuulRequestHeader(SESSION_ID, request.getSession().getId()); appendUserInfoToRequestBody(ctx, userInfo); } } catch (final MalformedURLException e) { throw new ApplicationRuntimeException("Could not form valid URL", e); } catch (final IOException ex) { ctx.setSendZuulResponse(false); throw new ApplicationRuntimeException("Problem while setting RequestInfo..", ex); } return null; }