Example usage for javax.servlet.http HttpSession getMaxInactiveInterval

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

Introduction

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

Prototype

public int getMaxInactiveInterval();

Source Link

Document

Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.

Usage

From source file:at.gv.egovernment.moa.id.configuration.filter.AuthenticationFilter.java

public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterchain)
        throws IOException, ServletException {

    HttpServletRequest httpServletRequest = (HttpServletRequest) req;
    HttpServletResponse httpServletResponse = (HttpServletResponse) resp;

    HttpSession session = httpServletRequest.getSession();

    Object authuserobj = session.getAttribute(Constants.SESSION_AUTH);
    AuthenticatedUser authuser = (AuthenticatedUser) authuserobj;

    String requestURL = WebAppUtil.getRequestURLWithParameters(httpServletRequest, true);

    log.trace("Request URL: " + requestURL);

    AuthenticationManager authManager = AuthenticationManager.getInstance();
    if (!authManager.isActiveUser(authuser)) {
        //user is not active anymore. Invalidate session and reauthenticate user
        String authID = (String) session.getAttribute(Constants.SESSION_PVP2REQUESTID);
        session.invalidate();//from ww  w  .  jav a  2 s.  c o  m
        authuser = null;

        //TODO: set infotext

        session = httpServletRequest.getSession(true);
        session.setAttribute(Constants.SESSION_PVP2REQUESTID, authID);
    }

    if (authuser == null && !this.isExcluded(requestURL)) {

        if (config.isLoginDeaktivated()) {
            //add dummy Daten
            log.warn("Authentication is deaktivated. Dummy authentication-information are used!");

            if (authuser == null) {
                int sessionTimeOut = session.getMaxInactiveInterval();
                Date sessionExpired = new Date(
                        new Date().getTime() + (sessionTimeOut * Constants.ONE_MINUTE_IN_MILLIS));

                authuser = AuthenticatedUser.generateDefaultUser(sessionExpired);
                authManager.setActiveUser(authuser);

                //authuser = new AuthenticatedUser(1, "Max", "TestUser", true, false);
                httpServletRequest.getSession().setAttribute(Constants.SESSION_AUTH, authuser);
            }

            if (MiscUtil.isNotEmpty(getAuthenticatedPage())) {
                if (loginPageForward) {
                    log.debug("Authenticated page is set. Forwarding to \"" + getAuthenticatedPage() + "\".");
                    RequestDispatcher dispatcher = req.getRequestDispatcher(getAuthenticatedPage());
                    dispatcher.forward(httpServletRequest, httpServletResponse);
                } else {
                    log.debug("Authenticated page is set. Redirecting to \"" + getAuthenticatedPage() + "\".");
                    httpServletResponse
                            .sendRedirect(httpServletResponse.encodeRedirectURL(getAuthenticatedPage()));
                }
                return;
            }

        } else {
            if (MiscUtil.isNotEmpty(getAuthenticatedPage())) {
                log.debug(
                        "Unable to find authentication data. Authenticated page is given so there is no need to save original request url. "
                                + (loginPageForward ? "Forwarding" : "Redirecting") + " to login page \""
                                + loginPage + "\".");

            } else {
                log.debug("Unable to find authentication data. Storing request url and "
                        + (loginPageForward ? "forwarding" : "redirecting") + " to login page \"" + loginPage
                        + "\".");
                session.setAttribute(STORED_REQUEST_URL_ID, requestURL);

            }

            if (loginPageForward) {
                RequestDispatcher dispatcher = req.getRequestDispatcher(loginPage);
                dispatcher.forward(httpServletRequest, httpServletResponse);
                return;

            } else {
                httpServletResponse.sendRedirect(httpServletResponse.encodeRedirectURL(loginPage));
                return;

            }
        }

    } else {
        try {
            filterchain.doFilter(req, resp);

        } catch (Exception e) {

            //String redirectURL = "./index.action";
            //HttpServletResponse httpResp = (HttpServletResponse) resp;
            //redirectURL = httpResp.encodeRedirectURL(redirectURL);
            //resp.setContentType("text/html");
            //((HttpServletResponse) resp).setStatus(302);
            //httpResp.addHeader("Location", redirectURL);
            //log.warn("A Filter Error occurs -> Redirect to Login-Form");
        }
    }
}

From source file:UsingContexts.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    HttpSession session = request.getSession(true);

    Integer counter2 = (Integer) getServletContext().getAttribute("counter2");

    if (counter2 == null) {
        counter2 = new Integer(1);
    } else {/*from  w  w w.  ja v  a2  s .c  om*/
        counter2 = new Integer(counter2.intValue() + 1);
    }

    getServletContext().setAttribute("counter2", counter2);

    Integer counter = (Integer) session.getAttribute("counter");

    if (counter == null) {
        counter = new Integer(1);
    } else {
        counter = new Integer(counter.intValue() + 1);
    }

    session.setAttribute("counter", counter);

    out.println("<HTML>");
    out.println("<HEAD>");
    out.println("<TITLE>");
    out.println("Using Contexts");
    out.println("</TITLE>");
    out.println("</HEAD>");
    out.println("<BODY>");
    out.println("<H1>Using Contexts</H1>");

    out.println("Welcome! You have been here " + counter + " times.<BR>");

    out.println("Total page accesses: " + counter2 + "<BR>");

    if (session.isNew()) {
        out.println("This is a new session.<BR>");
    } else {
        out.println("This is not a new session.<BR>");
    }

    out.println("The session ID: " + session.getId() + "<BR>");
    out.println("Last time accessed: " + new Date(session.getLastAccessedTime()) + "<BR>");
    out.println("Creation time: " + new Date(session.getCreationTime()) + "<BR>");
    out.println("Timeout length: " + session.getMaxInactiveInterval() + " seconds<BR>");

    out.println("</BODY>");
    out.println("</HTML>");
}

From source file:org.apache.tapestry.request.RequestContext.java

/**
 * Writes the state of the context to the writer, typically for inclusion
 * in a HTML page returned to the user. This is useful
 * when debugging.  The Inspector uses this as well.
 *
 **///from  w ww . j a  v  a  2s.  c  o  m

public void write(IMarkupWriter writer) {
    // Create a box around all of this stuff ...

    writer.begin("table");
    writer.attribute("class", "request-context-border");
    writer.begin("tr");
    writer.begin("td");

    // Get the session, if it exists, and display it.

    HttpSession session = getSession();

    if (session != null) {
        object(writer, "Session");
        writer.begin("table");
        writer.attribute("class", "request-context-object");

        section(writer, "Properties");
        header(writer, "Name", "Value");

        pair(writer, "id", session.getId());
        datePair(writer, "creationTime", session.getCreationTime());
        datePair(writer, "lastAccessedTime", session.getLastAccessedTime());
        pair(writer, "maxInactiveInterval", session.getMaxInactiveInterval());
        pair(writer, "new", session.isNew());

        List names = getSorted(session.getAttributeNames());
        int count = names.size();

        for (int i = 0; i < count; i++) {
            if (i == 0) {
                section(writer, "Attributes");
                header(writer, "Name", "Value");
            }

            String name = (String) names.get(i);
            pair(writer, name, session.getAttribute(name));
        }

        writer.end(); // Session

    }

    object(writer, "Request");
    writer.begin("table");
    writer.attribute("class", "request-context-object");

    // Parameters ...

    List parameters = getSorted(_request.getParameterNames());
    int count = parameters.size();

    for (int i = 0; i < count; i++) {

        if (i == 0) {
            section(writer, "Parameters");
            header(writer, "Name", "Value(s)");
        }

        String name = (String) parameters.get(i);
        String[] values = _request.getParameterValues(name);

        writer.begin("tr");
        writer.attribute("class", getRowClass());
        writer.begin("th");
        writer.print(name);
        writer.end();
        writer.begin("td");

        if (values.length > 1)
            writer.begin("ul");

        for (int j = 0; j < values.length; j++) {
            if (values.length > 1)
                writer.beginEmpty("li");

            writer.print(values[j]);

        }

        writer.end("tr");
    }

    section(writer, "Properties");
    header(writer, "Name", "Value");

    pair(writer, "authType", _request.getAuthType());
    pair(writer, "characterEncoding", _request.getCharacterEncoding());
    pair(writer, "contentLength", _request.getContentLength());
    pair(writer, "contentType", _request.getContentType());
    pair(writer, "method", _request.getMethod());
    pair(writer, "pathInfo", _request.getPathInfo());
    pair(writer, "pathTranslated", _request.getPathTranslated());
    pair(writer, "protocol", _request.getProtocol());
    pair(writer, "queryString", _request.getQueryString());
    pair(writer, "remoteAddr", _request.getRemoteAddr());
    pair(writer, "remoteHost", _request.getRemoteHost());
    pair(writer, "remoteUser", _request.getRemoteUser());
    pair(writer, "requestedSessionId", _request.getRequestedSessionId());
    pair(writer, "requestedSessionIdFromCookie", _request.isRequestedSessionIdFromCookie());
    pair(writer, "requestedSessionIdFromURL", _request.isRequestedSessionIdFromURL());
    pair(writer, "requestedSessionIdValid", _request.isRequestedSessionIdValid());
    pair(writer, "requestURI", _request.getRequestURI());
    pair(writer, "scheme", _request.getScheme());
    pair(writer, "serverName", _request.getServerName());
    pair(writer, "serverPort", _request.getServerPort());
    pair(writer, "contextPath", _request.getContextPath());
    pair(writer, "servletPath", _request.getServletPath());

    // Now deal with any headers

    List headers = getSorted(_request.getHeaderNames());
    count = headers.size();

    for (int i = 0; i < count; i++) {
        if (i == 0) {
            section(writer, "Headers");
            header(writer, "Name", "Value");
        }

        String name = (String) headers.get(i);
        String value = _request.getHeader(name);

        pair(writer, name, value);
    }

    // Attributes

    List attributes = getSorted(_request.getAttributeNames());
    count = attributes.size();

    for (int i = 0; i < count; i++) {
        if (i == 0) {
            section(writer, "Attributes");
            header(writer, "Name", "Value");
        }

        String name = (String) attributes.get(i);

        pair(writer, name, _request.getAttribute(name));
    }

    // Cookies ...

    Cookie[] cookies = _request.getCookies();

    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {

            if (i == 0) {
                section(writer, "Cookies");
                header(writer, "Name", "Value");
            }

            Cookie cookie = cookies[i];

            pair(writer, cookie.getName(), cookie.getValue());

        } // Cookies loop
    }

    writer.end(); // Request

    object(writer, "Servlet");
    writer.begin("table");
    writer.attribute("class", "request-context-object");

    section(writer, "Properties");
    header(writer, "Name", "Value");

    pair(writer, "servlet", _servlet);
    pair(writer, "name", _servlet.getServletName());
    pair(writer, "servletInfo", _servlet.getServletInfo());

    ServletConfig config = _servlet.getServletConfig();

    List names = getSorted(config.getInitParameterNames());
    count = names.size();

    for (int i = 0; i < count; i++) {

        if (i == 0) {
            section(writer, "Init Parameters");
            header(writer, "Name", "Value");
        }

        String name = (String) names.get(i);
        ;
        pair(writer, name, config.getInitParameter(name));

    }

    writer.end(); // Servlet

    ServletContext context = config.getServletContext();

    object(writer, "Servlet Context");
    writer.begin("table");
    writer.attribute("class", "request-context-object");

    section(writer, "Properties");
    header(writer, "Name", "Value");

    pair(writer, "majorVersion", context.getMajorVersion());
    pair(writer, "minorVersion", context.getMinorVersion());
    pair(writer, "serverInfo", context.getServerInfo());

    names = getSorted(context.getInitParameterNames());
    count = names.size();
    for (int i = 0; i < count; i++) {
        if (i == 0) {
            section(writer, "Initial Parameters");
            header(writer, "Name", "Value");
        }

        String name = (String) names.get(i);
        pair(writer, name, context.getInitParameter(name));
    }

    names = getSorted(context.getAttributeNames());
    count = names.size();
    for (int i = 0; i < count; i++) {
        if (i == 0) {
            section(writer, "Attributes");
            header(writer, "Name", "Value");
        }

        String name = (String) names.get(i);
        pair(writer, name, context.getAttribute(name));
    }

    writer.end(); // Servlet Context

    writeSystemProperties(writer);

    writer.end("table"); // The enclosing border
}

From source file:org.sakaiproject.portal.util.ErrorReporter.java

@SuppressWarnings("rawtypes")
private String requestDisplay(HttpServletRequest request) {
    ResourceBundle rb = rbDefault;
    StringBuilder sb = new StringBuilder();
    try {//from   ww  w.j  a va2  s  . com
        sb.append(rb.getString("bugreport.request")).append("\n");
        sb.append(rb.getString("bugreport.request.authtype")).append(request.getAuthType()).append("\n");
        sb.append(rb.getString("bugreport.request.charencoding")).append(request.getCharacterEncoding())
                .append("\n");
        sb.append(rb.getString("bugreport.request.contentlength")).append(request.getContentLength())
                .append("\n");
        sb.append(rb.getString("bugreport.request.contenttype")).append(request.getContentType()).append("\n");
        sb.append(rb.getString("bugreport.request.contextpath")).append(request.getContextPath()).append("\n");
        sb.append(rb.getString("bugreport.request.localaddr")).append(request.getLocalAddr()).append("\n");
        sb.append(rb.getString("bugreport.request.localname")).append(request.getLocalName()).append("\n");
        sb.append(rb.getString("bugreport.request.localport")).append(request.getLocalPort()).append("\n");
        sb.append(rb.getString("bugreport.request.method")).append(request.getMethod()).append("\n");
        sb.append(rb.getString("bugreport.request.pathinfo")).append(request.getPathInfo()).append("\n");
        sb.append(rb.getString("bugreport.request.protocol")).append(request.getProtocol()).append("\n");
        sb.append(rb.getString("bugreport.request.querystring")).append(request.getQueryString()).append("\n");
        sb.append(rb.getString("bugreport.request.remoteaddr")).append(request.getRemoteAddr()).append("\n");
        sb.append(rb.getString("bugreport.request.remotehost")).append(request.getRemoteHost()).append("\n");
        sb.append(rb.getString("bugreport.request.remoteport")).append(request.getRemotePort()).append("\n");
        sb.append(rb.getString("bugreport.request.requesturl")).append(request.getRequestURL()).append("\n");
        sb.append(rb.getString("bugreport.request.scheme")).append(request.getScheme()).append("\n");
        sb.append(rb.getString("bugreport.request.servername")).append(request.getServerName()).append("\n");
        sb.append(rb.getString("bugreport.request.headers")).append("\n");
        for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {
            String headerName = (String) e.nextElement();
            boolean censor = (censoredHeaders.get(headerName) != null);
            for (Enumeration he = request.getHeaders(headerName); he.hasMoreElements();) {
                String headerValue = (String) he.nextElement();
                sb.append(rb.getString("bugreport.request.header")).append(headerName).append(":")
                        .append(censor ? "---censored---" : headerValue).append("\n");
            }
        }
        sb.append(rb.getString("bugreport.request.parameters")).append("\n");
        for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {

            String parameterName = (String) e.nextElement();
            boolean censor = (censoredParameters.get(parameterName) != null);
            String[] paramvalues = request.getParameterValues(parameterName);
            for (int i = 0; i < paramvalues.length; i++) {
                sb.append(rb.getString("bugreport.request.parameter")).append(parameterName).append(":")
                        .append(i).append(":").append(censor ? "----censored----" : paramvalues[i])
                        .append("\n");
            }
        }
        sb.append(rb.getString("bugreport.request.attributes")).append("\n");
        for (Enumeration e = request.getAttributeNames(); e.hasMoreElements();) {
            String attributeName = (String) e.nextElement();
            Object attribute = request.getAttribute(attributeName);
            boolean censor = (censoredAttributes.get(attributeName) != null);
            sb.append(rb.getString("bugreport.request.attribute")).append(attributeName).append(":")
                    .append(censor ? "----censored----" : attribute).append("\n");
        }
        HttpSession session = request.getSession(false);
        if (session != null) {
            DateFormat serverLocaleDateFormat = DateFormat.getDateInstance(DateFormat.FULL,
                    Locale.getDefault());
            sb.append(rb.getString("bugreport.session")).append("\n");
            sb.append(rb.getString("bugreport.session.creation")).append(session.getCreationTime())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.lastaccess")).append(session.getLastAccessedTime())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.creationdatetime"))
                    .append(serverLocaleDateFormat.format(session.getCreationTime())).append("\n");
            sb.append(rb.getString("bugreport.session.lastaccessdatetime"))
                    .append(serverLocaleDateFormat.format(session.getLastAccessedTime())).append("\n");
            sb.append(rb.getString("bugreport.session.maxinactive")).append(session.getMaxInactiveInterval())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.attributes")).append("\n");
            for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) {
                String attributeName = (String) e.nextElement();
                Object attribute = session.getAttribute(attributeName);
                boolean censor = (censoredAttributes.get(attributeName) != null);
                sb.append(rb.getString("bugreport.session.attribute")).append(attributeName).append(":")
                        .append(censor ? "----censored----" : attribute).append("\n");
            }

        }
    } catch (Exception ex) {
        M_log.error("Failed to generate request display", ex);
        sb.append("Error " + ex.getMessage());
    }

    return sb.toString();
}

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

public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    if (isDisabled()) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }//w  ww. j av  a 2  s . c o  m
    String method = req.getMethod();
    if (req.getParameter(METHOD_TO_CALL) != null) {
        method = req.getParameter(METHOD_TO_CALL).toUpperCase();
    }
    if (!isMethodAllowed(method)) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return null;
    }
    long startTime = System.currentTimeMillis();
    String sessionId = null;
    try {
        final HttpSession session = req.getSession();
        if (logger.isInfoEnabled()) {
            sessionId = session.getId();
        }
        URLResolver urlResolver = urlResolverFactory.createURLResolver(req.getPathInfo(), req.getServerName(),
                workspace, req);

        req.setAttribute("urlResolver", urlResolver);

        session.setAttribute("workspace", urlResolver.getWorkspace());

        if (sessionExpiryTime != null && session.getMaxInactiveInterval() != sessionExpiryTime * 60) {
            session.setMaxInactiveInterval(sessionExpiryTime * 60);
        }

        RenderContext renderContext = createRenderContext(req, resp, jcrSessionFactory.getCurrentUser());
        renderContext.setWorkspace(urlResolver.getWorkspace());

        urlResolver.setRenderContext(renderContext);
        req.getSession().setAttribute(Constants.SESSION_LOCALE, urlResolver.getLocale());
        jcrSessionFactory.setCurrentLocale(urlResolver.getLocale());
        if (renderContext.isPreviewMode() && req.getParameter(ALIAS_USER) != null
                && !JahiaUserManagerService.isGuest(jcrSessionFactory.getCurrentUser())) {
            JahiaUserManagerService userManagerService = ServicesRegistry.getInstance()
                    .getJahiaUserManagerService();
            JCRUserNode userNode = userManagerService.lookupUser(req.getParameter(ALIAS_USER),
                    urlResolver.getSiteKey());
            if (userNode != null) {
                jcrSessionFactory.setCurrentAliasedUser(userNode.getJahiaUser());
            }
        }

        // check permission
        try {
            if (!hasAccess(urlResolver.getNode())) {
                if (JahiaUserManagerService.isGuest(jcrSessionFactory.getCurrentUser())) {
                    throw new JahiaUnauthorizedException();
                } else {
                    throw new JahiaForbiddenAccessException();
                }
            }
        } catch (PathNotFoundException e) {

        }

        renderContext.setSiteInfo(urlResolver.getSiteInfo());

        if (renderContext.isPreviewMode() && req.getParameter(PREVIEW_DATE) != null
                && !JahiaUserManagerService.isGuest(jcrSessionFactory.getCurrentUser())) {
            Calendar previewDate = Calendar.getInstance();
            previewDate.setTime(new Date(new Long(req.getParameter(PREVIEW_DATE))));
            jcrSessionFactory.setCurrentPreviewDate(previewDate);
        }
        if (method.equals(METHOD_GET)) {
            Resource resource;
            resource = urlResolver.getResource();
            if (!StringUtils.isEmpty(urlResolver.getRedirectUrl())
                    && (StringUtils.isEmpty(resource.getTemplate())
                            || StringUtils.equals(resource.getTemplate(), "default"))) {
                Map<String, List<String>> parameters = new HashMap<String, List<String>>();
                parameters.put(NEW_NODE_OUTPUT_FORMAT, LIST_WITH_EMPTY_STRING);
                parameters.put(REDIRECT_HTTP_RESPONSE_CODE, REDIRECT_CODE_MOVED_PERMANENTLY);

                performRedirect(urlResolver.getRedirectUrl(),
                        StringUtils.isEmpty(urlResolver.getVanityUrl())
                                ? "/" + urlResolver.getLocale().toString() + urlResolver.getPath()
                                : urlResolver.getVanityUrl(),
                        req, resp, parameters, false);
            } else {
                renderContext.setMainResource(resource);
                if (renderContext.getSite() == null) {
                    // If Site has not been resolved by the servlet (so far only dashboard mode is doing that
                    JCRSiteNode site = resource.getNode().getResolveSite();
                    if (!Url.isLocalhost(req.getServerName()) && !renderContext.isEditMode()) {
                        JCRSessionWrapper session1 = resource.getNode().getSession();
                        if (urlResolver.getSiteKey() != null
                                && (site == null || !site.getSiteKey().equals(urlResolver.getSiteKey()))) {
                            site = (JCRSiteNode) session1.getNode("/sites/" + urlResolver.getSiteKey());
                        } else if (renderContext.isLiveMode() && urlResolver.getSiteKeyByServerName() != null
                                && (site == null
                                        || !site.getSiteKey().equals(urlResolver.getSiteKeyByServerName()))) {
                            site = (JCRSiteNode) session1
                                    .getNode("/sites/" + urlResolver.getSiteKeyByServerName());
                        }
                    }
                    String jsite = null;
                    HttpServletRequest request = renderContext.getRequest();
                    if (request != null) {
                        jsite = request.getParameter("jsite");
                    }
                    if (jsite == null && renderContext.getMainResource() != null) {
                        jsite = (String) renderContext.getMainResource().getModuleParams().get("jsite");
                    }
                    if (jsite != null) {
                        try {
                            site = (JCRSiteNode) resource.getNode().getSession().getNodeByIdentifier(jsite);
                        } catch (ItemNotFoundException e) {
                            if (JahiaUserManagerService.isGuest(jcrSessionFactory.getCurrentUser())) {
                                throw new JahiaUnauthorizedException();
                            } else {
                                throw new JahiaForbiddenAccessException();
                            }
                        }
                    }
                    if (resource.getNode().getPath().startsWith("/sites/") && (site == null || (!site.getPath()
                            .startsWith("/modules/")
                            && !site.isAllowsUnlistedLanguages()
                            && !(renderContext.isLiveMode()
                                    ? site.getActiveLiveLanguagesAsLocales().contains(urlResolver.getLocale())
                                    : site.getLanguagesAsLocales().contains(urlResolver.getLocale()))))) {
                        throw new PathNotFoundException("This language does not exist on this site");
                    }
                    renderContext.setSite(site);
                }
                //                    resource.pushWrapper("wrapper.fullpage");

                if (urlResolver.getPath().endsWith(".do")) {
                    Action action = templateService.getActions().get(resource.getResolvedTemplate());
                    Map<String, List<String>> parameters = toParameterMapOfListOfString(req);
                    if (action != null) {
                        doAction(req, resp, urlResolver, renderContext, resource, action, parameters);
                    } else {
                        logger.error("Action {} does not exist", resource.getResolvedTemplate());
                        throw new PathNotFoundException("Action does not exist");
                    }
                } else {
                    long lastModified = getLastModified(resource, renderContext);

                    if (lastModified == -1) {
                        // servlet doesn't support if-modified-since, no reason
                        // to go through further expensive logic
                        doGet(req, resp, renderContext, resource, startTime);
                    } else {
                        long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
                        if (ifModifiedSince < (lastModified / 1000 * 1000)) {
                            // If the servlet mod time is later, call doGet()
                            // Round down to the nearest second for a proper compare
                            // A ifModifiedSince of -1 will always be less
                            maybeSetLastModified(resp, lastModified);
                            doGet(req, resp, renderContext, resource, startTime);
                        } else {
                            resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                        }
                    }
                }
            }
        } else if (method.equals(METHOD_HEAD)) {
            doHead(req, resp);

        } else if (method.equals(METHOD_POST)) {
            doPost(req, resp, renderContext, urlResolver);

        } else if (method.equals(METHOD_PUT)) {
            doPut(req, resp, renderContext, urlResolver);

        } else if (method.equals(METHOD_DELETE)) {
            doDelete(req, resp, renderContext, urlResolver);

        } else if (method.equals(METHOD_OPTIONS)) {
            doOptions(req, resp);

        } else if (method.equals(METHOD_TRACE)) {
            doTrace(req, resp);

        } else {
            //
            // Note that this means NO servlet supports whatever
            // method was requested, anywhere on this server.
            //
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }
    } catch (Exception e) {
        List<ErrorHandler> handlers = templateService.getErrorHandler();
        for (ErrorHandler handler : handlers) {
            if (handler.handle(e, req, resp)) {
                return null;
            }
        }
        DefaultErrorHandler.getInstance().handle(e, req, resp);
    } finally {
        if (logger.isInfoEnabled()) {
            StringBuilder sb = new StringBuilder(100);
            sb.append("Rendered [").append(req.getRequestURI());
            if (jcrSessionFactory.getCurrentUser() != null) {
                sb.append("] user=[").append(jcrSessionFactory.getCurrentUser().getUsername());
            }
            sb.append("] ip=[").append(req.getRemoteAddr()).append("] sessionID=[").append(sessionId)
                    .append("] in [").append(System.currentTimeMillis() - startTime).append("ms]");
            logger.info(sb.toString());
        }
    }
    return null;
}

From source file:com.adito.security.DefaultLogonController.java

private synchronized void moveSessionTimeoutBlocks(HttpSession oldSession, HttpSession newSession) {
    Map sessionTimeoutBlocks = (Map) oldSession.getAttribute(Constants.SESSION_TIMEOUT_BLOCKS);
    if (sessionTimeoutBlocks != null) {
        newSession.setAttribute(Constants.SESSION_TIMEOUT_BLOCKS, sessionTimeoutBlocks);
    }//from   w w w.  ja v  a 2  s.co  m
    Integer vpnClientSessionTimeoutBlockId = (Integer) oldSession
            .getAttribute(Constants.AGENT_SESSION_TIMEOUT_BLOCK_ID);
    if (vpnClientSessionTimeoutBlockId != null) {
        newSession.setAttribute(Constants.AGENT_SESSION_TIMEOUT_BLOCK_ID, vpnClientSessionTimeoutBlockId);
    }
    newSession.setMaxInactiveInterval(sessionTimeoutBlocks == null || sessionTimeoutBlocks.size() == 0
            ? oldSession.getMaxInactiveInterval()
            : -1);
}

From source file:at.gv.egovernment.moa.id.configuration.struts.action.IndexAction.java

public String authenticate() {

    try {//from w w w  . j  a va 2s .  co m
        populateBasicInformations();

    } catch (BasicActionException e) {
        return Constants.STRUTS_ERROR;

    }

    pvp2LoginActiv = configuration.isPVP2LoginActive();

    String key = null;

    if (MiscUtil.isNotEmpty(username)) {
        if (ValidationHelper.containsPotentialCSSCharacter(username, false)) {
            log.warn("Username contains potentail XSS characters: " + username);
            addActionError(LanguageHelper.getErrorString("validation.edituser.username.valid",
                    new Object[] { ValidationHelper.getPotentialCSSCharacter(false) }, request));
            return Constants.STRUTS_ERROR;
        }
    } else {
        log.warn("Username is empty");
        addActionError(LanguageHelper.getErrorString("validation.edituser.username.empty", request));
        return Constants.STRUTS_ERROR;
    }

    if (MiscUtil.isEmpty(password)) {
        log.warn("Password is empty");
        addActionError(LanguageHelper.getErrorString("validation.edituser.password.empty", request));
        return Constants.STRUTS_ERROR;

    } else {
        key = AuthenticationHelper.generateKeyFormPassword(password);
        if (key == null) {
            addActionError(LanguageHelper.getErrorString("validation.edituser.password.valid", request));
            return Constants.STRUTS_ERROR;
        }
    }

    UserDatabase dbuser = ConfigurationDBRead.getUserWithUserName(username);
    if (dbuser == null) {
        log.warn("Unknown Username");
        addActionError(LanguageHelper.getErrorString("webpages.index.login.notallowed", request));
        return Constants.STRUTS_ERROR;

    } else {
        //TODO: maybe remove this default value in a later version
        if (dbuser.isIsUsernamePasswordAllowed() == null)
            dbuser.setIsUsernamePasswordAllowed(true);

        if (!dbuser.isIsActive() || !dbuser.isIsUsernamePasswordAllowed()) {
            log.warn("Username " + dbuser.getUsername()
                    + " is not active or Username/Password login is not allowed");
            addActionError(LanguageHelper.getErrorString("webpages.index.login.notallowed", request));
            return Constants.STRUTS_ERROR;
        }

        if (!dbuser.getPassword().equals(key)) {
            log.warn("Username " + dbuser.getUsername() + " use a false password");
            addActionError(LanguageHelper.getErrorString("webpages.index.login.notallowed", request));
            return Constants.STRUTS_ERROR;
        }

        //TODO: maybe remove this default value in a later version 
        boolean ismandateuser = false;
        if (dbuser.isIsMandateUser() != null)
            ismandateuser = dbuser.isIsMandateUser();

        int sessionTimeOut = session.getMaxInactiveInterval();
        Date sessionExpired = new Date(
                new Date().getTime() + (sessionTimeOut * Constants.ONE_MINUTE_IN_MILLIS));

        AuthenticatedUser authuser = new AuthenticatedUser(dbuser, true, ismandateuser, false,
                dbuser.getHjid() + "dbID", "username/password", sessionExpired);

        //store user as authenticated user
        AuthenticationManager authManager = AuthenticationManager.getInstance();
        authManager.setActiveUser(authuser);

        Date date = DateTimeHelper.parseDateTime(dbuser.getLastLogin());
        if (date != null)
            authuser.setLastLogin(date);
        ;

        dbuser.setLastLogin(DateTimeHelper.getDateTime(new Date()));

        try {
            ConfigurationDBUtils.saveOrUpdate(dbuser);

        } catch (MOADatabaseException e) {
            log.warn("UserDatabase communicaton error", e);
            addActionError(LanguageHelper.getErrorString("error.login", request));
            return Constants.STRUTS_ERROR;
        } finally {
            ConfigurationDBUtils.closeSession();
        }

        HttpSession session = generateNewJSession(request);
        session.setAttribute(Constants.SESSION_AUTH, authuser);

        return Constants.STRUTS_SUCCESS;
    }
}

From source file:org.wings.session.WingServlet.java

public final SessionServlet getSessionServlet(HttpServletRequest request, HttpServletResponse response,
        boolean createSessionServlet) throws ServletException {
    final HttpSession httpSession = request.getSession(true);

    // it should be enough to synchronize on the http session object...
    synchronized (httpSession) {
        SessionServlet sessionServlet = null;

        if (httpSession != null) {
            sessionServlet = (SessionServlet) httpSession.getAttribute(lookupName);
        }/*from  w w  w  . j  av a 2s .c om*/

        // Sanity check - maybe this is a stored/deserialized session servlet?
        if (sessionServlet != null && !sessionServlet.isValid()) {
            sessionServlet.destroy();
            sessionServlet = null;
        }

        /*
         * we are only interested in a new session, if the response is
         * not null. If it is null, then we just called getSessionServlet()
         * for lookup purposes and are satisfied, if we don't get anything.
         */
        if (sessionServlet == null) {
            if (createSessionServlet) {
                log.info("no session servlet, create new one");
                sessionServlet = newSession(request, response);
                httpSession.setAttribute(lookupName, sessionServlet);
            } else {
                return null;
            }
        }

        if (log.isDebugEnabled()) {
            StringBuilder message = new StringBuilder().append("session id: ")
                    .append(request.getRequestedSessionId()).append(", created at: ")
                    .append(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
                            .format(new java.util.Date(httpSession.getCreationTime())))
                    .append(", identified via:")
                    .append(request.isRequestedSessionIdFromCookie() ? " cookie" : "")
                    .append(request.isRequestedSessionIdFromURL() ? " URL" : "").append(", expiring after: ")
                    .append(httpSession.getMaxInactiveInterval()).append("s ");
            log.debug(message.toString());
            //log.debug("session valid " + request.isRequestedSessionIdValid());
            //log.debug("session httpsession id " + httpSession.getId());
            //log.debug("session httpsession new " + httpSession.isNew());
            //log.debug("session last accessed at " +
            //        new java.util.Date(httpSession.getLastAccessedTime()));
            //log.debug("session expiration timeout (s) " +
            //        httpSession.getMaxInactiveInterval());
            //log.debug("session contains wings session " +
            //        (httpSession.getAttribute(lookupName) != null));
        }

        sessionServlet.getSession().getExternalizeManager().setResponse(response);

        /* Handling of the requests character encoding.
         * --------------------------------------------
         * The following block is needed for a correct handling of
         * non-ISO-8859-1 data:
         *
         * Using LocaleCharacterSet and/or charset.properties we can
         * advise the client to use i.e. UTF-8 as character encoding.
         * Once told the browser consequently also encodes his requests
         * in the choosen characterset of the sings session. This is
         * achieved by adding the HTML code
         * <meta http-equiv="Content-Type" content="text/html;charset="<charset>">
         * to the generated pages.
         *
         * If the user hasn't overridden the encoding in their browser,
         * then all form data (e.g. mueller) is submitted with data encoded
         * like m%C3%BCller because byte pair C3 BC is how the german
         * u-umlaut is represented in UTF-8. If the form is
         * iso-8859-1 encoded then you get m%FCller, because byte FC is
         * how it is presented in iso-8859-1.
         *
         * So the browser behaves correctly by sending his form input
         * correctly encoded in the advised character encoding. The issue
         * is that the servlet container is typically unable to determine
         * the correct encoding of this form data. By proposal the browser
         * should als declare the used character encoding for his data.
         * But actual browsers omit this information and hence the servlet
         * container is unable to guess the right encoding (Tomcat actually
         * thenalways guesses ISO 8859-1). This results in totally
         * scrumbled up data for all non ISO-8859-1 character encodings.
         * With the block below we tell the servlet container about the
         * character encoding we expect in the browsers request and hence
         * the servlet container can do the correct decoding.
         * This has to be done at very first, otherwise the servlet
         * container will ignore this setting.
         */
        if ((request.getCharacterEncoding() == null)) { // was servlet container able to identify encoding?
            try {
                String sessionCharacterEncoding = sessionServlet.getSession().getCharacterEncoding();
                // We know better about the used character encoding than tomcat
                log.debug("Advising servlet container to interpret request as " + sessionCharacterEncoding);
                request.setCharacterEncoding(sessionCharacterEncoding);
            } catch (UnsupportedEncodingException e) {
                log.warn("Problem on applying current session character encoding", e);
            }
        }

        return sessionServlet;
    }
}

From source file:org.jahia.admin.sites.ManageSites.java

/**
 * Display Delete Site confirmation.//from   w  ww  .  j a va2 s  . co m
 *
 * @param request  Servlet request.
 * @param response Servlet response.
 * @param session  HttpSession object.
 */
private void displayDelete(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws IOException, ServletException {
    //logger.debug(" display delete site started ");

    // change session time out to 1 hour ( the extraction can be very long !)
    int timeOut = session.getMaxInactiveInterval();

    try {
        session.setMaxInactiveInterval(7200);

        // get site...
        String site_id = StringUtils.defaultString(request.getParameter("siteid")).trim();
        Integer siteID = new Integer(site_id);

        JahiaSite site = sMgr.getSite(siteID.intValue());

        // retrieve previous form values...
        String jahiaDisplayMessage = Jahia.COPYRIGHT;
        String siteTitle = (String) request.getAttribute("siteTitle");
        String siteServerName = (String) request.getAttribute("siteServerName");
        String siteKey = (String) request.getAttribute("siteKey");
        String siteDescr = (String) request.getAttribute("siteDescr");

        // set default values...
        if (siteTitle == null) {
            siteTitle = site.getTitle();
        }
        if (siteServerName == null) {
            siteServerName = site.getServerName();
        }
        if (siteKey == null) {
            siteKey = site.getSiteKey();
        }
        if (siteDescr == null) {
            siteDescr = site.getDescr();
        }

        // set request attributes...
        request.setAttribute("jahiaDisplayMessage", jahiaDisplayMessage);
        request.setAttribute("siteTitle", siteTitle);
        request.setAttribute("siteServerName", siteServerName);
        request.setAttribute("siteKey", siteKey);
        request.setAttribute("siteDescr", siteDescr);
        request.setAttribute("siteID", siteID);

        // list of user providers
        JahiaUserManagerService userServ = ServicesRegistry.getInstance().getJahiaUserManagerService();
        List<JahiaUserManagerProvider> usrProviders = new ArrayList<JahiaUserManagerProvider>();
        for (JahiaUserManagerProvider usrProviderBean : userServ.getProviderList()) {
            if (!usrProviderBean.isReadOnly()) {
                usrProviders.add(usrProviderBean);
            }
        }
        request.setAttribute("usrProviders", usrProviders);

        // redirect...
        JahiaAdministration.doRedirect(request, response, session, JSP_PATH + "site_delete.jsp");
    } catch (Exception e) {
        logger.error("Error while display site delete UI", e);
        // redirect to list...
        String jahiaDisplayMessage = getMessage("org.jahia.admin.warningMsg..processingError.label");
        session.setAttribute(CLASS_NAME + "jahiaDisplayMessage", jahiaDisplayMessage);
        displayList(request, response, session);
    } finally {
        // restore time out
        session.setMaxInactiveInterval(timeOut);
    }

    // reset display message...
    session.setAttribute(CLASS_NAME + "jahiaDisplayMessage", Jahia.COPYRIGHT);
}