List of usage examples for javax.servlet ServletRequest setAttribute
public void setAttribute(String name, Object o);
From source file:org.egov.lib.rrbac.filter.RuleInterceptorFilter.java
@Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { // from action, for which actions rule should be applied expecting parameter with name // AUTHRULE_OBJECT_ID and value is id of the // product entity. Eg : In case of PTIS BasicPoperty primary key if (request.getParameter("AUTHRULE_OBJECT_ID") != null) { final HttpServletRequest httpRequest = (HttpServletRequest) request; final Action action = this.getAction(httpRequest); final List<AuthorizationRule> authRuleList = this.authRuleService .findAllByNamedQuery("authRulesByAction", action); for (final AuthorizationRule authRule : authRuleList) { final Object object = this.getEntity(httpRequest, authRule); final List authResList = this.getRuleAuthentication(securityUtils.getCurrentUser(), authRule, object);// ww w. jav a 2s . c o m final boolean authorized = Boolean.valueOf(authResList.get(0).toString()); if (!authorized) { // if authorization fails throwing AuthorizationException // setting message key to request, from script when authorization failed request.setAttribute("AuthRuleErrMsgKey", authResList.get(1).toString()); throw new AuthorizationException(authResList.get(1).toString()); } } } chain.doFilter(request, response); }
From source file:org.codice.ddf.security.filter.websso.WebSSOFilter.java
/** * Provides filtering for every registered http context. Checks for an * existing session (via the SAML assertion included as a cookie). If it * doesn't exist, it then looks up the current context and determines the * proper handlers to include in the chain. Each handler is given the * opportunity to locate their specific tokens if they exist or to go off * and obtain them. Once a token has been received that we know how to * convert to a SAML assertion, we attach them to the request and continue * down the chain./* www . j a va 2s .com*/ * * @param servletRequest incoming http request * @param servletResponse response stream for returning the response * @param filterChain chain of filters to be invoked following this filter * @throws IOException * @throws ServletException */ @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { LOGGER.debug("Performing doFilter() on WebSSOFilter"); HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; HttpServletResponse httpResponse = (HttpServletResponse) servletResponse; String path = StringUtils.isNotBlank(httpRequest.getContextPath()) ? httpRequest.getContextPath() : httpRequest.getServletPath() + StringUtils.defaultString(httpRequest.getPathInfo()); if (StringUtils.isEmpty(path)) { path = httpRequest.getRequestURI(); } LOGGER.debug("Handling request for path {}", path); String realm = BaseAuthenticationToken.DEFAULT_REALM; boolean isWhiteListed = false; if (contextPolicyManager != null) { ContextPolicy policy = contextPolicyManager.getContextPolicy(path); if (policy != null) { realm = policy.getRealm(); } isWhiteListed = contextPolicyManager.isWhiteListed(path); } // set this so the login filter can easily determine the realm servletRequest.setAttribute(ContextPolicy.ACTIVE_REALM, realm); if (isWhiteListed) { LOGGER.debug("Context of {} has been whitelisted, adding a NO_AUTH_POLICY attribute to the header.", path); servletRequest.setAttribute(ContextPolicy.NO_AUTH_POLICY, true); filterChain.doFilter(httpRequest, httpResponse); } else { // make sure request didn't come in with NO_AUTH_POLICY set servletRequest.setAttribute(ContextPolicy.NO_AUTH_POLICY, null); // now handle the request and set the authentication token LOGGER.debug("Handling request for {} in security realm {}.", path, realm); handleRequest(httpRequest, httpResponse, filterChain, getHandlerList(path)); } }
From source file:org.apache.catalina.core.ApplicationDispatcher.java
private void doInclude(ServletRequest request, ServletResponse response) throws ServletException, IOException { // Set up to handle the specified request and response setup(request, response, true);//from ww w. ja v a 2 s . co m // Create a wrapped response to use for this request // ServletResponse wresponse = null; ServletResponse wresponse = wrapResponse(); // Handle a non-HTTP include if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) { if (log.isDebugEnabled()) log.debug(" Non-HTTP Include"); request.setAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, new Integer(ApplicationFilterFactory.INCLUDE)); request.setAttribute(ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, origServletPath); invoke(request, outerResponse); unwrapResponse(); } // Handle an HTTP named dispatcher include else if (name != null) { if (log.isDebugEnabled()) log.debug(" Named Dispatcher Include"); ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(); wrequest.setAttribute(Globals.NAMED_DISPATCHER_ATTR, name); if (servletPath != null) wrequest.setServletPath(servletPath); wrequest.setAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, new Integer(ApplicationFilterFactory.INCLUDE)); wrequest.setAttribute(ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, origServletPath); invoke(outerRequest, outerResponse); unwrapRequest(); unwrapResponse(); } // Handle an HTTP path based include else { if (log.isDebugEnabled()) log.debug(" Path Based Include"); ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(); String contextPath = context.getPath(); /* StringBuffer sb = new StringBuffer(); if (contextPath != null) sb.append(contextPath); if (servletPath != null) sb.append(servletPath); if (pathInfo != null) sb.append(pathInfo); if (sb.length() > 0) */ if (requestURI != null) wrequest.setAttribute(Globals.INCLUDE_REQUEST_URI_ATTR, requestURI); if (contextPath != null) wrequest.setAttribute(Globals.INCLUDE_CONTEXT_PATH_ATTR, contextPath); if (servletPath != null) wrequest.setAttribute(Globals.INCLUDE_SERVLET_PATH_ATTR, servletPath); if (pathInfo != null) wrequest.setAttribute(Globals.INCLUDE_PATH_INFO_ATTR, pathInfo); if (queryString != null) { wrequest.setAttribute(Globals.INCLUDE_QUERY_STRING_ATTR, queryString); wrequest.setQueryParams(queryString); } wrequest.setAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, new Integer(ApplicationFilterFactory.INCLUDE)); wrequest.setAttribute(ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, origServletPath); invoke(outerRequest, outerResponse); unwrapRequest(); unwrapResponse(); } }
From source file:org.ambraproject.web.VirtualJournalContextFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException { final Collection<String> virtualJournals = configuration.getList(CONF_VIRTUALJOURNALS_JOURNALS); String defaultJournal = configuration.getString(CONF_VIRTUALJOURNALS_DEFAULT); // need to do <rule> based processing String journalName = findMatchingVirtualJournal(configuration, (HttpServletRequest) request); if (journalName != null) { if (log.isTraceEnabled()) { log.trace("journal from rules: journal = \"" + journalName + "\""); }// ww w .jav a2 s .c o m } else { // was a simple config <default> specified? journalName = defaultJournal; if (log.isTraceEnabled()) { log.trace("journal from defaults: journal = \"" + journalName + "\""); } } // empty if default not set if (journalName == null) { journalName = ""; if (log.isTraceEnabled()) { log.trace("Default journal not set"); } } if (log.isDebugEnabled()) { log.debug("journal = \"" + journalName + "\" for " + ((HttpServletRequest) request).getRequestURL()); } // put virtualJournal context in the ServletRequest for webapp to use request.setAttribute(VirtualJournalContext.PUB_VIRTUALJOURNAL_CONTEXT, new VirtualJournalContext(journalName, defaultJournal, request.getScheme(), request.getServerPort(), request.getServerName(), ((HttpServletRequest) request).getContextPath(), virtualJournals)); /* * Establish a "Nested Diagnostic Context" for logging, e.g. prefix log entries w/journal name * http://logging.apache.org/log4j/docs/api/org/apache/log4j/NDC.html */ NDC.push(journalName); try { // continue the Filter chain ... filterChain.doFilter(request, response); } finally { // cleanup "Nested Diagnostic Context" for logging NDC.pop(); NDC.remove(); // TODO: appropriate place to cleanup for Thread? } }
From source file:org.eclipse.skalli.view.internal.filter.ProjectDetailsFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; String userId = (String) request.getAttribute(Consts.ATTRIBUTE_USERID); Project project = (Project) request.getAttribute(Consts.ATTRIBUTE_PROJECT); boolean isProjectAdmin = BooleanUtils .toBoolean((Boolean) request.getAttribute(Consts.ATTRIBUTE_PROJECTADMIN)); boolean isProjectAdminInParentChain = BooleanUtils .toBoolean((Boolean) request.getAttribute(Consts.ATTRIBUTE_PARENTPROJECTADMIN)); String action = request.getParameter(Consts.PARAM_ACTION); String windowName = StringUtils.strip(httpRequest.getPathInfo(), "/"); //$NON-NLS-1$ if (project != null) { if (!project.isDeleted()) { windowName = project.getProjectId(); } else {// www. j a va 2 s.c om windowName = project.getUuid().toString(); } ProjectTemplateService templateService = Services.getRequiredService(ProjectTemplateService.class); ProjectTemplate projectTemplate = templateService .getProjectTemplateById(project.getProjectTemplateId()); request.setAttribute(Consts.ATTRIBUTE_PROJECTTEMPLATE, projectTemplate); request.setAttribute(Consts.ATTRIBUTE_NATURE, projectTemplate.getProjectNature().toString()); if (userId != null) { FavoritesService favoritesService = Services.getService(FavoritesService.class); Favorites favorites = null; if (favoritesService == null) { favorites = new Favorites(userId); } else { favorites = favoritesService.getFavorites(userId); } request.setAttribute(Consts.ATTRIBUTE_FAVORITES, favorites.asMap()); boolean showIssues = isProjectAdmin || isProjectAdminInParentChain; request.setAttribute(Consts.ATTRIBUTE_SHOW_ISSUES, isProjectAdmin); if (showIssues) { IssuesService issuesService = Services.getService(IssuesService.class); if (issuesService != null) { if (Consts.PARAM_VALUE_VALIDATE.equals(action)) { ValidationService validationService = Services.getService(ValidationService.class); if (validationService != null) { validationService.validate(Project.class, project.getUuid(), Severity.INFO, userId); } } Issues issues = issuesService.getByUUID(project.getUuid()); if (issues != null && issues.hasIssues()) { request.setAttribute(Consts.ATTRIBUTE_ISSUES, issues); request.setAttribute(Consts.ATTRIBUTE_MAX_SEVERITY, issues.getIssues().first().getSeverity().name()); } } } request.setAttribute(Consts.ATTRIBUTE_PROJECTCONTEXTLINKS, getOrderedVisibleProjectContextLinks(project, userId)); } String pathInfo = httpRequest.getPathInfo(); if (pathInfo != null) { int infoBoxIndex = pathInfo.indexOf(Consts.URL_INFOBOXES); if (infoBoxIndex > 0) { if (StringUtils.isNotBlank(action)) { String infoBoxShortName = pathInfo.substring(infoBoxIndex + Consts.URL_INFOBOXES.length()); if (infoBoxShortName.startsWith(FilterUtil.PATH_SEPARATOR)) { infoBoxShortName = infoBoxShortName.substring(1); } filterInfobox(project, infoBoxShortName, action, userId); } } } } request.setAttribute(Consts.ATTRIBUTE_WINDOWNAME, windowName); request.setAttribute(Consts.ATTRIBUTE_EDITMODE, false); String appUri = Consts.URL_VAADIN_PROJECTS + windowName; if (StringUtils.isNotBlank(action)) { if (action.equals(Consts.PARAM_VALUE_EDIT)) { request.setAttribute(Consts.ATTRIBUTE_EDITMODE, true); appUri = appUri + "/edit"; //$NON-NLS-1$ } } request.setAttribute(Consts.ATTRIBUTE_APP_URI, appUri); // proceed along the chain chain.doFilter(request, response); }
From source file:gov.nih.nci.cabig.caaers.web.security.FabricatedAuthenticationFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { throw new ServletException("Can only process HttpServletRequest"); }/*from www. j ava2 s. com*/ if (!(response instanceof HttpServletResponse)) { throw new ServletException("Can only process HttpServletResponse"); } HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; HttpSession httpSession = httpRequest.getSession(); final SecurityContext contextBeforeExec = SecurityContextHolder.getContext(); Authentication authBeforeExec = contextBeforeExec.getAuthentication(); OriginalAuthenticationHolder.setAuthentication(authBeforeExec); try { if (request.getAttribute(FILTER_APPLIED) == null) { doProcessing(httpRequest, httpResponse, chain); request.setAttribute(FILTER_APPLIED, true); } Authentication fabricatedAuth = SecurityContextHolder.getContext().getAuthentication(); if (fabricatedAuth != null) { GrantedAuthority[] fabAuthorities = fabricatedAuth.getAuthorities(); if (fabAuthorities == null || fabAuthorities.length < 1) { throw new AccessDeniedException( "Your account permissions do not provide you access to this page."); } } prepareRolesCollections(httpRequest); chain.doFilter(httpRequest, httpResponse); } finally { request.removeAttribute(FILTER_APPLIED); SecurityContextHolder.setContext(contextBeforeExec); SecurityContextHolder.getContext().setAuthentication(authBeforeExec); if (httpSession != null) { httpSession.setAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); } OriginalAuthenticationHolder.setAuthentication(null); CurrentEntityHolder.setEntity(null); } return; }
From source file:org.sonatype.nexus.security.filter.authc.NexusHttpAuthenticationFilter.java
@Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { // this will be true if cookie is sent with request and it is valid Subject subject = getSubject(request, response); // NEXUS-607: fix for cookies, when sent from client. They will expire once // and we are not sending them anymore. boolean loggedIn = subject.isAuthenticated(); if (loggedIn) { return true; }//from w w w.j a v a 2 s . c om if (isLoginAttempt(request, response)) { try { loggedIn = executeLogin(request, response); } // if no username or password is supplied, an IllegalStateException (runtime) // is thrown, so if anything fails in executeLogin just assume failed login catch (Exception e) { getLogger().error("Unable to login", e); loggedIn = false; } } else { // let the user "fall thru" until we get some permission problem if (getNexusConfiguration().isAnonymousAccessEnabled()) { loggedIn = executeAnonymousLogin(request, response); } } if (!loggedIn) { sendChallenge(request, response); } else { request.setAttribute(AUTH_SCHEME_KEY, getAuthcScheme()); request.setAttribute(AUTH_REALM_KEY, getApplicationName()); } return loggedIn; }
From source file:org.gridsphere.servlets.GridSphereFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { log.info("START"); if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; //PersistenceManagerService pms = null; // If first time being called, instantiate all portlets if (firstDoGet.equals(Boolean.TRUE)) { SettingsService settingsService = (SettingsService) PortletServiceFactory .createPortletService(SettingsService.class, true); // check if database file exists String release = SportletProperties.getInstance().getProperty("gridsphere.release"); int idx = release.lastIndexOf(" "); String gsversion = release.substring(idx + 1); //System.err.println("gsversion=" + gsversion); String dbpath = settingsService.getRealSettingsPath("/database/GS_" + gsversion); File dbfile = new File(dbpath); if (!dbfile.exists()) { request.setAttribute("setup", "true"); RequestDispatcher rd = request.getRequestDispatcher("/setup"); rd.forward(request, response); return; }/* w w w .j a v a2 s. c o m*/ PersistenceManagerService pms = (PersistenceManagerService) PortletServiceFactory .createPortletService(PersistenceManagerService.class, true); PersistenceManagerRdbms pm = null; boolean noAdmin = true; try { log.info("Starting a database transaction"); pm = pms.createGridSphereRdbms(); pm.setClassLoader(Thread.currentThread().getContextClassLoader()); pm.beginTransaction(); RoleManagerService roleService = (RoleManagerService) PortletServiceFactory .createPortletService(RoleManagerService.class, true); noAdmin = roleService.getUsersInRole(PortletRole.ADMIN).isEmpty(); pm.endTransaction(); } catch (StaleObjectStateException staleEx) { log.error("This interceptor does not implement optimistic concurrency control!"); log.error("Your application will not work until you add compensation actions!"); } catch (Throwable ex) { ex.printStackTrace(); pm.endTransaction(); try { pm.rollbackTransaction(); } catch (Throwable rbEx) { log.error("Could not rollback transaction after exception!", rbEx); } } if (noAdmin) { request.setAttribute("setup", "true"); RequestDispatcher rd = request.getRequestDispatcher("/setup"); rd.forward(request, response); return; } if (!portletsLoaded) { System.err.println("Loading portlets!!!"); log.info("Loading portlets"); try { // load all portlets PortletManagerService portletManager = (PortletManagerService) PortletServiceFactory .createPortletService(PortletManagerService.class, true); portletManager.loadAllPortletWebApplications(req, res); portletsLoaded = Boolean.TRUE; } catch (Exception e) { log.error("GridSphere initialization failed!", e); RequestDispatcher rd = req.getRequestDispatcher("/jsp/errors/init_error.jsp"); req.setAttribute("error", e); rd.forward(req, res); return; } } PortletsSetupModuleService portletsSetupModuleService = null; try { portletsSetupModuleService = (PortletsSetupModuleService) PortletServiceFactory .createPortletService(PortletsSetupModuleService.class, true); if (!portletsSetupModuleService.isPreInitSetupDone()) { request.setAttribute("setup", "true"); RequestDispatcher rd = request.getRequestDispatcher("/setup"); rd.forward(request, response); return; } } catch (Exception e) { log.error("GridSphere initialization failed!", e); RequestDispatcher rd = req.getRequestDispatcher("/jsp/errors/init_error.jsp"); req.setAttribute("error", e); rd.forward(req, res); return; } if (!portletsInitialized) { System.err.println("Initializing portlets!!!"); log.info("Initializing portlets"); try { // initialize all portlets PortletManagerService portletManager = (PortletManagerService) PortletServiceFactory .createPortletService(PortletManagerService.class, true); portletManager.initAllPortletWebApplications(req, res); portletsInitialized = Boolean.TRUE; } catch (Exception e) { log.error("GridSphere initialization failed!", e); RequestDispatcher rd = req.getRequestDispatcher("/jsp/errors/init_error.jsp"); req.setAttribute("error", e); rd.forward(req, res); return; } } if (!portletsSetupModuleService.isPostInitSetupDone()) { request.setAttribute("setup", "true"); RequestDispatcher rd = request.getRequestDispatcher("/setup"); rd.forward(request, response); return; } firstDoGet = Boolean.FALSE; } String pathInfo = req.getPathInfo(); StringBuffer requestURL = req.getRequestURL(); String requestURI = req.getRequestURI(); String query = req.getQueryString(); log.info("\ncontext path = " + req.getContextPath() + " servlet path=" + req.getServletPath()); log.info("\n pathInfo= " + pathInfo + " query= " + query); log.info(" requestURL= " + requestURL + " requestURI= " + requestURI + "\n"); String extraInfo = ""; // use the servlet path to determine where to forward // expect servlet path = /servletpath/XXXX String path = req.getServletPath(); int start = path.indexOf("/", 1); if ((start > 0) && (path.length() - 1) > start) { String parsePath = path.substring(start + 1); //System.err.println(parsePath); extraInfo = "?"; StringTokenizer st = new StringTokenizer(parsePath, "/"); String layoutId = null; if (st.hasMoreTokens()) { layoutId = (String) st.nextElement(); extraInfo += SportletProperties.LAYOUT_PAGE_PARAM + "=" + layoutId; } if (st.hasMoreTokens()) { String cid = (String) st.nextElement(); extraInfo += "&" + SportletProperties.COMPONENT_ID + "=" + cid; } if (st.hasMoreTokens()) { // check for /a/ or /r/ to indicate if it's a render or action String phase = (String) st.nextElement(); if (phase.equals("a")) { if (st.hasMoreTokens()) { extraInfo += "&" + SportletProperties.IS_ACTION + "=1" + "&" + SportletProperties.DEFAULT_PORTLET_ACTION + "=" + (String) st.nextElement(); } else { extraInfo += "&" + SportletProperties.IS_ACTION + "=1"; } } else if (phase.equals("r")) { if (st.hasMoreTokens()) { extraInfo += "&" + SportletProperties.DEFAULT_PORTLET_RENDER + "=" + (String) st.nextElement(); } else { extraInfo += "&" + SportletProperties.DEFAULT_PORTLET_RENDER + "="; } } else if (phase.equals("m")) { if (st.hasMoreTokens()) { extraInfo += "&" + SportletProperties.PORTLET_MODE + "=" + (String) st.nextElement(); } } else if (phase.equals("s")) { if (st.hasMoreTokens()) { extraInfo += "&" + SportletProperties.PORTLET_WINDOW + "=" + (String) st.nextElement(); } } HttpSession session = req.getSession(); //capture after login redirect (GPF-463 feature) URI but not for: // - login or register layout // - logged in users // - actions (security reasons) // - sessions which already has captured URI if (!"login".equals(layoutId) && !"register".equals(layoutId) && !"a".equals(phase) && null != session && null == session.getAttribute(SportletProperties.PORTLET_USER) && null == session.getAttribute(SportletProperties.PORTAL_REDIRECT_PATH)) { String afterLoginRedirect = requestURI; if (null != query) { afterLoginRedirect += '?' + query; } session.setAttribute(SportletProperties.PORTAL_REDIRECT_PATH, afterLoginRedirect); } } if (query != null) { extraInfo += "&" + query; } //String ctxPath = "/" + configService.getProperty("gridsphere.context"); } //chain.doFilter(request, response); String ctxPath = "/gs"; log.info("forwarded URL: " + ctxPath + extraInfo); context.getRequestDispatcher(ctxPath + extraInfo).forward(req, res); log.info("END"); } }
From source file:com.netspective.sparx.navigate.NavigationPage.java
/** * Main method for handling the logic and content of the page. Generally, a navigation page is broken into * several sections: header, metadata, body, and footer. If there are no forwards/redirects configured, the page * sections are handled by calling the following methods: <code>handlePageMetaData()</code>, <code>handlePageHeader()</code>, * <code>handlePageBody()</code>, and <code>handlePageFooter()</code> methods. * * @param writer Writer object to write the page output to * @param nc current navigation context *//* www . ja v a 2 s . c o m*/ public void handlePage(Writer writer, NavigationContext nc) throws ServletException, IOException { Flags flags = (Flags) nc.getActiveState().getFlags(); enterPage(nc); if (getBodyType().getValueIndex() == NavigationPageBodyType.FORWARD) { // if we're forwarding to another resource we don't want to put anything into the response otherwise // there will be an illegal state exception -- so, we don't create headers, footers, etc because that's // the user's responsibility in the forwarded resource. String forwardUrl = getForward().getTextValue(nc); ServletRequest req = nc.getRequest(); RequestDispatcher rd = req.getRequestDispatcher(forwardUrl); req.setAttribute(REQATTRNAME_NAVIGATION_CONTEXT, nc); rd.forward(req, nc.getResponse()); req.removeAttribute(REQATTRNAME_NAVIGATION_CONTEXT); } else if (bodyAffectsNavigationContext(nc)) { // render the body first and let it modify the navigation context StringWriter body = new StringWriter(); boolean hasError = false; try { handlePageBody(body, nc); } catch (Exception e) { getLog().error("Error occurred while handling the page.", e); if (!findErrorPage(nc, e)) nc.setErrorPageException(getOwner().getDefaultErrorPage(), e, e.getClass()); nc.getErrorPage().handlePageBody(writer, nc); hasError = true; } if (!hasError && !nc.isRedirected()) { if (flags.flagIsSet(Flags.HANDLE_META_DATA)) handlePageMetaData(writer, nc); if (flags.flagIsSet(Flags.HANDLE_HEADER)) handlePageHeader(writer, nc); writer.write(body.getBuffer().toString()); if (flags.flagIsSet(Flags.HANDLE_FOOTER)) handlePageFooter(writer, nc); } // try and do an early GC if possible body = null; } else { if (flags.flagIsSet(Flags.HANDLE_META_DATA)) handlePageMetaData(writer, nc); if (flags.flagIsSet(Flags.HANDLE_HEADER)) handlePageHeader(writer, nc); try { handlePageBody(writer, nc); } catch (Exception e) { getLog().error("Error occurred while handling the page.", e); if (!findErrorPage(nc, e)) nc.setErrorPageException(getOwner().getDefaultErrorPage(), e, e.getClass()); nc.getErrorPage().handlePageBody(writer, nc); } if (flags.flagIsSet(Flags.HANDLE_FOOTER)) handlePageFooter(writer, nc); } exitPage(nc); }
From source file:com.iflytek.edu.cloud.frame.web.filter.ServiceMetricsFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; StatHttpServletResponseWrapper responseWrapper = new StatHttpServletResponseWrapper(httpResponse); final String method = request.getParameter(Constants.SYS_PARAM_KEY_METHOD); final String appkey = request.getParameter(Constants.SYS_PARAM_KEY_APPKEY); long startNano = System.nanoTime(); long startMillis = System.currentTimeMillis(); serviceAppStat.beforeInvoke();//from w w w. j a v a 2 s .c om ServiceMethodStat methodStat = serviceAppStat.getMethodStat(appkey, method); if (methodStat == null) { methodStat = serviceAppStat.getMethodStat(appkey, method); } if (methodStat != null) { methodStat.beforeInvoke(startMillis); } Throwable error = null; try { chain.doFilter(request, responseWrapper); } catch (IOException e) { error = e; throw e; } catch (ServletException e) { error = e; throw e; } catch (RuntimeException e) { error = e; throw e; } catch (Error e) { error = e; throw e; } finally { long endNano = System.nanoTime(); long nanos = endNano - startNano; serviceAppStat.afterInvoke(error, nanos); if (methodStat != null) { methodStat.afterInvoke(error, nanos); request.setAttribute(SERVICE_EXEC_TIME, nanos / (1000 * 1000)); } } }