Example usage for javax.servlet.http HttpServletRequest getContextPath

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

Introduction

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

Prototype

public String getContextPath();

Source Link

Document

Returns the portion of the request URI that indicates the context of the request.

Usage

From source file:edu.vt.middleware.servlet.filter.RequestDumperFilter.java

/** {@inheritDoc} */
@SuppressWarnings(value = "unchecked")
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    if (this.config == null) {
        return;// w ww  .  ja va2 s .  com
    }

    // Just pass through to next filter if we're not at TRACE level
    if (!logger.isTraceEnabled()) {
        chain.doFilter(request, response);
        return;
    }

    // Create a variable to hold the (possibly different) request
    // passed to downstream filters
    ServletRequest downstreamRequest = request;

    // Render the generic servlet request properties
    final StringWriter sw = new StringWriter();
    final PrintWriter writer = new PrintWriter(sw);
    writer.println("Dumping request...");
    writer.println("-----------------------------------------------------");
    writer.println("REQUEST received " + Calendar.getInstance().getTime());
    writer.println(" characterEncoding=" + request.getCharacterEncoding());
    writer.println("     contentLength=" + request.getContentLength());
    writer.println("       contentType=" + request.getContentType());
    writer.println("            locale=" + request.getLocale());
    writer.print("           locales=");

    final Enumeration<Locale> locales = request.getLocales();
    for (int i = 0; locales.hasMoreElements(); i++) {
        if (i > 0) {
            writer.print(", ");
        }
        writer.print(locales.nextElement());
    }
    writer.println();

    final Enumeration<String> paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
        final String name = paramNames.nextElement();
        writer.print("         parameter=" + name + "=");

        final String[] values = request.getParameterValues(name);
        for (int i = 0; i < values.length; i++) {
            if (i > 0) {
                writer.print(", ");
            }
            writer.print(values[i]);
        }
        writer.println();
    }
    writer.println("          protocol=" + request.getProtocol());
    writer.println("        remoteAddr=" + request.getRemoteAddr());
    writer.println("        remoteHost=" + request.getRemoteHost());
    writer.println("            scheme=" + request.getScheme());
    writer.println("        serverName=" + request.getServerName());
    writer.println("        serverPort=" + request.getServerPort());
    writer.println("          isSecure=" + request.isSecure());

    // Render the HTTP servlet request properties
    if (request instanceof HttpServletRequest) {
        final HttpServletRequest hrequest = (HttpServletRequest) request;
        writer.println("       contextPath=" + hrequest.getContextPath());

        Cookie[] cookies = hrequest.getCookies();
        if (cookies == null) {
            cookies = new Cookie[0];
        }
        for (int i = 0; i < cookies.length; i++) {
            writer.println("            cookie=" + cookies[i].getName() + "=" + cookies[i].getValue());
        }

        final Enumeration<String> headerNames = hrequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            final String name = headerNames.nextElement();
            final String value = hrequest.getHeader(name);
            writer.println("            header=" + name + "=" + value);
        }
        writer.println("            method=" + hrequest.getMethod());
        writer.println("          pathInfo=" + hrequest.getPathInfo());
        writer.println("       queryString=" + hrequest.getQueryString());
        writer.println("        remoteUser=" + hrequest.getRemoteUser());
        writer.println("requestedSessionId=" + hrequest.getRequestedSessionId());
        writer.println("        requestURI=" + hrequest.getRequestURI());
        writer.println("       servletPath=" + hrequest.getServletPath());

        // Create a wrapped request that contains the request body
        // and that we will pass to downstream filters
        final ByteArrayRequestWrapper wrappedRequest = new ByteArrayRequestWrapper(hrequest);
        downstreamRequest = wrappedRequest;
        writer.println(wrappedRequest.getRequestBodyAsString());
    }
    writer.println("-----------------------------------------------------");

    // Log the resulting string
    writer.flush();
    logger.trace(sw.getBuffer().toString());

    // Pass control on to the next filter
    chain.doFilter(downstreamRequest, response);
}

From source file:es.logongas.ix3.web.security.impl.WebSessionSidStorageImplAbstractJws.java

@Override
public void deleteSid(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
    Cookie cookie = new Cookie(jwsCookieName, "");
    cookie.setHttpOnly(false);//from w  w w  .j a va  2s.c  om
    cookie.setPath(httpServletRequest.getContextPath() + "/");
    httpServletResponse.addCookie(cookie);
}

From source file:ar.sgt.resolver.filter.ResolverFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    log.trace("Entering filter processing");
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    String path = req.getRequestURI();
    if (!req.getContextPath().isEmpty()) {
        path = StringUtils.removeStartIgnoreCase(path, req.getContextPath());
    }//ww w . j  a v a2 s. c  om
    if (path.startsWith("//")) {
        path = path.substring(1);
    }
    if (this.excludePath != null) {
        String fp = StringUtils.left(path, path.indexOf("/", 1));
        if (this.excludePath.contains(fp)) {
            log.trace("Skip path {}", path);
            chain.doFilter(request, response);
            return;
        }
    }
    if (this.appendBackSlash) {
        if (!path.endsWith("/"))
            path = path + "/";
    }
    log.debug("Resolve path: {}", path);
    Rule rule = resolverConfig.findRule(path);
    if (rule != null) {
        log.debug("Found rule {} using processor {}", rule.getName() == null ? "Unnamed" : rule.getName(),
                rule.getProcessor());
        if (rule.getName() != null) {
            req.setAttribute(RuleConstant.CURRENT_RULE, rule.getName());
            req.setAttribute(RuleConstant.CURRENT_PATH, req.getRequestURI());
        }
        ResolverContext context = new ResolverContext(filterConfig.getServletContext(), req, resp,
                rule.parseParams(), req.getMethod());
        String redirect = null;
        if (rule.getRedirect() != null) {
            // check first if there is a named rule matching
            if (rule.getProcessor().equals(PermanentRedirectProcessor.class.getName())) {
                redirect = rule.getRedirect();
            } else {
                UrlReverse reverse = new UrlReverse(resolverConfig);
                try {
                    redirect = req.getContextPath() + reverse.resolve(rule.getRedirect());
                    log.trace("Using named rule {}", rule.getRedirect());
                } catch (ReverseException e) {
                    log.error(e.getMessage());
                    redirect = rule.getRedirect();
                } catch (RuleNotFoundException e) {
                    log.trace("Rule with name {} not found. Simple url redirect", rule.getRedirect());
                    redirect = rule.getRedirect();
                }
            }
        }
        ProcessorContext processorContext = new ProcessorContext(rule, redirect);
        Processor processor;
        try {
            processor = loadClass(rule.getProcessor());
            processor.process(processorContext, context);
        } catch (HttpError e) {
            log.debug("Handling HTTP ERROR {}", e.getHttpErrorCode());
            resp.sendError(e.getHttpErrorCode());
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new ServletException(e);
        }
    } else {
        log.trace("No matching rule found");
        chain.doFilter(request, response);
    }
}

From source file:se.vgregion.userassociations.hook.UserCommunityActionTest.java

@Test
public void testRun() throws Exception {
    UserCommunityAction action = new UserCommunityAction();
    UserLocalService userLocalService = mock(UserLocalService.class);
    ReflectionTestUtils.setField(action, "userLocalService", userLocalService);
    Portal portal = mock(Portal.class);
    ReflectionTestUtils.setField(action, "portal", portal);

    HttpServletRequest req = mock(HttpServletRequest.class);
    HttpServletResponse res = mock(HttpServletResponse.class);
    HttpSession session = mock(HttpSession.class);
    when(req.getSession()).thenReturn(session);
    when(req.getContextPath()).thenReturn("/");

    User user = getUser(0l, 12345l, "mockUser", new long[] {});
    Group vgr = mock(Group.class);
    when(vgr.getName()).thenReturn("VGRegion");
    when(vgr.hasPrivateLayouts()).thenReturn(true);
    when(user.getGroups()).thenReturn(Arrays.asList(vgr));
    when(portal.getUserId(req)).thenReturn(123l);
    when(userLocalService.getUser(123l)).thenReturn(user);

    action.run(req, res);//from   w w  w  .ja v a 2s.  c o  m

    verify(session).setAttribute(eq(WebKeys.LAST_PATH), anyString());
}

From source file:se.vgregion.userassociations.hook.UserCommunityActionTest.java

@Test
public void testRun2() throws Exception {
    UserCommunityAction action = new UserCommunityAction();
    UserLocalService userLocalService = mock(UserLocalService.class);
    ReflectionTestUtils.setField(action, "userLocalService", userLocalService);
    Portal portal = mock(Portal.class);
    ReflectionTestUtils.setField(action, "portal", portal);

    HttpServletRequest req = mock(HttpServletRequest.class);
    HttpServletResponse res = mock(HttpServletResponse.class);
    HttpSession session = mock(HttpSession.class);
    when(req.getSession()).thenReturn(session);
    when(req.getContextPath()).thenReturn("/");

    User user = getUser(0l, 12345l, "mockUser", new long[] {});
    Group extern = mock(Group.class);
    when(extern.getName()).thenReturn("Extern");
    when(extern.hasPrivateLayouts()).thenReturn(true);
    when(user.getGroups()).thenReturn(Arrays.asList(extern));
    when(portal.getUserId(req)).thenReturn(123l);
    when(userLocalService.getUser(123l)).thenReturn(user);

    action.run(req, res);/*from  w w w.  j  a  va 2  s  .  c  o  m*/

    verify(session).setAttribute(eq(WebKeys.LAST_PATH), anyString());
}

From source file:com.sonymobile.jenkins.plugins.kerberossso.KerberosSSOFilter.java

/**
 * Filters every request made to the server to determine and set authentication of the user.
 * 1. Find out if the user is already authenticated (by checking the securityContext).
 * 2. Otherwise, authenticate the user from his Kerberos ticket and,
 * 3. Set him as authenticated by setting a new securityContext.
 * During the negotiation process used by Spnego, none of the filters after this one in the chain
 * will be allowed to execute./*from  w w w  . j  av a 2 s.  c  o  m*/
 *
 * @param request the Servlet request to serve
 * @param response the Servlet response to serve
 * @param chain the filter chain determining which filter will execute after ours.
 * @throws IOException if redirection goes wrong or if another filter in the chain fails.
 * @throws ServletException if the authentication fails.
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if ((!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse))
            || containsBypassHeader(request)) {
        chain.doFilter(request, response);
        return;
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String userContentPath = httpRequest.getContextPath() + "/userContent";

    if (httpRequest.getRequestURI().startsWith(userContentPath)) {
        chain.doFilter(request, response);
        return;
    }

    SpnegoHttpServletResponse spnegoHttpResponse = new SpnegoHttpServletResponse(
            (HttpServletResponse) response);

    if (PluginImpl.getInstance().isRedirectEnabled()
            && !httpRequest.getLocalAddr().equals(httpRequest.getRemoteAddr())) {
        // If Local and Remote address is the same, the user is Localhost and shouldn't be redirected.

        String requestedDomain = new URL(httpRequest.getRequestURL().toString()).getHost();
        String requestedURL = httpRequest.getRequestURL().toString();
        if (!requestedDomain.toLowerCase().contains(PluginImpl.getInstance().getRedirect().toLowerCase())) {

            String redirect = requestedURL.replaceFirst(requestedDomain,
                    requestedDomain + "." + PluginImpl.getInstance().getRedirect());
            spnegoHttpResponse.sendRedirect(redirect);
        }
    }

    // A user is "always" authenticated by Jenkins as anonymous when not authenticated in any other way.
    if (SecurityContextHolder.getContext().getAuthentication() == null
            || !SecurityContextHolder.getContext().getAuthentication().isAuthenticated()
            || Functions.isAnonymous()) {
        Functions.advertiseHeaders((HttpServletResponse) response); //Adds headers for CLI

        Principal principal;

        try {
            principal = authenticator.authenticate(httpRequest, spnegoHttpResponse);
        } catch (LoginException e) {
            logger.log(Level.WARNING, "Failed to fetch spnegoPrincipal name for user");
            chain.doFilter(request, spnegoHttpResponse);
            return;
        }

        // Expecting negotiation
        if (principal == null) {
            return;
        }

        String principalName = principal.getName();

        if (principalName.contains("@")) {
            principalName = principalName.substring(0, principalName.indexOf("@"));
        }

        try {
            SecurityRealm realm = Jenkins.getInstance().getSecurityRealm();
            UserDetails userDetails = realm.loadUserByUsername(principalName);
            Authentication authToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(),
                    userDetails.getPassword(), userDetails.getAuthorities());

            ACL.impersonate(authToken);
            if (Jenkins.getVersion().isNewerThan(new VersionNumber("1.568"))) {
                try {
                    Method fireLoggedIn = SecurityListener.class.getMethod("fireLoggedIn", String.class);
                    fireLoggedIn.invoke(null, userDetails.getUsername());
                } catch (Exception e) {
                    logger.log(Level.WARNING, "Failed to invoke fireLoggedIn method", e);
                }
            }
            logger.log(Level.FINE, "Authenticated user {0}", userDetails.getUsername());
        } catch (UsernameNotFoundException e) {
            logger.log(Level.WARNING, "Username {0} not registered by Jenkins", principalName);
        } catch (NullPointerException e) {
            logger.log(Level.WARNING, "User authentication failed");
            e.printStackTrace();
        } catch (DataAccessException e) {
            logger.log(Level.WARNING, "No access to user database");
            e.printStackTrace();
        }
    }

    chain.doFilter(request, response);
}

From source file:org.socialsignin.springsocial.security.signin.SpringSocialSecurityAccessDeniedHandler.java

private boolean providerCombinationAllowsAccessForEvaluator(HttpServletRequest request,
        Authentication existingAuthentication, WebInvocationPrivilegeEvaluator evaluator,
        Set<String> additionProviderIdsCombination) {
    return evaluator.isAllowed(request.getContextPath(), getUri(request), request.getMethod(),
            springSocialSecurityAuthenticationFactory.updateAuthenticationForNewProviders(
                    existingAuthentication, additionProviderIdsCombination));

}

From source file:com.codename1.corsproxy.CORSProxy.java

@Override
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        Header header) {/*from   ww w  .java 2 s .  c  o m*/
    List<HttpCookie> cookies = HttpCookie.parse(header.getValue());
    String path = servletRequest.getContextPath(); // path starts with / or is empty string
    path += servletRequest.getServletPath(); // servlet path starts with / or is empty string

    for (HttpCookie cookie : cookies) {
        //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
        String proxyCookieName = getCookieNamePrefix() + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(path); //set to the path of the proxy servlet
        // don't set cookie domain
        //servletCookie.setSecure(cookie.getSecure());
        servletCookie.setSecure(false);
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}

From source file:org.codemucker.testserver.capturing.CapturedRequest.java

public CapturedRequest(final HttpServletRequest req) {
    scheme = req.getScheme();//from   ww w.j a  va  2 s. c om
    host = req.getServerName();
    port = req.getServerPort();
    contextPath = req.getContextPath();
    servletPath = req.getServletPath();
    pathInfo = req.getPathInfo();
    characterEncoding = req.getCharacterEncoding();
    method = req.getMethod();
    final Cookie[] cookies = req.getCookies();

    // cookies
    if (cookies != null) {
        for (final Cookie cookie : cookies) {
            this.cookies.add(new CapturedCookie(cookie));
        }
    }
    // headers
    for (@SuppressWarnings("unchecked")
    final Enumeration<String> names = req.getHeaderNames(); names.hasMoreElements();) {
        final String name = names.nextElement();
        @SuppressWarnings("unchecked")
        final Enumeration<String> values = req.getHeaders(name);
        if (values != null) {
            for (; values.hasMoreElements();) {
                this.addHeader(new CapturedHeader(name, values.nextElement()));
            }
        }
    }
    // if we use the normal 'toString' on maps, and arrays, we get pretty
    // poor results
    // Use ArrayLists instead to get a nice output
    @SuppressWarnings("unchecked")
    final Map<String, String[]> paramMap = req.getParameterMap();
    if (paramMap != null) {
        for (final String key : paramMap.keySet()) {
            final String[] vals = paramMap.get(key);
            this.parameters.put(key, new ArrayList<String>(Arrays.asList(vals)));
        }
    }
    // handle multipart posts
    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        final FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        final ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            @SuppressWarnings("unchecked")
            final List<FileItem> items = upload.parseRequest(req);
            for (final FileItem item : items) {
                fileItems.add(new CapturedFileItem(item));
            }
        } catch (final FileUploadException e) {
            throw new RuntimeException("Error handling multipart content", e);
        }
    }

}