Example usage for javax.servlet.http HttpServletResponse isCommitted

List of usage examples for javax.servlet.http HttpServletResponse isCommitted

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse isCommitted.

Prototype

public boolean isCommitted();

Source Link

Document

Returns a boolean indicating if the response has been committed.

Usage

From source file:fr.univlille2.ecm.platform.ui.web.auth.cas2.SecurityExceptionHandler.java

@Override
public void handleException(HttpServletRequest request, HttpServletResponse response, Throwable t)
        throws IOException, ServletException {

    @SuppressWarnings("deprecation")
    Throwable unwrappedException = unwrapException(t);
    log.debug("handleException#in");
    if (!ExceptionHelper.isSecurityError(unwrappedException)
            && !response.containsHeader(SSO_INITIAL_URL_REQUEST_KEY)) {
        super.handleException(request, response, t);
        return;//  w ww. j a  v a  2 s.c  o  m
    }

    Principal principal = request.getUserPrincipal();
    NuxeoPrincipal nuxeoPrincipal = null;
    if (principal instanceof NuxeoPrincipal) {
        nuxeoPrincipal = (NuxeoPrincipal) principal;
        // redirect to login than to requested page
        if (nuxeoPrincipal.isAnonymous()) {
            response.resetBuffer();

            String urlToReach = getURLToReach(request);
            log.debug(String.format("handleException#urlToReach#%s", urlToReach));
            Cookie cookieUrlToReach = new Cookie(NXAuthConstants.SSO_INITIAL_URL_REQUEST_KEY, urlToReach);
            cookieUrlToReach.setPath("/");
            cookieUrlToReach.setMaxAge(60);
            response.addCookie(cookieUrlToReach);
            log.debug(String.format("handleException#cookieUrlToReach#%s", cookieUrlToReach.getName()));
            if (!response.isCommitted()) {
                request.getRequestDispatcher(CAS_REDIRECTION_URL).forward(request, response);
            }
            FacesContext.getCurrentInstance().responseComplete();
        }
    }
    // go back to default handler
    super.handleException(request, response, t);
}

From source file:org.opencms.main.OpenCmsServlet.java

/**
 * Displays an error code handler loaded from the OpenCms VFS, 
 * or if such a page does not exist,//from www . ja v a2s.  c  o m
 * displays the default servlet container error code.<p>
 *  
 * @param req the current request
 * @param res the current response
 * @param errorCode the error code to display
 * @throws IOException if something goes wrong
 * @throws ServletException if something goes wrong
 */
protected void openErrorHandler(HttpServletRequest req, HttpServletResponse res, int errorCode)
        throws IOException, ServletException {

    String handlerUri = (new StringBuffer(64)).append(HANDLE_VFS_PATH).append(errorCode)
            .append(HANDLE_VFS_SUFFIX).toString();
    CmsObject cms;
    CmsFile file;
    try {
        // create OpenCms context, this will be set in the root site            
        cms = OpenCms.initCmsObject(OpenCms.getDefaultUsers().getUserGuest());
        cms.getRequestContext().setUri(handlerUri);
        // read the error handler file
        file = cms.readFile(handlerUri, CmsResourceFilter.IGNORE_EXPIRATION);
    } catch (CmsException e) {
        // unlikely to happen as the OpenCms "Guest" context can always be initialized
        CmsMessageContainer container = Messages.get().container(Messages.LOG_INIT_CMSOBJECT_IN_HANDLER_2,
                new Integer(errorCode), handlerUri);
        if (LOG.isWarnEnabled()) {
            LOG.warn(org.opencms.jsp.Messages.getLocalizedMessage(container, req), e);
        }
        // however, if it _does_ happen, then we really can't continue here
        if (!res.isCommitted()) {
            // since the handler file is not accessible, display the default error page
            res.sendError(errorCode, e.getLocalizedMessage());
        }
        return;
    }
    try {
        // provide the original error code in a request attribute
        req.setAttribute(CmsRequestUtil.ATTRIBUTE_ERRORCODE, new Integer(errorCode));
        OpenCms.getResourceManager().loadResource(cms, file, req, res);
    } catch (CmsException e) {
        // unable to load error page handler VFS resource
        CmsMessageContainer container = Messages.get().container(Messages.ERR_SHOW_ERR_HANDLER_RESOURCE_2,
                new Integer(errorCode), handlerUri);
        throw new ServletException(org.opencms.jsp.Messages.getLocalizedMessage(container, req), e);
    }
}

From source file:org.codehaus.groovy.grails.plugins.springsecurity.GrailsAccessDeniedHandlerImpl.java

/**
 * {@inheritDoc}/* ww  w  .j  a  v a  2s  .c om*/
 * @see org.springframework.security.ui.AccessDeniedHandler#handle(
 *    javax.servlet.ServletRequest, javax.servlet.ServletResponse,
 *    org.springframework.security.AccessDeniedException)
 */
public void handle(final ServletRequest req, final ServletResponse res, final AccessDeniedException e)
        throws IOException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    if (errorPage != null || (ajaxErrorPage != null && request.getHeader(ajaxHeader) != null)) {
        boolean includePort = true;
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = portResolver.getServerPort(request);
        String contextPath = request.getContextPath();
        boolean inHttp = "http".equals(scheme.toLowerCase());
        boolean inHttps = "https".equals(scheme.toLowerCase());

        if (inHttp && (serverPort == 80)) {
            includePort = false;
        } else if (inHttps && (serverPort == 443)) {
            includePort = false;
        }

        String commonRedirectUrl = scheme + "://" + serverName + ((includePort) ? (":" + serverPort) : "")
                + contextPath;
        String redirectUrl = commonRedirectUrl;
        if (ajaxErrorPage != null && request.getHeader(ajaxHeader) != null) {
            redirectUrl += ajaxErrorPage;
        } else if (errorPage != null) {
            redirectUrl += errorPage;
        } else {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
        }

        response.sendRedirect(response.encodeRedirectURL(redirectUrl));
    }

    if (!response.isCommitted()) {
        // Send 403 (we do this after response has been written)
        response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
    }
}

From source file:org.apache.roller.weblogger.ui.rendering.servlets.PageServlet.java

/**
 * Handle GET requests for weblog pages.
 *///from   w  ww. ja  va2  s . com
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("Entering");

    // do referrer processing, if it's enabled
    // NOTE: this *must* be done first because it triggers a hibernate flush
    // which will close the active session and cause lazy init exceptions
    // otherwise
    if (this.processReferrers) {
        boolean spam = this.processReferrer(request);
        if (spam) {
            log.debug("spammer, giving 'em a 403");
            if (!response.isCommitted()) {
                response.reset();
            }
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
    }

    Weblog weblog = null;
    boolean isSiteWide = false;

    WeblogPageRequest pageRequest = null;
    try {
        pageRequest = new WeblogPageRequest(request);

        weblog = pageRequest.getWeblog();
        if (weblog == null) {
            throw new WebloggerException("unable to lookup weblog: " + pageRequest.getWeblogHandle());
        }

        // is this the site-wide weblog?
        isSiteWide = WebloggerRuntimeConfig.isSiteWideWeblog(pageRequest.getWeblogHandle());
    } catch (Exception e) {
        // some kind of error parsing the request or looking up weblog
        log.debug("error creating page request", e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // determine the lastModified date for this content
    long lastModified = System.currentTimeMillis();
    if (isSiteWide) {
        lastModified = siteWideCache.getLastModified().getTime();
    } else if (weblog.getLastModified() != null) {
        lastModified = weblog.getLastModified().getTime();
    }

    // 304 Not Modified handling.
    // We skip this for logged in users to avoid the scenerio where a user
    // views their weblog, logs in, then gets a 304 without the 'edit' links

    if (!pageRequest.isLoggedIn()) {
        if (ModDateHeaderUtil.respondIfNotModified(request, response, lastModified)) {
            return;
        } else {
            // set last-modified date
            ModDateHeaderUtil.setLastModifiedHeader(response, lastModified);
        }
    }

    // generate cache key
    String cacheKey = null;
    if (isSiteWide) {
        cacheKey = siteWideCache.generateKey(pageRequest);
    } else {
        cacheKey = weblogPageCache.generateKey(pageRequest);
    }

    // Development only. Reload if theme has been modified
    if (themeReload && !weblog.getEditorTheme().equals(WeblogTemplate.ACTION_CUSTOM)
            && (pageRequest.getPathInfo() == null || pageRequest.getPathInfo() != null)) {
        try {
            ThemeManager manager = WebloggerFactory.getWeblogger().getThemeManager();
            boolean reloaded = manager.reLoadThemeFromDisk(weblog.getEditorTheme());
            if (reloaded) {
                if (isSiteWide) {
                    siteWideCache.clear();
                } else {
                    weblogPageCache.clear();
                }
                I18nMessages.reloadBundle(weblog.getLocaleInstance());
            }

        } catch (Exception ex) {
            log.error("ERROR - reloading theme " + ex);
        }
    }

    // cached content checking
    if ((!this.excludeOwnerPages || !pageRequest.isLoggedIn()) && request.getAttribute("skipCache") == null) {

        CachedContent cachedContent = null;
        if (isSiteWide) {
            cachedContent = (CachedContent) siteWideCache.get(cacheKey);
        } else {
            cachedContent = (CachedContent) weblogPageCache.get(cacheKey, lastModified);
        }

        if (cachedContent != null) {
            log.debug("HIT " + cacheKey);

            // allow for hit counting
            if (!isSiteWide) {
                this.processHit(weblog, request.getRequestURL().toString(), request.getHeader("referer"));
            }

            response.setContentLength(cachedContent.getContent().length);
            response.setContentType(cachedContent.getContentType());
            response.getOutputStream().write(cachedContent.getContent());
            return;
        } else {
            log.debug("MISS " + cacheKey);
        }
    }

    log.debug("Looking for template to use for rendering");

    // figure out what template to use
    ThemeTemplate page = null;

    // If this is a popup request, then deal with it specially
    // TODO: do we really need to keep supporting this?
    if (request.getParameter("popup") != null) {
        try {
            // Does user have a popupcomments page?
            page = weblog.getTheme().getTemplateByName("_popupcomments");
        } catch (Exception e) {
            // ignored ... considered page not found
        }

        // User doesn't have one so return the default
        if (page == null) {
            page = new StaticThemeTemplate("templates/weblog/popupcomments.vm", "velocity");
        }

        // If request specified the page, then go with that
    } else if ("page".equals(pageRequest.getContext())) {
        page = pageRequest.getWeblogPage();

        // if we don't have this page then 404, we don't let
        // this one fall through to the default template
        if (page == null) {
            if (!response.isCommitted()) {
                response.reset();
            }
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // If request specified tags section index, then look for custom
        // template
    } else if ("tags".equals(pageRequest.getContext()) && pageRequest.getTags() != null) {
        try {
            page = weblog.getTheme().getTemplateByAction(ThemeTemplate.ACTION_TAGSINDEX);
        } catch (Exception e) {
            log.error("Error getting weblog page for action 'tagsIndex'", e);
        }

        // if we don't have a custom tags page then 404, we don't let
        // this one fall through to the default template
        if (page == null) {
            if (!response.isCommitted()) {
                response.reset();
            }
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // If this is a permalink then look for a permalink template
    } else if (pageRequest.getWeblogAnchor() != null) {
        try {
            page = weblog.getTheme().getTemplateByAction(ThemeTemplate.ACTION_PERMALINK);
        } catch (Exception e) {
            log.error("Error getting weblog page for action 'permalink'", e);
        }
    }

    // if we haven't found a page yet then try our default page
    if (page == null) {
        try {
            page = weblog.getTheme().getDefaultTemplate();
        } catch (Exception e) {
            log.error("Error getting default page for weblog = " + weblog.getHandle(), e);
        }
    }

    // Still no page? Then that is a 404
    if (page == null) {
        if (!response.isCommitted()) {
            response.reset();
        }
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    log.debug("page found, dealing with it");

    // validation. make sure that request input makes sense.
    boolean invalid = false;
    if (pageRequest.getWeblogPageName() != null && page.isHidden()) {
        invalid = true;
    }
    if (pageRequest.getLocale() != null) {

        // locale view only allowed if weblog has enabled it
        if (!pageRequest.getWeblog().isEnableMultiLang()) {
            invalid = true;
        }
    }
    if (pageRequest.getWeblogAnchor() != null) {

        // permalink specified.
        // entry must exist, be published before current time, and locale
        // must match
        WeblogEntry entry = pageRequest.getWeblogEntry();
        if (entry == null) {
            invalid = true;
        } else if (pageRequest.getLocale() != null && !entry.getLocale().startsWith(pageRequest.getLocale())) {
            invalid = true;
        } else if (!entry.isPublished()) {
            invalid = true;
        } else if (new Date().before(entry.getPubTime())) {
            invalid = true;
        }
    } else if (pageRequest.getWeblogCategoryName() != null) {

        // category specified. category must exist.
        if (pageRequest.getWeblogCategory() == null) {
            invalid = true;
        }
    } else if (pageRequest.getTags() != null && pageRequest.getTags().size() > 0) {

        try {
            // tags specified. make sure they exist.
            WeblogEntryManager wmgr = WebloggerFactory.getWeblogger().getWeblogEntryManager();
            invalid = !wmgr.getTagComboExists(pageRequest.getTags(), (isSiteWide) ? null : weblog);
        } catch (WebloggerException ex) {
            invalid = true;
        }
    }

    if (invalid) {
        log.debug("page failed validation, bailing out");
        if (!response.isCommitted()) {
            response.reset();
        }
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // do we need to force a specific locale for the request?
    if (pageRequest.getLocale() == null && !weblog.isShowAllLangs()) {
        pageRequest.setLocale(weblog.getLocale());
    }

    // allow for hit counting
    if (!isSiteWide) {
        this.processHit(weblog, request.getRequestURL().toString(), request.getHeader("referer"));
    }

    // looks like we need to render content
    // set the content deviceType
    String contentType = "text/html; charset=utf-8";
    if (StringUtils.isNotEmpty(page.getOutputContentType())) {
        contentType = page.getOutputContentType() + "; charset=utf-8";
    } else {
        String mimeType = RollerContext.getServletContext().getMimeType(page.getLink());
        if (mimeType != null) {
            // we found a match ... set the content deviceType
            contentType = mimeType + "; charset=utf-8";
        } else {
            contentType = "text/html; charset=utf-8";
        }
    }

    HashMap model = new HashMap();
    try {
        PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, request, response, "",
                false, 8192, true);

        // special hack for menu tag
        request.setAttribute("pageRequest", pageRequest);

        // populate the rendering model
        Map initData = new HashMap();
        initData.put("requestParameters", request.getParameterMap());
        initData.put("parsedRequest", pageRequest);
        initData.put("pageContext", pageContext);

        // define url strategy
        initData.put("urlStrategy", WebloggerFactory.getWeblogger().getUrlStrategy());

        // if this was a comment posting, check for comment form
        WeblogEntryCommentForm commentForm = (WeblogEntryCommentForm) request.getAttribute("commentForm");
        if (commentForm != null) {
            initData.put("commentForm", commentForm);
        }

        // Load models for pages
        String pageModels = WebloggerConfig.getProperty("rendering.pageModels");
        ModelLoader.loadModels(pageModels, model, initData, true);
        // Load special models for site-wide blog
        if (WebloggerRuntimeConfig.isSiteWideWeblog(weblog.getHandle())) {
            String siteModels = WebloggerConfig.getProperty("rendering.siteModels");
            ModelLoader.loadModels(siteModels, model, initData, true);
        }

        // Load weblog custom models
        ModelLoader.loadCustomModels(weblog, model, initData);

        // ick, gotta load pre-3.0 model stuff as well :(
        ModelLoader.loadOldModels(model, request, response, pageContext, pageRequest,
                WebloggerFactory.getWeblogger().getUrlStrategy());
    } catch (WebloggerException ex) {
        log.error("Error loading model objects for page", ex);

        if (!response.isCommitted()) {
            response.reset();
        }
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    // lookup Renderer we are going to use
    Renderer renderer = null;
    try {
        log.debug("Looking up renderer");
        renderer = RendererManager.getRenderer(page, pageRequest.getDeviceType());
    } catch (Exception e) {
        // nobody wants to render my content :(
        log.error("Couldn't find renderer for page " + page.getId(), e);

        if (!response.isCommitted()) {
            response.reset();
        }
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // render content. use size of about 24K for a standard page
    CachedContent rendererOutput = new CachedContent(24567, contentType);
    try {
        log.debug("Doing rendering");
        renderer.render(model, rendererOutput.getCachedWriter());

        // flush rendered output and close
        rendererOutput.flush();
        rendererOutput.close();
    } catch (Exception e) {
        // bummer, error during rendering
        log.error("Error during rendering for page " + page.getId(), e);

        if (!response.isCommitted()) {
            response.reset();
        }
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // post rendering process
    // flush rendered content to response
    log.debug("Flushing response output");
    response.setContentType(contentType);
    response.setContentLength(rendererOutput.getContent().length);
    response.getOutputStream().write(rendererOutput.getContent());

    // cache rendered content. only cache if user is not logged in?
    if ((!this.excludeOwnerPages || !pageRequest.isLoggedIn()) && request.getAttribute("skipCache") == null) {
        log.debug("PUT " + cacheKey);

        // put it in the right cache
        if (isSiteWide) {
            siteWideCache.put(cacheKey, rendererOutput);
        } else {
            weblogPageCache.put(cacheKey, rendererOutput);
        }
    } else {
        log.debug("SKIPPED " + cacheKey);
    }

    log.debug("Exiting");
}

From source file:it.classhidra.core.controller.bsController.java

public static void service_ErrorRedirect(String id_action, ServletContext servletContext,
        HttpServletRequest request, HttpServletResponse response) {
    String redirectURI = "";
    try {//  ww w.  jav a 2 s.  c o  m
        if (getAction_config() == null || getAction_config().getError() == null
                || getAction_config().getError().equals(""))
            redirectURI = "/error.jsp";
        else
            redirectURI = getAction_config().getError();
        if (!response.isCommitted())
            servletContext.getRequestDispatcher(redirectURI).forward(request, response);
        else
            servletContext.getRequestDispatcher(redirectURI).include(request, response);
    } catch (Exception ex) {
        writeLog(request,
                "Controller generic redirect error. Action: [" + id_action + "] URI: [" + redirectURI + "]");
    }
}

From source file:it.classhidra.core.controller.bsController.java

public static void service_AuthRedirect(String id_action, ServletContext servletContext,
        HttpServletRequest request, HttpServletResponse response) {
    String redirectURI = "";
    try {//from   w  w  w .  ja v a2  s . c om
        if (getAction_config() == null || getAction_config().getAuth_error() == null
                || getAction_config().getAuth_error().equals("")) {
            redirectURI = "";
        } else
            redirectURI = getAction_config().getAuth_error();
        if (!response.isCommitted())
            servletContext.getRequestDispatcher(redirectURI).forward(request, response);
        else
            servletContext.getRequestDispatcher(redirectURI).include(request, response);
    } catch (Exception ex) {
        writeLog(request,
                "Controller authentication error. Action: [" + id_action + "] URI: [" + redirectURI + "]");
    }
}

From source file:org.apache.chemistry.opencmis.server.impl.atompub.CmisAtomPubServlet.java

/**
 * Prints the error HTML page.//from ww w.ja  va  2 s . c  o m
 */
protected void printError(Exception ex, HttpServletRequest request, HttpServletResponse response) {
    int statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    String exceptionName = "runtime";

    if (ex instanceof CmisRuntimeException) {
        LOG.error(createLogMessage(ex, request), ex);
        statusCode = getErrorCode((CmisRuntimeException) ex);
    } else if (ex instanceof CmisStorageException) {
        LOG.error(createLogMessage(ex, request), ex);
        statusCode = getErrorCode((CmisStorageException) ex);
        exceptionName = ((CmisStorageException) ex).getExceptionName();
    } else if (ex instanceof CmisBaseException) {
        statusCode = getErrorCode((CmisBaseException) ex);
        exceptionName = ((CmisBaseException) ex).getExceptionName();

        if (statusCode == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) {
            LOG.error(createLogMessage(ex, request), ex);
        }
    } else if (ex instanceof IOException) {
        LOG.warn(createLogMessage(ex, request), ex);
    } else {
        LOG.error(createLogMessage(ex, request), ex);
    }

    if (response.isCommitted()) {
        LOG.warn("Failed to send error message to client. Response is already committed.", ex);
        return;
    }

    String message = ex.getMessage();
    if (!(ex instanceof CmisBaseException)) {
        message = "An error occurred!";
    }

    try {
        response.resetBuffer();
        response.setStatus(statusCode);
        response.setContentType("text/html");
        response.setCharacterEncoding(IOUtils.UTF8);

        PrintWriter pw = response.getWriter();

        pw.print("<html><head><title>Apache Chemistry OpenCMIS - " + exceptionName + " error</title>"
                + "<style><!--H1 {font-size:24px;line-height:normal;font-weight:bold;background-color:#f0f0f0;color:#003366;border-bottom:1px solid #3c78b5;padding:2px;} "
                + "BODY {font-family:Verdana,arial,sans-serif;color:black;font-size:14px;} "
                + "HR {color:#3c78b5;height:1px;}--></style></head><body>");
        pw.print("<h1>HTTP Status " + statusCode + " - <!--exception-->" + exceptionName
                + "<!--/exception--></h1>");
        pw.print("<p><!--message-->");
        StringEscapeUtils.ESCAPE_HTML4.translate(message, pw);
        pw.print("<!--/message--></p>");

        String st = ExceptionHelper.getStacktraceAsString(ex);
        if (st != null) {
            pw.print("<hr noshade='noshade'/><!--stacktrace--><pre>\n<!--key-->stacktrace<!--/key><!--value-->"
                    + st + "<!--/value-->\n</pre><!--/stacktrace--><hr noshade='noshade'/>");
        }

        if (ex instanceof CmisBaseException) {
            Map<String, String> additionalData = ((CmisBaseException) ex).getAdditionalData();
            if (additionalData != null && !additionalData.isEmpty()) {
                pw.print("<hr noshade='noshade'/>Additional data:<br><br>");
                for (Map.Entry<String, String> e : additionalData.entrySet()) {
                    pw.print("<!--key-->");
                    StringEscapeUtils.ESCAPE_HTML4.translate(e.getKey(), pw);
                    pw.print("<!--/key--> = <!--value-->");
                    StringEscapeUtils.ESCAPE_HTML4.translate(e.getValue(), pw);
                    pw.print("<!--/value--><br>");
                }
            }
        }

        pw.print("</body></html>");
    } catch (Exception e) {
        LOG.error(createLogMessage(ex, request), e);
        try {
            response.sendError(statusCode, message);
        } catch (Exception en) {
            // there is nothing else we can do
        }
    }
}

From source file:org.openbravo.authentication.AuthenticationManager.java

/**
 * Used in the service method of the {@link HttpSecureAppServlet} to know if the request is
 * authenticated or not. This method calls the <b>doAuthenticate</b> that makes the actual checks
 * and could be easily extended by sub-classes. Returns the user id if the user is already logged
 * in or null if is not authenticated.//from  w ww.j  a  va 2  s  . c o m
 * 
 * @param request
 *          HTTP request object to handle parameters and session attributes
 * @param response
 *          HTTP response object to handle possible redirects
 * @return the value of AD_User_ID if the user is already authenticated or <b>null</b> if not
 */
public final String authenticate(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, ServletException, IOException {

    if (localAdress == null) {
        localAdress = HttpBaseUtils.getLocalAddress(request);
    }

    final String userId = doAuthenticate(request, response);

    final VariablesSecureApp vars = new VariablesSecureApp(request, false);
    if (StringUtils.isEmpty(vars.getSessionValue("#AD_SESSION_ID"))) {
        setDBSession(request, userId, SUCCESS_SESSION_STANDARD, true);
    }

    // if we in 'forceLogin' state, there is no need to process any other code
    if (userId == null && "Y".equals(request.getSession().getAttribute("forceLogin"))) {
        return null;
    }

    // A restricted resource can define a custom login URL
    // It just need to set an the attribute loginURL in the request
    final String customLoginURL = (String) request.getAttribute("loginURL");

    final String loginURL = localAdress
            + (customLoginURL == null || "".equals(customLoginURL) ? defaultServletUrl : customLoginURL);

    if (userId == null && !response.isCommitted()) {
        response.sendRedirect(loginURL);
        return null;
    }

    return userId;
}

From source file:org.apache.struts2.dispatcher.ServletDispatcherResult.java

/**
 * Dispatches to the given location. Does its forward via a RequestDispatcher. If the
 * dispatch fails a 404 error will be sent back in the http response.
 *
 * @param finalLocation the location to dispatch to.
 * @param invocation    the execution state of the action
 * @throws Exception if an error occurs. If the dispatch fails the error will go back via the
 *                   HTTP request./*  w w w.j  a  v a2  s  .c  om*/
 */
public void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Forwarding to location " + finalLocation);
    }

    PageContext pageContext = ServletActionContext.getPageContext();

    if (pageContext != null) {
        pageContext.include(finalLocation);
    } else {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        RequestDispatcher dispatcher = request.getRequestDispatcher(finalLocation);

        //add parameters passed on the location to #parameters
        // see WW-2120
        if (StringUtils.isNotEmpty(finalLocation) && finalLocation.indexOf("?") > 0) {
            String queryString = finalLocation.substring(finalLocation.indexOf("?") + 1);
            Map<String, Object> parameters = getParameters(invocation);
            Map<String, Object> queryParams = urlHelper.parseQueryString(queryString, true);
            if (queryParams != null && !queryParams.isEmpty())
                parameters.putAll(queryParams);
        }

        // if the view doesn't exist, let's do a 404
        if (dispatcher == null) {
            response.sendError(404, "result '" + finalLocation + "' not found");
            return;
        }

        //if we are inside an action tag, we always need to do an include
        Boolean insideActionTag = (Boolean) ObjectUtils
                .defaultIfNull(request.getAttribute(StrutsStatics.STRUTS_ACTION_TAG_INVOCATION), Boolean.FALSE);

        // If we're included, then include the view
        // Otherwise do forward
        // This allow the page to, for example, set content type
        if (!insideActionTag && !response.isCommitted()
                && (request.getAttribute("javax.servlet.include.servlet_path") == null)) {
            request.setAttribute("struts.view_uri", finalLocation);
            request.setAttribute("struts.request_uri", request.getRequestURI());

            dispatcher.forward(request, response);
        } else {
            dispatcher.include(request, response);
        }
    }
}

From source file:org.jahia.bin.Render.java

protected void doGet(HttpServletRequest req, HttpServletResponse resp, RenderContext renderContext,
        Resource resource, long startTime) throws RepositoryException, RenderException, IOException {
    loggingService.startProfiler("MAIN");
    resp.setCharacterEncoding(getSettingsBean().getCharacterEncoding());
    String out = renderService.render(resource, renderContext).trim();
    if (renderContext.getRedirect() != null && !resp.isCommitted()) {
        resp.sendRedirect(renderContext.getRedirect());
    } else if (!renderContext.isPortletActionRequest()) {
        resp.setContentType(renderContext.getContentType() != null ? renderContext.getContentType()
                : getDefaultContentType(resource.getTemplateType()));
        resp.getWriter().print(out);// ww w .j  a v  a2  s  .  co m
    }
    String sessionID = "";
    HttpSession httpSession = req.getSession(false);
    if (httpSession != null) {
        sessionID = httpSession.getId();
    }
    loggingService.stopProfiler("MAIN");
    if (loggingService.isEnabled()) {
        loggingService.logContentEvent(renderContext.getUser().getName(), req.getRemoteAddr(), sessionID,
                resource.getNode().getIdentifier(), resource.getNode().getPath(),
                resource.getNode().getPrimaryNodeType().getName(), "pageViewed", req.getHeader("User-Agent"),
                req.getHeader("Referer"), Long.toString(System.currentTimeMillis() - startTime));
    }
}