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:org.apache.ranger.security.web.filter.RangerKRBAuthenticationFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    String authtype = PropertiesUtil.getProperty(RANGER_AUTH_TYPE);
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (isSpnegoEnable(authtype)) {
        KerberosName.setRules(PropertiesUtil.getProperty(NAME_RULES, "DEFAULT"));
        Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
        String userName = null;/*w w  w  .  j  av  a2s  . c o m*/
        Cookie[] cookie = httpRequest.getCookies();
        if (cookie != null) {
            for (Cookie c : cookie) {
                String cname = c.getName();
                if (cname != null && cname.equalsIgnoreCase("u")) {
                    int ustr = cname.indexOf("u=");
                    if (ustr != -1) {
                        int andStr = cname.indexOf("&", ustr);
                        if (andStr != -1) {
                            userName = cname.substring(ustr + 2, andStr);
                        }
                    }
                } else if (cname != null && cname.equalsIgnoreCase(AUTH_COOKIE_NAME)) {
                    int ustr = cname.indexOf("u=");
                    if (ustr != -1) {
                        int andStr = cname.indexOf("&", ustr);
                        if (andStr != -1) {
                            userName = cname.substring(ustr + 2, andStr);
                        }
                    }
                }
            }
        }
        if ((existingAuth == null || !existingAuth.isAuthenticated()) && (!StringUtils.isEmpty(userName))) {
            //--------------------------- To Create Ranger Session --------------------------------------         
            String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER");
            //if we get the userName from the token then log into ranger using the same user
            final List<GrantedAuthority> grantedAuths = new ArrayList<>();
            grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole));
            final UserDetails principal = new User(userName, "", grantedAuths);
            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "",
                    grantedAuths);
            WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest);
            ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
            RangerAuthenticationProvider authenticationProvider = new RangerAuthenticationProvider();
            Authentication authentication = authenticationProvider.authenticate(finalAuthentication);
            authentication = getGrantedAuthority(authentication);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            request.setAttribute("spnegoEnabled", true);
            LOG.info("Logged into Ranger as = " + userName);
        } else {
            try {
                super.doFilter(request, response, filterChain);
            } catch (Exception e) {
                throw restErrorUtil
                        .createRESTException("RangerKRBAuthenticationFilter Failed : " + e.getMessage());
            }
        }
    } else {
        filterChain.doFilter(request, response);
    }
}

From source file:org.xwiki.resource.servlet.RoutingFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    // Only handle HTTP Servlet requests...
    if (!(request instanceof HttpServletRequest)) {
        chain.doFilter(request, response);
        return;//  www. j  av  a2s  .  c o  m
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    // Step 1: Construct an ExtendedURL to make it easy to manipulate the URL segments
    ExtendedURL extendedURL = constructExtendedURL(httpRequest);

    // Step 2: Extract the Resource Type from the ExtendedURL
    ResourceTypeResolver<ExtendedURL> urlResourceTypeResolver = getResourceTypeResolver();
    ResourceType resourceType;
    try {
        resourceType = urlResourceTypeResolver.resolve(extendedURL, Collections.<String, Object>emptyMap());
    } catch (Exception e) {
        // Failed to resolve the passed ExtendedURL. This means it's not a URL that should be handled by a Resource
        // Reference Handler and we let it go through so that the next Filter or Servlet from web.xml will handle
        // it. Note that since some URL schemes may want to handle features like short URLs where the Resource Type
        // is omitted, this catch will not be called in this case and this is why we need Step 2 below in order
        // to recognize static resources and serve them!
        chain.doFilter(request, response);
        return;
    }

    // Step 3: Handle static resources simply by letting them go through so that the Servlet Container will use its
    // default Servlet to serve static content.
    // Note: This step is a performance optimization only as it would also work to go directly at step 4 since there
    // would be no handler found for static resources and thus the Servlet Container would continue processing the
    // content of web.xml and would serve static files using its File Servlet.
    if (resourceType.equals(ResourcesResourceReference.TYPE)
            || resourceType.equals(SkinsResourceReference.TYPE)) {
        chain.doFilter(request, response);
        return;
    }

    // Step 4: Check if there's a Handler available for the Resource Type
    ResourceReferenceHandlerManager<ResourceType> resourceReferenceHandlerManager = getResourceReferenceHandlerManager();
    // Note that ATM the EntityResourceReferenceHandler is configured to NOT handle "bin" Resource Types. See
    // the comment in EntityResourceReferenceHandler#getSupportedResourceReferences() for more details. This allows
    // to fallback on the Filter/Servlet chain as defined by the web.xml and have XWikiAction be called to handle
    // "bin" Resource Types. It also allows other mappings to be used to handle other resource types such as
    // "rest", "webdav" and "xmlrpc" Resource Types.
    if (!resourceReferenceHandlerManager.canHandle(resourceType)) {
        // Let it go through so that the next Filter or Servlet from web.xml will handle it.
        chain.doFilter(request, response);
        return;
    }

    // Step 4: There is a Handler to handle our request, call the Resource Handler Servlet. Note that calling a
    // Sevlet gives us more flexibility if we wish to execute some more Filters before the Servlet executes for
    // example.
    //
    // However before doing that, we save the Resource Type so that the Servlet doesn't have to extract it again!
    // We also save the URL since we don't want to have to compute the full URL again in the Resource Reference
    // Handler Servlet!
    request.setAttribute(RESOURCE_TYPE_NAME, resourceType);
    request.setAttribute(RESOURCE_EXTENDEDURL, extendedURL);
    this.servletContext.getNamedDispatcher("resourceReferenceHandler").forward(request, response);
}

From source file:org.wso2.carbon.identity.application.authentication.endpoint.AuthenticationEndpointFilter.java

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

    String redirectUrl = null;/*from  w w w  . j  a  v  a2s  .  c  o m*/
    String appSpecificCustomPageConfigKey = null;
    String serviceProviderName = servletRequest.getParameter(REQUEST_PARAM_SP) != null
            ? servletRequest.getParameter(REQUEST_PARAM_SP)
            : servletRequest.getParameter(REQUEST_PARAM_APPLICATION) != null
                    ? servletRequest.getParameter(REQUEST_PARAM_APPLICATION)
                    : null;
    String relativePath = ((HttpServletRequest) servletRequest).getRequestURI()
            .substring(((HttpServletRequest) servletRequest).getContextPath().length());
    if (StringUtils.isNotBlank(serviceProviderName)) {
        appSpecificCustomPageConfigKey = AuthenticationEndpointUtil.getApplicationSpecificCustomPageConfigKey(
                CharacterEncoder.getSafeText(serviceProviderName), relativePath);
    }

    if (appSpecificCustomPageConfigKey != null) {
        // Check for application specific custom page mappings matching the request uri.
        redirectUrl = AuthenticationEndpointUtil.getCustomPageRedirectUrl(
                context.getInitParameter(appSpecificCustomPageConfigKey),
                ((HttpServletRequest) servletRequest).getQueryString());
    }

    if (redirectUrl == null) {
        // No application specific custom page mappings.
        // Check for global custom page mappings matching the request uri.
        redirectUrl = AuthenticationEndpointUtil.getCustomPageRedirectUrl(
                context.getInitParameter(relativePath), ((HttpServletRequest) servletRequest).getQueryString());
    }

    if (redirectUrl != null) {
        // There is a custom configuration matching the request uri. Redirect.
        if (log.isDebugEnabled()) {
            log.debug("There is a custom configuration matching the request uri. Redirecting to : "
                    + redirectUrl);
        }
        ((HttpServletResponse) servletResponse).sendRedirect(redirectUrl);
        return;
    }

    if (((HttpServletRequest) servletRequest).getRequestURI().contains(URI_LOGIN)) {
        String hrdParam = CharacterEncoder.getSafeText(servletRequest.getParameter(REQUEST_PARAM_HRD));
        if (hrdParam != null && "true".equalsIgnoreCase(hrdParam)) {
            servletRequest.getRequestDispatcher("domain.jsp").forward(servletRequest, servletResponse);
            return;
        }

        Map<String, String> idpAuthenticatorMapping = new HashMap<String, String>();
        String authenticators = CharacterEncoder
                .getSafeText(servletRequest.getParameter(REQUEST_PARAM_AUTHENTICATORS));
        if (authenticators != null) {
            String[] authenticatorIdPMappings = authenticators.split(";");
            for (String authenticatorIdPMapping : authenticatorIdPMappings) {
                String[] authenticatorIdPMapArr = authenticatorIdPMapping.split(":");
                for (int i = 1; i < authenticatorIdPMapArr.length; i++) {
                    if (idpAuthenticatorMapping.containsKey(authenticatorIdPMapArr[i])) {
                        idpAuthenticatorMapping.put(authenticatorIdPMapArr[i],
                                idpAuthenticatorMapping.get(authenticatorIdPMapArr[i]) + ","
                                        + authenticatorIdPMapArr[0]);
                    } else {
                        idpAuthenticatorMapping.put(authenticatorIdPMapArr[i], authenticatorIdPMapArr[0]);
                    }
                }
            }
        }

        if (!idpAuthenticatorMapping.isEmpty()) {
            servletRequest.setAttribute(Constants.IDP_AUTHENTICATOR_MAP, idpAuthenticatorMapping);
        }

        String loadPage;
        String protocolType = CharacterEncoder.getSafeText(servletRequest.getParameter(REQUEST_PARAM_TYPE));
        if (SAMLSSO.equals(protocolType)) {
            loadPage = URI_SAMLSSO_LOGIN;
        } else if (OPENID.equals(protocolType)) {
            loadPage = URI_OPENID_LOGIN;
        } else if (PASSIVESTS.equals(protocolType)) {
            loadPage = URI_PASSIVESTS_LOGIN;
        } else if (OAUTH2.equals(protocolType) || OIDC.equals(protocolType)) {
            loadPage = URI_OAUTH2_LOGIN;
        } else if (FIDO.equals(protocolType)) {
            loadPage = "authentication.jsp";
        } else {
            loadPage = "login.jsp";
        }
        servletRequest.getRequestDispatcher(loadPage).forward(servletRequest, servletResponse);
    } else {
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

From source file:org.apache.catalina.core.ApplicationDispatcher.java

/**
 * Ask the resource represented by this RequestDispatcher to process
 * the associated request, and create (or append to) the associated
 * response.// w w  w . j  a v  a 2s. c  om
 * <p>
 * <strong>IMPLEMENTATION NOTE</strong>: This implementation assumes
 * that no filters are applied to a forwarded or included resource,
 * because they were already done for the original request.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
private void invoke(ServletRequest request, ServletResponse response) throws IOException, ServletException {

    // Checking to see if the context classloader is the current context
    // classloader. If it's not, we're saving it, and setting the context
    // classloader to the Context classloader
    ClassLoader oldCCL = Thread.currentThread().getContextClassLoader();
    ClassLoader contextClassLoader = context.getLoader().getClassLoader();

    if (oldCCL != contextClassLoader) {
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    } else {
        oldCCL = null;
    }

    // Initialize local variables we may need
    HttpServletRequest hrequest = null;
    if (request instanceof HttpServletRequest)
        hrequest = (HttpServletRequest) request;
    HttpServletResponse hresponse = null;
    if (response instanceof HttpServletResponse)
        hresponse = (HttpServletResponse) response;
    Servlet servlet = null;
    IOException ioException = null;
    ServletException servletException = null;
    RuntimeException runtimeException = null;
    boolean unavailable = false;

    // Check for the servlet being marked unavailable
    if (wrapper.isUnavailable()) {
        log(sm.getString("applicationDispatcher.isUnavailable", wrapper.getName()));
        if (hresponse == null) {
            ; // NOTE - Not much we can do generically
        } else {
            long available = wrapper.getAvailable();
            if ((available > 0L) && (available < Long.MAX_VALUE))
                hresponse.setDateHeader("Retry-After", available);
            hresponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                    sm.getString("applicationDispatcher.isUnavailable", wrapper.getName()));
        }
        unavailable = true;
    }

    // Allocate a servlet instance to process this request
    try {
        if (!unavailable) {
            //                if (debug >= 2)
            //                    log("  Allocating servlet instance");
            servlet = wrapper.allocate();
            //                if ((debug >= 2) && (servlet == null))
            //                    log("    No servlet instance returned!");
        }
    } catch (ServletException e) {
        log(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e);
        servletException = e;
        servlet = null;
    } catch (Throwable e) {
        log(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e);
        servletException = new ServletException(
                sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e);
        servlet = null;
    }

    // Get the FilterChain Here
    ApplicationFilterFactory factory = ApplicationFilterFactory.getInstance();
    ApplicationFilterChain filterChain = factory.createFilterChain(request, wrapper, servlet);
    // Call the service() method for the allocated servlet instance
    try {
        String jspFile = wrapper.getJspFile();
        if (jspFile != null)
            request.setAttribute(Globals.JSP_FILE_ATTR, jspFile);
        else
            request.removeAttribute(Globals.JSP_FILE_ATTR);
        support.fireInstanceEvent(InstanceEvent.BEFORE_DISPATCH_EVENT, servlet, request, response);
        // for includes/forwards
        if ((servlet != null) && (filterChain != null)) {
            filterChain.doFilter(request, response);
        }
        // Servlet Service Method is called by the FilterChain
        request.removeAttribute(Globals.JSP_FILE_ATTR);
        support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response);
    } catch (ClientAbortException e) {
        request.removeAttribute(Globals.JSP_FILE_ATTR);
        support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response);
        ioException = e;
    } catch (IOException e) {
        request.removeAttribute(Globals.JSP_FILE_ATTR);
        support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response);
        log(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e);
        ioException = e;
    } catch (UnavailableException e) {
        request.removeAttribute(Globals.JSP_FILE_ATTR);
        support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response);
        log(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e);
        servletException = e;
        wrapper.unavailable(e);
    } catch (ServletException e) {
        request.removeAttribute(Globals.JSP_FILE_ATTR);
        support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response);
        Throwable rootCause = e;
        Throwable rootCauseCheck = null;

        // Extra aggressive rootCause finding
        do {
            try {
                rootCauseCheck = (Throwable) PropertyUtils.getProperty(rootCause, "rootCause");
                if (rootCauseCheck != null)
                    rootCause = rootCauseCheck;

            } catch (ClassCastException ex) {
                rootCauseCheck = null;
            } catch (IllegalAccessException ex) {
                rootCauseCheck = null;
            } catch (NoSuchMethodException ex) {
                rootCauseCheck = null;
            } catch (java.lang.reflect.InvocationTargetException ex) {
                rootCauseCheck = null;
            }
        } while (rootCauseCheck != null);

        log(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), rootCause);
        servletException = e;
    } catch (RuntimeException e) {
        request.removeAttribute(Globals.JSP_FILE_ATTR);
        support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response);
        log(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e);
        runtimeException = e;
    }

    // Release the filter chain (if any) for this request
    try {
        if (filterChain != null)
            filterChain.release();
    } catch (Throwable e) {
        log.error(sm.getString("standardWrapper.releaseFilters", wrapper.getName()), e);
        //FIXME Exception handling needs to be simpiler to what is in the StandardWrapperValue
    }

    // Deallocate the allocated servlet instance
    try {
        if (servlet != null) {
            wrapper.deallocate(servlet);
        }
    } catch (ServletException e) {
        log(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e);
        servletException = e;
    } catch (Throwable e) {
        log(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e);
        servletException = new ServletException(
                sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e);
    }

    // Reset the old context class loader
    if (oldCCL != null)
        Thread.currentThread().setContextClassLoader(oldCCL);

    // Rethrow an exception if one was thrown by the invoked servlet
    if (ioException != null)
        throw ioException;
    if (servletException != null)
        throw servletException;
    if (runtimeException != null)
        throw runtimeException;

}

From source file:org.commoncrawl.service.listcrawler.MultiPartFilter.java

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *//*w  w w  .  j a  v a 2s .  c  om*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    LOG.info("Hit doFilter");
    HttpServletRequest srequest = (HttpServletRequest) request;
    if (srequest.getContentType() == null || !srequest.getContentType().startsWith("multipart/form-data")) {
        LOG.info(srequest.toString());
        LOG.info("Rejecting. Invalid mime type:" + srequest.getContentType());
        chain.doFilter(request, response);
        return;
    }

    LOG.info("OK Looks Good So Far");

    BufferedInputStream in = new BufferedInputStream(request.getInputStream());
    String content_type = srequest.getContentType();

    // TODO - handle encodings

    String boundary = "--" + value(content_type.substring(content_type.indexOf("boundary=")));
    byte[] byteBoundary = (boundary + "--").getBytes(StringUtil.__ISO_8859_1);
    MultiMap params = new MultiMap();

    try {
        // Get first boundary
        byte[] bytes = TypeUtil.readLine(in);
        String line = bytes == null ? null : new String(bytes, "UTF-8");
        if (line == null || !line.equals(boundary)) {
            throw new IOException("Missing initial multi part boundary");
        }

        // Read each part
        boolean lastPart = false;
        String content_disposition = null;
        String file_content_type = null;
        while (!lastPart) {
            while (true) {
                bytes = TypeUtil.readLine(in);
                // If blank line, end of part headers
                if (bytes == null || bytes.length == 0)
                    break;
                line = new String(bytes, "UTF-8");

                // 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;
                    else if (key.equals("content-type"))
                        file_content_type = 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) {
                continue;
            }
            if (name == null || name.length() == 0) {
                continue;
            }

            OutputStream out = null;
            File file = null;
            try {
                if (filename != null && filename.length() > 0) {
                    file = File.createTempFile("MultiPart", "", tempdir);
                    LOG.info("Got FileName:" + filename + " Creating Temp File:" + file);
                    out = new FileOutputStream(file);

                    UploadFileData uploadData = new UploadFileData();

                    uploadData.fieldName = name;
                    uploadData.incomingFile = file;
                    uploadData.incomingFilename = filename;
                    uploadData.incomingContentType = file_content_type;

                    request.setAttribute(name, uploadData);

                    params.put(name, filename);

                    if (_deleteFiles) {
                        //file.deleteOnExit();
                        ArrayList<UploadFileData> files = (ArrayList<UploadFileData>) request
                                .getAttribute(FILES);
                        if (files == null) {
                            files = new ArrayList<UploadFileData>();
                            request.setAttribute(FILES, files);
                        }
                        files.add(uploadData);
                    }

                } 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 {
                if (out != null) {
                    out.close();
                }
            }

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

        // handle request
        chain.doFilter(new Wrapper(srequest, params), response);
    } catch (IOException e) {
        LOG.error("###Exception In Multipart:" + CCStringUtils.stringifyException(e));
        throw e;
    } finally {
        LOG.info("Deleting Files Here");
        deleteFiles(request);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.filters.WebappDaoFactorySparqlPrep.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 ww.j  av  a2 s.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;
        }
    }

    javax.sql.DataSource ds = JenaDataSourceSetupBase.getApplicationDataSource(_ctx);
    StoreDesc storeDesc = (StoreDesc) _ctx.getAttribute("storeDesc");
    OntModelSelector oms = (OntModelSelector) _ctx.getAttribute("unionOntModelSelector");
    String defaultNamespace = (String) _ctx.getAttribute("defaultNamespace");
    Connection sqlConn = null;
    SDBConnection conn = null;
    Store store = null;
    Dataset dataset = null;
    WebappDaoFactory wadf = null;

    try {
        if (ds == null || storeDesc == null || oms == null) {
            throw new RuntimeException("SDB store not property set up");
        }

        try {
            sqlConn = ds.getConnection();
            conn = new SDBConnection(sqlConn);
        } catch (SQLException sqe) {
            throw new RuntimeException("Unable to connect to database", sqe);
        }
        if (conn != null) {
            store = SDBFactory.connectStore(conn, storeDesc);
            dataset = SDBFactory.connectDataset(store);
            VitroRequest vreq = new VitroRequest((HttpServletRequest) request);

            log.info("---------");

            Enumeration<String> headStrs = vreq.getHeaderNames();
            while (headStrs.hasMoreElements()) {
                String head = headStrs.nextElement();
                log.info(head + " : " + vreq.getHeader(head));
            }

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

            log.info("Accept-Language: " + vreq.getHeader("Accept-Language"));
            Enumeration<Locale> locs = vreq.getLocales();
            while (locs.hasMoreElements()) {
                Locale locale = locs.nextElement();
                langs.add(locale.toString().replace("_", "-"));
                log.info(locale.toString() + " / " + locale.getLanguage() + " + " + locale.getCountry() + " : "
                        + locale.getDisplayCountry() + " | " + locale.getLanguage() + " : "
                        + locale.getDisplayLanguage());
            }
            WebappDaoFactoryConfig config = new WebappDaoFactoryConfig();
            config.setDefaultNamespace(defaultNamespace);
            config.setPreferredLanguages(langs);

            //okay let's make a graph-backed model
            String endpointURI = ConfigurationProperties.getBean(request)
                    .getProperty("VitroConnection.DataSource.endpointURI");

            Graph g = new SparqlGraphMultilingual(endpointURI, langs);
            //Graph g = new SparqlGraph(endpointURI);

            Model m = ModelFactory.createModelForGraph(g);
            OntModel om = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, m);
            oms = new SingleContentOntModelSelector(om, oms.getDisplayModel(), oms.getUserAccountsModel());

            dataset = DatasetFactory.create(new SparqlDatasetGraph(endpointURI));

            //DataSource datasource = DatasetFactory.create();
            //datasource.addNamedModel("fake:fake", m);
            //dataset = datasource;         

            vreq.setAssertionsWebappDaoFactory(wadf);

            wadf = new WebappDaoFactoryJena(oms, config);
            //wadf = new WebappDaoFactorySDB(oms, dataset, config);
            vreq.setWebappDaoFactory(wadf);
            vreq.setFullWebappDaoFactory(wadf);
            vreq.setUnfilteredWebappDaoFactory(wadf);
            vreq.setWebappDaoFactory(wadf);
            vreq.setDataset(dataset);
            vreq.setJenaOntModel(om);
            vreq.setOntModelSelector(oms);
        }
    } catch (Throwable t) {
        log.error("Unable to filter request to set up SDB connection", t);
    }

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

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

}

From source file:org.shareok.data.webserv.filters.UserSessionFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    try {/*from   www  .j ava2s  .  c o  m*/
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String contextPath = httpRequest.getServletPath();
        if (contextPath.contains("/")) {
            contextPath = contextPath.split("/")[1];
        } //.getContextPath();
        if (null != contextPath && !"".equals(contextPath)
                && ShareokdataManager.requiredUserAuthentication(contextPath)) {
            SessionRepository<Session> repo = (SessionRepository<Session>) httpRequest
                    .getAttribute(SessionRepository.class.getName());

            if (contextPath.equals("register")) {
                String email = (String) httpRequest.getParameter("email");
                String password = (String) httpRequest.getParameter("password");
                String userName = (String) httpRequest.getParameter("nickname");
                if (null == email || "".equals(email)) {
                    throw new UserRegisterInfoNotFoundException(
                            "Valid email register information is required!");
                }
                if (null == password || "".equals(password)) {
                    throw new UserRegisterInfoNotFoundException("Valid password is required for registration!");
                }
                /*****************
                 * Some password validation logic here:
                 */
                ExpiringSession session = (ExpiringSession) repo.createSession();
                session.setMaxInactiveIntervalInSeconds(600);
                String sessionId = session.getId();
                RedisUser user = redisUserService.findUserByUserEmail(email);
                if (null != user && password.equals(user.getPassword())) {
                    session.setAttribute(ShareokdataManager.getSessionRedisUserAttributeName(), user);
                    user.setSessionKey(sessionId);
                    user.setUserName(userName);
                    redisUserService.updateUser(user);
                } else if (null == user) {
                    ApplicationContext context = new ClassPathXmlApplicationContext("redisContext.xml");
                    user = (RedisUser) context.getBean("redisUser");

                    user.setEmail(email);
                    user.setPassword(password);
                    user.setSessionKey(sessionId);
                    redisUserService.addUser(user);
                } else if (null != user && !password.equals(user.getPassword())) {
                    throw new UserRegisterInfoNotFoundException(
                            "Your login information does not match our records!`");
                }

                session.setAttribute(ShareokdataManager.getSessionRedisUserAttributeName(), user);
                repo.save(session);
                chain.doFilter(request, response);
                //                    HttpServletResponse httpReponse = (HttpServletResponse)response;
                //                    httpReponse.sendRedirect("/webserv/home");
            } else {
                boolean sessionValidated = false;
                HttpSession session = (HttpSession) httpRequest.getSession(false);
                if (null != session) {
                    ExpiringSession exSession = (ExpiringSession) repo.getSession(session.getId());
                    if (null != exSession) {
                        RedisUser user = (RedisUser) session
                                .getAttribute(ShareokdataManager.getSessionRedisUserAttributeName());
                        if (null != user) {
                            RedisUser userPersisted = redisUserService.findAuthenticatedUser(user.getEmail(),
                                    session.getId());
                            if (null != userPersisted) {
                                sessionValidated = true;
                            }
                        }
                    }
                }

                if (!sessionValidated) {
                    if (null != session) {
                        repo.delete(session.getId());
                        session.setAttribute(ShareokdataManager.getSessionRedisUserAttributeName(), null);
                        session.invalidate();
                    }
                    httpRequest.logout();
                    //request.getRequestDispatcher("/WEB-INF/jsp/logout.jsp").forward(request, response);
                    HttpServletResponse httpReponse = (HttpServletResponse) response;
                    httpReponse.sendRedirect("/webserv/login");
                } else {
                    chain.doFilter(request, response);
                }
            }
        } else {
            chain.doFilter(request, response);
        }
    } catch (IOException ex) {
        request.setAttribute("errorMessage", ex);
        request.getRequestDispatcher("/WEB-INF/jsp/userError.jsp").forward(request, response);
    } catch (ServletException ex) {
        request.setAttribute("errorMessage", ex);
        request.getRequestDispatcher("/WEB-INF/jsp/userError.jsp").forward(request, response);
    } catch (UserRegisterInfoNotFoundException ex) {
        request.setAttribute("errorMessage", ex);
        request.getRequestDispatcher("/WEB-INF/jsp/userError.jsp").forward(request, response);
    }

}