Example usage for javax.servlet ServletRequest setAttribute

List of usage examples for javax.servlet ServletRequest setAttribute

Introduction

In this page you can find the example usage for javax.servlet ServletRequest setAttribute.

Prototype

public void setAttribute(String name, Object o);

Source Link

Document

Stores an attribute in this request.

Usage

From source file:com.google.zxing.web.DecodeServlet.java

private static void processImage(BufferedImage image, ServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    LuminanceSource source = new BufferedImageLuminanceSource(image);
    BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
    Collection<Result> results = Lists.newArrayListWithCapacity(1);

    try {//from w w  w .j a v  a2  s.c om

        Reader reader = new MultiFormatReader();
        ReaderException savedException = null;
        try {
            // Look for multiple barcodes
            MultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader);
            Result[] theResults = multiReader.decodeMultiple(bitmap, HINTS);
            if (theResults != null) {
                results.addAll(Arrays.asList(theResults));
            }
        } catch (ReaderException re) {
            savedException = re;
        }

        if (results.isEmpty()) {
            try {
                // Look for pure barcode
                Result theResult = reader.decode(bitmap, HINTS_PURE);
                if (theResult != null) {
                    results.add(theResult);
                }
            } catch (ReaderException re) {
                savedException = re;
            }
        }

        if (results.isEmpty()) {
            try {
                // Look for normal barcode in photo
                Result theResult = reader.decode(bitmap, HINTS);
                if (theResult != null) {
                    results.add(theResult);
                }
            } catch (ReaderException re) {
                savedException = re;
            }
        }

        if (results.isEmpty()) {
            try {
                // Try again with other binarizer
                BinaryBitmap hybridBitmap = new BinaryBitmap(new HybridBinarizer(source));
                Result theResult = reader.decode(hybridBitmap, HINTS);
                if (theResult != null) {
                    results.add(theResult);
                }
            } catch (ReaderException re) {
                savedException = re;
            }
        }

        if (results.isEmpty()) {
            handleException(savedException, response);
            return;
        }

    } catch (RuntimeException re) {
        // Call out unexpected errors in the log clearly
        log.log(Level.WARNING, "Unexpected exception from library", re);
        throw new ServletException(re);
    }

    String fullParameter = request.getParameter("full");
    boolean minimalOutput = fullParameter != null && !Boolean.parseBoolean(fullParameter);
    if (minimalOutput) {
        response.setContentType(MediaType.PLAIN_TEXT_UTF_8.toString());
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        try (Writer out = new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8)) {
            for (Result result : results) {
                out.write(result.getText());
                out.write('\n');
            }
        }
    } else {
        request.setAttribute("results", results);
        request.getRequestDispatcher("decoderesult.jspx").forward(request, response);
    }
}

From source file:org.ms123.common.jetty.LoginFilter.java

public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    long before = System.currentTimeMillis();
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;
    String pathInfo = request.getPathInfo();
    infob("\n\n<==========================================> ");
    info("doFilter -> " + pathInfo);
    infob("date: " + new Date());
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = (String) headerNames.nextElement();
        debug("\t" + headerName + " = " + request.getHeader(headerName));
    }//from   w ww . j a va  2 s  .c om
    if (pathInfo == null) {
        info("==== NOK:pathInfo is null");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        infob("<##############################################\n\n");
        return;
    }
    String[] arr = pathInfo.split("/");
    String namespace = null;
    if (arr.length < 2) {
        namespace = "RPC";
    } else {
        if (arr[1].equals("repo")) {
            namespace = arr[2];
        } else {
            namespace = arr[1];
        }
    }
    for (int i = 0; i < arr.length; i++) {
        debug("\tpathinfo[" + i + "]:" + arr[i]);
    }
    debug("\tNamespace:" + namespace);
    if (pathInfo.indexOf("/checkcredentials") != -1) {
        String cred = request.getParameter("credentials");
        if (checkCredentials(namespace, cred, true)) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }
        infob("<##############################################\n\n");
        return;
    }
    String auth = request.getHeader("Authorization");
    debug("auth:" + auth);
    String credentials = null;
    if (auth != null || request.getParameter("credentials") != null) {
        String a = null;
        if (auth != null && auth.toLowerCase().startsWith("basic ")) {
            a = auth.trim().split(" ")[1];
        } else {
            a = request.getParameter("credentials");
        }
        credentials = Base64.decode(a);
        int ind = credentials.indexOf(":");
        if (ind != -1) {
            String username = credentials.substring(0, ind);
            req.setAttribute(USERNAME, username);
        }
    }
    String firstSegment = arr[1];
    String method = request.getMethod();
    boolean isStaticResource = false;
    boolean ok = false;
    if (method != null && "get".equals(method.toLowerCase())) {
        if (arr.length > 3 && "sw".equals(arr[1]) && "website".equals(arr[3])) {
            ok = true;
        } else if ("sw".equals(firstSegment) || "repo".equals(firstSegment)) {
            if (isStaticResource(pathInfo)) {
                ok = true;
                isStaticResource = true;
            }
        } else if (pathInfo.equals("/robots.txt")) {
            ok = true;
        } else if (pathInfo.startsWith("/openfire")) {
            ok = true;
        } else if (pathInfo.startsWith("/sw/common") || pathInfo.startsWith("/sw/website")
                || pathInfo.startsWith("/sw/legacy") || pathInfo.startsWith("/sw/resource")) {
            ok = true;
        }
    } else if (request.getHeader("Origin") != null && method != null
            && "options".equals(method.toLowerCase())) {
        ok = true;
    }

    if (request.getParameter("rpc") != null || request.getRequestURI().startsWith("/rpc")) {
        ok = false;
    }
    if (request.getParameter("ws") != null || request.getRequestURI().startsWith("/ws")) {
        ok = false;
    }

    Map<String, Object> accessRule = null;
    if (isStaticResource && isRepoRequest(pathInfo)) {
        List<Map<String, Object>> rules = getAccessRules(namespace);
        accessRule = getMatchingAccessRule(namespace, pathInfo, rules);
        if (accessRule != null) {
            ok = false;
        }
    }

    info(pathInfo + ";" + credentials + "/ok:" + ok + "/accessRule:" + accessRule);
    if (ok || checkCredentials(namespace, credentials, false)) {
        if (accessRule != null) {
            String username = (String) req.getAttribute(USERNAME);
            if (!m_permissionService.isFileAccesPermitted(username,
                    (List) accessRule.get(PermissionService.PERMITTED_USERS),
                    (List) accessRule.get(PermissionService.PERMITTED_ROLES))) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return;
            }
        }
        info(">>>> OK," + Thread.currentThread().getName());
        RequestMapper rm = new RequestMapper(request);
        ThreadContext.loadThreadContext(rm, response);
        info(request.getPathInfo() + "|" + request.getMethod() + "|Uri:" + request.getRequestURI());
        info(request.getRequestURL() + "|Url:" + request.getServletPath() + "|QS:" + request.getQueryString());
        chain.doFilter(rm, response);
        info(">>>> End FILTER:" + ThreadContext.getThreadContext().get(ThreadContext.SESSION_MANAGER) + "/"
                + new Date().getTime());
        Date startTime = ThreadContext.getThreadContext().getStartTime();
        ThreadContext.getThreadContext().finalize(null);
        ThreadContext.getThreadContext().remove();
        displayInfo("Finish", startTime);
    } else {
        info("==== NOK");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
    infob("<##############################################\n\n");
}

From source file:org.wso2.sample.is.sso.agent.SSOAgentSampleFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {

    String httpBinding = servletRequest.getParameter(SSOAgentConstants.SSOAgentConfig.SAML2.HTTP_BINDING);
    if (httpBinding != null && !httpBinding.isEmpty()) {
        if ("HTTP-POST".equals(httpBinding)) {
            httpBinding = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST";
        } else if ("HTTP-Redirect".equals(httpBinding)) {
            httpBinding = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect";
        } else {//from w  w  w  . j a v a 2  s  .  co  m
            LOGGER.log(Level.INFO, "Unknown SAML2 HTTP Binding. Defaulting to HTTP-POST");
            httpBinding = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST";
        }
    } else {
        LOGGER.log(Level.INFO, "SAML2 HTTP Binding not found in request. Defaulting to HTTP-POST");
        httpBinding = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST";
    }
    SSOAgentConfig config = (SSOAgentConfig) filterConfig.getServletContext()
            .getAttribute(SSOAgentConstants.CONFIG_BEAN_NAME);
    config.getSAML2().setHttpBinding(httpBinding);
    config.getOpenId()
            .setClaimedId(servletRequest.getParameter(SSOAgentConstants.SSOAgentConfig.OpenID.CLAIMED_ID));
    config.getOpenId().setMode(servletRequest.getParameter(SSOAgentConstants.OpenID.OPENID_MODE));

    if (StringUtils.isNotEmpty(servletRequest.getParameter(USERNAME))
            && StringUtils.isNotEmpty(servletRequest.getParameter(PASSWORD))) {

        String authorization = servletRequest.getParameter(USERNAME) + ":"
                + servletRequest.getParameter(PASSWORD);
        // Base64 encoded username:password value
        authorization = new String(Base64.encode(authorization.getBytes(CHARACTER_ENCODING)));
        String htmlPayload = "<html>\n" + "<body>\n" + "<p>You are now redirected back to "
                + properties.getProperty("SAML2.IdPURL") + " \n"
                + "If the redirection fails, please click the post button.</p>\n"
                + "<form method='post' action='" + properties.getProperty("SAML2.IdPURL") + "'>\n"
                + "<input type='hidden' name='sectoken' value='" + authorization + "'/>\n" + "<p>\n"
                + "<!--$saml_params-->\n" + "<button type='submit'>POST</button>\n" + "</p>\n" + "</form>\n"
                + "<script type='text/javascript'>\n" + "document.forms[0].submit();\n" + "</script>\n"
                + "</body>\n" + "</html>";
        config.getSAML2().setPostBindingRequestHTMLPayload(htmlPayload);
    } else {
        // Reset previously sent HTML payload
        config.getSAML2().setPostBindingRequestHTMLPayload(null);
    }
    servletRequest.setAttribute(SSOAgentConstants.CONFIG_BEAN_NAME, config);
    super.doFilter(servletRequest, servletResponse, filterChain);
}

From source file:org.eclipse.orion.server.configurator.servlet.AuthorizedUserFilter.java

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

    String remoteUser = httpRequest.getRemoteUser();

    String userName = remoteUser;
    if (userName == null) {
        userName = authenticationService.getAuthenticatedUser(httpRequest, httpResponse, authProperties);
        if (userName == null)
            userName = IAuthenticationService.ANONYMOUS_LOGIN_VALUE;
    }/*from   ww w. j a  v a 2 s. c o  m*/

    try {
        String requestPath = httpRequest.getServletPath()
                + (httpRequest.getPathInfo() == null ? "" : httpRequest.getPathInfo());
        if (!AuthorizationService.checkRights(userName, requestPath, httpRequest.getMethod())) {
            if (IAuthenticationService.ANONYMOUS_LOGIN_VALUE.equals(userName)) {
                userName = authenticationService.authenticateUser(httpRequest, httpResponse, authProperties);
                if (userName == null)
                    return;
            } else {
                setNotAuthorized(httpRequest, httpResponse, requestPath);
                return;
            }
        }

        String xCreateOptions = httpRequest.getHeader("X-Create-Options");
        if (xCreateOptions != null) {
            String sourceLocation = null;
            ;
            try {
                String method = xCreateOptions.contains("move") ? "POST" : "GET";
                JSONObject requestObject = OrionServlet.readJSONRequest(httpRequest);
                sourceLocation = requestObject.getString("Location");
                String normalizedLocation = new URI(sourceLocation).normalize().getPath();
                normalizedLocation = normalizedLocation.startsWith(httpRequest.getContextPath())
                        ? normalizedLocation.substring(httpRequest.getContextPath().length())
                        : null;
                if (normalizedLocation == null
                        || !AuthorizationService.checkRights(userName, normalizedLocation, method)) {
                    setNotAuthorized(httpRequest, httpResponse, sourceLocation);
                    return;
                }
            } catch (URISyntaxException e) {
                setNotAuthorized(httpRequest, httpResponse, sourceLocation);
                return;
            } catch (JSONException e) {
                // ignore, and fall through
            }
        }

        if (remoteUser == null && !IAuthenticationService.ANONYMOUS_LOGIN_VALUE.equals(userName)) {
            request.setAttribute(HttpContext.REMOTE_USER, userName);
            request.setAttribute(HttpContext.AUTHENTICATION_TYPE, authenticationService.getAuthType());
        }
    } catch (CoreException e) {
        httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    chain.doFilter(request, response);
}

From source file:edu.cornell.mannlib.vitro.webapp.filters.WebappDaoFactorySDBPrep.java

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

    if (request.getAttribute("WebappDaoFactorySDBPrep.setup") != null) {
        // don't run multiple times
        filterChain.doFilter(request, response);
        return;//from  w w  w . j a v a2s. co m
    }

    for (Pattern skipPattern : skipPatterns) {
        Matcher match = skipPattern.matcher(((HttpServletRequest) request).getRequestURI());
        if (match.matches()) {
            log.debug("request matched a skipPattern, skipping VitroRequestPrep");
            filterChain.doFilter(request, response);
            return;
        }
    }

    OntModelSelector oms = ModelContext.getUnionOntModelSelector(_ctx);
    OntModelSelector baseOms = ModelContext.getBaseOntModelSelector(_ctx);
    String defaultNamespace = (String) _ctx.getAttribute("defaultNamespace");
    WebappDaoFactory wadf = null;
    VitroRequest vreq = new VitroRequest((HttpServletRequest) request);

    List<String> langs = new ArrayList<String>();

    log.debug("Accept-Language: " + vreq.getHeader("Accept-Language"));
    Enumeration<Locale> locs = vreq.getLocales();
    while (locs.hasMoreElements()) {
        Locale locale = locs.nextElement();
        langs.add(locale.toString().replace("_", "-"));
    }
    if (langs.isEmpty()) {
        langs.add("en");
    }
    WebappDaoFactoryConfig config = new WebappDaoFactoryConfig();
    config.setDefaultNamespace(defaultNamespace);
    config.setPreferredLanguages(langs);

    RDFServiceFactory factory = RDFServiceUtils.getRDFServiceFactory(_ctx);

    //RDFService rdfService = factory.getRDFService();
    RDFService unfilteredRDFService = factory.getShortTermRDFService();
    RDFService rdfService = null;

    if (!"false"
            .equals(ConfigurationProperties.getBean(vreq).getProperty("RDFService.languageFilter", "true"))) {
        rdfService = new LanguageFilteringRDFService(unfilteredRDFService, langs);
    } else {
        rdfService = unfilteredRDFService;
    }

    Dataset dataset = new RDFServiceDataset(rdfService);
    wadf = new WebappDaoFactorySDB(rdfService, oms, config);
    WebappDaoFactory assertions = new WebappDaoFactorySDB(rdfService, baseOms, config,
            SDBDatasetMode.ASSERTIONS_ONLY);
    vreq.setRDFService(rdfService);
    vreq.setUnfilteredRDFService(unfilteredRDFService);
    vreq.setWebappDaoFactory(wadf);
    vreq.setAssertionsWebappDaoFactory(assertions);
    vreq.setFullWebappDaoFactory(wadf);
    vreq.setUnfilteredWebappDaoFactory(
            new WebappDaoFactorySDB(rdfService, ModelContext.getUnionOntModelSelector(_ctx)));
    vreq.setDataset(dataset);
    vreq.setOntModelSelector(baseOms);

    vreq.setJenaOntModel(ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, dataset.getDefaultModel()));

    request.setAttribute("WebappDaoFactorySDBPrep.setup", 1);

    try {
        filterChain.doFilter(request, response);
        return;
    } finally {
        if (wadf != null) {
            wadf.close();
        }
    }

}

From source file:org.wso2.carbon.identity.captcha.filter.CaptchaFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {

    try {/*  w w  w  .j  ava 2  s.c o m*/

        List<CaptchaConnector> captchaConnectors = CaptchaDataHolder.getInstance().getCaptchaConnectors();

        CaptchaConnector selectedCaptchaConnector = null;
        for (CaptchaConnector captchaConnector : captchaConnectors) {
            if (captchaConnector.canHandle(servletRequest, servletResponse) && (selectedCaptchaConnector == null
                    || captchaConnector.getPriority() > selectedCaptchaConnector.getPriority())) {
                selectedCaptchaConnector = captchaConnector;
            }
        }

        if (selectedCaptchaConnector == null) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // Check whether captcha is required or will reach to the max failed attempts with the current attempt.
        CaptchaPreValidationResponse captchaPreValidationResponse = selectedCaptchaConnector
                .preValidate(servletRequest, servletResponse);

        if (captchaPreValidationResponse == null) {
            // Captcha connector failed to response. Default is success.
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

        if (captchaPreValidationResponse.isCaptchaValidationRequired()) {
            try {
                boolean validCaptcha = selectedCaptchaConnector.verifyCaptcha(servletRequest, servletResponse);
                if (!validCaptcha) {
                    log.warn("Captcha validation failed for the user.");
                    httpResponse.sendRedirect(CaptchaUtil.getOnFailRedirectUrl(httpRequest.getHeader("referer"),
                            captchaPreValidationResponse.getOnCaptchaFailRedirectUrls(),
                            captchaPreValidationResponse.getCaptchaAttributes()));
                    return;
                }
            } catch (CaptchaClientException e) {
                log.warn("Captcha validation failed for the user. Cause : " + e.getMessage());
                httpResponse.sendRedirect(CaptchaUtil.getOnFailRedirectUrl(httpRequest.getHeader("referer"),
                        captchaPreValidationResponse.getOnCaptchaFailRedirectUrls(),
                        captchaPreValidationResponse.getCaptchaAttributes()));
                return;
            }
        }

        // Enable reCaptcha for the destination.
        if (captchaPreValidationResponse.isEnableCaptchaForRequestPath()) {
            if (captchaPreValidationResponse.getCaptchaAttributes() != null) {
                for (Map.Entry<String, String> parameter : captchaPreValidationResponse.getCaptchaAttributes()
                        .entrySet()) {
                    servletRequest.setAttribute(parameter.getKey(), parameter.getValue());
                }
            }
            doFilter(captchaPreValidationResponse, servletRequest, servletResponse, filterChain);
            return;
        }

        // Below the no. of max failed attempts, including the current attempt
        if (!captchaPreValidationResponse.isPostValidationRequired()
                || (!captchaPreValidationResponse.isCaptchaValidationRequired()
                        && !captchaPreValidationResponse.isMaxFailedLimitReached())) {
            doFilter(captchaPreValidationResponse, servletRequest, servletResponse, filterChain);
            return;
        }

        CaptchaHttpServletResponseWrapper responseWrapper = new CaptchaHttpServletResponseWrapper(httpResponse);
        doFilter(captchaPreValidationResponse, servletRequest, responseWrapper, filterChain);

        CaptchaPostValidationResponse postValidationResponse = selectedCaptchaConnector
                .postValidate(servletRequest, responseWrapper);

        // Check whether this attempt is failed
        if (postValidationResponse == null || postValidationResponse.isSuccessfulAttempt()) {
            if (responseWrapper.isRedirect()) {
                httpResponse.sendRedirect(responseWrapper.getRedirectURL());
            }
            return;
        }

        if (postValidationResponse.isEnableCaptchaResponsePath() && responseWrapper.isRedirect()) {
            httpResponse.sendRedirect(CaptchaUtil.getUpdatedUrl(responseWrapper.getRedirectURL(),
                    postValidationResponse.getCaptchaAttributes()));
        }
    } catch (CaptchaException e) {
        log.error("Error occurred in processing captcha.", e);
        ((HttpServletResponse) servletResponse).sendRedirect(
                CaptchaUtil.getErrorPage("Server Error", "Something " + "went wrong. Please try again"));
    }
}

From source file:org.nuxeo.ecm.platform.ui.web.auth.NuxeoAuthenticationFilter.java

private boolean switchUser(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;

    String deputyLogin = (String) httpRequest.getAttribute(SWITCH_USER_KEY);
    String targetPageAfterSwitch = (String) httpRequest.getAttribute(PAGE_AFTER_SWITCH);
    if (targetPageAfterSwitch == null) {
        targetPageAfterSwitch = LoginScreenHelper.getStartupPagePath();
    }//from  w ww  .  ja  v a  2  s  .c o  m

    CachableUserIdentificationInfo cachableUserIdent = retrieveIdentityFromCache(httpRequest);
    String originatingUser = cachableUserIdent.getUserInfo().getUserName();

    if (deputyLogin == null) {
        // simply switch back to the previous identity
        NuxeoPrincipal currentPrincipal = (NuxeoPrincipal) cachableUserIdent.getPrincipal();
        String previousUser = currentPrincipal.getOriginatingUser();
        if (previousUser == null) {
            return false;
        }
        deputyLogin = previousUser;
        originatingUser = null;
    }

    try {
        cachableUserIdent.getLoginContext().logout();
    } catch (LoginException e1) {
        log.error("Error while logout from main identity", e1);
    }

    httpRequest.getSession(false);
    service.reinitSession(httpRequest);

    CachableUserIdentificationInfo newCachableUserIdent = new CachableUserIdentificationInfo(deputyLogin,
            deputyLogin);

    newCachableUserIdent.getUserInfo().setLoginPluginName(TrustingLoginPlugin.NAME);
    newCachableUserIdent.getUserInfo().setAuthPluginName(cachableUserIdent.getUserInfo().getAuthPluginName());

    Principal principal = doAuthenticate(newCachableUserIdent, httpRequest);
    if (principal != null && principal != DIRECTORY_ERROR_PRINCIPAL) {
        NuxeoPrincipal nxUser = (NuxeoPrincipal) principal;
        if (originatingUser != null) {
            nxUser.setOriginatingUser(originatingUser);
        }
        propagateUserIdentificationInformation(cachableUserIdent);
    }

    // reinit Seam so the afterResponseComplete does not crash
    // ServletLifecycle.beginRequest(httpRequest);

    // flag redirect to avoid being caught by URLPolicy
    request.setAttribute(DISABLE_REDIRECT_REQUEST_KEY, Boolean.TRUE);
    String baseURL = service.getBaseURL(request);
    ((HttpServletResponse) response).sendRedirect(baseURL + targetPageAfterSwitch);

    return true;
}

From source file:eu.semlibproject.annotationserver.filters.AuthFilter.java

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

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;

    // Try to set the servlet context path (used to overcome
    // limit of servlet containers that does not support sevlet
    // specification >= 2.5
    super.setServletContextPath(httpRequest);

    // This is a workaround for Tomcat 5.x. A better option would be to make this setting
    // in filter initialization but in this case Tomcat 5.x throw an exception 'cos
    // getServletContext.getContextPath is not supported in Servlet specfication 2.4 (Tomcat 5.x).
    if (!authenticationLoginFormSet) {
        authenticationLoginFormSet = true;
        ConfigManager.getInstance().setAuthenticationFormPath(authenticationLoginFrom);
    }//ww w. ja v a  2s .  c  o m

    String requestedMethods = httpRequest.getMethod();
    String cookieValue = CookiesManager.getInstance().isUserAuthorizedFromCookie(httpRequest, resp);
    String requestedPath = httpRequest.getPathInfo();

    boolean openApi = false;
    if (requestedPath != null && requestedPath.contains("/open/")) {
        openApi = true;
    }

    // skip this part if authentication is not enabled and if we are a preflight request
    if (authenticationEnabled && !"OPTIONS".equalsIgnoreCase(requestedMethods) && !isANoAuthAPI(httpRequest)
            && !openApi) {

        if (request instanceof HttpServletRequest) {

            boolean authorized = false;
            String acceptedFormat = httpRequest.getHeader(SemlibConstants.HTTP_HEADER_ACCEPT);

            // Check the cookie to see if the user is authorized or not                                
            if (StringUtils.isNotBlank(cookieValue)) {
                authorized = true;
            }

            if (!authorized) {
                if (acceptedFormat != null && acceptedFormat.contains(MediaType.APPLICATION_JSON)) {
                    // Generate the JSON redirect response
                    try {
                        JSONObject jsonData = new JSONObject();
                        jsonData.put(SemlibConstants.REDIRECT_TO, authenticationLoginFrom);

                        resp.setContentType(MediaType.APPLICATION_JSON);
                        resp.setCharacterEncoding(SemlibConstants.UTF8);

                        PrintWriter out = resp.getWriter();
                        out.print(jsonData.toString());
                    } catch (JSONException ex) {
                        logger.log(Level.SEVERE, null, ex);
                        resp.sendError(500);
                    }
                } else {
                    // send a normal 302 response                        
                    resp.sendRedirect(authenticationLoginFrom);
                }
            } else {

                // Pass the token of the current logged user to the APIs                    
                request.setAttribute(SemlibConstants.LOGGED_USER_ATTR, cookieValue);

                User currentUser = TokenManager.getInstance().getUserFromToken(cookieValue);
                if (!currentUser.isAlreadyCheckedForRepository()) {
                    // Init or update the users information (into the DB)
                    boolean correctlyInitiliazed = UsersManager.getInstance()
                            .initOrUpdateUserInformationOnDB(cookieValue);
                    currentUser.setCheckedForRepository(correctlyInitiliazed);
                }

                // The user is authenticated/authorized
                chain.doFilter(request, response);
            }

        } else {
            // Return a bad request                
            resp.sendError(400);
        }

    } else {

        if (!"OPTIONS".equalsIgnoreCase(requestedMethods)) {
            if (StringUtils.isNotBlank(cookieValue)) {
                request.setAttribute(SemlibConstants.LOGGED_USER_ATTR, cookieValue);
            } else if (!authenticationEnabled && !isANoAuthAPI(httpRequest) && !openApi) {
                // In this case we need to create an anonymous user
                User anonUser = User.createAnonymousUser();
                request.setAttribute(SemlibConstants.LOGGED_USER_ATTR, anonUser.getAccessToken());
            }
        }

        chain.doFilter(request, response);
    }
}

From source file:net.lightbody.bmp.proxy.jetty.servlet.MultiPartFilter.java

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *///from  w  w w . ja  v a  2 s.  co m
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest srequest = (HttpServletRequest) request;
    if (srequest.getContentType() == null || !srequest.getContentType().startsWith("multipart/form-data")) {
        chain.doFilter(request, response);
        return;
    }
    LineInput in = new LineInput(request.getInputStream());
    String content_type = srequest.getContentType();
    String boundary = "--" + value(content_type.substring(content_type.indexOf("boundary=")));
    byte[] byteBoundary = (boundary + "--").getBytes(StringUtil.__ISO_8859_1);
    MultiMap params = new MultiMap();

    // Get first boundary
    String line = in.readLine();
    if (!line.equals(boundary)) {
        log.warn(line);
        throw new IOException("Missing initial multi part boundary");
    }

    // Read each part
    boolean lastPart = false;
    String content_disposition = null;
    while (!lastPart) {
        while ((line = in.readLine()) != null) {
            // If blank line, end of part headers
            if (line.length() == 0)
                break;
            // place part header key and value in map
            int c = line.indexOf(':', 0);
            if (c > 0) {
                String key = line.substring(0, c).trim().toLowerCase();
                String value = line.substring(c + 1, line.length()).trim();
                if (key.equals("content-disposition"))
                    content_disposition = value;
            }
        }
        // Extract content-disposition
        boolean form_data = false;
        if (content_disposition == null) {
            throw new IOException("Missing content-disposition");
        }

        StringTokenizer tok = new StringTokenizer(content_disposition, ";");
        String name = null;
        String filename = null;
        while (tok.hasMoreTokens()) {
            String t = tok.nextToken().trim();
            String tl = t.toLowerCase();
            if (t.startsWith("form-data"))
                form_data = true;
            else if (tl.startsWith("name="))
                name = value(t);
            else if (tl.startsWith("filename="))
                filename = value(t);
        }

        // Check disposition
        if (!form_data) {
            log.warn("Non form-data part in multipart/form-data");
            continue;
        }
        if (name == null || name.length() == 0) {
            log.warn("Part with no name in multipart/form-data");
            continue;
        }

        OutputStream out = null;
        File file = null;
        try {
            if (filename != null && filename.length() > 0) {
                file = File.createTempFile("MultiPart", "", tempdir);
                out = new FileOutputStream(file);
                request.setAttribute(name, file);
                params.put(name, filename);
            } else
                out = new ByteArrayOutputStream();

            int state = -2;
            int c;
            boolean cr = false;
            boolean lf = false;

            // loop for all lines`
            while (true) {
                int b = 0;
                while ((c = (state != -2) ? state : in.read()) != -1) {
                    state = -2;
                    // look for CR and/or LF
                    if (c == 13 || c == 10) {
                        if (c == 13)
                            state = in.read();
                        break;
                    }
                    // look for boundary
                    if (b >= 0 && b < byteBoundary.length && c == byteBoundary[b])
                        b++;
                    else {
                        // this is not a boundary
                        if (cr)
                            out.write(13);
                        if (lf)
                            out.write(10);
                        cr = lf = false;
                        if (b > 0)
                            out.write(byteBoundary, 0, b);
                        b = -1;
                        out.write(c);
                    }
                }
                // check partial boundary
                if ((b > 0 && b < byteBoundary.length - 2) || (b == byteBoundary.length - 1)) {
                    if (cr)
                        out.write(13);
                    if (lf)
                        out.write(10);
                    cr = lf = false;
                    out.write(byteBoundary, 0, b);
                    b = -1;
                }
                // boundary match
                if (b > 0 || c == -1) {
                    if (b == byteBoundary.length)
                        lastPart = true;
                    if (state == 10)
                        state = -2;
                    break;
                }
                // handle CR LF
                if (cr)
                    out.write(13);
                if (lf)
                    out.write(10);
                cr = (c == 13);
                lf = (c == 10 || state == 10);
                if (state == 10)
                    state = -2;
            }
        } finally {
            IO.close(out);
        }

        if (file == null) {
            byte[] bytes = ((ByteArrayOutputStream) out).toByteArray();
            params.add(name, bytes);
        }
    }

    chain.doFilter(new Wrapper(srequest, params), response);

    // TODO delete the files if they still exist.
}