Example usage for javax.servlet.http HttpServletRequest isSecure

List of usage examples for javax.servlet.http HttpServletRequest isSecure

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest isSecure.

Prototype

public boolean isSecure();

Source Link

Document

Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS.

Usage

From source file:org.dbflute.saflute.web.servlet.filter.RequestLoggingFilter.java

protected void buildRequestInfo(StringBuilder sb, HttpServletRequest request, HttpServletResponse response,
        boolean showResponse) {
    sb.append("Request class=" + request.getClass().getName());
    sb.append(", RequestedSessionId=").append(request.getRequestedSessionId());

    sb.append(LF).append(IND);// w  ww.j a v  a 2 s .  co m
    sb.append(", REQUEST_URI=").append(request.getRequestURI());
    sb.append(", SERVLET_PATH=").append(request.getServletPath());
    sb.append(", CharacterEncoding=" + request.getCharacterEncoding());
    sb.append(", ContentLength=").append(request.getContentLength());

    sb.append(LF).append(IND);
    sb.append(", ContentType=").append(request.getContentType());
    sb.append(", Locale=").append(request.getLocale());
    sb.append(", Locales=");
    final Enumeration<?> locales = request.getLocales();
    boolean first = true;
    while (locales.hasMoreElements()) {
        final Locale locale = (Locale) locales.nextElement();
        if (first) {
            first = false;
        } else {
            sb.append(", ");
        }
        sb.append(locale.toString());
    }
    sb.append(", Scheme=").append(request.getScheme());
    sb.append(", isSecure=").append(request.isSecure());

    sb.append(LF).append(IND);
    sb.append(", SERVER_PROTOCOL=").append(request.getProtocol());
    sb.append(", REMOTE_ADDR=").append(request.getRemoteAddr());
    sb.append(", REMOTE_HOST=").append(request.getRemoteHost());
    sb.append(", SERVER_NAME=").append(request.getServerName());
    sb.append(", SERVER_PORT=").append(request.getServerPort());

    sb.append(LF).append(IND);
    sb.append(", ContextPath=").append(request.getContextPath());
    sb.append(", REQUEST_METHOD=").append(request.getMethod());
    sb.append(", PathInfo=").append(request.getPathInfo());
    sb.append(", RemoteUser=").append(request.getRemoteUser());

    sb.append(LF).append(IND);
    sb.append(", REQUEST_URL=").append(request.getRequestURL());
    sb.append(LF).append(IND);
    sb.append(", QUERY_STRING=").append(request.getQueryString());
    if (showResponse) {
        sb.append(LF).append(IND);
        buildResponseInfo(sb, request, response);
    }

    sb.append(LF);
    buildRequestHeaders(sb, request);
    buildRequestParameters(sb, request);
    buildCookies(sb, request);
    buildRequestAttributes(sb, request);
    buildSessionAttributes(sb, request);
}

From source file:org.apache.ranger.common.ServiceUtil.java

public boolean isValidateHttpsAuthentication(String serviceName, HttpServletRequest request) {
    boolean isValidAuthentication = false;
    boolean httpEnabled = PropertiesUtil.getBooleanProperty("ranger.service.http.enabled", true);
    X509Certificate[] certchain = (X509Certificate[]) request
            .getAttribute("javax.servlet.request.X509Certificate");
    String ipAddress = request.getHeader("X-FORWARDED-FOR");
    if (ipAddress == null) {
        ipAddress = request.getRemoteAddr();
    }//from w  ww.ja  v a  2s. co  m
    boolean isSecure = request.isSecure();

    if (serviceName == null || serviceName.isEmpty()) {
        LOG.error("ServiceName not provided");
        throw restErrorUtil.createRESTException("Unauthorized access.",
                MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
    }

    RangerService service = null;
    try {
        service = svcStore.getServiceByName(serviceName);
    } catch (Exception e) {
        LOG.error("Requested Service not found. serviceName=" + serviceName);
        throw restErrorUtil.createRESTException("Service:" + serviceName + " not found",
                MessageEnums.DATA_NOT_FOUND);
    }
    if (service == null) {
        LOG.error("Requested Service not found. serviceName=" + serviceName);
        throw restErrorUtil.createRESTException("Service:" + serviceName + " not found",
                MessageEnums.DATA_NOT_FOUND);
    }
    if (!service.getIsEnabled()) {
        LOG.error("Requested Service is disabled. serviceName=" + serviceName);
        throw restErrorUtil.createRESTException("Unauthorized access.",
                MessageEnums.OPER_NOT_ALLOWED_FOR_STATE);
    }
    if (!httpEnabled) {
        if (!isSecure) {
            LOG.error("Unauthorized access. Only https is allowed. serviceName=" + serviceName);
            throw restErrorUtil.createRESTException("Unauthorized access -" + " only https allowed",
                    MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
        }
        if (certchain == null || certchain.length == 0) {
            LOG.error("Unauthorized access. Unable to get client certificate. serviceName=" + serviceName);
            throw restErrorUtil.createRESTException(
                    "Unauthorized access -" + " unable to get client certificate",
                    MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
        }

        // Check if common name is found in service config
        Map<String, String> configMap = service.getConfigs();
        String cnFromConfig = configMap.get("commonNameForCertificate");
        if (cnFromConfig == null || "".equals(cnFromConfig.trim())) {
            LOG.error(
                    "Unauthorized access. No common name for certificate set. Please check your service config");
            throw restErrorUtil.createRESTException(
                    "Unauthorized access. No common name for certificate set. Please check your service config",
                    MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
        }

        String cnFromConfigForTest = cnFromConfig;
        boolean isRegEx = cnFromConfig.toLowerCase().startsWith(REGEX_PREFIX_STR);
        if (isRegEx) {
            cnFromConfigForTest = cnFromConfig.substring(REGEX_PREFIX_STR_LENGTH);
        }

        // Perform SAN validation
        try {
            Collection<List<?>> subjectAltNames = certchain[0].getSubjectAlternativeNames();
            if (subjectAltNames != null) {
                for (List<?> sanItem : subjectAltNames) {
                    if (sanItem.size() == 2) {
                        Integer sanType = (Integer) sanItem.get(0);
                        String sanValue = (String) sanItem.get(1);
                        if ((sanType == 2 || sanType == 7)
                                && (matchNames(sanValue, cnFromConfigForTest, isRegEx))) {
                            if (LOG.isDebugEnabled())
                                LOG.debug("Client Cert verification successful, matched SAN:" + sanValue);
                            isValidAuthentication = true;
                            break;
                        }
                    }
                }
            }
        } catch (Throwable e) {
            LOG.error("Unauthorized access. Error getting SAN from certificate", e);
            throw restErrorUtil.createRESTException(
                    "Unauthorized access - Error getting SAN from client certificate",
                    MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
        }

        // Perform common name validation only if SAN validation did not succeed
        if (!isValidAuthentication) {
            String commonName = null;
            if (certchain != null) {
                X509Certificate clientCert = certchain[0];
                String dn = clientCert.getSubjectX500Principal().getName();
                try {
                    LdapName ln = new LdapName(dn);
                    for (Rdn rdn : ln.getRdns()) {
                        if (rdn.getType().equalsIgnoreCase("CN")) {
                            commonName = rdn.getValue() + "";
                            break;
                        }
                    }
                    if (commonName == null) {
                        LOG.error("Unauthorized access. CName is null. serviceName=" + serviceName);
                        throw restErrorUtil.createRESTException(
                                "Unauthorized access - Unable to find Common Name from [" + dn + "]",
                                MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
                    }
                } catch (InvalidNameException e) {
                    LOG.error("Invalid Common Name. CName=" + commonName + ", serviceName=" + serviceName, e);
                    throw restErrorUtil.createRESTException("Unauthorized access - Invalid Common Name",
                            MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
                }
            }
            if (commonName != null) {
                if (matchNames(commonName, cnFromConfigForTest, isRegEx)) {
                    if (LOG.isDebugEnabled())
                        LOG.debug("Client Cert verification successful, matched CN " + commonName + " with "
                                + cnFromConfigForTest + ", wildcard match = " + isRegEx);
                    isValidAuthentication = true;
                }

                if (!isValidAuthentication) {
                    LOG.error("Unauthorized access. expected [" + cnFromConfigForTest + "], found ["
                            + commonName + "], serviceName=" + serviceName);
                    throw restErrorUtil.createRESTException("Unauthorized access. expected ["
                            + cnFromConfigForTest + "], found [" + commonName + "]",
                            MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
                }
            }
        }
    } else {
        isValidAuthentication = true;
    }
    return isValidAuthentication;
}

From source file:com.globalsight.everest.webapp.pagehandler.tasks.TaskDetailHandler.java

private void dtpDownload(HttpServletRequest p_request, HttpServletResponse p_response)
        throws IOException, EnvoyServletException {

    byte[] buf = new byte[4096];

    // Craete the zip file
    File downloadFile = new File(this.getFullTargetFilePath(p_request));
    FileInputStream inDownloadFile = new FileInputStream(downloadFile);

    File zipFile = new File(this.getTargetFilePath(p_request) + "dtpDownloadFile.zip");
    ZipOutputStream outZipFile = new ZipOutputStream(new FileOutputStream(zipFile));

    outZipFile.putNextEntry(new ZipEntry(this.getTargetFileName(p_request)));
    for (int len = 0; (len = inDownloadFile.read(buf)) > 0;) {
        outZipFile.write(buf, 0, len);/*from  ww w .ja va  2  s.  co  m*/
    }
    outZipFile.closeEntry();
    inDownloadFile.close();
    outZipFile.close();

    p_response.setContentType("application/zip");
    p_response.setHeader("Content-Disposition", "attachment; filename=" + zipFile.getName() + ";");
    if (p_request.isSecure()) {
        setHeaderForHTTPSDownload(p_response);
    }
    p_response.setContentLength((int) zipFile.length());

    // Send the zip file to the client
    byte[] inBuff = new byte[4096];
    FileInputStream fis = new FileInputStream(zipFile);
    int bytesRead = 0;
    while ((bytesRead = fis.read(inBuff)) != -1) {
        p_response.getOutputStream().write(inBuff, 0, bytesRead);
    }

    if (bytesRead > 0) {
        p_response.getOutputStream().write(inBuff, 0, bytesRead);
    }
    fis.close();

    zipFile.delete();
}

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

/**
 * @param request/*from   ww w  .j av a2  s . c o m*/
 * @param response
 * @param scheme
 */
public void logon(HttpServletRequest request, HttpServletResponse response, AuthenticationScheme scheme)
        throws Exception {
    User user = scheme.getUser();

    // Check logon is currently allowed
    String logonNotAllowedReason = LogonControllerFactory.getInstance().checkLogonAllowed(user);

    if (logonNotAllowedReason != null) {
        log.warn("Logon not allowed because '" + logonNotAllowedReason + "'");
        throw new Exception(logonNotAllowedReason);
    }

    if (log.isInfoEnabled()) {
        log.info("Session logon ticket is "
                + (String) request.getSession().getAttribute(Constants.LOGON_TICKET));
        log.info("Logging on " + scheme.getUsername() + " for scheme " + scheme.getSchemeName());
    }
    // Sucessful login, remove any locks
    unlockUser(scheme.getUsername());

    String host = (request.isSecure()
            || SystemProperties.get("jetty.force.HTTPSRedirect", "false").equals("true") ? "https" : "http")
            + "://" + request.getHeader(HttpConstants.HDR_HOST);

    request.getSession().setAttribute(Constants.HOST, host);
    SessionInfo info = null;
    boolean fireEvent = false;
    if (request.getSession().getAttribute(Constants.SESSION_LOCKED) == null) {
        InetAddress address = InetAddress.getByName(request.getRemoteAddr());
        int sessionType = SessionInfo.getSessionTypeForUserAgent(request.getHeader("User-Agent"));
        checkForMultipleSessions(user, address, sessionType);
        info = addLogonTicket(request, response, user, address, sessionType);
        try {
            info.getHttpSession().setAttribute(Constants.VPN_AUTOSTART,
                    CoreUtil.getUsersProfileProperty(info.getHttpSession(), "client.autoStart", user));
        } catch (Exception e) {
            throw new SecurityErrorException(SecurityErrorException.INTERNAL_ERROR, e.getMessage());
        }
        fireEvent = true;
    }
    // Initialise the session
    initialiseSession(request.getSession(), user);
    // Build the menus
    CoreUtil.resetMainNavigation(request.getSession());

    char[] pw = getPasswordFromCredentials(scheme);
    String mode = Property.getProperty(new SystemConfigKey("security.privateKeyMode"));
    if (!mode.equals("disabled")) {

        try {
            PublicKeyStore.getInstance().verifyPrivateKey(user.getPrincipalName(), pw);
        } catch (PromptForPasswordException e) {
            CoreUtil.addPageInterceptListener(request.getSession(),
                    new PromptForPrivateKeyPassphraseInterceptListener());
        } catch (UpdatePrivateKeyPassphraseException e) {
            if (mode.equals("prompt")) {
                CoreUtil.addPageInterceptListener(request.getSession(),
                        new PromptForPrivateKeyPassphraseInterceptListener());
            } else {
                CoreUtil.addPageInterceptListener(request.getSession(),
                        new UpdatePrivateKeyPassphraseInterceptListener());
            }
        }
    }

    /*
     * Make sure the logon event gets fired after the private key has
     * been initialised. This is repeated in the actions the page
     * intercept listeners redirect to
     */
    if (fireEvent) {
        CoreServlet.getServlet()
                .fireCoreEvent(new CoreEvent(this, CoreEventConstants.LOGON, scheme, info)
                        .addAttribute(CoreAttributeConstants.EVENT_ATTR_IP_ADDRESS, request.getRemoteAddr())
                        .addAttribute(CoreAttributeConstants.EVENT_ATTR_HOST, request.getRemoteHost())
                        .addAttribute(CoreAttributeConstants.EVENT_ATTR_SCHEME, scheme.getSchemeName()));
    }
}

From source file:org.alfresco.repo.web.scripts.solr.SOLRAuthenticationFilter.java

public void doFilter(ServletContext context, ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    /*      if(secureComms == SecureCommsType.ALFRESCO)
          {/*ww  w .  j av  a2s.c o m*/
             // Need to get as a byte array because we need to read the request twice, once for authentication
             // and again by the web service.
             SOLRHttpServletRequestWrapper requestWrapper = new SOLRHttpServletRequestWrapper(httpRequest, encryptionUtils);
               
             if(logger.isDebugEnabled())
             {
    logger.debug("Authenticating " + httpRequest.getRequestURI());
             }
               
             if(encryptionUtils.authenticate(httpRequest, requestWrapper.getDecryptedBody()))
             {
    try
    {
       OutputStream out = response.getOutputStream();
               
       GenericResponseWrapper responseWrapper = new GenericResponseWrapper(httpResponse);
               
       // TODO - do I need to chain to other authenticating filters - probably not?
       // Could also remove sending of credentials with http request
       chain.doFilter(requestWrapper, responseWrapper);
               
       Pair<byte[], AlgorithmParameters> pair = encryptor.encrypt(KeyProvider.ALIAS_SOLR, null, responseWrapper.getData());
               
       encryptionUtils.setResponseAuthentication(httpRequest, httpResponse, responseWrapper.getData(), pair.getSecond());
            
       httpResponse.setHeader("Content-Length", Long.toString(pair.getFirst().length));
       out.write(pair.getFirst());
       out.close();
    }
    catch(Exception e)
    {
       throw new AlfrescoRuntimeException("", e);
    }
             }
             else
             {
    httpResponse.setStatus(401);
             }
          }
          else */if (secureComms == SecureCommsType.HTTPS) {
        if (httpRequest.isSecure()) {
            // https authentication
            chain.doFilter(request, response);
        } else {
            throw new AlfrescoRuntimeException("Expected a https request");
        }
    } else {
        chain.doFilter(request, response);
    }
}

From source file:org.sakaiproject.portal.charon.handlers.PDAHandler.java

@Override
public int doGet(String[] parts, HttpServletRequest req, HttpServletResponse res, Session session)
        throws PortalHandlerException {
    if ((parts.length == 3) && parts[1].equals(PDAHandler.URL_FRAGMENT)
            && parts[2].equals(XLoginHandler.URL_FRAGMENT)) {
        try {/*from   w  ww .j  av a2s .c o m*/
            portal.doLogin(req, res, session, "/pda", true);
            return END;
        } catch (Exception ex) {
            throw new PortalHandlerException(ex);
        }
    } else if ((parts.length >= 2) && (parts[1].equals("pda"))) {
        // Indicate that we are the controlling portal
        session.setAttribute(PortalService.SAKAI_CONTROLLING_PORTAL, PDAHandler.URL_FRAGMENT);
        try {

            //check if we want to force back to the classic view
            String forceClassic = req.getParameter(Portal.FORCE_CLASSIC_REQ_PARAM);
            if (StringUtils.equals(forceClassic, "yes")) {

                log.debug("PDAHandler - force.classic");

                //set the portal mode cookie to force classic
                Cookie c = new Cookie(Portal.PORTAL_MODE_COOKIE_NAME, Portal.FORCE_CLASSIC_COOKIE_VALUE);
                c.setPath("/");
                c.setMaxAge(-1);

                //need to set domain and https as per RequestFilter
                if (System.getProperty(SAKAI_COOKIE_DOMAIN) != null) {
                    c.setDomain(System.getProperty(SAKAI_COOKIE_DOMAIN));
                }
                if (req.isSecure() == true) {
                    c.setSecure(true);
                }
                res.addCookie(c);

                //redirect to classic view
                res.sendRedirect(req.getContextPath());
            }

            // /portal/pda/site-id
            String siteId = null;
            if (parts.length >= 3) {
                siteId = parts[2];
            }

            // SAK-12873
            // If we have no site at all and are not logged in - and there is 
            // only one gateway site, go directly to the gateway site
            if (siteId == null && session.getUserId() == null) {
                String siteList = ServerConfigurationService.getString("gatewaySiteList");
                String gatewaySiteId = ServerConfigurationService.getGatewaySiteId();
                if (siteList.trim().length() == 0 && gatewaySiteId.trim().length() != 0) {
                    siteId = gatewaySiteId;
                }
            }

            // Tool resetting URL - clear state and forward to the real tool
            // URL
            // /portal/pda/site-id/tool-reset/toolId
            // 0 1 2 3 4
            String toolId = null;
            if ((siteId != null) && (parts.length == 5) && (parts[3].equals("tool-reset"))) {
                toolId = parts[4];
                String toolUrl = req.getContextPath() + "/pda/" + siteId + "/tool"
                        + Web.makePath(parts, 4, parts.length);
                String queryString = Validator.generateQueryString(req);
                if (queryString != null) {
                    toolUrl = toolUrl + "?" + queryString;
                }
                portalService.setResetState("true");
                res.sendRedirect(toolUrl);
                return RESET_DONE;
            }

            // Tool after the reset
            // /portal/pda/site-id/tool/toolId
            if ((parts.length > 4) && (parts[3].equals("tool"))) {
                // look for page and pick up the top-left tool to show
                toolId = parts[4];
            }

            String forceLogout = req.getParameter(Portal.PARAM_FORCE_LOGOUT);
            if ("yes".equalsIgnoreCase(forceLogout) || "true".equalsIgnoreCase(forceLogout)) {
                portal.doLogout(req, res, session, "/pda");
                return END;
            }

            if (session.getUserId() == null) {
                String forceLogin = req.getParameter(Portal.PARAM_FORCE_LOGIN);
                if ("yes".equalsIgnoreCase(forceLogin) || "true".equalsIgnoreCase(forceLogin)) {
                    portal.doLogin(req, res, session, URLUtils.getSafePathInfo(req), false);
                    return END;
                }
            }

            SitePage page = null;
            // /portal/site/site-id/page/page-id
            // /portal/pda/site-id/page/page-id
            // 1 2 3 4
            if ((parts.length == 5) && (parts[3].equals("page"))) {
                // look for page and pick up the top-left tool to show
                String pageId = parts[4];
                page = SiteService.findPage(pageId);
                if (page == null) {
                    portal.doError(req, res, session, Portal.ERROR_WORKSITE);
                    return END;
                } else {
                    List<ToolConfiguration> tools = page.getTools(0);
                    if (tools != null && !tools.isEmpty()) {
                        toolId = tools.get(0).getId();
                    }
                    parts[3] = "tool";
                    parts[4] = toolId;
                }
            }

            // Set the site language
            Site site = null;
            if (siteId == null && session.getUserId() != null) {
                site = portal.getSiteHelper().getMyWorkspace(session);
            } else {
                try {
                    Set<SecurityAdvisor> advisors = (Set<SecurityAdvisor>) session
                            .getAttribute("sitevisit.security.advisor");
                    if (advisors != null) {
                        for (SecurityAdvisor advisor : advisors) {
                            SecurityService.pushAdvisor(advisor);
                        }
                    }

                    // This should understand aliases as well as IDs
                    site = portal.getSiteHelper().getSiteVisit(siteId);
                } catch (IdUnusedException e) {
                } catch (PermissionException e) {
                }
            }
            if (site != null) {
                super.setSiteLanguage(site);
            }

            // See if we can buffer the content, if not, pass the request through
            boolean allowBuffer = false;
            ToolConfiguration siteTool = SiteService.findTool(toolId);
            String commonToolId = null;

            String toolContextPath = null;
            String toolPathInfo = null;

            if (parts.length >= 5) {
                toolContextPath = req.getContextPath() + req.getServletPath() + Web.makePath(parts, 1, 5);
                toolPathInfo = Web.makePath(parts, 5, parts.length);
            }
            Object BC = null;
            if (siteTool != null && parts.length >= 5) {
                commonToolId = siteTool.getToolId();

                // Does the tool allow us to buffer?
                allowBuffer = allowBufferContent(req, site, siteTool);

                if (allowBuffer) {

                    // Should we bypass buffering based on the request?
                    boolean matched = checkBufferBypass(req, siteTool);

                    if (matched) {
                        ActiveTool tool = ActiveToolManager.getActiveTool(commonToolId);
                        portal.forwardTool(tool, req, res, siteTool, siteTool.getSkin(), toolContextPath,
                                toolPathInfo);
                        return END;
                    }
                    // Inform includeTool called by portal.includePortal below
                    ThreadLocalManager.set("sakai:inline-tool", "true");
                }
            }

            // Prepare for the full output...
            PortalRenderContext rcontext = portal.includePortal(req, res, session, siteId, toolId,
                    req.getContextPath() + req.getServletPath(), "pda", /* doPages */false,
                    /* resetTools */true, /* includeSummary */false, /* expandSite */false);

            if (allowBuffer) {
                BC = bufferContent(req, res, session, toolId, toolContextPath, toolPathInfo, siteTool);

                // If the buffered response was not parseable
                if (BC instanceof ByteArrayServletResponse) {
                    ByteArrayServletResponse bufferResponse = (ByteArrayServletResponse) BC;
                    StringBuffer queryUrl = req.getRequestURL();
                    String queryString = req.getQueryString();
                    if (queryString != null)
                        queryUrl.append('?').append(queryString);
                    // SAK-25494 - This probably should be a log.debug later
                    String msg = "Post buffer bypass CTI=" + commonToolId + " URL=" + queryUrl;
                    String redir = bufferResponse.getRedirect();
                    if (redir != null)
                        msg = msg + " redirect to=" + redir;
                    log.warn(msg);
                    bufferResponse.forwardResponse();
                    return END;
                }
            }

            //  TODO: Should this be a property?  Probably because it does cause an 
            // uncached SQL query
            portal.includeSubSites(rcontext, req, session, siteId, req.getContextPath() + req.getServletPath(),
                    "pda", /* resetTools */ true);

            // Add the buttons
            if (siteTool != null) {
                boolean showResetButton = !"false"
                        .equals(siteTool.getConfig().getProperty(TOOLCONFIG_SHOW_RESET_BUTTON));
                rcontext.put("showResetButton", Boolean.valueOf(showResetButton));
                if (toolContextPath != null && showResetButton) {
                    rcontext.put("resetActionUrl", toolContextPath.replace("/tool/", "/tool-reset/"));
                }
            }

            // Include the buffered content if we have it
            if (BC instanceof Map) {
                rcontext.put("bufferedResponse", Boolean.TRUE);
                Map<String, String> bufferMap = (Map<String, String>) BC;
                rcontext.put("responseHead", (String) bufferMap.get("responseHead"));
                rcontext.put("responseBody", (String) bufferMap.get("responseBody"));
            }

            // Add any device specific information to the context
            portal.setupMobileDevice(req, rcontext);

            addLocale(rcontext, site);

            portal.sendResponse(rcontext, res, "pda", null);

            try {
                boolean presenceEvents = ServerConfigurationService.getBoolean("presence.events.log", true);
                if (presenceEvents)
                    org.sakaiproject.presence.cover.PresenceService.setPresence(siteId + "-presence");
            } catch (Exception e) {
                return END;
            }
            return END;
        } catch (Exception ex) {
            throw new PortalHandlerException(ex);
        }
    } else {
        return NEXT;
    }
}

From source file:org.sakaiproject.util.RequestFilter.java

/**
 * This is called when a request is made to a node that is in the process of closing down
 * and so we don't want to allow new session to be created.
 * @param req The servlet request./*from   w  w  w .  j a  va2  s . c om*/
 * @param res The servlet response.
 */
protected void closingRedirect(HttpServletRequest req, HttpServletResponse res) throws IOException {
    // We should avoid redirecting on non get methods as the body will be lost.
    if (!"GET".equals(req.getMethod())) {
        M_log.warn("Non GET request for " + req.getPathInfo());
    }

    // We could check that we aren't in a redirect loop here, but if the load balancer doesn't know that
    // a node is no longer responding to new sessions it may still be sending it new clients, and so after
    // a couple of redirects it should hop off this node.
    String value = getRedirectNode();
    // set the cookie
    Cookie c = new Cookie(cookieName, value);
    c.setPath("/");
    // Delete the cookie
    c.setMaxAge(0);
    if (cookieDomain != null) {
        c.setDomain(cookieDomain);
    }
    if (req.isSecure() == true) {
        c.setSecure(true);
    }
    addCookie(res, c);

    // We want the non-decoded ones so we don't have to re-encode.
    StringBuilder url = new StringBuilder(req.getRequestURI());
    if (req.getQueryString() != null) {
        url.append("?").append(req.getQueryString());
    }
    res.sendRedirect(url.toString());
}

From source file:com.tremolosecurity.idp.providers.Saml2Idp.java

private void postResponse(final SamlTransaction transaction, HttpServletRequest request,
        HttpServletResponse response, AuthInfo authInfo, UrlHolder holder)
        throws MalformedURLException, ServletException, UnsupportedEncodingException, IOException {

    User mapped = null;/*from   w  w  w.  j  a  v  a  2s . c o  m*/
    try {

        if (authInfo.getAttribs().get(transaction.nameIDAttr) == null) {
            StringBuffer b = new StringBuffer();
            b.append("No attribute mapping for '").append(transaction.nameIDAttr).append("'");
            throw new ServletException(b.toString());
        }

        User orig = new User(authInfo.getAttribs().get(transaction.nameIDAttr).getValues().get(0));
        orig.getAttribs().putAll(authInfo.getAttribs());
        mapped = this.mapper.mapUser(orig);
    } catch (Exception e) {
        throw new ServletException("Could not map user", e);
    }

    String subject = authInfo.getAttribs().get(transaction.nameIDAttr).getValues().get(0);

    Saml2Trust trust = trusts.get(transaction.issuer);

    if (transaction.authnCtxName == null) {
        transaction.authnCtxName = trust.params.get("defaultAuthCtx").getValues().get(0);
    }

    PrivateKey pk = holder.getConfig().getPrivateKey(this.idpSigKeyName);
    java.security.cert.X509Certificate cert = holder.getConfig().getCertificate(this.idpSigKeyName);
    java.security.cert.X509Certificate spEncCert = holder.getConfig().getCertificate(trust.spEncCert);

    StringBuffer issuer = new StringBuffer();
    URL url = new URL(request.getRequestURL().toString());

    if (request.isSecure()) {
        issuer.append("https://");
    } else {
        issuer.append("http://");
    }

    issuer.append(url.getHost());

    if (url.getPort() != -1) {
        issuer.append(':').append(url.getPort());
    }

    ConfigManager cfg = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);
    //issuer.append(holder.getUrl().getUri());
    issuer.append(cfg.getAuthIdPPath()).append(this.idpName);

    Saml2Assertion resp = new Saml2Assertion(subject, pk, cert, spEncCert, issuer.toString(),
            transaction.postToURL, transaction.issuer, trust.signAssertion, trust.signResponse,
            trust.encAssertion, transaction.nameIDFormat, transaction.authnCtxName);

    for (String attrName : mapped.getAttribs().keySet()) {
        resp.getAttribs().add(mapped.getAttribs().get(attrName));
    }

    //resp.getAttribs().add(new Attribute("groups","admin"));

    String respXML = "";

    try {
        respXML = resp.generateSaml2Response();
    } catch (Exception e) {
        throw new ServletException("Could not generate SAMLResponse", e);
    }

    if (logger.isDebugEnabled()) {
        logger.debug(respXML);
    }

    String base64 = Base64.encodeBase64String(respXML.getBytes("UTF-8"));

    request.setAttribute("postdata", base64);
    request.setAttribute("postaction", transaction.postToURL);

    if (transaction.relayState != null) {
        request.setAttribute("relaystate", transaction.relayState);
    } else {
        request.setAttribute("relaystate", "");
    }

    ST st = new ST(this.saml2PostTemplate, '$', '$');
    st.add("relaystate", (String) request.getAttribute("relaystate"));
    st.add("postdata", base64);
    st.add("postaction", transaction.postToURL);
    response.setContentType("text/html");
    response.getWriter().write(st.render());

}

From source file:ru.org.linux.user.UserEventController.java

/**
 *  ? ?  ?//from   w ww. java 2  s. c  o  m
 *
 * @param request    ?
 * @param response   
 * @param offset     ?
 * @param forceReset ? ?? 
 * @return 
 * @throws Exception  ? ? :-(
 */
@RequestMapping("/notifications")
public ModelAndView showNotifications(HttpServletRequest request, HttpServletResponse response,
        @ModelAttribute("notifications") Action action,
        @RequestParam(value = "offset", defaultValue = "0") int offset,
        @RequestParam(value = "forceReset", defaultValue = "false") boolean forceReset) throws Exception {
    Template tmpl = Template.getTemplate(request);
    if (!tmpl.isSessionAuthorized()) {
        throw new AccessViolationException("not authorized");
    }

    String filterAction = action.getFilter();
    UserEventFilterEnum eventFilter;
    if (filterValues.contains(filterAction)) {
        eventFilter = UserEventFilterEnum.valueOf(filterAction.toUpperCase());
    } else {
        eventFilter = UserEventFilterEnum.ALL;
    }

    User currentUser = tmpl.getCurrentUser();
    String nick = currentUser.getNick();

    Map<String, Object> params = new HashMap<>();
    params.put("nick", nick);
    params.put("forceReset", forceReset);
    if (eventFilter != UserEventFilterEnum.ALL) {
        params.put("addition_query", "&filter=" + eventFilter.getValue());
    } else {
        params.put("addition_query", "");
    }

    if (offset < 0) {
        offset = 0;
    }

    boolean firstPage = offset == 0;
    int topics = tmpl.getProf().getTopics();

    if (topics > 200) {
        topics = 200;
    }

    params.put("firstPage", firstPage);
    params.put("topics", topics);
    params.put("offset", offset);

    params.put("disable_event_header", true);

    /* define timestamps for caching */
    long time = System.currentTimeMillis();
    int delay = firstPage ? 90 : 60 * 60;
    response.setDateHeader("Expires", time + 1000 * delay);
    params.put("unreadCount", currentUser.getUnreadEvents());
    params.put("isMyNotifications", true);

    response.addHeader("Cache-Control", "no-cache");
    List<UserEvent> list = userEventService.getRepliesForUser(currentUser, true, topics, offset, eventFilter);
    List<PreparedUserEvent> prepared = userEventService.prepare(list, false, request.isSecure());

    if ("POST".equalsIgnoreCase(request.getMethod())) {
        userEventService.resetUnreadReplies(currentUser);
    } else {
        params.put("enableReset", true);
    }

    params.put("topicsList", prepared);
    params.put("hasMore", list.size() == topics);

    return new ModelAndView("show-replies", params);
}

From source file:org.josso.wls10.agent.WLSSessionEnforcementServletFilter.java

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

    HttpServletRequest hreq = (HttpServletRequest) request;

    HttpServletResponse hres = (HttpServletResponse) response;

    HttpSession session = hreq.getSession(true);

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

    String contextPath = hreq.getContextPath();
    String vhost = hreq.getServerName();
    SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(vhost, contextPath);

    // ------------------------------------------------------------------
    // Check for the single sign on cookie
    // ------------------------------------------------------------------
    if (log.isDebugEnabled())
        log.debug("Checking for SSO cookie");
    Cookie cookie = null;/*w  ww .j a  v a2s  .c o m*/
    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;
        }
    }
    if (cookie != null && !cookie.getValue().equals("-")) {
        String jossoSessionId = cookie.getValue();

        if (log.isDebugEnabled())
            log.debug("asserting SSO session for : " + jossoSessionId);

        SSOAgentRequest sessionAssertionRequest;

        sessionAssertionRequest = doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_ASSERT_SESSION,
                jossoSessionId, null, null, hreq, hres);

        // TODO: Agents should be able to pass back responses corresponding to the submitted request.
        try {
            _agent.processRequest(sessionAssertionRequest);
            if (log.isDebugEnabled())
                log.debug("asserted successfully SSO session for : " + jossoSessionId);
        } catch (FatalSSOSessionException e) {
            if (log.isDebugEnabled())
                log.debug("error asserting SSO session : " + jossoSessionId);

            String requestedResourceUrl;

            // Clear previous COOKIE ...
            Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure());
            hres.addCookie(ssoCookie);
            session.invalidate();
            requestedResourceUrl = _agent.buildBackToURL(hreq, "");
            hres.sendRedirect(hres.encodeRedirectURL(requestedResourceUrl));
            return;
        }

    }

    filterChain.doFilter(hreq, hres);

}