Java Code Examples for javax.servlet.ServletRequest

The following are top voted examples for showing how to use javax.servlet.ServletRequest. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: IPPR2016   File: JwtFilter.java   View source code 9 votes vote down vote up
@Override
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
    throws IOException, ServletException {
  final HttpServletRequest request = (HttpServletRequest) req;

  final String authHeader = request.getHeader("Authorization");
  if (authHeader == null || !authHeader.startsWith("Bearer ")) {
    ExceptionUtils.createUnauthorizedException("Missing or invalid Authorization header.", res);
    return;
  }

  try {
    final String token = authHeader.substring(7); // The part after "Bearer "
    final Claims claims =
        Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody();
    request.setAttribute("claims", claims);
  } catch (final Exception e) {
    ExceptionUtils.createUnauthorizedException("Invalid token", res);
    return;
  }

  chain.doFilter(req, res);
}
 
Example 2
Project: tomcat7   File: ApplicationRequest.java   View source code 7 votes vote down vote up
/**
 * Set the request that we are wrapping.
 *
 * @param request The new wrapped request
 */
@Override
public void setRequest(ServletRequest request) {

    super.setRequest(request);

    // Initialize the attributes for this request
    synchronized (attributes) {
        attributes.clear();
        Enumeration<String> names = request.getAttributeNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            Object value = request.getAttribute(name);
            attributes.put(name, value);
        }
    }

}
 
Example 3
Project: tomcat7   File: TestStandardContext.java   View source code 7 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    PrintWriter out = response.getWriter();
    out.print(getClass().getName());
    chain.doFilter(request, response);
}
 
Example 4
Project: oscm   File: AuthorizationFilter.java   View source code 6 votes vote down vote up
private void send401(ServletRequest httpRequest,
        HttpServletResponse httpResponse, HttpSession session, boolean asTM) {
    // Return 401 error
    String clientLocale = httpRequest.getLocale().getLanguage();
    if (clientLocale.equals(LOCALE_JA)) {
        clientLocale = LOCALE_DEFAULT;
    }
    httpResponse.setHeader(
            "WWW-Authenticate",
            "Basic realm=\""
                    + Messages.get(clientLocale,
                            (asTM ? "ui.config.authentication.tm"
                                    : "ui.config.authentication.appadmin"))
                    + "\"");
    httpResponse.setStatus(401);
    session.invalidate();

}
 
Example 5
Project: logistimo-web-service   File: MediaSecurityFilter.java   View source code 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
    throws IOException, ServletException {

  HttpServletRequest req = (HttpServletRequest) request;
  HttpServletResponse resp = (HttpServletResponse) response;
  String servletPath = req.getServletPath() + req.getPathInfo();
  xLogger.fine("Servlet path: ", servletPath);
  if (req.getCharacterEncoding() == null) {
    request.setCharacterEncoding(Constants.UTF8);
  }

  if (!(StringUtils.isNotBlank(servletPath) && servletPath.startsWith(MEDIA_ENDPOINT_URL))) {
    resp.sendError(HttpServletResponse.SC_NOT_FOUND);
    return;
  }
  if (filterChain != null) {
    filterChain.doFilter(request, response);
  }
}
 
Example 6
Project: zkAdmin   File: LoginFilter.java   View source code 6 votes vote down vote up
@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
    if (!((HttpServletRequest)request).getRequestURL().toString().endsWith(".json")) {
        setFailureAttribute(request, e);
        return true;
    }
    try {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        String message = e.getClass().getSimpleName();
        if ("IncorrectCredentialsException".equals(message)
                || "UnknownAccountException".equals(message)
                ) {
            out.println("{\"code\":-100010,\"info\":\"账号或密码错误\"}");
        }else if("ExcessiveAttemptsException".equals(message)){
            out.println("{\"code\":-100020,\"info\":\"密码错误次数超过限制,请10分钟后重试!\"}");
        }else if("LockedAccountException".equals(message)){
            out.println("{\"code\":-100030,\"info\":\"账号已停用!\"}");
        } else {
            out.println("{\"code\":-100500,\"info\":\"未知错误\"}");
        }
        out.flush();
        out.close();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    return false;
}
 
Example 7
Project: lazycat   File: ApplicationDispatcher.java   View source code 6 votes vote down vote up
@Override
public void dispatch(ServletRequest request, ServletResponse response) throws ServletException, IOException {
	if (Globals.IS_SECURITY_ENABLED) {
		try {
			PrivilegedDispatch dp = new PrivilegedDispatch(request, response);
			AccessController.doPrivileged(dp);
		} catch (PrivilegedActionException pe) {
			Exception e = pe.getException();

			if (e instanceof ServletException)
				throw (ServletException) e;
			throw (IOException) e;
		}
	} else {
		doDispatch(request, response);
	}
}
 
Example 8
Project: unitimes   File: XSSFilter.java   View source code 6 votes vote down vote up
/**
   * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
   *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
   */
  public void doFilter( ServletRequest request, 
          			  ServletResponse response,
          			  FilterChain chain ) throws IOException, ServletException {
      
      // Get Filter Init Parameters
      String replaceStrParam = filterConfig.getInitParameter("replace_string");
      String addlCharsParam = filterConfig.getInitParameter("additional_chars");
      
      // Set variables
      if(replaceStrParam!=null)
          replaceStr = replaceStrParam;
      if(addlCharsParam!=null)
          addlChars = addlCharsParam;
      
      // Construct allowed characters pattern
      String charPattern = "([^" + charsAllowed + addlChars + "]+)(%0A)";        
      
      // Instantiate actual filter
      RequestXSSFilter rxs = new RequestXSSFilter( 
              (HttpServletRequest) request, replaceStr, charPattern);

// Process request
chain.doFilter(rxs,response);

  }
 
Example 9
Project: lams   File: ApplicationRequest.java   View source code 6 votes vote down vote up
/**
 * Set the request that we are wrapping.
 *
 * @param request The new wrapped request
 */
public void setRequest(ServletRequest request) {

    super.setRequest(request);

    // Initialize the attributes for this request
    synchronized (attributes) {
        attributes.clear();
        Enumeration names = request.getAttributeNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            Object value = request.getAttribute(name);
            attributes.put(name, value);
        }
    }

}
 
Example 10
Project: BasicsProject   File: PageFilter.java   View source code 6 votes vote down vote up
/**这个方法完成实际的过滤操作。当客户请求访问与过滤器关联的URL的时候,Servlet过滤器将先执行doFilter方法。FilterChain参数用于访问后续过滤器。*/
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		
		//忽略不过滤页面
		if(!Statics.ignore_login_page.contains(httpRequest.getServletPath())){
			long memberId = StorageUtil.init(httpRequest.getSession()).getLoginMemberId();
			if(memberId==ReturnUtil.NOT_LOGIN_CODE){
				String url = httpRequest.getScheme()+"://"+httpRequest.getServerName()+":"+httpRequest.getServerPort()+httpRequest.getContextPath();
				DataUtil.OutStreamByResponse(httpResponse, "<script type='text/javascript'>top.location.href= '"+url+Statics.Login_Page+"';</script>");
				return;
			}
		}
		chain.doFilter(request, response);
//		httpRequest.getScheme();//协议类型			http
//		httpRequest.getServerName();//域名		mycdsxlc.f3322.net
//		httpRequest.getServerPort();//端口号		8989
//		httpRequest.getContextPath();//项目名		/Report
//		httpRequest.getServletPath();//请求页面	/web/index.jsp
//		httpRequest.getQueryString();//参数		null
	}
 
Example 11
Project: cas4.0.x-server-wechat   File: SafeDispatcherServlet.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 * @throws ApplicationContextException if the DispatcherServlet does not
 * initialize properly, but the servlet attempts to process a request.
 */
@Override
public void service(final ServletRequest req, final ServletResponse resp)
    throws ServletException, IOException {
    /*
     * Since our container calls only this method and not any of the other
     * HttpServlet runtime methods, such as doDelete(), etc., delegating
     * this method is sufficient to delegate all of the methods in the
     * HttpServlet API.
     */
    if (this.initSuccess) {
        this.delegate.service(req, resp);
    } else {
        throw new ApplicationContextException("Unable to initialize application context.");
    }
}
 
Example 12
Project: parabuild-ci   File: ExampleFilter.java   View source code 6 votes vote down vote up
/**
    * Time the processing that is performed by all subsequent filters in the
    * current filter stack, including the ultimately invoked servlet.
    *
    * @param request The servlet request we are processing
    * @param result The servlet response we are creating
    * @param chain The filter chain we are processing
    *
    * @exception IOException if an input/output error occurs
    * @exception ServletException if a servlet error occurs
    */
   public void doFilter(ServletRequest request, ServletResponse response,
                        FilterChain chain)
throws IOException, ServletException {

// Store ourselves as a request attribute (if requested)
if (attribute != null)
    request.setAttribute(attribute, this);

// Time and log the subsequent processing
long startTime = System.currentTimeMillis();
       chain.doFilter(request, response);
long stopTime = System.currentTimeMillis();
filterConfig.getServletContext().log
    (this.toString() + ": " + (stopTime - startTime) +
     " milliseconds");

   }
 
Example 13
Project: DDNS_Server   File: AdminFilter.java   View source code 6 votes vote down vote up
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    HttpSession session = request.getSession(false);

    if (session == null || session.getAttribute("LoggedUser") == null) {
        response.sendRedirect(request.getContextPath() + "/index.jsp"); // No logged-in user found, so redirect to login page.
    } else {
    	DynUser currentUser = (DynUser) session.getAttribute("LoggedUser");
    	if (!currentUser.isAdmin()) {
    		response.sendRedirect(request.getContextPath() + "/app/dashboard.jsp"); // No admin user found, so redirect to dashboard page.
    	} else {        	
    		chain.doFilter(req, res); // Logged-in user found, so just continue request.
    	}
    }
}
 
Example 14
Project: jerrydog   File: HeaderLoggerValve.java   View source code 6 votes vote down vote up
@Override
public void invoke(Request request, Response response, ValveContext valveContext) throws IOException, ServletException {
    valveContext.invokeNext(request, response);

    System.out.println("Header Logger Valve:");
    ServletRequest sreq = request.getRequest();
    if(sreq instanceof HttpServletRequest){
        HttpServletRequest hreq = (HttpServletRequest) sreq;
        Enumeration<String> headerNames = hreq.getHeaderNames();
        while (headerNames.hasMoreElements()){
            String headerName = headerNames.nextElement().toString();
            String headerValue = hreq.getHeader(headerName);
            System.out.println(headerName + ": " + headerValue);
        }
    }else {
        System.out.println("Not an HTTP Request");
    }
    System.out.println("-------------------------------------");
}
 
Example 15
Project: fuck_zookeeper   File: HTTPBasicAuth.java   View source code 6 votes vote down vote up
@Override
public void doFilter(ServletRequest req0, ServletResponse resp0,
        FilterChain chain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req0;
    HttpServletResponse response = (HttpServletResponse) resp0;

    String authorization = request.getHeader("Authorization");
    if (authorization != null) {
        String c[] = parseAuthorization(authorization);
        if (c != null && credentials.containsKey(c[0])
                && credentials.get(c[0]).equals(c[1])) {
            chain.doFilter(request, response);
            return;
        }
    }

    response.setHeader("WWW-Authenticate", "Basic realm=\"Restricted\"");
    response.sendError(401);
}
 
Example 16
Project: ssm-web   File: CheckSessionOutFilter.java   View source code 6 votes vote down vote up
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest hsrq = (HttpServletRequest) request;
    HttpServletResponse hsrp = (HttpServletResponse) response;
    String clientType = hsrq.getParameter("clientType");
    if ("WORD".equals(clientType)) {
        chain.doFilter(request, response);
    } else {
        SessionUser person = null;
        String reqPage = hsrq.getServletPath();
        if (!reqPage.trim().equals("/login.do") && !reqPage.trim().equals("/logout.do")
                ) {
            person = (SessionUser) hsrq.getSession().getAttribute(SysConstants.SESSION_USER_KEY);
            if (person == null) {
                hsrp.sendRedirect("login.do");
                return;
            }
        }
        chain.doFilter(request, response);
    }

}
 
Example 17
Project: lams   File: AsyncContextImpl.java   View source code 6 votes vote down vote up
public AsyncContextImpl(final HttpServerExchange exchange, final ServletRequest servletRequest, final ServletResponse servletResponse, final ServletRequestContext servletRequestContext, boolean requestSupplied, final AsyncContextImpl previousAsyncContext) {
    this.exchange = exchange;
    this.servletRequest = servletRequest;
    this.servletResponse = servletResponse;
    this.servletRequestContext = servletRequestContext;
    this.requestSupplied = requestSupplied;
    this.previousAsyncContext = previousAsyncContext;
    initiatingThread = Thread.currentThread();
    exchange.dispatch(SameThreadExecutor.INSTANCE, new Runnable() {
        @Override
        public void run() {
            exchange.setDispatchExecutor(null);
            initialRequestDone();
        }
    });
}
 
Example 18
Project: automat   File: TokenFilter.java   View source code 6 votes vote down vote up
public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {
	HttpServletRequest request = (HttpServletRequest) servletRequest;
	if (isWhiteReq(request.getRequestURI())) {
		chain.doFilter(request, response);
	} else {
		String token = request.getHeader("token");
		if (StringUtils.isNotBlank(token)) {
			try {
				Token tokenInfo = TokenUtil.getTokenInfo(token);
				if (tokenInfo != null) {
					Long now = System.currentTimeMillis();
					if (now - tokenInfo.getTime() < 1000 * 60 * 30) {
						String value = tokenInfo.getValue();
						TokenUtil.setTokenInfo(token, value);
						WebUtil.saveCurrentUser(request, value);
					}
				}
			} catch (Exception e) {
				logger.error("token检查发生异常:", e);
			}
		}
		// 响应
		if (DataUtil.isEmpty(WebUtil.getCurrentUser(request))) {
			response.setContentType("text/html; charset=UTF-8");
			Map<String, Object> modelMap = InstanceUtil.newLinkedHashMap();
			modelMap.put("httpCode", HttpCode.UNAUTHORIZED.value());
			modelMap.put("msg", HttpCode.UNAUTHORIZED.msg());
			modelMap.put("timestamp", System.currentTimeMillis());
			PrintWriter out = response.getWriter();
			out.println(JSON.toJSONString(modelMap));
			out.flush();
			out.close();
		} else {
			chain.doFilter(request, response);
		}
	}
}
 
Example 19
Project: oscm   File: AuthorizationFilterTest.java   View source code 6 votes vote down vote up
@Test
public void handleChangeUserPasswordRequest_errorAccountNotLocked()
        throws Exception {
    // given
    doReturn(Boolean.TRUE).when(authReqDataMock).isRequestedToChangePwd();
    doReturn("secret").when(authReqDataMock).getNewPassword();
    doReturn("secret").when(authReqDataMock).getNewPassword2();
    doReturn(userDetails).when(identityServiceMock).getUser(
            any(VOUser.class));
    doReturn("error.changePassword").when(requestMock).getAttribute(
            Constants.REQ_ATTR_ERROR_KEY);

    // when
    boolean result = authFilter
            .handleChangeUserPasswordRequest(chainMock, requestMock,
                    responseMock, authReqDataMock, identityServiceMock);

    // then
    assertFalse("Unsuccessful password change", result);
    verify(authFilter, never()).sendRedirect(any(HttpServletRequest.class),
            any(HttpServletResponse.class), anyString());
    verify(chainMock, times(2)).doFilter(any(ServletRequest.class),
            any(ServletResponse.class));
}
 
Example 20
Project: oscm   File: AuthorizationFilterTest.java   View source code 6 votes vote down vote up
@Before
public void setup() throws Exception {

    requestMock = mock(HttpServletRequest.class);
    responseMock = mock(HttpServletResponse.class);
    chainMock = mock(FilterChain.class);
    authReqDataMock = mock(AuthorizationRequestData.class);
    authSettingsMock = mock(AuthenticationSettings.class);

    authFilter = spy(new AuthorizationFilter());
    authFilter.authSettings = authSettingsMock;

    doReturn(authReqDataMock).when(authFilter).initializeRequestDataObject(
            any(HttpServletRequest.class));

    userDetails = createCustomer();
    identityServiceMock = mock(IdentityService.class);
    serviceAccessMock = mock(ServiceAccess.class);
    doReturn(userDetails).when(identityServiceMock).getCurrentUserDetails();
    doReturn(identityServiceMock).when(serviceAccessMock).getService(
            IdentityService.class);
    doNothing().when(authFilter).forward(any(String.class),
            any(ServletRequest.class), any(ServletResponse.class));

}
 
Example 21
Project: renren-fast   File: OAuth2Filter.java   View source code 6 votes vote down vote up
@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    httpResponse.setContentType("application/json;charset=utf-8");
    try {
        //处理登录失败的异常
        Throwable throwable = e.getCause() == null ? e : e.getCause();
        R r = R.error(HttpStatus.SC_UNAUTHORIZED, throwable.getMessage());

        String json = new Gson().toJson(r);
        httpResponse.getWriter().print(json);
    } catch (IOException e1) {

    }

    return false;
}
 
Example 22
Project: apache-tomcat-7.0.73-with-comment   File: ExampleFilter.java   View source code 6 votes vote down vote up
/**
 * Time the processing that is performed by all subsequent filters in the
 * current filter stack, including the ultimately invoked servlet.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 * @param chain The filter chain we are processing
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain chain)
    throws IOException, ServletException {

    // Store ourselves as a request attribute (if requested)
    if (attribute != null)
        request.setAttribute(attribute, this);

    // Time and log the subsequent processing
    long startTime = System.currentTimeMillis();
    chain.doFilter(request, response);
    long stopTime = System.currentTimeMillis();
    filterConfig.getServletContext().log
        (this.toString() + ": " + (stopTime - startTime) +
         " milliseconds");

}
 
Example 23
Project: nymph   File: EncodingFilter.java   View source code 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {
	request.setCharacterEncoding(defaultEncoding);
	response.setCharacterEncoding(defaultEncoding);
	chain.doFilter(request, response);
}
 
Example 24
Project: apache-tomcat-7.0.73-with-comment   File: TestStandardContext.java   View source code 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    PrintWriter out = response.getWriter();
    out.print(getClass().getName());
    chain.doFilter(request, response);
}
 
Example 25
Project: oscm   File: HttpMethodFilter.java   View source code 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {

    if (!(request instanceof HttpServletRequest)
            || !(response instanceof HttpServletResponse)) {
        response.getWriter().print(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String method = httpRequest.getMethod();
    if (forbiddenHttpMethods.contains(method)) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, method
                + " not allowed.");
        return;
    }

    chain.doFilter(request, response);
}
 
Example 26
Project: webside   File: RoleFilter.java   View source code 6 votes vote down vote up
@Override
protected boolean onAccessDenied(ServletRequest request,
		ServletResponse response) throws Exception {
	
		Subject subject = getSubject(request, response);  
        if (subject.getPrincipal() == null) {//表示没有登录,重定向到登录页面  
            saveRequest(request);  
            WebUtils.issueRedirect(request, response, ShiroUtils.LOGIN_URL);  
        } else {  
        	if(ShiroUtils.isAjax(request)){
    			Map<String, Object> result = new HashMap<String, Object>();
    			result.put("status", "401");
    			result.put("message", "sorry,您没有权限");
    			result.put("url", ShiroUtils.UNAUTHORIZED);
    			ShiroUtils.writeJson(response, result);
    		}else
    		{
    			if (StringUtils.hasText(ShiroUtils.UNAUTHORIZED)) {//如果有未授权页面跳转过去  
	                WebUtils.issueRedirect(request, response, ShiroUtils.UNAUTHORIZED);  
	            } else {//否则返回401未授权状态码  
	                WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);  
	            } 
    		}
        }  
	return false;
}
 
Example 27
Project: DWSurvey   File: FormAuthenticationWithLockFilter.java   View source code 6 votes vote down vote up
@Override
public boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
    AuthenticationToken token = createToken(request, response);
    if (token == null) {
        String msg = "createToken method implementation returned null. A valid non-null AuthenticationToken "
                + "must be created in order to execute a login attempt.";
        throw new IllegalStateException(msg);
    }
    if (checkIfAccountLocked(request)) {
        return onLoginFailure(token, new ExcessiveAttemptsException(), request, response);
    } else {
        if (!doLogin(request, response, token)) {
            resetAccountLock(getUsername(request));
            return false;
        }
        return true;
    }
}
 
Example 28
Project: atbash-octopus   File: WebUtils.java   View source code 6 votes vote down vote up
/**
 * Redirects the to the request url from a previously
 * {@link #saveRequest(ServletRequest) saved} request, or if there is no saved request, redirects the
 * end user to the specified {@code fallbackUrl}.  If there is no saved request or fallback url, this method
 * throws an {@link IllegalStateException}.
 * <p/>
 * This method is primarily used to support a common login scenario - if an unauthenticated user accesses a
 * page that requires authentication, it is expected that request is
 * {@link #saveRequest(ServletRequest) saved} first and then redirected to the login page. Then,
 * after a successful login, this method can be called to redirect them back to their originally requested URL, a
 * nice usability feature.
 *
 * @param request     the incoming request
 * @param response    the outgoing response
 * @param fallbackUrl the fallback url to redirect to if there is no saved request available.
 * @throws IllegalStateException if there is no saved request and the {@code fallbackUrl} is {@code null}.
 * @throws IOException           if there is an error redirecting
 */
public static void redirectToSavedRequest(ServletRequest request, ServletResponse response, String fallbackUrl)
        throws IOException {
    String successUrl = null;
    boolean contextRelative = true;
    SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(request);
    if (savedRequest != null && savedRequest.getMethod().equalsIgnoreCase(AccessControlFilter.GET_METHOD)) {
        successUrl = savedRequest.getRequestUrl();
        contextRelative = false;
    }

    if (successUrl == null) {
        successUrl = fallbackUrl;
    }

    if (successUrl == null) {
        throw new IllegalStateException("Success URL not available via saved request or via the " +
                "successUrlFallback method parameter. One of these must be non-null for " +
                "issueSuccessRedirect() to work.");
    }

    WebUtils.issueRedirect(request, response, successUrl, null, contextRelative);
}
 
Example 29
Project: lazycat   File: AsyncContextImpl.java   View source code 6 votes vote down vote up
public void setStarted(Context context, ServletRequest request, ServletResponse response,
		boolean originalRequestResponse) {

	synchronized (asyncContextLock) {
		this.request.getCoyoteRequest().action(ActionCode.ASYNC_START, this);

		this.context = context;
		this.servletRequest = request;
		this.servletResponse = response;
		this.hasOriginalRequestAndResponse = originalRequestResponse;
		this.event = new AsyncEvent(this, request, response);

		List<AsyncListenerWrapper> listenersCopy = new ArrayList<AsyncListenerWrapper>();
		listenersCopy.addAll(listeners);
		listeners.clear();
		for (AsyncListenerWrapper listener : listenersCopy) {
			try {
				listener.fireOnStartAsync(event);
			} catch (Throwable t) {
				ExceptionUtils.handleThrowable(t);
				log.warn("onStartAsync() failed for listener of type [" + listener.getClass().getName() + "]", t);
			}
		}
	}
}
 
Example 30
Project: gitplex-mit   File: GitFilter.java   View source code 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
		FilterChain chain) throws IOException, ServletException {
	HttpServletRequest httpRequest = (HttpServletRequest) request;
	HttpServletResponse httpResponse = (HttpServletResponse) response;

	try {
		if (GitSmartHttpTools.isInfoRefs(httpRequest)) {
			if (gitPlex.isReady())
				processRefs(httpRequest, httpResponse);
			else
				throw new GitException("Server is not ready");
		} else if (GitSmartHttpTools.isReceivePack(httpRequest) || GitSmartHttpTools.isUploadPack(httpRequest)) {
			if (gitPlex.isReady())
				processPacks(httpRequest, httpResponse);
			else
				throw new GitException("Server is not ready");
		} else {
			chain.doFilter(request, response);
		}
	} catch (GitException|InterruptedException|ExecutionException e) {
		logger.error("Error serving git request", e);
		GitSmartHttpTools.sendError(httpRequest, httpResponse, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
	}
}
 
Example 31
Project: simpleauth   File: SimpleAuthFilter.java   View source code 6 votes vote down vote up
@Override
public void doFilter(final ServletRequest request, final ServletResponse response,
		final FilterChain chain) throws IOException, ServletException {
	if (request instanceof HttpServletRequest) {
		final HttpServletRequest req = ((HttpServletRequest) request);
		final HttpServletResponse res = ((HttpServletResponse) response);
		final String header = req.getHeader(SimpleAuth.HTTP_HEADER);
		if (header != null) {
			final String[] sp = header.split(" ");
			// Authentication: torch TOKEN
			if (sp.length == 2) {
				final String scheme = sp[0], param = sp[1];
				if (SimpleAuth.SCHEME.equals(scheme)) {
					if (sa.verify(param)) {
						chain.doFilter(request, response);
						return;
					}
				}
			}
		}
		if (!res.isCommitted()) {
			final String err = "FORBIDDEN\r\n";
			res.reset();
			res.setStatus(HttpServletResponse.SC_FORBIDDEN);
			res.setContentLength(err.length());
			res.setContentType("text/plain");
			res.setCharacterEncoding("ISO-8859-1");
			res.setHeader("Pragma", "no-cache");
			res.setHeader("Cache-Control", "private, no-cache, no-store, must-revalidate");
			res.setHeader(getClass().getSimpleName(), "deny");
			res.getWriter().print(err);
			return;
		}
	}
	if (!response.isCommitted()) {
		response.reset();
	}
	throw new ServletException(new UnsupportedOperationException());
}
 
Example 32
Project: bootstrap   File: ErrorToJsonFilter.java   View source code 6 votes vote down vote up
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException {
	try {
		chain.doFilter(request, response);
	} catch (final Exception exception) {
		// Error before security/jax-rs management
		log.error("High level error", exception);
		
		// Catch this stack
		final HttpServletResponse response3 = (HttpServletResponse) response;
		response3.setStatus(Status.INTERNAL_SERVER_ERROR.getStatusCode());
		response3.setContentType(MediaType.APPLICATION_JSON_TYPE.toString());
		response3.setCharacterEncoding(StandardCharsets.UTF_8.name());
		response3.getOutputStream().write("{\"code\":\"internal\"}".getBytes(StandardCharsets.UTF_8));
		response3.flushBuffer();
	}

}
 
Example 33
Project: Spring-Boot-Server   File: UrlFilter.java   View source code 6 votes vote down vote up
@Override
public void doFilter(ServletRequest srequset, ServletResponse sresponse, FilterChain filterChain)
		throws IOException, ServletException {
	//new两个,一个用来遍历,一个用来换数据
	CumServlet cumRequestWrapper=new CumServlet((HttpServletRequest) srequset);
	CumServlet cumRequestWrapper2=new CumServlet((HttpServletRequest) srequset);
	Iterator<Entry<String, String[]>> iterator = cumRequestWrapper.getParams().entrySet().iterator();
	while(iterator.hasNext()){
		Entry<String, String[]> next = iterator.next();
		String key = next.getKey();
		//解码两次
		String decode = URLDecoder.decode(next.getValue()[0], "utf-8");
		String decode2 = URLDecoder.decode(decode, "utf-8");
		cumRequestWrapper2.addParameter(key, decode2);
	}
       filterChain.doFilter(cumRequestWrapper2, sresponse);  
	
}
 
Example 34
Project: lams   File: TilesUtilImpl.java   View source code 5 votes vote down vote up
/**
 * Get definition factory from appropriate servlet context.
 * @return Definitions factory or <code>null</code> if not found.
 */
public DefinitionsFactory getDefinitionsFactory(
    ServletRequest request,
    ServletContext servletContext) {
        
    return (DefinitionsFactory) servletContext.getAttribute(DEFINITIONS_FACTORY);
}
 
Example 35
Project: apache-tomcat-7.0.73-with-comment   File: StandardContext.java   View source code 5 votes vote down vote up
@Override
public boolean fireRequestDestroyEvent(ServletRequest request) {
    Object instances[] = getApplicationEventListeners();

    if ((instances != null) && (instances.length > 0)) {

        ServletRequestEvent event = 
            new ServletRequestEvent(getServletContext(), request);

        for (int i = 0; i < instances.length; i++) {
            int j = (instances.length -1) -i;
            if (instances[j] == null)
                continue;
            if (!(instances[j] instanceof ServletRequestListener))
                continue;
            ServletRequestListener listener =
                (ServletRequestListener) instances[j];
            
            try {
                listener.requestDestroyed(event);
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
                getLogger().error(sm.getString(
                        "standardContext.requestListener.requestInit",
                        instances[j].getClass().getName()), t);
                request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t);
                return false;
            }
        }
    }
    return true;
}
 
Example 36
Project: -Spring-SpringMVC-Mybatis-   File: UpmsAuthenticationFilter.java   View source code 5 votes vote down vote up
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
    Subject subject = getSubject(request, response);
    Session session = subject.getSession();
    // 判断请求类型
    String upmsType = PropertiesFileUtil.getInstance("zheng-upms-client").get("zheng.upms.type");
    session.setAttribute(UpmsConstant.UPMS_TYPE, upmsType);
    if ("client".equals(upmsType)) {
        return validateClient(request, response);
    }
    if ("server".equals(upmsType)) {
        return subject.isAuthenticated();
    }
    return false;
}
 
Example 37
Project: orange-mathoms-logging   File: RequestIdFilter.java   View source code 5 votes vote down vote up
/**
 * Filter implementation
 * <ul>
 * <li>checks whether the current request has an attached request id,
 * <li>if not, tries to get one from request headers (implements end-to-end
 * callflow traceability),
 * <li>if not, generates one
 * <li>attaches it to the request (as an attribute) and to the {@link MDC}
 * context.
 * </ul>
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
	// checks whether the current request has an attached request id
	String reqId = (String) request.getAttribute(attributeName);
	if (reqId == null) {
		// retrieve id from request headers
		if (request instanceof HttpServletRequest) {
			reqId = ((HttpServletRequest) request).getHeader(headerName);
		}
		if (reqId == null) {
			// no requestId (either from attributes or headers): generate
			// one
			reqId = Long.toHexString(System.nanoTime());
		}
		// attach to request
		request.setAttribute(attributeName, reqId);
	}

	// attach to MDC context
	MDC.put(mdcName, reqId);

	try {
		chain.doFilter(request, response);
	} finally {
		// remove from MDC context
		MDC.remove(mdcName);
	}
}
 
Example 38
Project: microprofile-open-api   File: ApiOriginFilter.java   View source code 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;
        res.addHeader("Access-Control-Allow-Origin", "*");
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        res.addHeader("Access-Control-Allow-Headers", "Content-Type, api_key, Authorization");
        chain.doFilter(request, response);
}
 
Example 39
Project: myfaces-trinidad   File: GlobalConfiguratorImpl.java   View source code 5 votes vote down vote up
@Override
public Map<String, String[]> getRequestParameterValuesMap()
{
  _checkRequest();
  if (_requestParameterValuesMap == null)
  {
    _requestParameterValuesMap = new ServletRequestParameterValuesMap((ServletRequest) getRequest());
  }
  return _requestParameterValuesMap;
}
 
Example 40
Project: acmeair-modular   File: RESTCookieSessionFilter.java   View source code 5 votes vote down vote up
@Override
public void doFilter(ServletRequest req, ServletResponse resp,	FilterChain chain) throws IOException, ServletException {
	HttpServletRequest request = (HttpServletRequest)req;
	HttpServletResponse response = (HttpServletResponse)resp;	
	
	String path = request.getContextPath() + request.getServletPath() + request.getPathInfo();

	
	if (path.endsWith(LOGIN_PATH) || path.endsWith(LOGOUT_PATH) || path.endsWith(LOADDB_PATH)) {
		// if logging in, logging out, or loading the database, let the request flow
		chain.doFilter(req, resp);
		return;
	}
	
	Cookie cookies[] = request.getCookies();
	Cookie sessionCookie = null;

	if (cookies != null) {
		for (Cookie c : cookies) {
			if (c.getName().equals(LoginREST.SESSIONID_COOKIE_NAME)) {
				sessionCookie = c;
			}
			if (sessionCookie!=null)
				break; 
		}
		String sessionId = "";
		if (sessionCookie!=null) // We need both cookie to work
			sessionId= sessionCookie.getValue().trim();
		// did this check as the logout currently sets the cookie value to "" instead of aging it out
		// see comment in LogingREST.java
		if (sessionId.equals("")) {
			response.sendError(HttpServletResponse.SC_FORBIDDEN);
			return;
		}
		
		JSONObject jsonObject = authService.validateSession(sessionId);
		if (jsonObject != null) {
			String loginUser=(String) jsonObject.get("customerid");				
			request.setAttribute(LOGIN_USER, loginUser);
			chain.doFilter(req, resp);
			return;
		} else {
			response.sendError(HttpServletResponse.SC_FORBIDDEN);
			return;
		}
	}
	
	// if we got here, we didn't detect the session cookie, so we need to return 404
	response.sendError(HttpServletResponse.SC_FORBIDDEN);
}