Example usage for javax.servlet.http HttpSession invalidate

List of usage examples for javax.servlet.http HttpSession invalidate

Introduction

In this page you can find the example usage for javax.servlet.http HttpSession invalidate.

Prototype

public void invalidate();

Source Link

Document

Invalidates this session then unbinds any objects bound to it.

Usage

From source file:com.sundevils.web.controller.TopController.java

@RequestMapping(value = "/Home", method = { RequestMethod.POST, RequestMethod.GET })
public ModelAndView getHome(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws IOException {
    String role = (String) session.getAttribute("Role");
    if (role == null) {
        ModelAndView model = new ModelAndView();
        model.setViewName("index");
        return model;
    } else {//from   w ww .  ja v  a 2 s.c o  m
        try {
            ModelAndView model = new ModelAndView();
            if (role.equals("MANAGER")) {
                model.setViewName("managerhome");
            } else if (role.equals("EMPLOYEE")) {
                model.setViewName("employeehome");
            } else if (role.equals("ADMIN")) {
                model.setViewName("admin");
            } else if (role.equals("MERCHANT")) {
                model.setViewName("merchanthome");
            } else if (role.equals("USER")) {
                model.setViewName("customerhome");
            } else if (role.equals("GOVERNMENT")) {
                model.setViewName("governmenthome");
            } else {
                model.addObject("loggedIn", "User is already logged in to the other system");
                model.setViewName("login");
            }

            return model;
        } catch (Exception e) {
            ModelAndView model = new ModelAndView();
            LoginHandler handler = new LoginHandler();
            String userName = (String) session.getAttribute("USERNAME");
            handler.updateLoggedInFlag(userName, 0);
            session.invalidate();
            model.setViewName("index");
            return model;

        }
    }
}

From source file:org.josso.servlet.agent.GenericServletSSOAgentFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest hreq = (HttpServletRequest) request;

    HttpServletResponse hres = (HttpServletResponse) response;

    if (log.isDebugEnabled())
        log.debug("Processing : " + hreq.getContextPath());

    try {/*from   www  .j  av  a  2  s .com*/
        // ------------------------------------------------------------------
        // Check with the agent if this context should be processed.
        // ------------------------------------------------------------------
        String contextPath = hreq.getContextPath();
        String vhost = hreq.getServerName();

        // In catalina, the empty context is considered the root context
        if ("".equals(contextPath))
            contextPath = "/";

        if (!_agent.isPartnerApp(vhost, contextPath)) {
            filterChain.doFilter(hreq, hres);
            if (log.isDebugEnabled())
                log.debug("Context is not a josso partner app : " + hreq.getContextPath());

            return;
        }

        // ------------------------------------------------------------------
        // Check some basic HTTP handling
        // ------------------------------------------------------------------
        // P3P Header for IE 6+ compatibility when embedding JOSSO in a IFRAME
        SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(vhost, contextPath);
        if (cfg.isSendP3PHeader() && !hres.isCommitted()) {
            hres.setHeader("P3P", cfg.getP3PHeaderValue());
        }

        HttpSession session = hreq.getSession(true);

        // ------------------------------------------------------------------
        // Check if the partner application required the login form
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking if its a josso_login_request for '" + hreq.getRequestURI() + "'");

        if (hreq.getRequestURI().endsWith(_agent.getJossoLoginUri())
                || hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) {

            if (log.isDebugEnabled())
                log.debug("josso_login_request received for uri '" + hreq.getRequestURI() + "'");

            //save referer url in case the user clicked on Login from some public resource (page)
            //so agent can redirect the user back to that page after successful login
            if (hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) {
                saveLoginBackToURL(hreq, hres, session, true);
            } else {
                saveLoginBackToURL(hreq, hres, session, false);
            }

            String loginUrl = _agent.buildLoginUrl(hreq);

            if (log.isDebugEnabled())
                log.debug("Redirecting to login url '" + loginUrl + "'");

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            hres.sendRedirect(hres.encodeRedirectURL(loginUrl));

            return;

        }

        // ------------------------------------------------------------------
        // Check if the partner application required a logout
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking if its a josso_logout request for '" + hreq.getRequestURI() + "'");

        if (hreq.getRequestURI().endsWith(_agent.getJossoLogoutUri())) {

            if (log.isDebugEnabled())
                log.debug("josso_logout request received for uri '" + hreq.getRequestURI() + "'");

            String logoutUrl = _agent.buildLogoutUrl(hreq, cfg);

            if (log.isDebugEnabled())
                log.debug("Redirecting to logout url '" + logoutUrl + "'");

            // Clear previous COOKIE ...
            Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure());
            hres.addCookie(ssoCookie);

            // invalidate session (unbind josso security context)
            session.invalidate();

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            hres.sendRedirect(hres.encodeRedirectURL(logoutUrl));

            return;

        }

        // ------------------------------------------------------------------
        // Check for the single sign on cookie
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking for SSO cookie");
        Cookie cookie = null;
        Cookie cookies[] = hreq.getCookies();
        if (cookies == null)
            cookies = new Cookie[0];
        for (int i = 0; i < cookies.length; i++) {
            if (org.josso.gateway.Constants.JOSSO_SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) {
                cookie = cookies[i];
                break;
            }
        }

        // Get our session ...

        String jossoSessionId = (cookie == null) ? null : cookie.getValue();
        GenericServletLocalSession localSession = new GenericServletLocalSession(session);

        // ------------------------------------------------------------------
        // Check if the partner application submitted custom login form
        // ------------------------------------------------------------------

        if (log.isDebugEnabled()) {
            log.debug("Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'");
        }
        if (hreq.getRequestURI().endsWith(_agent.getJossoAuthenticationUri())) {

            if (log.isDebugEnabled()) {
                log.debug("josso_authentication received for uri '" + hreq.getRequestURI() + "'");
            }

            GenericServletSSOAgentRequest customAuthRequest = (GenericServletSSOAgentRequest) doMakeSSOAgentRequest(
                    cfg.getId(), SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession,
                    null, hreq, hres);

            _agent.processRequest(customAuthRequest);

            return;
        }

        if (cookie == null || cookie.getValue().equals("-")) {

            // ------------------------------------------------------------------
            // Trigger LOGIN OPTIONAL if required
            // ------------------------------------------------------------------

            if (log.isDebugEnabled())
                log.debug("SSO cookie is not present, verifying optional login process ");

            // We have no cookie, remember me is enabled and a security check without assertion was received ...
            // This means that the user could not be identified ... go back to the original resource
            if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") == null) {

                if (log.isDebugEnabled())
                    log.debug(_agent.getJossoSecurityCheckUri()
                            + " received without assertion.  Login Optional Process failed");

                String requestURI = getSavedRequestURL(hreq);
                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
                return;

            }

            // This is a standard anonymous request!
            if (!hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())) {

                if (!_agent.isResourceIgnored(cfg, hreq) && _agent.isAutomaticLoginRequired(hreq, hres)) {

                    if (log.isDebugEnabled())
                        log.debug("SSO cookie is not present, attempting automatic login");

                    // Save current request, so we can co back to it later ...
                    saveRequestURL(hreq, hres);
                    String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                    if (log.isDebugEnabled())
                        log.debug("Redirecting to login url '" + loginUrl + "'");

                    //set non cache headers
                    _agent.prepareNonCacheResponse(hres);
                    hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                    return;
                } else {
                    if (log.isDebugEnabled())
                        log.debug("SSO cookie is not present, but login optional process is not required");
                }
            }

            if (log.isDebugEnabled())
                log.debug("SSO cookie is not present, checking for outbound relaying");

            if (!(hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") != null)) {
                log.debug("SSO cookie not present and relaying was not requested, skipping");
                filterChain.doFilter(hreq, hres);
                return;
            }

        }

        // ------------------------------------------------------------------
        // Check if this URI is subject to SSO protection
        // ------------------------------------------------------------------
        if (_agent.isResourceIgnored(cfg, hreq)) {
            filterChain.doFilter(hreq, hres);
            return;
        }

        if (log.isDebugEnabled())
            log.debug("Session is: " + session);

        // ------------------------------------------------------------------
        // Invoke the SSO Agent
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Executing agent...");

        // ------------------------------------------------------------------
        // Check if a user has been authenitcated and should be checked by the agent.
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'");

        if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                && hreq.getParameter("josso_assertion_id") != null) {

            if (log.isDebugEnabled())
                log.debug("josso_security_check received for uri '" + hreq.getRequestURI() + "' assertion id '"
                        + hreq.getParameter("josso_assertion_id"));

            String assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER);

            GenericServletSSOAgentRequest relayRequest;

            if (log.isDebugEnabled())
                log.debug("Outbound relaying requested for assertion id [" + assertionId + "]");

            relayRequest = (GenericServletSSOAgentRequest) doMakeSSOAgentRequest(cfg.getId(),
                    SSOAgentRequest.ACTION_RELAY, null, localSession, assertionId, hreq, hres);

            SingleSignOnEntry entry = _agent.processRequest(relayRequest);
            if (entry == null) {
                // This is wrong! We should have an entry here!
                log.error(
                        "Outbound relaying failed for assertion id [" + assertionId + "], no Principal found.");
                // Throw an exception and let the container send the INERNAL SERVER ERROR
                throw new ServletException("No Principal found. Verify your SSO Agent Configuration!");
            }

            if (log.isDebugEnabled())
                log.debug("Outbound relaying succesfull for assertion id [" + assertionId + "]");

            if (log.isDebugEnabled())
                log.debug("Assertion id [" + assertionId + "] mapped to SSO session id [" + entry.ssoId + "]");

            // The cookie is valid to for the partner application only ... in the future each partner app may
            // store a different auth. token (SSO SESSION) value
            cookie = _agent.newJossoCookie(hreq.getContextPath(), entry.ssoId, hreq.isSecure());
            hres.addCookie(cookie);

            // Redirect the user to the original request URI (which will cause
            // the original request to be restored)
            String requestURI = getSavedSplashResource(hreq);
            if (requestURI == null) {
                requestURI = getSavedRequestURL(hreq);
                if (requestURI == null) {

                    if (cfg.getDefaultResource() != null) {
                        requestURI = cfg.getDefaultResource();
                    } else {
                        // If no saved request is found, redirect to the partner app root :
                        requestURI = hreq.getRequestURI().substring(0,
                                (hreq.getRequestURI().length() - _agent.getJossoSecurityCheckUri().length()));
                    }

                    // If we're behind a reverse proxy, we have to alter the URL ... this was not necessary on tomcat 5.0 ?!
                    String singlePointOfAccess = _agent.getSinglePointOfAccess();
                    if (singlePointOfAccess != null) {
                        requestURI = singlePointOfAccess + requestURI;
                    } else {
                        String reverseProxyHost = hreq
                                .getHeader(org.josso.gateway.Constants.JOSSO_REVERSE_PROXY_HEADER);
                        if (reverseProxyHost != null) {
                            requestURI = reverseProxyHost + requestURI;
                        }
                    }

                    if (log.isDebugEnabled())
                        log.debug("No saved request found, using : '" + requestURI + "'");
                }
            }

            clearSavedRequestURLs(hreq, hres);
            _agent.clearAutomaticLoginReferer(hreq, hres);
            _agent.prepareNonCacheResponse(hres);

            // Check if we have a post login resource :
            String postAuthURI = cfg.getPostAuthenticationResource();
            if (postAuthURI != null) {
                String postAuthURL = _agent.buildPostAuthUrl(hres, requestURI, postAuthURI);
                if (log.isDebugEnabled())
                    log.debug("Redirecting to post-auth-resource '" + postAuthURL + "'");
                hres.sendRedirect(postAuthURL);
            } else {
                if (log.isDebugEnabled())
                    log.debug("Redirecting to original '" + requestURI + "'");
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
            }

            return;
        }

        SSOAgentRequest r = doMakeSSOAgentRequest(cfg.getId(),
                SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT, jossoSessionId, localSession, null, hreq,
                hres);
        SingleSignOnEntry entry = _agent.processRequest(r);

        if (log.isDebugEnabled())
            log.debug("Executed agent.");

        // Get session map for this servlet context.
        Map sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP);
        if (sessionMap.get(localSession.getWrapped()) == null) {
            // the local session is new so, make the valve listen for its events so that it can
            // map them to local session events.
            // Not supported : session.addSessionListener(this);
            sessionMap.put(session, localSession);
        }

        // ------------------------------------------------------------------
        // Has a valid user already been authenticated?
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Process request for '" + hreq.getRequestURI() + "'");

        if (entry != null) {
            if (log.isDebugEnabled())
                log.debug("Principal '" + entry.principal + "' has already been authenticated");
            // TODO : Not supported
            // (request).setAuthType(entry.authType);
            // (request).setUserPrincipal(entry.principal);
        } else {
            log.info("No Valid SSO Session, attempt an optional login?");
            // This is a standard anonymous request!

            if (cookie != null) {
                // cookie is not valid
                cookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure());
                hres.addCookie(cookie);
            }

            if (cookie != null
                    || (getSavedRequestURL(hreq) == null && _agent.isAutomaticLoginRequired(hreq, hres))) {

                if (log.isDebugEnabled())
                    log.debug("SSO Session is not valid, attempting automatic login");

                // Save current request, so we can co back to it later ...
                saveRequestURL(hreq, hres);
                String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                if (log.isDebugEnabled())
                    log.debug("Redirecting to login url '" + loginUrl + "'");

                //set non cache headers
                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                return;
            } else {
                if (log.isDebugEnabled())
                    log.debug("SSO cookie is not present, but login optional process is not required");
            }

        }

        // propagate the login and logout URLs to
        // partner applications.
        hreq.setAttribute("org.josso.agent.gateway-login-url", _agent.getGatewayLoginUrl());
        hreq.setAttribute("org.josso.agent.gateway-logout-url", _agent.getGatewayLogoutUrl());
        hreq.setAttribute("org.josso.agent.ssoSessionid", jossoSessionId);

        // ------------------------------------------------------------------
        // Invoke the next Valve in our pipeline
        // ------------------------------------------------------------------
        filterChain.doFilter(hreq, hres);
    } finally {
        if (log.isDebugEnabled())
            log.debug("Processed : " + hreq.getContextPath());
    }
}

From source file:com.sundevils.web.controller.TopController.java

@RequestMapping(value = "/unlockinternal**", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView unlockinternalPage(HttpServletRequest request, HttpServletResponse response,
        HttpSession session) {

    String role = (String) session.getAttribute("Role");
    if (role != null && role.equals("ADMIN")) {
        ModelAndView model = new ModelAndView();
        UnlockInternalAccountHandler handler = new UnlockInternalAccountHandler();
        model.addObject("unlock_msg", "Here are pending unlock requests");
        String usrname = "";
        model.addObject("request_results", handler.readrequestHandler());
        if (request.getParameter("refresh") != null) {
            model.addObject("request_results", handler.readrequestHandler());
        }//from  www .j a va2 s . c  o m
        if (request.getParameter("submit") != null) {

            usrname = request.getParameter("username");
            if (usrname.isEmpty()) {
                model.addObject("unlock_msg", "Error empty field");
            } else {
                boolean res = (Boolean) handler.updaterequestHandler(usrname);
                LoginHandler lg = new LoginHandler();
                lg.updateLockedFlag(usrname, 0);
                if (res)
                    model.addObject("unlock_msg", handler.requestHandler(usrname));
                else
                    model.addObject("unlock_msg", "No pending requests or incorrect username");
            }

        }

        model.addObject("title", "Unlock users");
        model.setViewName("unlockinternaluser");
        return model;
    } else {
        ModelAndView model = new ModelAndView();
        LoginHandler handler = new LoginHandler();
        String userName = (String) session.getAttribute("USERNAME");
        handler.updateLoggedInFlag(userName, 0);
        session.invalidate();
        model.setViewName("index");
        return model;
    }
}

From source file:org.jahia.ajax.gwt.content.server.JahiaContentManagementServiceImpl.java

@Override
public SessionValidationResult isValidSession() throws GWTJahiaServiceException {
    // >0 : schedule poll repeating for this value
    // 0 : session expire
    // <0 : polling deactivated
    final String loginUrl = getLogingUrl();
    final HttpSession session = getRequest().getSession(false);
    if (session != null) {
        Long date = (Long) session.getAttribute("lastPoll");
        long lastAccessed = session.getLastAccessedTime();
        long now = System.currentTimeMillis();
        boolean invalidated = false;
        if (date != null && (date / 1000 == lastAccessed / 1000)) {
            // last call was (probably) a poll call
            long first = (Long) session.getAttribute("firstPoll");
            if (logger.isDebugEnabled()) {
                logger.debug("Inactive since : " + (now - first));
            }//from w ww .  j  av  a2 s.c  om
            if (now - first < session.getMaxInactiveInterval() * 1000) {
                session.setMaxInactiveInterval(session.getMaxInactiveInterval() - (int) ((now - first) / 1000));
            } else {
                session.invalidate();
                invalidated = true;
            }
        } else {
            session.setAttribute("firstPoll", now);
        }

        if (!invalidated) {
            session.setAttribute("lastPoll", now);
        }
        return new SessionValidationResult(loginUrl, sessionPollingFrequency);
    } else {
        return new SessionValidationResult(loginUrl, 0);
    }
}

From source file:com.sundevils.web.controller.TopController.java

@RequestMapping(value = { "**/changeaccount" }, method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView changeaccount(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws IOException {

    String role = (String) session.getAttribute("Role");
    if (role == null) {
        ModelAndView model = new ModelAndView();
        model.setViewName("index");
        return model;
    } else if (role.equals("USER") || role.equals("MERCHANT")) {
        ModelAndView model = new ModelAndView();
        if (request.getParameter("search") != null) {
            ModifyUsersHandler handler = new ModifyUsersHandler();
            String test = (String) handler.getaccounttypeHandler(
                    (String) request.getSession().getAttribute("USERNAME"),
                    request.getParameter("accountnumber"));
            if (!(test.equals("Saving Account") || test.equals("Checking Account"))) {
                model.addObject("status", "Invalid account");
                model.setViewName("searchaccounttochange");
            } else {
                model.addObject("account",
                        handler.getaccounttypeHandler((String) request.getSession().getAttribute("USERNAME"),
                                request.getParameter("accountnumber")));
                model.addObject("managers", handler.requestManagers());
                model.addObject("accountnumber", request.getParameter("accountnumber"));
                model.setViewName("changeaccount");
            }/* ww  w .  j av  a 2  s  . c  om*/
        } else {
            model.setViewName("searchaccounttochange");
        }

        return model;
    } else {
        ModelAndView model = new ModelAndView();
        LoginHandler handler = new LoginHandler();
        String userName = (String) session.getAttribute("USERNAME");
        handler.updateLoggedInFlag(userName, 0);
        session.invalidate();
        model.setViewName("index");
        return model;
    }

}

From source file:com.sundevils.web.controller.TopController.java

@RequestMapping(value = "/viewTransactions**", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView viewTransactions(HttpServletRequest request, HttpServletResponse response,
        HttpSession session) {
    String User = "";
    String role = "";
    User = request.getParameter("UserName");
    //User = (String)session.getAttribute("User");
    ModelAndView model = new ModelAndView();
    List<TransactionRequestDetails> transReqstdetails = new ArrayList<TransactionRequestDetails>();
    transactionViewRequestHandler handler = new transactionViewRequestHandler();
    role = (String) session.getAttribute("Role");
    if (role == null) {
        model = new ModelAndView();
        model.setViewName("index");
        return model;
    } else if (role.equals("MANAGER")) {
        ResultSet rs = handler.transactionViewHandler(User);
        try {//from   w  w  w  .j a v  a  2  s .  co  m
            while (rs.next()) {
                TransactionRequestDetails view = new TransactionRequestDetails();
                view.setUserName(rs.getString("username"));
                view.setTransactionID(rs.getString("transactionid"));
                view.setTransactionAmount(rs.getString("transactionamount"));
                view.setSourceAccount(rs.getString("sourceaccountnumber"));
                view.setDestAccount(rs.getString("destinationaccountnumber"));
                view.setDateandTime(rs.getString("dateandtime"));
                view.setTransferType(rs.getString("transfertype"));
                view.setStatus(rs.getString("status"));
                transReqstdetails.add(view);
            }

            model.addObject("requestView", transReqstdetails);
        } catch (Exception e) {
            model = new ModelAndView();
            LoginHandler handler_logout = new LoginHandler();
            String userName = (String) session.getAttribute("USERNAME");
            handler_logout.updateLoggedInFlag(userName, 0);
            session.invalidate();
            model.setViewName("index");
            LOG.error("Issue while viewing the transactions" + e.getMessage());
        }
        model.setViewName("ViewTransactions");
        return model;
    } else {
        model = new ModelAndView();
        LoginHandler handler_login = new LoginHandler();
        String userName = (String) session.getAttribute("USERNAME");
        handler_login.updateLoggedInFlag(userName, 0);
        session.invalidate();
        model.setViewName("index");
        return model;
    }
}

From source file:org.josso.jaspi.agent.JASPISSOAuthModule.java

@Override
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject)
        throws AuthException {

    HttpServletRequest hreq = (HttpServletRequest) messageInfo.getRequestMessage();
    HttpServletResponse hres = (HttpServletResponse) messageInfo.getResponseMessage();

    if (log.isDebugEnabled()) {
        log.debug("Processing : " + hreq.getContextPath() + " [" + hreq.getRequestURL() + "]");
    }/*from   w  ww . j a  va2 s .com*/

    try {
        // ------------------------------------------------------------------
        // Check with the agent if this context should be processed.
        // ------------------------------------------------------------------
        String contextPath = hreq.getContextPath();
        String vhost = hreq.getServerName();

        // In catalina, the empty context is considered the root context
        if ("".equals(contextPath)) {
            contextPath = "/";
        }

        if (!_agent.isPartnerApp(vhost, contextPath)) {
            if (log.isDebugEnabled()) {
                log.debug("Context is not a josso partner app : " + hreq.getContextPath());
            }
            AuthStatus status = AuthStatus.SUCCESS;
            return status;
        }

        // ------------------------------------------------------------------
        // Check some basic HTTP handling
        // ------------------------------------------------------------------
        // P3P Header for IE 6+ compatibility when embedding JOSSO in a IFRAME
        SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(vhost, contextPath);
        if (cfg.isSendP3PHeader() && !hres.isCommitted()) {
            hres.setHeader("P3P", cfg.getP3PHeaderValue());
        }

        // Get our session ...
        HttpSession session = hreq.getSession(true);

        // ------------------------------------------------------------------
        // Check if the partner application required the login form
        // ------------------------------------------------------------------
        if (log.isDebugEnabled()) {
            log.debug("Checking if its a josso_login_request for '" + hreq.getRequestURI() + "'");
        }

        if (hreq.getRequestURI().endsWith(_agent.getJossoLoginUri())
                || hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) {

            if (log.isDebugEnabled()) {
                log.debug("josso_login_request received for uri '" + hreq.getRequestURI() + "'");
            }

            //save referer url in case the user clicked on Login from some public resource (page)
            //so agent can redirect the user back to that page after successful login
            if (hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) {
                saveLoginBackToURL(hreq, hres, session, true);
            } else {
                saveLoginBackToURL(hreq, hres, session, false);
            }

            String loginUrl = _agent.buildLoginUrl(hreq);

            if (log.isDebugEnabled()) {
                log.debug("Redirecting to login url '" + loginUrl + "'");
            }

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            hres.sendRedirect(hres.encodeRedirectURL(loginUrl));

            // Request is authorized for this URI
            return AuthStatus.SEND_CONTINUE;
        }

        // ------------------------------------------------------------------
        // Check if the partner application required a logout
        // ------------------------------------------------------------------
        if (log.isDebugEnabled()) {
            log.debug("Checking if its a josso_logout request for '" + hreq.getRequestURI() + "'");
        }

        if (hreq.getRequestURI().endsWith(_agent.getJossoLogoutUri())) {

            if (log.isDebugEnabled()) {
                log.debug("josso_logout request received for uri '" + hreq.getRequestURI() + "'");
            }

            String logoutUrl = _agent.buildLogoutUrl(hreq, cfg);

            if (log.isDebugEnabled()) {
                log.debug("Redirecting to logout url '" + logoutUrl + "'");
            }

            // Clear previous COOKIE ...
            Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure());
            hres.addCookie(ssoCookie);

            // invalidate session (unbind josso security context)
            session.invalidate();

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            hres.sendRedirect(hres.encodeRedirectURL(logoutUrl));

            // Request is authorized for this URI
            return AuthStatus.SEND_CONTINUE;
        }

        // ------------------------------------------------------------------
        // Check for the single sign on cookie
        // ------------------------------------------------------------------
        if (log.isDebugEnabled()) {
            log.debug("Checking for SSO cookie");
        }
        Cookie cookie = null;
        Cookie cookies[] = hreq.getCookies();
        if (cookies == null) {
            cookies = new Cookie[0];
        }
        for (int i = 0; i < cookies.length; i++) {
            if (org.josso.gateway.Constants.JOSSO_SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) {
                cookie = cookies[i];
                break;
            }
        }

        String jossoSessionId = (cookie == null) ? null : cookie.getValue();
        if (log.isDebugEnabled()) {
            log.debug("Session is: " + session);
        }

        // Get session map for this servlet context.
        Map sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP);
        if (sessionMap == null) {
            synchronized (this) {
                sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP);
                if (sessionMap == null) {
                    sessionMap = Collections.synchronizedMap(new HashMap());
                    hreq.getSession().getServletContext().setAttribute(KEY_SESSION_MAP, sessionMap);
                }
            }
        }

        LocalSession localSession = (LocalSession) sessionMap.get(session.getId());
        if (localSession == null) {
            localSession = new JASPILocalSession(session);
            // the local session is new so, make the valve listen for its events so that it can
            // map them to local session events.
            // Not Supported : session.addSessionListener(this);
            sessionMap.put(session.getId(), localSession);

        }

        // ------------------------------------------------------------------
        // Check if the partner application submitted custom login form
        // ------------------------------------------------------------------

        if (log.isDebugEnabled()) {
            log.debug("Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'");
        }
        if (hreq.getRequestURI().endsWith(_agent.getJossoAuthenticationUri())) {

            if (log.isDebugEnabled()) {
                log.debug("josso_authentication received for uri '" + hreq.getRequestURI() + "'");
            }

            JASPISSOAgentRequest customAuthRequest = (JASPISSOAgentRequest) doMakeSSOAgentRequest(cfg.getId(),
                    SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession, null, hreq,
                    hres);

            _agent.processRequest(customAuthRequest);

            // Request is authorized
            return AuthStatus.SEND_CONTINUE;
        }

        if (cookie == null || cookie.getValue().equals("-")) {

            // ------------------------------------------------------------------
            // Trigger LOGIN OPTIONAL if required
            // ------------------------------------------------------------------

            if (log.isDebugEnabled())
                log.debug("SSO cookie is not present, verifying optional login process ");

            // We have no cookie, remember me is enabled and a security check without assertion was received ...
            // This means that the user could not be identified ... go back to the original resource
            if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") == null) {

                if (log.isDebugEnabled())
                    log.debug(_agent.getJossoSecurityCheckUri()
                            + " received without assertion.  Login Optional Process failed");

                String requestURI = this.getSavedRequestURL(hreq);
                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
                AuthStatus status = AuthStatus.SEND_CONTINUE;
                return status;
            }

            // This is a standard anonymous request!
            if (!hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())) {

                // If saved request is NOT null, we're in the middle of another process ...
                if (!_agent.isResourceIgnored(cfg, hreq) && _agent.isAutomaticLoginRequired(hreq, hres)) {

                    if (log.isDebugEnabled()) {
                        log.debug("SSO cookie is not present, attempting automatic login");
                    }

                    // Save current request, so we can co back to it later ...
                    saveRequestURL(hreq, hres);
                    String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                    if (log.isDebugEnabled()) {
                        log.debug("Redirecting to login url '" + loginUrl + "'");
                    }

                    //set non cache headers
                    _agent.prepareNonCacheResponse(hres);
                    hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                    //hreq.getRequestDispatcher(loginUrl).forward(hreq, hres);
                    AuthStatus status = AuthStatus.SEND_CONTINUE;
                    return status;
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("SSO cookie is not present, but login optional process is not required");
                    }
                }
            }

            if (log.isDebugEnabled()) {
                log.debug("SSO cookie is not present, checking for outbound relaying");
            }

            if (!(hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") != null)) {
                log.debug("SSO cookie not present and relaying was not requested, skipping");
                AuthStatus status = AuthStatus.SUCCESS;
                return status;
            }

        }

        // ------------------------------------------------------------------
        // Check if this URI is subject to SSO protection
        // ------------------------------------------------------------------
        if (_agent.isResourceIgnored(cfg, hreq)) {
            // Ignored resources are authorized
            return AuthStatus.SUCCESS;
        }

        // This URI should be protected by SSO, go on ...
        if (log.isDebugEnabled()) {
            log.debug("Session is: " + session);
        }

        // ------------------------------------------------------------------
        // Invoke the SSO Agent
        // ------------------------------------------------------------------
        if (log.isDebugEnabled()) {
            log.debug("Executing agent...");
        }

        // ------------------------------------------------------------------
        // Check if a user has been authenticated and should be checked by the agent.
        // ------------------------------------------------------------------
        if (log.isDebugEnabled()) {
            log.debug("Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'");
        }

        if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                && hreq.getParameter("josso_assertion_id") != null) {

            if (log.isDebugEnabled()) {
                log.debug("josso_security_check received for uri '" + hreq.getRequestURI() + "' assertion id '"
                        + hreq.getParameter("josso_assertion_id"));
            }

            String assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER);

            JASPISSOAgentRequest relayRequest;

            if (log.isDebugEnabled()) {
                log.debug("Outbound relaying requested for assertion id [" + assertionId + "]");
            }

            relayRequest = (JASPISSOAgentRequest) doMakeSSOAgentRequest(cfg.getId(),
                    SSOAgentRequest.ACTION_RELAY, null, localSession, assertionId, hreq, hres);

            SingleSignOnEntry entry = _agent.processRequest(relayRequest);
            if (entry == null) {
                // This is wrong! We should have an entry here!
                if (log.isDebugEnabled()) {
                    log.debug("Outbound relaying failed for assertion id [" + assertionId
                            + "], no Principal found.");
                }
                // Throw an exception, we will handle it below !
                throw new RuntimeException(
                        "Outbound relaying failed. No Principal found. Verify your SSO Agent Configuration!");
            } else {
                // Add the SSOUser as a Principal
                if (!clientSubject.getPrincipals().contains(entry.principal)) {
                    clientSubject.getPrincipals().add(entry.principal);
                }
                SSORole[] ssoRolePrincipals = _agent.getRoleSets(cfg.getId(), entry.ssoId,
                        relayRequest.getNodeId());
                List<String> rolesList = new ArrayList<String>();

                for (int i = 0; i < ssoRolePrincipals.length; i++) {
                    if (clientSubject.getPrincipals().contains(ssoRolePrincipals[i])) {
                        continue;
                    }
                    rolesList.add(ssoRolePrincipals[i].getName());

                    clientSubject.getPrincipals().add(ssoRolePrincipals[i]);
                    log.debug("Added SSORole Principal to the Subject : " + ssoRolePrincipals[i]);
                }

                registerWithCallbackHandler(entry.principal, entry.principal.getName(), entry.ssoId,
                        rolesList.toArray(new String[rolesList.size()]));
            }

            if (log.isDebugEnabled()) {
                log.debug("Outbound relaying succesfull for assertion id [" + assertionId + "]");
            }

            if (log.isDebugEnabled()) {
                log.debug("Assertion id [" + assertionId + "] mapped to SSO session id [" + entry.ssoId + "]");
            }

            // The cookie is valid to for the partner application only ... in the future each partner app may
            // store a different auth. token (SSO SESSION) value
            cookie = _agent.newJossoCookie(hreq.getContextPath(), entry.ssoId, hreq.isSecure());
            hres.addCookie(cookie);

            //Redirect user to the saved splash resource (in case of auth request) or to request URI otherwise
            String requestURI = getSavedSplashResource(hreq);
            if (requestURI == null) {
                requestURI = getSavedRequestURL(hreq);
                if (requestURI == null) {

                    if (cfg.getDefaultResource() != null) {
                        requestURI = cfg.getDefaultResource();
                    } else {
                        // If no saved request is found, redirect to the partner app root :
                        requestURI = hreq.getRequestURI().substring(0,
                                (hreq.getRequestURI().length() - _agent.getJossoSecurityCheckUri().length()));
                    }

                    // If we're behind a reverse proxy, we have to alter the URL ... this was not necessary on tomcat 5.0 ?!
                    String singlePointOfAccess = _agent.getSinglePointOfAccess();
                    if (singlePointOfAccess != null) {
                        requestURI = singlePointOfAccess + requestURI;
                    } else {
                        String reverseProxyHost = hreq
                                .getHeader(org.josso.gateway.Constants.JOSSO_REVERSE_PROXY_HEADER);
                        if (reverseProxyHost != null) {
                            requestURI = reverseProxyHost + requestURI;
                        }
                    }

                    if (log.isDebugEnabled())
                        log.debug("No saved request found, using : '" + requestURI + "'");
                }
            }

            _agent.clearAutomaticLoginReferer(hreq, hres);
            _agent.prepareNonCacheResponse(hres);

            // Check if we have a post login resource :
            String postAuthURI = cfg.getPostAuthenticationResource();
            if (postAuthURI != null) {
                String postAuthURL = _agent.buildPostAuthUrl(hres, requestURI, postAuthURI);
                if (log.isDebugEnabled()) {
                    log.debug("Redirecting to post-auth-resource '" + postAuthURL + "'");
                }
                hres.sendRedirect(postAuthURL);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Redirecting to original '" + requestURI + "'");
                }
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
            }

            AuthStatus status = AuthStatus.SEND_SUCCESS;
            return status;
        }

        if (log.isDebugEnabled()) {
            log.debug("Creating Security Context for Session [" + session + "]");
        }
        SSOAgentRequest r = doMakeSSOAgentRequest(cfg.getId(),
                SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT, jossoSessionId, localSession, null, hreq,
                hres);
        SingleSignOnEntry entry = _agent.processRequest(r);

        if (log.isDebugEnabled()) {
            log.debug("Executed agent.");
        }

        // ------------------------------------------------------------------
        // Has a valid user already been authenticated?
        // ------------------------------------------------------------------
        if (log.isDebugEnabled()) {
            log.debug("Process request for '" + hreq.getRequestURI() + "'");
        }

        if (entry != null) {
            if (log.isDebugEnabled()) {
                log.debug("Principal '" + entry.principal + "' has already been authenticated");
            }
            // Add the SSOUser as a Principal
            if (!clientSubject.getPrincipals().contains(entry.principal)) {
                clientSubject.getPrincipals().add(entry.principal);
            }
            SSORole[] ssoRolePrincipals = _agent.getRoleSets(cfg.getId(), entry.ssoId, r.getNodeId());
            List<String> rolesList = new ArrayList<String>();
            for (int i = 0; i < ssoRolePrincipals.length; i++) {
                if (clientSubject.getPrincipals().contains(ssoRolePrincipals[i])) {
                    continue;
                }
                rolesList.add(ssoRolePrincipals[i].getName());
                clientSubject.getPrincipals().add(ssoRolePrincipals[i]);
                log.debug("Added SSORole Principal to the Subject : " + ssoRolePrincipals[i]);
            }
            registerWithCallbackHandler(entry.principal, entry.principal.getName(), entry.ssoId,
                    rolesList.toArray(new String[rolesList.size()]));
        } else {
            log.debug("No Valid SSO Session, attempt an optional login?");
            // This is a standard anonymous request!

            if (cookie != null) {
                // cookie is not valid
                cookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure());
                hres.addCookie(cookie);
            }

            if (cookie != null
                    || (getSavedRequestURL(hreq) == null && _agent.isAutomaticLoginRequired(hreq, hres))) {
                if (log.isDebugEnabled()) {
                    log.debug("SSO Session is not valid, attempting automatic login");
                }

                // Save current request, so we can co back to it later ...
                saveRequestURL(hreq, hres);
                String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                if (log.isDebugEnabled()) {
                    log.debug("Redirecting to login url '" + loginUrl + "'");
                }

                //set non cache headers
                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(loginUrl));

                // Request is authorized for this URI
                return AuthStatus.SEND_CONTINUE;
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("SSO cookie is not present, but login optional process is not required");
                }
            }

        }

        // propagate the login and logout URLs to
        // partner applications.
        hreq.setAttribute("org.josso.agent.gateway-login-url", _agent.getGatewayLoginUrl());
        hreq.setAttribute("org.josso.agent.gateway-logout-url", _agent.getGatewayLogoutUrl());
        hreq.setAttribute("org.josso.agent.ssoSessionid", jossoSessionId);

        clearSavedRequestURLs(hreq, hres);

        AuthStatus status = AuthStatus.SUCCESS;
        return status;
    } catch (Throwable t) {
        log.warn(t.getMessage(), t);
        throw new AuthException(t.getMessage());
        //return AuthStatus.FAILURE;
    } finally {
        if (log.isDebugEnabled()) {
            log.debug("Processed : " + hreq.getContextPath() + " [" + hreq.getRequestURL() + "]");
        }
    }
}

From source file:net.groupbuy.controller.shop.LoginController.java

/**
 * ??/*  ww  w. j a  v a2s.co  m*/
 */
@RequestMapping(value = "/submit", method = RequestMethod.POST)
public @ResponseBody Message submit(String captchaId, String captcha, String username,
        HttpServletRequest request, HttpServletResponse response, HttpSession session) {
    String password = rsaService.decryptParameter("enPassword", request);
    rsaService.removePrivateKey(request);

    if (!captchaService.isValid(CaptchaType.memberLogin, captchaId, captcha)) {
        return Message.error("shop.captcha.invalid");
    }
    if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
        return Message.error("shop.common.invalid");
    }
    Member member;
    Setting setting = SettingUtils.get();
    if (setting.getIsEmailLogin() && username.contains("@")) {
        List<Member> members = memberService.findListByEmail(username);
        if (members.isEmpty()) {
            member = null;
        } else if (members.size() == 1) {
            member = members.get(0);
        } else {
            return Message.error("shop.login.unsupportedAccount");
        }
    } else {
        member = memberService.findByUsername(username);
    }
    if (member == null) {
        return Message.error("shop.login.unknownAccount");
    }
    if (!member.getIsEnabled()) {
        return Message.error("shop.login.disabledAccount");
    }
    if (member.getIsLocked()) {
        if (ArrayUtils.contains(setting.getAccountLockTypes(), AccountLockType.member)) {
            int loginFailureLockTime = setting.getAccountLockTime();
            if (loginFailureLockTime == 0) {
                return Message.error("shop.login.lockedAccount");
            }
            Date lockedDate = member.getLockedDate();
            Date unlockDate = DateUtils.addMinutes(lockedDate, loginFailureLockTime);
            if (new Date().after(unlockDate)) {
                member.setLoginFailureCount(0);
                member.setIsLocked(false);
                member.setLockedDate(null);
                memberService.update(member);
            } else {
                return Message.error("shop.login.lockedAccount");
            }
        } else {
            member.setLoginFailureCount(0);
            member.setIsLocked(false);
            member.setLockedDate(null);
            memberService.update(member);
        }
    }

    if (!DigestUtils.md5Hex(password).equals(member.getPassword())) {
        int loginFailureCount = member.getLoginFailureCount() + 1;
        if (loginFailureCount >= setting.getAccountLockCount()) {
            member.setIsLocked(true);
            member.setLockedDate(new Date());
        }
        member.setLoginFailureCount(loginFailureCount);
        memberService.update(member);
        if (ArrayUtils.contains(setting.getAccountLockTypes(), AccountLockType.member)) {
            return Message.error("shop.login.accountLockCount", setting.getAccountLockCount());
        } else {
            return Message.error("shop.login.incorrectCredentials");
        }
    }
    member.setLoginIp(request.getRemoteAddr());
    member.setLoginDate(new Date());
    member.setLoginFailureCount(0);
    memberService.update(member);

    Cart cart = cartService.getCurrent();
    if (cart != null) {
        if (cart.getMember() == null) {
            cartService.merge(member, cart);
            WebUtils.removeCookie(request, response, Cart.ID_COOKIE_NAME);
            WebUtils.removeCookie(request, response, Cart.KEY_COOKIE_NAME);
        }
    }

    Map<String, Object> attributes = new HashMap<String, Object>();
    Enumeration<?> keys = session.getAttributeNames();
    while (keys.hasMoreElements()) {
        String key = (String) keys.nextElement();
        attributes.put(key, session.getAttribute(key));
    }
    session.invalidate();
    session = request.getSession();
    for (Entry<String, Object> entry : attributes.entrySet()) {
        session.setAttribute(entry.getKey(), entry.getValue());
    }

    session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(member.getId(), username));
    WebUtils.addCookie(request, response, Member.USERNAME_COOKIE_NAME, member.getUsername());

    return SUCCESS_MESSAGE;
}

From source file:contestWebsite.ContactUs.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Query query = new Query("user")
            .setFilter(new FilterPredicate("name", FilterOperator.EQUAL, req.getParameter("name")));
    List<Entity> users = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(3));
    Entity feedback = new Entity("feedback");
    if (users.size() != 0) {
        feedback.setProperty("user-id", users.get(0).getProperty("user-id"));
    }//from  w  w w  .  jav a2 s .  c o m

    String name = escapeHtml4(req.getParameter("name"));
    String school = escapeHtml4(req.getParameter("school"));
    String comment = escapeHtml4(req.getParameter("text"));
    String email = escapeHtml4(req.getParameter("email"));

    HttpSession sess = req.getSession(true);
    sess.setAttribute("name", name);
    sess.setAttribute("school", school);
    sess.setAttribute("email", email);
    sess.setAttribute("comment", comment);

    Entity contestInfo = Retrieve.contestInfo();
    if (!(Boolean) sess.getAttribute("nocaptcha")) {
        URL reCaptchaURL = new URL("https://www.google.com/recaptcha/api/siteverify");
        String charset = java.nio.charset.StandardCharsets.UTF_8.name();
        String reCaptchaQuery = String.format("secret=%s&response=%s&remoteip=%s",
                URLEncoder.encode((String) contestInfo.getProperty("privateKey"), charset),
                URLEncoder.encode(req.getParameter("g-recaptcha-response"), charset),
                URLEncoder.encode(req.getRemoteAddr(), charset));

        final URLConnection connection = new URL(reCaptchaURL + "?" + reCaptchaQuery).openConnection();
        connection.setRequestProperty("Accept-Charset", charset);
        String response = CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() {
            @Override
            public InputStream getInput() throws IOException {
                return connection.getInputStream();
            }
        }, Charsets.UTF_8));

        try {
            JSONObject JSONResponse = new JSONObject(response);
            if (!JSONResponse.getBoolean("success")) {
                resp.sendRedirect("/contactUs?captchaError=1");
                return;
            }
        } catch (JSONException e) {
            e.printStackTrace();
            resp.sendRedirect("/contactUs?captchaError=1");
            return;
        }
    }

    feedback.setProperty("name", name);
    feedback.setProperty("school", school);
    feedback.setProperty("email", email);
    feedback.setProperty("comment", new Text(comment));
    feedback.setProperty("resolved", false);

    Transaction txn = datastore.beginTransaction();
    try {
        datastore.put(feedback);
        txn.commit();

        Session session = Session.getDefaultInstance(new Properties(), null);
        String appEngineEmail = (String) contestInfo.getProperty("account");

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(appEngineEmail, "Tournament Website Admin"));
            msg.addRecipient(Message.RecipientType.TO,
                    new InternetAddress((String) contestInfo.getProperty("email"), "Contest Administrator"));
            msg.setSubject("Question about tournament from " + name);
            msg.setReplyTo(new InternetAddress[] { new InternetAddress(req.getParameter("email"), name),
                    new InternetAddress(appEngineEmail, "Tournament Website Admin") });

            VelocityEngine ve = new VelocityEngine();
            ve.init();

            VelocityContext context = new VelocityContext();
            context.put("name", name);
            context.put("email", email);
            context.put("school", school);
            context.put("message", comment);

            StringWriter sw = new StringWriter();
            Velocity.evaluate(context, sw, "questionEmail",
                    ((Text) contestInfo.getProperty("questionEmail")).getValue());
            msg.setContent(sw.toString(), "text/html");
            Transport.send(msg);
        } catch (MessagingException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
            return;
        }

        resp.sendRedirect("/contactUs?updated=1");
        sess.invalidate();
    } catch (Exception e) {
        e.printStackTrace();
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
    } finally {
        if (txn.isActive()) {
            txn.rollback();
        }
    }
}