Java Code Examples for javax.servlet.ServletResponse

The following are top voted examples for showing how to use javax.servlet.ServletResponse. 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: EasyController   File: ActionDispatcherFilter.java   View source code 9 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;

    request.setCharacterEncoding(encoding);
    response.setCharacterEncoding(encoding);

    String target = request.getRequestURI();
    if (contextPathLength != 0) {
        target = target.substring(contextPathLength);
    }

    boolean handle = actionHandler.handle(target, request, response);

    if (!handle) {// 没有处理则放行
        chain.doFilter(request, response);
    }
}
 
Example 3
Project: xproject   File: DynamicUrlPermissionsShiroFilter.java   View source code 6 votes vote down vote up
public void doFilter(ServletRequest request, ServletResponse response,
		FilterChain chain) throws IOException, ServletException {
	try {
		getDelegateShrioFilter().doFilter(request, response, chain);
	} catch (UnknownSessionException e) {
		System.out.println(e);
		if(HttpUtils.isAsynRequest((HttpServletRequest) request)){
			Result<Object> result = new Result<Object>();
			result.setSuccess(false);
			result.setMessage("对不起,您的会话已过期,请重新登录!");
			HttpUtils.asynOutputResponse((HttpServletResponse) response, ContentType.APPLICATION_JSON, JsonUtils.object2Json(result));
		}else{
			throw e;
		}
	}
}
 
Example 4
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 5
Project: klask-io   File: JWTFilter.java   View source code 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
    throws IOException, ServletException {
    try {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String jwt = resolveToken(httpServletRequest);
        if (StringUtils.hasText(jwt)) {
            if (this.tokenProvider.validateToken(jwt)) {
                Authentication authentication = this.tokenProvider.getAuthentication(jwt);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    } catch (ExpiredJwtException eje) {
        log.info("Security exception for user {} - {}", eje.getClaims().getSubject(), eje.getMessage());
        ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
 
Example 6
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 7
Project: parabuild-ci   File: AgentManagerServlet.java   View source code 6 votes vote down vote up
/**
 * Will accept requests only from build manager.
 */
public void service(final ServletRequest request, final ServletResponse response) throws IOException, ServletException {

  // Prohibit non-remote manager address
  final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
  final String remoteAddr = httpServletRequest.getRemoteAddr();
  if (!DISABLE_SOURCE_IP_ADDRESS_CHECK && !remoteAddr.equals(BUILD_MANAGER_ADDRESS)) {
    final HttpServletResponse httpServletResponce = (HttpServletResponse) response;
    httpServletResponce.setStatus(HttpServletResponse.SC_FORBIDDEN);
    IoUtils.closeHard(request.getInputStream());
    IoUtils.closeHard(response.getOutputStream());
    return;
  }

  // Execute normally
  super.service(request, response);
}
 
Example 8
Project: ServiceServer   File: CORSFilter.java   View source code 6 votes vote down vote up
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest)request;
    String ori = req.getHeader("Origin");
    if (ori != null && allowedOrigins.contains(ori)) {
        HttpServletResponse res = (HttpServletResponse)response;
        res.setHeader("Access-Control-Allow-Origin", ori);
        res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        res.setHeader("Access-Control-Max-Age", "3600");
        res.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        res.setHeader("Access-Control-Allow-Credentials", "true");
    }
    chain.doFilter(request, response);
}
 
Example 9
Project: jira-confluence-javamelody   File: TestJiraMonitoringFilter.java   View source code 6 votes vote down vote up
/** Test.
 * @throws ServletException e
 * @throws IOException e */
@Test
public void testNoHttp() throws ServletException, IOException {
	// non http
	final FilterChain servletChain = createNiceMock(FilterChain.class);
	final ServletRequest servletRequest = createNiceMock(ServletRequest.class);
	final ServletResponse servletResponse = createNiceMock(ServletResponse.class);
	replay(config);
	replay(context);
	replay(servletRequest);
	replay(servletResponse);
	replay(servletChain);
	jiraMonitoringFilter.init(config);
	jiraMonitoringFilter.doFilter(servletRequest, servletResponse, servletChain);
	verify(config);
	verify(context);
	verify(servletRequest);
	verify(servletResponse);
	verify(servletChain);
}
 
Example 10
Project: aws-xray-sdk-java   File: AWSXRayServletFilter.java   View source code 6 votes vote down vote up
public void postFilter(ServletRequest request, ServletResponse response) {
    Segment segment = recorder.getCurrentSegment();
    if (null != segment) {
        HttpServletResponse httpServletResponse = castServletResponse(response);

        if (null != httpServletResponse) {
            Map<String, Object> responseAttributes = new HashMap<String, Object>();

            int responseCode = httpServletResponse.getStatus();
            switch (responseCode/100) {
                case 4:
                    segment.setError(true);
                    if (responseCode == 429) {
                        segment.setThrottle(true);
                    }
                    break;
                case 5:
                    segment.setFault(true);
                    break;
                default:
                    break;
            }
            responseAttributes.put("status", responseCode);


            Optional<Integer> contentLength = getContentLength(httpServletResponse);
            if (contentLength.isPresent()) {
                responseAttributes.put("content_length", contentLength.get());
            }

            segment.putHttp("response", responseAttributes);
        }

        recorder.endSegment();
    }
}
 
Example 11
Project: incubator-servicecomb-java-chassis   File: RestAsyncListener.java   View source code 6 votes vote down vote up
@Override
public void onTimeout(AsyncEvent event) throws IOException {
  // in this time, maybe:
  // 1.invocation in executor's queue
  // 2.already executing in executor
  // 3.already send response
  // to avoid concurrent, must lock request
  ServletRequest request = event.getSuppliedRequest();
  HttpServletRequestEx requestEx = (HttpServletRequestEx) request.getAttribute(RestConst.REST_REQUEST);

  synchronized (requestEx) {
    ServletResponse response = event.getAsyncContext().getResponse();
    if (!response.isCommitted()) {
      LOGGER.error("Rest request timeout, method {}, path {}.", requestEx.getMethod(), requestEx.getRequestURI());
      // invocation in executor's queue
      response.setContentType(MediaType.APPLICATION_JSON);

      // we don't know if developers declared one statusCode in contract
      // so we use cse inner statusCode here
      ((HttpServletResponse) response).setStatus(ExceptionFactory.PRODUCER_INNER_STATUS_CODE);
      PrintWriter out = response.getWriter();
      out.write(TIMEOUT_MESSAGE);
      response.flushBuffer();
    }

    request.removeAttribute(RestConst.REST_REQUEST);
  }
}
 
Example 12
Project: webside   File: RememberMeFilter.java   View source code 6 votes vote down vote up
@Override
protected boolean isAccessAllowed(ServletRequest request,
		ServletResponse response, Object mappedValue) {
	Subject subject = getSubject(request, response);

	// 如果 isAuthenticated 为 false 证明不是登录过的,同时 isRememberd 为true 证明是没登陆直接通过记住我功能进来的
	if (!subject.isAuthenticated() && subject.isRemembered()) {
		// 获取session的USERSESSION属性来看session是不是空的
		if(null == ShiroAuthenticationManager.getSessionAttribute(ShiroUtils.USERSESSION))
		{
			// 初始化
			UserEntity userEntity = (UserEntity) subject.getPrincipal();
			ShiroAuthenticationManager.setSessionAttribute(ShiroUtils.USERSESSION, userEntity);
		}
	}

	// 这个方法本来只返回 subject.isAuthenticated() 现在我们加上 subject.isRemembered()
	// 让它同时也兼容remember这种情况
	return subject.isAuthenticated() || subject.isRemembered();
}
 
Example 13
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 14
Project: springboot-shiro-cas-mybatis   File: MyShiroFilterFactoryBean.java   View source code 6 votes vote down vote up
@Override
public void doFilterInternal(ServletRequest servletRequest, ServletResponse servletResponse,
		FilterChain chain)
		throws ServletException, IOException {
	HttpServletRequest request = (HttpServletRequest)servletRequest;
	String str = request.getRequestURI().toLowerCase();
	boolean flag = true;
	int idx = 0;
	if ((idx = str.indexOf(".")) > 0){
		str = str.substring(idx);
		if (ignoreExt.contains(str.toLowerCase())){
			flag = false;
		}
	}
	if (flag){
		super.doFilterInternal(servletRequest, servletResponse, chain);
	} else {
		chain.doFilter(servletRequest, servletResponse);
	}
}
 
Example 15
Project: cas4.0.x-server-wechat   File: SafeDispatcherServletTests.java   View source code 6 votes vote down vote up
@Test
public void testService() throws ServletException, IOException {
    this.safeServlet.init(this.mockConfig);

    ServletRequest mockRequest = new MockHttpServletRequest();
    ServletResponse mockResponse = new MockHttpServletResponse();

    try {
        this.safeServlet.service(mockRequest, mockResponse);
    } catch (final ApplicationContextException ace) {
        // good, threw the exception we expected.
        return;
    }

    fail("Should have thrown ApplicationContextException since init() failed.");
}
 
Example 16
Project: yadaframework   File: CheckSessionFilter.java   View source code 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
	// FIXME per qualche strana ragione la sessione non scade se questa url viene ripetutamente chiamata!
	// Per ovviare al problema, faccio il controllo via js con un timeout pari a quello di sessione, in modo che quando arriva è già scaduta,
	// e male che vada la sessione dura il doppio del session timeout impostato (metti che un ajax rinfresca subito dopo il page load per cui il js che entra qui si trova la sessione ancora attiva e la rinfresca)
	if ((servletRequest instanceof HttpServletRequest) && (servletResponse instanceof HttpServletResponse)) {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		String requestUri = request.getRequestURI();
		if (requestUri.endsWith(COMMAND)) {
			HttpSession session = request.getSession(false);
			String result = "expired";
			if (session!=null) {
				result = "active";
			}
			if (log.isDebugEnabled()) {
				log.debug(COMMAND + " returned " + result + (session!=null?" "+session.getId():""));
			}
			Writer out = response.getWriter();
			out.write(result);
			out.close();
			return;
		} 
	}
	filterChain.doFilter(servletRequest, servletResponse);
}
 
Example 17
Project: Mastering-Java-EE-Development-with-WildFly   File: MyBarFilter.java   View source code 6 votes vote down vote up
private void doBeforeProcessing(ServletRequest request, ServletResponse response)
		throws IOException, ServletException {
	try (PrintWriter out = response.getWriter()) {
		out.print("my--");
		out.flush();
	}
}
 
Example 18
Project: ditb   File: StaticUserWebFilter.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;
  // 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);
  }
}
 
Example 19
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("/login_out.do")
                ) {

            person = (SessionUser) hsrq.getSession().getAttribute(SysConstants.SESSION_USER_KEY);
            if (person == null) {
                hsrp.sendRedirect("login.do");
                return;
            }
        }
        chain.doFilter(request, response);
    }

}
 
Example 20
Project: aem-osgi-annotation-demo   File: SampleFelixFilter.java   View source code 6 votes vote down vote up
@Override
public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {

    final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request;
    logger.info("Felix Filter: request for {}", slingRequest.getRequestPathInfo().getResourcePath());

    filterChain.doFilter(request, response);
}
 
Example 21
Project: zkAdmin   File: LoginFilter.java   View source code 6 votes vote down vote up
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    if (isLoginRequest(request, response)) {
        if (isLoginSubmission(request, response)) {
            if (log.isTraceEnabled()) {
                log.trace("Login submission detected.  Attempting to execute login.");
            }
            return executeLogin(request, response);
        } else {
            if (log.isTraceEnabled()) {
                log.trace("Login page view.");
            }
            // allow them to see the login page ;)
            return true;
        }
    } else {
        if (log.isTraceEnabled()) {
            log.trace("Attempting to access a path which requires authentication.  Forwarding to the "
                    + "Authentication url [" + getLoginUrl() + "]");
        }
        if (!((HttpServletRequest)request).getRequestURL().toString().endsWith(".json")) {
            saveRequestAndRedirectToLogin(request, response);
        } else {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println("{\"code\":-203,\"info\":\"login\"}");
            out.flush();
            out.close();
        }
        return false;
    }
}
 
Example 22
Project: demo-spring-boot-security-oauth2   File: SimpleCORSFilter.java   View source code 6 votes vote down vote up
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
	HttpServletResponse response = (HttpServletResponse) res;
	HttpServletRequest request = (HttpServletRequest) req;
	String originHeader = request.getHeader("Origin");
	response.setHeader("Access-Control-Allow-Origin", originHeader);
	response.setHeader("Access-Control-Allow-Credentials", "true");
	response.setHeader("Access-Control-Allow-Methods", "*");
	response.setHeader("Access-Control-Max-Age", "3600");
	response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Key, Authorization");
	
	if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        chain.doFilter(req, res);
    }
	
}
 
Example 23
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 24
Project: tomcat7   File: InstanceSupport.java   View source code 6 votes vote down vote up
/**
 * Notify all lifecycle event listeners that a particular event has
 * occurred for this Container.  The default implementation performs
 * this notification synchronously using the calling thread.
 *
 * @param type Event type
 * @param servlet The relevant Servlet for this event
 * @param request The servlet request we are processing
 * @param response The servlet response we are processing
 * @param exception Exception that occurred
 */
public void fireInstanceEvent(String type, Servlet servlet,
                              ServletRequest request,
                              ServletResponse response,
                              Throwable exception) {

    if (listeners.length == 0)
        return;

    InstanceEvent event = new InstanceEvent(wrapper, servlet, type,
                                            request, response, exception);
    InstanceListener interested[] = listeners;
    for (int i = 0; i < interested.length; i++)
        interested[i].instanceEvent(event);

}
 
Example 25
Project: apache-tomcat-7.0.73-with-comment   File: TestMimeHeaders.java   View source code 6 votes vote down vote up
private void setupHeadersTest(Tomcat tomcat) {
    Context ctx = tomcat.addContext("", getTemporaryDirectory()
            .getAbsolutePath());
    Tomcat.addServlet(ctx, "servlet", new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override
        public void service(ServletRequest req, ServletResponse res)
                throws ServletException, IOException {
            res.setContentType("text/plain; charset=ISO-8859-1");
            res.getWriter().write("OK");
        }
    });
    ctx.addServletMapping("/", "servlet");

    alv = new HeaderCountLogValve();
    tomcat.getHost().getPipeline().addValve(alv);
}
 
Example 26
Project: lazycat   File: ExpiresFilter.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) {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;

		if (response.isCommitted()) {
			if (log.isDebugEnabled()) {
				log.debug(sm.getString("expiresFilter.responseAlreadyCommited", httpRequest.getRequestURL()));
			}
			chain.doFilter(request, response);
		} else {
			XHttpServletResponse xResponse = new XHttpServletResponse(httpRequest, httpResponse);
			chain.doFilter(request, xResponse);
			if (!xResponse.isWriteResponseBodyStarted()) {
				// Empty response, manually trigger
				// onBeforeWriteResponseBody()
				onBeforeWriteResponseBody(httpRequest, xResponse);
			}
		}
	} else {
		chain.doFilter(request, response);
	}
}
 
Example 27
Project: jerrydog   File: InstanceSupport.java   View source code 6 votes vote down vote up
/**
 * Notify all lifecycle event listeners that a particular event has
 * occurred for this Container.  The default implementation performs
 * this notification synchronously using the calling thread.
 *
 * @param type Event type
 * @param servlet The relevant Servlet for this event
 * @param request The servlet request we are processing
 * @param response The servlet response we are processing
 */
public void fireInstanceEvent(String type, Servlet servlet,
                              ServletRequest request,
                              ServletResponse response) {

    if (listeners.length == 0)
        return;

    InstanceEvent event = new InstanceEvent(wrapper, servlet, type,
                                            request, response);
    InstanceListener interested[] = null;
    synchronized (listeners) {
        interested = (InstanceListener[]) listeners.clone();
    }
    for (int i = 0; i < interested.length; i++)
        interested[i].instanceEvent(event);

}
 
Example 28
Project: lemon   File: BeforeInvocationFilter.java   View source code 5 votes vote down vote up
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    ProxyFilterChain proxyFilterChain = new ProxyFilterChain();

    for (Filter filter : filters) {
        proxyFilterChain.setInvokeNextFilter(false);
        filter.doFilter(request, response, proxyFilterChain);

        if (!proxyFilterChain.isInvokeNextFilter()) {
            return;
        }
    }

    chain.doFilter(request, response);
}
 
Example 29
Project: lams   File: JspFactoryImpl.java   View source code 5 votes vote down vote up
PrivilegedGetPageContext(JspFactoryImpl factory, Servlet servlet,
        ServletRequest request, ServletResponse response, String errorPageURL,
        boolean needsSession, int bufferSize, boolean autoflush) {
    this.factory = factory;
    this.servlet = servlet;
    this.request = request;
    this.response = response;
    this.errorPageURL = errorPageURL;
    this.needsSession = needsSession;
    this.bufferSize = bufferSize;
    this.autoflush = autoflush;
}
 
Example 30
Project: xmanager   File: ShiroAjaxSessionFilter.java   View source code 5 votes vote down vote up
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
	HttpServletRequest req = WebUtils.toHttp(request);
	String xmlHttpRequest = req.getHeader("X-Requested-With");
	if (StringUtils.isNotBlank(xmlHttpRequest)) {
		if (xmlHttpRequest.equalsIgnoreCase("XMLHttpRequest")) {
			HttpServletResponse res = WebUtils.toHttp(response);
			// 采用res.sendError(401);在Easyui中会处理掉error,$.ajaxSetup中监听不到
			res.setHeader("oauthstatus", "401");
			return false;
		}
	}
	return super.onAccessDenied(request, response);
}
 
Example 31
Project: lemon   File: ProxyFilter.java   View source code 5 votes vote down vote up
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    if (enable) {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String contextPath = req.getContextPath();
        String requestUri = req.getRequestURI();
        String path = requestUri.substring(contextPath.length());

        // 如果在黑名单中,直接略过
        if (isExcluded(path)) {
            chain.doFilter(request, response);

            return;
        }

        // 如果符合redirect规则,进行跳转
        if (urlPatternMatcher.shouldRedirect(path)) {
            res.sendRedirect(contextPath + path + "/");

            return;
        }

        // 如果都没问题,才会继续进行判断
        if (urlPatternMatcher.matches(path)) {
            filter.doFilter(request, response, chain);
        } else {
            chain.doFilter(request, response);
        }
    } else {
        chain.doFilter(request, response);
    }
}
 
Example 32
Project: ChemistryAdministrativePortal   File: LoginFilter.java   View source code 5 votes vote down vote up
/**
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
	// TODO Auto-generated method stub
	// place your code here
	HttpServletRequest loginRequest = (HttpServletRequest) request;
	if((User)loginRequest.getSession().getAttribute("user") != null) {
		chain.doFilter(request, response);
	}
	
	else {
		loginRequest.getRequestDispatcher("/index.jsp").forward(request, response);
	}
}
 
Example 33
Project: sjk   File: LoginFilter.java   View source code 5 votes vote down vote up
/**
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
        ServletException {
    // 开始权限过滤
    // 1 判断是否登录
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    String reqPath = req.getServletPath();
    if ((reqPath.endsWith(".d") || reqPath.endsWith(".json")) && reqPath.indexOf("doLogin.d") == -1
            && reqPath.indexOf("doLogoff.d") == -1 && reqPath.indexOf("userReg.d") == -1) {
        User u = (User) req.getSession().getAttribute("user");
        if (null == u) {
            resp.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
            // PrintWriter out = resp.getWriter();
            // req.getRequestDispatcher("/login.html").forward(req,
            // resp);
            // return;
            // if (reqPath.startsWith("/user")) {
            // resp.sendError(HttpServletResponse.SC_FORBIDDEN);
            // //
            // req.getRequestDispatcher("/user/getCurUserInfo.d").forward(req,
            // resp);
            // return;
            // } else {
            // req.getRequestDispatcher("/login.html").forward(req, resp);
            // return;
            // }
        }

    }

    // logger.debug("login check ...{}" + reqPath);
    chain.doFilter(request, response);
}
 
Example 34
Project: kinota-server   File: CorsFilter.java   View source code 5 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,DELETE,PUT");
    response.setHeader("Access-Control-Allow-Headers", "Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Max-Age", "180");

    filterChain.doFilter(servletRequest, servletResponse);
}
 
Example 35
Project: servlet-auth   File: AuthRequestFilter.java   View source code 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    HttpSession session = req.getSession(false);
    String loginURI = req.getContextPath() + "/login";

    boolean loggedIn = session != null && session.getAttribute("user") != null;
    boolean loginRequest = req.getRequestURI().equals(loginURI);
    boolean resourceRequest = req.getRequestURI().startsWith(req.getContextPath() + RESOURCE_IDENTIFIER + "/");
    boolean ajaxRequest = "partial/ajax".equals(req.getHeader("Faces-Request"));

    if (loggedIn || loginRequest || resourceRequest) {
        if (!resourceRequest) {
            res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            res.setHeader("Pragma", "no-cache");
            res.setDateHeader("Expires", 0);
        }
        chain.doFilter(new AuthRequestWrapper((HttpServletRequest) request), response);
    } else if (ajaxRequest) {
        response.setContentType("text/xml");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().printf(AJAX_REDIRECT_XML, loginURI);
    } else {
        res.sendRedirect(loginURI);
    }
}
 
Example 36
Project: Purchase-order-process-template   File: HistoryFilter.java   View source code 5 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    String pathInfo = ((HttpServletRequest) servletRequest).getPathInfo();
    if (pathInfo.endsWith("comment")) {
        ((HttpServletResponse) servletResponse).sendRedirect("/api" + pathInfo.replaceAll("/engine/default/task", ""));
    }
    filterChain.doFilter(servletRequest, servletResponse);
}
 
Example 37
Project: tomcat7   File: TestStandardContext.java   View source code 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    response.setContentType("text/plain");
    response.getWriter().print("Filter");
    chain.doFilter(request, response);
}
 
Example 38
Project: easyweb   File: AjaxSessionManager.java   View source code 5 votes vote down vote up
/**
 * 获取sessionId从请求中
 *
 * @param request
 * @param response
 * @return
 */
private Serializable getReferencedSessionId(ServletRequest request, ServletResponse response) {
    String id = this.getSessionIdCookieValue(request, response);
    if (id != null) {
        request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "cookie");
    } else {
        id = this.getUriPathSegmentParamValue(request, "JSESSIONID");
        if (id == null) {
            // 获取请求头中的session
            id = WebUtils.toHttp(request).getHeader(this.authorization);
            if (id == null) {
                String name = this.getSessionIdName();
                id = request.getParameter(name);
                if (id == null) {
                    id = request.getParameter(name.toLowerCase());
                }
            }
        }
        if (id != null) {
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "url");
        }
    }

    if (id != null) {
        request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
        request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
    }

    return id;
}
 
Example 39
Project: framework   File: PayManager.java   View source code 5 votes vote down vote up
/**
 * 封装支付结果服务器通知
 * <b>注意:这个页面是支付宝服务器端自动调用这个页面的链接地址,
 * 这个页面根据支付宝反馈过来的信息修改网站的定单状态,更新完成后需要返回一个success给支付宝.,
 * 不能含有任何其它的字符包括html语言.
 * </b>
 * <p><a href="https://doc.open.alipay.com/docs/doc.htm?spm=a219a.7629140.0.0.Xh0Gbu&treeId=62&articleId=104743&docType=1">开发文档</p>
 *
 * @param servletRequest
 * @param servletResponse
 * @return
 */
public static PayResultNotifyResponse parsePayResultNotify(ServletRequest servletRequest, ServletResponse servletResponse) {
	HttpServletRequest request = (HttpServletRequest) servletRequest;
	HttpServletResponse response = (HttpServletResponse) servletResponse;
	//获取支付宝POST过来反馈信息
	Map<String, String> params = requestToMap(request);
	//获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
	if (AlipayNotify.verify(params)) {//验证成功
		return (PayResultNotifyResponse) mapToObject(params, PayResultNotifyResponse.class);
	} else {//验证失败
		return null;
	}
}
 
Example 40
Project: oscm   File: BaseBesFilterTest.java   View source code 5 votes vote down vote up
@Before
public void setup() {
    rdoMock = mock(AuthorizationRequestData.class);

    requestMock = mock(HttpServletRequest.class);

    filter = new BaseBesFilter() {
        @Override
        public void doFilter(ServletRequest arg0, ServletResponse arg1,
                FilterChain arg2) throws IOException, ServletException {
        }
    };
}