/** * Rewrites all request without a file extension to <code>/index.html</code> and returns it * to the {@link DefaultServlet}. This is necessary because for URLs which will be handled * in Angular.js. It requires that Angular.js is loaded and that is by returning the content * of the index.html. */ @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request) { @Override public String getServletPath() { return ""; } @Override public String getRequestURI() { return ""; } @Override public String getPathInfo() { return super.getPathInfo().matches(".*\\/[^\\/]*\\.[^\\/]*$") ? super.getPathInfo() : "/index.html"; } }; final RequestDispatcher dispatcher = getServletContext().getNamedDispatcher("default"); dispatcher.forward(wrapper, response); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException { HttpServletRequestWrapper quoted = new RequestQuoter((HttpServletRequest) request); HttpServletResponse httpResponse = (HttpServletResponse) response; String mime = inferMimeType(request); if (mime == null) { httpResponse.setContentType("text/plain; charset=utf-8"); } else if (mime.startsWith("text/html")) { // HTML with unspecified encoding, we want to // force HTML with utf-8 encoding // This is to avoid the following security issue: // http://openmya.hacker.jp/hasegawa/security/utf7cs.html httpResponse.setContentType("text/html; charset=utf-8"); } else if (mime.startsWith("application/xml")) { httpResponse.setContentType("text/xml; charset=utf-8"); } chain.doFilter(quoted, httpResponse); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; // if the user is already authenticated, don't override it if (httpRequest.getRemoteUser() != null) { chain.doFilter(request, response); } else { HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(httpRequest) { @Override public Principal getUserPrincipal() { return user; } @Override public String getRemoteUser() { return username; } }; chain.doFilter(wrapper, response); } }
@Test public void testFilter() throws Exception { FilterConfig config = mockConfig("myuser"); StaticUserFilter suf = new StaticUserFilter(); suf.init(config); ArgumentCaptor<HttpServletRequestWrapper> wrapperArg = ArgumentCaptor.forClass(HttpServletRequestWrapper.class); FilterChain chain = mock(FilterChain.class); suf.doFilter(mock(HttpServletRequest.class), mock(ServletResponse.class), chain); Mockito.verify(chain).doFilter(wrapperArg.capture(), Mockito.<ServletResponse>anyObject()); HttpServletRequestWrapper wrapper = wrapperArg.getValue(); assertEquals("myuser", wrapper.getUserPrincipal().getName()); assertEquals("myuser", wrapper.getRemoteUser()); suf.destroy(); }
private HttpServletRequest wrapRequest(final HttpServletRequest request, boolean jukebox) { final String playerId = createPlayerIfNecessary(request, jukebox); return new HttpServletRequestWrapper(request) { @Override public String getParameter(String name) { // Returns the correct player to be used in PlayerService.getPlayer() if ("player".equals(name)) { return playerId; } // Support old style ID parameters. if ("id".equals(name)) { return mapId(request.getParameter("id")); } return super.getParameter(name); } }; }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(new HttpServletRequestWrapper( (HttpServletRequest) request) { @Override public String getRequestURI() { try { return URLDecoder.decode(super.getRequestURI(), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException( "Cannot decode request URI.", e); } } }, response); }
private static HttpServletRequest getWrappedHttpServletRequest(HttpServletRequest request) throws IOException { //TODO is it really necessary to wrap the request into a BufferedInputStream? // If not, then we could remove the check for multipart upload. // The check is needed as we get an IOException (Resetting to invalid mark) for files more than 8193 bytes. boolean resetSupported = true; String contentType = request.getHeader(HEADER_CONTENT_TYPE); if (contentType != null && contentType.startsWith(MULTIPART_FORM_DATA)) { resetSupported = false; } final PublicApiServletInputStream sis = new PublicApiServletInputStream(request.getInputStream(), resetSupported); HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request) { public ServletInputStream getInputStream() throws java.io.IOException { return sis; } }; return wrapper; }
@Test public void testNewSessionIdCreatedIfSessionWasInvalidated() { HttpServletRequest wrappedSimple = mock(HttpServletRequest.class); RepositoryBackedHttpSession invalidSession = mock(RepositoryBackedHttpSession.class); RepositoryBackedHttpSession newSession = mock(RepositoryBackedHttpSession.class); when(newSession.getId()).thenReturn(NEW_SESSION_ID); when(invalidSession.getId()).thenReturn(SESSION_ID); when(invalidSession.isValid()).thenReturn(false); HttpRequestWrapper wrappedHttpRequestWrapper = spy(new HttpRequestWrapper(wrappedSimple, servletContext)); wrappedHttpRequestWrapper.session = invalidSession; HttpServletRequest wrappedComplex = new HttpServletRequestWrapper(wrappedHttpRequestWrapper); HttpRequestWrapper req = new HttpRequestWrapper(wrappedComplex, servletContext); when(sessionManager.getSession(req, true, SESSION_ID)).thenReturn(invalidSession); when(sessionManager.getSession(req, true, null)).thenReturn(newSession); RepositoryBackedHttpSession session2 = req.getSession(); Assert.assertNotNull(session2); assertEquals(NEW_SESSION_ID, session2.getId()); }
/** * Test to upload a file to a part * * @throws Exception */ @Test public void uploadFileToPart() throws Exception { //Given final File fileToUpload = new File(ResourceUtil.getFilePath(ResourceUtil.SOURCE_PART_STORAGE + ResourceUtil.TEST_PART_FILENAME1)); File uploadedFile = File.createTempFile(ResourceUtil.TARGET_PART_STORAGE + ResourceUtil.FILENAME_TARGET_PART, ResourceUtil.TEMP_SUFFIX); HttpServletRequestWrapper request = Mockito.mock(HttpServletRequestWrapper.class); Collection<Part> parts = new ArrayList<>(); parts.add(new PartImpl(fileToUpload)); Mockito.when(request.getParts()).thenReturn(parts); BinaryResource binaryResource = new BinaryResource(ResourceUtil.FILENAME1, ResourceUtil.DOCUMENT_SIZE, new Date()); OutputStream outputStream = new FileOutputStream(uploadedFile); Mockito.when(request.getRequestURI()).thenReturn(ResourceUtil.WORKSPACE_ID + "/parts/" + ResourceUtil.PART_TEMPLATE_ID + "/"); Mockito.when(productService.saveFileInPartIteration(Matchers.any(PartIterationKey.class), Matchers.anyString(), Matchers.anyString(), Matchers.anyInt())).thenReturn(binaryResource); Mockito.when(storageManager.getBinaryResourceOutputStream(binaryResource)).thenReturn(outputStream); //When Response response = partBinaryResource.uploadAttachedFiles(request, ResourceUtil.WORKSPACE_ID, ResourceUtil.PART_NUMBER, ResourceUtil.VERSION, ResourceUtil.ITERATION); //Then assertNotNull(response); assertEquals(response.getStatus(), 201); assertEquals(response.getStatusInfo(), Response.Status.CREATED); //delete temp file uploadedFile.deleteOnExit(); }
@Test public void decoratedNativeRequest() { HttpServletRequest decoratedRequest = new HttpServletRequestWrapper(servletRequest); HttpServletResponse decoratedResponse = new HttpServletResponseWrapper(servletResponse); ServletWebRequest request = new ServletWebRequest(decoratedRequest, decoratedResponse); assertSame(decoratedRequest, request.getNativeRequest()); assertSame(decoratedRequest, request.getNativeRequest(ServletRequest.class)); assertSame(decoratedRequest, request.getNativeRequest(HttpServletRequest.class)); assertSame(servletRequest, request.getNativeRequest(MockHttpServletRequest.class)); assertNull(request.getNativeRequest(MultipartRequest.class)); assertSame(decoratedResponse, request.getNativeResponse()); assertSame(decoratedResponse, request.getNativeResponse(ServletResponse.class)); assertSame(decoratedResponse, request.getNativeResponse(HttpServletResponse.class)); assertSame(servletResponse, request.getNativeResponse(MockHttpServletResponse.class)); assertNull(request.getNativeResponse(MultipartRequest.class)); }
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { filterChain.doFilter(new HttpServletRequestWrapper(request) { @Override public Principal getUserPrincipal() { return new Principal() { @Override public String getName() { return PRINCIPAL_NAME; } }; } }, new HttpServletResponseWrapper(response)); }
/** * Looks for the StripesRequesetWrapper for the specific request and returns it. This is done * by checking to see if the request is a StripesRequestWrapper, and if not, successively * unwrapping the request until the StripesRequestWrapper is found. * * @param request the ServletRequest that is wrapped by a StripesRequestWrapper * @return the StripesRequestWrapper that is wrapping the supplied request * @throws IllegalStateException if the request is not wrapped by Stripes */ public static StripesRequestWrapper findStripesWrapper(ServletRequest request) { // Loop through any request wrappers looking for the stripes one while ( !(request instanceof StripesRequestWrapper) && request != null && request instanceof HttpServletRequestWrapper) { request = ((HttpServletRequestWrapper) request).getRequest(); } // If we have our wrapper after the loop exits, we're good; otherwise... if (request instanceof StripesRequestWrapper) { return (StripesRequestWrapper) request; } else { throw new IllegalStateException(String.format("Request %s made it through to some part of Stripes " + "without being wrapped in a StripesRequestWrapper. The StripesFilter is " + "responsible for wrapping the request, so it is likely that either the " + "StripesFilter is not deployed, or that its mappings do not include the " + "DispatcherServlet _and_ *.jsp. Stripes does not require that the Stripes " + "wrapper is the only request wrapper, or the outermost; only that it is present.",((HttpServletRequest)request).getRequestURL().toString())); } }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { filterChain.doFilter(new HttpServletRequestWrapper((HttpServletRequest) request) { @Override public HttpSession getSession() { throw new UnsupportedOperationException("getSession() is not supported"); } @Override public HttpSession getSession(boolean create) { if (create) { throw new UnsupportedOperationException("getSession(true) is not supported"); } return null; } }, response); }
protected HttpServletRequest createSecurityContext(HttpServletRequest request, OAuthConsumer consumer, OAuthToken accessToken) { final Principal principal = new SimplePrincipal(consumer.getKey()); final Set<String> roles = getRoles(consumer); return new HttpServletRequestWrapper(request){ @Override public Principal getUserPrincipal(){ return principal; } @Override public boolean isUserInRole(String role){ return roles.contains(role); } @Override public String getAuthType(){ return OAUTH_AUTH_METHOD; } }; }
protected HttpServletRequest createSecurityContext(HttpServletRequest request, org.jboss.resteasy.auth.oauth.OAuthConsumer consumer, OAuthToken accessToken) { // Alternatively we can have an alias associated with a given key // Example: www.messageing.service : kermit final Principal principal = new SimplePrincipal(consumer.getKey()); final Set<String> roles = getProvider().convertPermissionsToRoles(accessToken.getPermissions()); return new HttpServletRequestWrapper(request){ @Override public Principal getUserPrincipal(){ return principal; } @Override public boolean isUserInRole(String role){ return roles.contains(role); } @Override public String getAuthType(){ return OAUTH_AUTH_METHOD; } }; }
protected HttpServletRequest createSecurityContext(HttpServletRequest request, String openId) { int index = openId.lastIndexOf("/"); String name = index != -1 ? openId.substring(index + 1) : openId; final Principal principal = new SimplePrincipal(name); final Set<String> roles = getRoles(name); return new HttpServletRequestWrapper(request){ @Override public Principal getUserPrincipal(){ return principal; } @Override public boolean isUserInRole(String role){ return roles.contains(role); } @Override public String getAuthType(){ return "OpenId"; } }; }
/** * * @param req HttpServletRequest * @param resp HttpServletResponse * @throws ServletException Exception * @throws IOException Exception */ @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { RequestDispatcher rd = getServletContext().getNamedDispatcher("default"); if (null != rd) { HttpServletRequest wrapped = new HttpServletRequestWrapper(req) { public String getServletPath() { return ""; } }; rd.forward(wrapped, resp); } }
public HttpServletRequest wrapRequest( final HttpSession session, final HttpServletRequest httpReq, final Subject subject) { return new HttpServletRequestWrapper(httpReq) { private final HttpSession httpSession = session; @Override public String getRemoteUser() { return subject.getUserName(); } @Override public Principal getUserPrincipal() { return new Principal() { @Override public String getName() { return subject.getUserName(); } }; } @Override public HttpSession getSession() { return httpSession; } }; }
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain fc) throws IOException, ServletException { boolean enable = sessionStoreManager.isEnableRedisStore(); HttpServletRequest request = (HttpServletRequest) servletRequest; if ((!enable) || (!shouldFilter(request) || (request instanceof HttpRequestWrapper))) { fc.doFilter(servletRequest, servletResponse); return; } HttpServletResponse response = (HttpServletResponse) servletResponse; RequestEvent requestEvent = new RequestEvent(request, response, sessionStoreManager); HttpServletRequestWrapper requestWrapper = sessionStoreManager.getRequestWrapper(requestEvent); try { fc.doFilter(requestWrapper, servletResponse); } finally { requestEvent.completed(request, response); } }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest wrappedRequest = new HttpServletRequestWrapper((HttpServletRequest) request) { @Override public HttpSession getSession() { throw new RuntimeException("HttpSession should not be used"); } @Override public HttpSession getSession(boolean create) { if (create) { throw new RuntimeException("HttpSession should not be used"); } return null; } }; filterChain.doFilter(wrappedRequest, response); }
@Override public void handle(HttpServletRequest request, HttpServletResponse response, HandlerChain chain) throws Exception { HttpServletRequest wrapped = new HttpServletRequestWrapper(request) { @Override public String getServletPath() { return ""; } @Override public String getPathInfo() { if (pathInfo == null) { return super.getPathInfo(); } else { return pathInfo; } } }; handler.forward(wrapped, response); }