Java Code Examples for javax.servlet.ServletResponse

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project candlepin, under directory /src/test/java/org/candlepin/servlet/filter/.

Source file: CandlepinPersistFilterTest.java

  18 
vote

@Test public void transaction() throws IOException, ServletException {
  ServletRequest req=mock(ServletRequest.class);
  ServletResponse rsp=mock(ServletResponse.class);
  FilterChain chain=mock(FilterChain.class);
  filter.doFilter(req,rsp,chain);
  verify(work,atLeastOnce()).begin();
  verify(work,atLeastOnce()).end();
  verify(chain,atLeastOnce()).doFilter(eq(req),eq(rsp));
}
 

Example 2

From project cas, under directory /cas-server-core/src/test/java/org/jasig/cas/web/init/.

Source file: SafeDispatcherServletTests.java

  18 
vote

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 (  ApplicationContextException ace) {
    return;
  }
  fail("Should have thrown ApplicationContextException since init() failed.");
}
 

Example 3

From project entando-core-engine, under directory /src/main/java/com/agiletec/aps/tags/.

Source file: ContentNegotiationTag.java

  18 
vote

/** 
 * Declares the correct contentType as resulted from the Content Negotiation
 * @see javax.servlet.jsp.tagext.Tag#doEndTag()
 */
public int doEndTag() throws JspException {
  ServletResponse response=this.pageContext.getResponse();
  StringBuffer contentType=new StringBuffer(this.getMimeType());
  contentType.append("; charset=");
  contentType.append(this.getCharset());
  response.setContentType(contentType.toString());
  return EVAL_PAGE;
}
 

Example 4

From project jAPS2, under directory /src/com/agiletec/aps/tags/.

Source file: ContentNegotiationTag.java

  18 
vote

/** 
 * Declares the correct contentType as resulted from the Content Negotiation
 * @see javax.servlet.jsp.tagext.Tag#doEndTag()
 */
public int doEndTag() throws JspException {
  ServletResponse response=this.pageContext.getResponse();
  StringBuffer contentType=new StringBuffer(this.getMimeType());
  contentType.append("; charset=");
  contentType.append(this.getCharset());
  response.setContentType(contentType.toString());
  return EVAL_PAGE;
}
 

Example 5

From project jboss-jstl-api_spec, under directory /src/main/java/javax/servlet/jsp/jstl/fmt/.

Source file: LocaleSupport.java

  18 
vote

private static void setResponseLocale(PageContext pc,Locale locale){
  ServletResponse response=pc.getResponse();
  response.setLocale(locale);
  if (pc.getSession() != null) {
    try {
      pc.setAttribute(REQUEST_CHAR_SET,response.getCharacterEncoding(),PageContext.SESSION_SCOPE);
    }
 catch (    IllegalStateException ex) {
    }
  }
}
 

Example 6

From project jsecurity, under directory /web/src/main/java/org/apache/ki/web/servlet/.

Source file: KiFilter.java

  18 
vote

/** 
 * @since 1.0 
 */
protected ServletResponse prepareServletResponse(ServletRequest request,ServletResponse response,FilterChain chain){
  ServletResponse toUse=response;
  if (isHttpSessions() && (request instanceof KiHttpServletRequest) && (response instanceof HttpServletResponse)) {
    toUse=wrapServletResponse((HttpServletResponse)response,(KiHttpServletRequest)request);
  }
  return toUse;
}
 

Example 7

From project AdServing, under directory /modules/server/adserver/src/main/java/net/mad/ads/server/servlet/.

Source file: AdServlet.java

  17 
vote

private void execute(final AsyncContext ctx,final AdContext adcontext){
  ctx.start(new Runnable(){
    public void run(){
      ServletResponse response=ctx.getResponse();
      PrintWriter out=null;
      try {
        out=response.getWriter();
        Map<String,Object> context=new HashMap<String,Object>();
        String adselect_url=RuntimeContext.getProperties().getProperty(AdServerConstants.CONFIG.PROPERTIES.ADSERVER_SELECT_URL,"");
        String adserver_url=RuntimeContext.getProperties().getProperty(AdServerConstants.CONFIG.PROPERTIES.ADSERVER_URL,"");
        context.put("adselect_url",adselect_url);
        context.put("adserver_url",adserver_url);
        context.put("adrequest_id",adcontext.getRequestid());
        context.put("enviroment",RuntimeContext.getEnviroment().toLowerCase());
        String content=RuntimeContext.getTemplateManager().processTemplate("ads",context);
        out.println(content);
      }
 catch (      Exception e) {
        log("Problem processing task",e);
        e.printStackTrace();
      }
 finally {
        if (out != null) {
          out.close();
        }
        ctx.complete();
      }
    }
  }
);
}
 

Example 8

From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/servlet/filter/.

Source file: AbstractGZIPFilter.java

  17 
vote

/** 
 * Creates output stream with GZIP delegation.
 * @return servlet output stream
 * @throws IOException io exception
 */
private ServletOutputStream createOutputStream() throws IOException {
  final ServletResponse servletResponse=this.getResponse();
  gzipStream=new GZIPOutputStream(servletResponse.getOutputStream());
  return new ServletOutputStream(){
    @Override public void write(    final int b) throws IOException {
      gzipStream.write(b);
    }
    @Override public void flush() throws IOException {
      gzipStream.flush();
    }
    @Override public void close() throws IOException {
      gzipStream.close();
    }
    @Override public void write(    final byte[] b) throws IOException {
      gzipStream.write(b);
    }
    @Override public void write(    final byte[] b,    final int off,    final int len) throws IOException {
      gzipStream.write(b,off,len);
    }
  }
;
}
 

Example 9

From project hoop, under directory /hoop-server/src/test/java/com/cloudera/lib/servlet/.

Source file: TestHostnameFilter.java

  17 
vote

@Test public void hostname() throws Exception {
  ServletRequest request=Mockito.mock(ServletRequest.class);
  Mockito.when(request.getRemoteAddr()).thenReturn("localhost");
  ServletResponse response=Mockito.mock(ServletResponse.class);
  final AtomicBoolean invoked=new AtomicBoolean();
  FilterChain chain=new FilterChain(){
    @Override public void doFilter(    ServletRequest servletRequest,    ServletResponse servletResponse) throws IOException, ServletException {
      Assert.assertEquals(HostnameFilter.get(),"localhost");
      invoked.set(true);
    }
  }
;
  Filter filter=new HostnameFilter();
  filter.init(null);
  Assert.assertNull(HostnameFilter.get());
  filter.doFilter(request,response,chain);
  Assert.assertTrue(invoked.get());
  Assert.assertNull(HostnameFilter.get());
  filter.destroy();
}
 

Example 10

From project cloudbees-api-client, under directory /cloudbees-api-client/src/test/java/com/cloudbees/api/util/.

Source file: ProxyServer.java

  16 
vote

public void service(ServletRequest req,ServletResponse res) throws ServletException, IOException {
  final HttpServletRequest request=(HttpServletRequest)req;
  final HttpServletResponse response=(HttpServletResponse)res;
  requestsReceived++;
  if (this.authentications != null && !this.authentications.isEmpty()) {
    String proxyAuthorization=request.getHeader("Proxy-Authorization");
    if (proxyAuthorization != null && proxyAuthorization.startsWith("Basic ")) {
      String proxyAuth=proxyAuthorization.substring(6);
      String authorization=B64Code.decode(proxyAuth);
      String[] authTokens=authorization.split(":");
      String user=authTokens[0];
      String password=authTokens[1];
      if (this.authentications.get(user) == null) {
        throw new IllegalArgumentException(user + " not found in the map!");
      }
      if (sleepTime > 0) {
        try {
          Thread.sleep(sleepTime);
        }
 catch (        InterruptedException e) {
        }
      }
      String authPass=this.authentications.get(user).toString();
      if (password.equals(authPass)) {
        super.service(req,res);
        return;
      }
    }
    response.addHeader("Proxy-Authenticate","Basic realm=\"Jetty Proxy Authorization\"");
    response.setStatus(HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED);
    return;
  }
  super.service(req,res);
}
 

Example 11

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/www/http/.

Source file: Webserver.java

  15 
vote

public void forward(ServletRequest _request,ServletResponse _response) throws ServletException, java.io.IOException {
  _request.removeAttribute("javax.servlet.forward.request_uri");
  _response.reset();
  servlet.service(new HttpServletRequestWrapper((HttpServletRequest)_request){
    public java.lang.String getPathInfo(){
      return dispatchLen >= dispatchPath.length() ? null : dispatchPath.substring(dispatchLen);
    }
    public String getRequestURI(){
      return dispatchPath;
    }
    public String getQueryString(){
      return dispatchQuery;
    }
    public String getPathTranslated(){
      ServletContext context=((HttpServletRequest)getRequest()).getSession().getServletContext();
      return context.getRealPath(((HttpServletRequest)getRequest()).getContextPath());
    }
    public String getServletPath(){
      return dispatchLen <= 0 ? "" : dispatchPath.substring(0,dispatchLen);
    }
    public synchronized Enumeration<?> getAttributeNames(){
      if (super.getAttribute("javax.servlet.forward.request_uri") == null) {
        setAttribute("javax.servlet.forward.request_uri",super.getRequestURI());
        setAttribute("javax.servlet.forward.context_path",this.getContextPath());
        setAttribute("javax.servlet.forward.servlet_path",super.getServletPath());
        setAttribute("javax.servlet.forward.path_info",super.getPathInfo());
        setAttribute("javax.servlet.forward.query_string",super.getQueryString());
      }
      return super.getAttributeNames();
    }
    public Object getAttribute(    String name){
      getAttributeNames();
      return super.getAttribute(name);
    }
  }
,_response);
}
 

Example 12

From project accesointeligente, under directory /src/org/accesointeligente/server/.

Source file: GWTCacheControlFilter.java

  15 
vote

public void doFilter(ServletRequest request,ServletResponse response,FilterChain filterChain) throws IOException, ServletException {
  HttpServletRequest httpRequest=(HttpServletRequest)request;
  String requestURI=httpRequest.getRequestURI();
  if (requestURI.contains(".nocache.")) {
    Date now=new Date();
    HttpServletResponse httpResponse=(HttpServletResponse)response;
    httpResponse.setDateHeader("Date",now.getTime());
    httpResponse.setDateHeader("Expires",now.getTime() - 86400000L);
    httpResponse.setHeader("Pragma","no-cache");
    httpResponse.setHeader("Cache-control","no-cache, no-store, must-revalidate");
  }
  filterChain.doFilter(request,response);
}
 

Example 13

From project aio-webos, under directory /webui/webos/src/main/java/org/exoplatform/webos/common/filter/.

Source file: LazyDesktopPageCreation.java

  15 
vote

public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  HttpServletRequest httpRequest=(HttpServletRequest)request;
  String userName=httpRequest.getRemoteUser();
  try {
    ExoContainer container=ExoContainerContext.getCurrentContainer();
    RequestLifeCycle.begin(container);
    if (userName != null) {
      try {
        Class.forName(UIDesktopPage.class.getName());
      }
 catch (      ClassNotFoundException e) {
        throw new ServletException(e);
      }
      createPortalConfig(container,userName);
      createUserPage(container,userName);
    }
  }
 catch (  Throwable t) {
    log.debug("Could not create User Portal Config or User Desktop Page for " + userName,t);
  }
 finally {
    chain.doFilter(httpRequest,response);
    RequestLifeCycle.end();
  }
}
 

Example 14

From project airlift, under directory /http-server/src/main/java/io/airlift/http/server/.

Source file: GZipRequestFilter.java

  15 
vote

public void doFilter(ServletRequest servletRequest,ServletResponse servletResponse,FilterChain filterChain) throws IOException, ServletException {
  HttpServletRequest request=(HttpServletRequest)servletRequest;
  HttpServletResponse response=(HttpServletResponse)servletResponse;
  String contentEncoding=request.getHeader("content-encoding");
  if (equalsIgnoreCase(contentEncoding,"gzip")) {
    filterChain.doFilter(new GZipRequestWrapper(request),servletResponse);
  }
 else {
    filterChain.doFilter(request,response);
  }
}
 

Example 15

From project ajah, under directory /ajah-servlet/src/main/java/com/ajah/servlet/filter/.

Source file: JSONPFilter.java

  15 
vote

/** 
 * Wraps a JSON response with a JSONP callback, if possible and appropriate.
 * @see com.ajah.servlet.filter.BaseFilter#doFilter(javax.servlet.ServletRequest,javax.servlet.ServletResponse,javax.servlet.FilterChain)
 */
@Override public void doFilter(final ServletRequest request,final ServletResponse response,final FilterChain chain) throws IOException, ServletException {
  final String callback=request.getParameter("callback");
  if (StringUtils.isBlank(callback)) {
    log.finest("Not adding callback, no \"callback\" parameter specified");
    chain.doFilter(request,response);
    return;
  }
  final OutputStream out=response.getOutputStream();
  final GenericResponseWrapper wrapper=new GenericResponseWrapper((HttpServletResponse)response);
  chain.doFilter(request,wrapper);
  if ("application/json".equals(wrapper.getContentType()) || "jsonp".equals(request.getParameter("format"))) {
    if (log.isLoggable(Level.FINEST)) {
      log.finest("Adding callback \"" + callback + "\" to  "+ wrapper.getData().length+ " bytes");
    }
    out.write(callback.getBytes());
    out.write('(');
    out.write(wrapper.getData());
    out.write(");".getBytes());
  }
 else {
    if (log.isLoggable(Level.FINEST)) {
      log.finest("Not adding callback, response is not JSON (" + wrapper.getContentType() + ")");
    }
    out.write(wrapper.getData());
  }
  out.close();
}
 

Example 16

From project alfredo, under directory /alfredo/src/test/java/com/cloudera/alfredo/server/.

Source file: TestAuthenticationFilter.java

  15 
vote

public void testDoFilterNotAuthenticated() throws Exception {
  AuthenticationFilter filter=new AuthenticationFilter();
  try {
    FilterConfig config=Mockito.mock(FilterConfig.class);
    Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn(DummyAuthenticationHandler.class.getName());
    Mockito.when(config.getInitParameterNames()).thenReturn(new Vector(Arrays.asList(AuthenticationFilter.AUTH_TYPE)).elements());
    filter.init(config);
    HttpServletRequest request=Mockito.mock(HttpServletRequest.class);
    Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar"));
    HttpServletResponse response=Mockito.mock(HttpServletResponse.class);
    FilterChain chain=Mockito.mock(FilterChain.class);
    Mockito.doAnswer(new Answer(){
      @Override public Object answer(      InvocationOnMock invocation) throws Throwable {
        fail();
        return null;
      }
    }
).when(chain).doFilter(Mockito.<ServletRequest>anyObject(),Mockito.<ServletResponse>anyObject());
    filter.doFilter(request,response,chain);
    Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  }
  finally {
    filter.destroy();
  }
}
 

Example 17

From project alphaportal_dev, under directory /sys-src/alphaportal/web/src/test/java/alpha/portal/webapp/filter/.

Source file: MockFilterChain.java

  15 
vote

public void doFilter(final ServletRequest request,final ServletResponse response) throws IOException, ServletException {
  String uri=((HttpServletRequest)request).getRequestURI();
  final String requestContext=((HttpServletRequest)request).getContextPath();
  if (StringUtils.isNotEmpty(requestContext) && uri.startsWith(requestContext)) {
    uri=uri.substring(requestContext.length());
  }
  this.forwardURL=uri;
  this.log.debug("Forwarding to: " + uri);
  final RequestDispatcher dispatcher=request.getRequestDispatcher(uri);
  dispatcher.forward(request,response);
}
 

Example 18

From project arquillian-container-weld, under directory /weld-ee-embedded-1.1/src/main/java/org/jboss/arquillian/container/weld/ee/embedded_1_1/mock/.

Source file: MockServletContext.java

  15 
vote

/** 
 * Wicket does not use the RequestDispatcher, so this implementation just returns a dummy value.
 * @param name The name of the resource to get the dispatcher for
 * @return The dispatcher
 */
public RequestDispatcher getRequestDispatcher(final String name){
  return new RequestDispatcher(){
    public void forward(    ServletRequest servletRequest,    ServletResponse servletResponse) throws IOException {
      servletResponse.getWriter().write("FORWARD TO RESOURCE: " + name);
    }
    public void include(    ServletRequest servletRequest,    ServletResponse servletResponse) throws IOException {
      servletResponse.getWriter().write("INCLUDE OF RESOURCE: " + name);
    }
  }
;
}
 

Example 19

From project arquillian-extension-warp, under directory /impl/src/main/java/org/jboss/arquillian/warp/impl/server/execution/.

Source file: WarpFilter.java

  15 
vote

/** 
 * Detects whenever the request is HTTP request and if yes, delegates to {@link #doFilterHttp(HttpServletRequest,HttpServletResponse,FilterChain)}.
 */
@Override public void doFilter(ServletRequest req,ServletResponse resp,final FilterChain chain) throws IOException, ServletException {
  if (req instanceof HttpServletRequest && resp instanceof HttpServletResponse) {
    doFilterHttp((HttpServletRequest)req,(HttpServletResponse)resp,chain);
  }
 else {
    chain.doFilter(req,resp);
  }
}
 

Example 20

From project arquillian-weld-embedded-1.1, under directory /src/main/java/org/jboss/arquillian/container/weld/ee/embedded_1_1/mock/.

Source file: MockServletContext.java

  15 
vote

/** 
 * Wicket does not use the RequestDispatcher, so this implementation just returns a dummy value.
 * @param name The name of the resource to get the dispatcher for
 * @return The dispatcher
 */
public RequestDispatcher getRequestDispatcher(final String name){
  return new RequestDispatcher(){
    public void forward(    ServletRequest servletRequest,    ServletResponse servletResponse) throws IOException {
      servletResponse.getWriter().write("FORWARD TO RESOURCE: " + name);
    }
    public void include(    ServletRequest servletRequest,    ServletResponse servletResponse) throws IOException {
      servletResponse.getWriter().write("INCLUDE OF RESOURCE: " + name);
    }
  }
;
}
 

Example 21

From project arquillian_deprecated, under directory /containers/weld-ee-embedded-1.1/src/main/java/org/jboss/arquillian/container/weld/ee/embedded_1_1/mock/.

Source file: MockServletContext.java

  15 
vote

/** 
 * Wicket does not use the RequestDispatcher, so this implementation just returns a dummy value.
 * @param name The name of the resource to get the dispatcher for
 * @return The dispatcher
 */
public RequestDispatcher getRequestDispatcher(final String name){
  return new RequestDispatcher(){
    public void forward(    ServletRequest servletRequest,    ServletResponse servletResponse) throws IOException {
      servletResponse.getWriter().write("FORWARD TO RESOURCE: " + name);
    }
    public void include(    ServletRequest servletRequest,    ServletResponse servletResponse) throws IOException {
      servletResponse.getWriter().write("INCLUDE OF RESOURCE: " + name);
    }
  }
;
}
 

Example 22

From project azure-sdk-for-java-samples, under directory /WAAD.WebSSO.JAVA/java/code/samples/sample/src/main/java/.

Source file: FederationFilter.java

  15 
vote

@Override public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  if (request instanceof HttpServletRequest) {
    HttpServletRequest httpRequest=(HttpServletRequest)request;
    if (!httpRequest.getRequestURL().toString().contains(this.loginPage)) {
      ConfigurableFederatedLoginManager loginManager=ConfigurableFederatedLoginManager.fromRequest(httpRequest);
      boolean allowedUrl=Pattern.compile(this.allowedRegex).matcher(httpRequest.getRequestURL().toString()).find();
      if (!allowedUrl && !loginManager.isAuthenticated()) {
        HttpServletResponse httpResponse=(HttpServletResponse)response;
        String encodedReturnUrl=URLUTF8Encoder.encode(httpRequest.getRequestURL().toString());
        httpResponse.setHeader("Location",this.loginPage + "?returnUrl=" + encodedReturnUrl);
        httpResponse.setStatus(302);
        return;
      }
    }
  }
  chain.doFilter(request,response);
}
 

Example 23

From project azure4j-blog-samples, under directory /ACSExample/src/com/persistent/azure/acs/filter/.

Source file: AuthorizationFilter.java

  15 
vote

@Override public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  HttpServletRequest httpServletRequest=(HttpServletRequest)request;
  HttpServletResponse httpServletResponse=(HttpServletResponse)response;
  String acsToken=httpServletRequest.getParameter("wresult");
  if (null != acsToken && acsToken.trim().length() == 0) {
    acsToken=null;
  }
  if (!(httpServletRequest.getRequestURI().contains("claims.do") && acsToken != null)) {
    Cookie[] cookies=httpServletRequest.getCookies();
    Cookie currentCookie=null;
    String cookieName=resourceBundle.getString("acs.cookie.name");
    if (cookies != null && cookies.length > 0) {
      for (      Cookie c : cookies) {
        if (cookieName.equals(c.getName())) {
          currentCookie=c;
          break;
        }
      }
    }
    if (currentCookie == null) {
      StringBuffer loginURL=new StringBuffer();
      loginURL.append(resourceBundle.getString("acs.url"));
      loginURL.append("/v2/wsfederation?wa=wsignin1.0&wtrealm=");
      loginURL.append(resourceBundle.getString("acs.realm"));
      httpServletResponse.sendRedirect(loginURL.toString());
    }
 else {
      chain.doFilter(request,response);
    }
  }
 else {
    chain.doFilter(request,response);
  }
}
 

Example 24

From project b3log-solo, under directory /core/src/main/java/org/b3log/solo/filter/.

Source file: AuthFilter.java

  15 
vote

/** 
 * If the specified request is NOT made by an authenticated user, sends  error 403.
 * @param request the specified request
 * @param response the specified response
 * @param chain filter chain
 * @throws IOException io exception
 * @throws ServletException servlet exception
 */
@Override public void doFilter(final ServletRequest request,final ServletResponse response,final FilterChain chain) throws IOException, ServletException {
  final HttpServletResponse httpServletResponse=(HttpServletResponse)response;
  final HttpServletRequest httpServletRequest=(HttpServletRequest)request;
  try {
    LoginProcessor.tryLogInWithCookie(httpServletRequest,httpServletResponse);
    final GeneralUser currentUser=userService.getCurrentUser(httpServletRequest);
    if (null == currentUser) {
      LOGGER.warning("The request has been forbidden");
      httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
      return;
    }
    final String currentUserEmail=currentUser.getEmail();
    LOGGER.log(Level.FINER,"Current user email[{0}]",currentUserEmail);
    if (users.isSoloUser(currentUserEmail)) {
      chain.doFilter(request,response);
      return;
    }
    LOGGER.warning("The request has been forbidden");
    httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
  }
 catch (  final Exception e) {
    httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
  }
}
 

Example 25

From project Blitz, under directory /src/com/laxser/blitz/.

Source file: BlitzFilter.java

  15 
vote

/** 
 * ???????? BlitzFilter ???????????????????????????????????????????????????????????????? ????????????????????litz??????????????????????????????eb?????????????????
 */
@Override public void doFilter(ServletRequest request,final ServletResponse response,final FilterChain filterChain) throws IOException, ServletException {
  final HttpServletRequest httpRequest=(HttpServletRequest)request;
  final HttpServletResponse httpResponse=(HttpServletResponse)response;
  if (logger.isDebugEnabled()) {
    StringBuffer sb=httpRequest.getRequestURL();
    String query=httpRequest.getQueryString();
    if (query != null && query.length() > 0) {
      sb.append("?").append(query);
    }
    logger.debug(httpRequest.getMethod() + " " + sb.toString());
  }
  supportsBlitzpipe(httpRequest);
  final RequestPath requestPath=new RequestPath(httpRequest);
  if (quicklyPass(requestPath)) {
    notMatched(filterChain,httpRequest,httpResponse,requestPath);
    return;
  }
  boolean matched=false;
  try {
    final Blitz Blitz=new Blitz(modules,mappingTree,httpRequest,httpResponse,requestPath);
    matched=Blitz.start();
  }
 catch (  Throwable exception) {
    throwServletException(requestPath,exception);
  }
  if (!matched) {
    notMatched(filterChain,httpRequest,httpResponse,requestPath);
  }
}
 

Example 26

From project CalendarPortlet, under directory /src/main/java/org/jasig/portlet/calendar/mvc/.

Source file: AggregationAwareFilterBean.java

  15 
vote

@Override public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  if (this.elementsProvider.getIncludedType((HttpServletRequest)request) == Included.AGGREGATED) {
    if (logger.isDebugEnabled()) {
      logger.debug("Aggregation enabled, delegating to filter: " + this.filter);
    }
    this.filter.doFilter(request,response,chain);
  }
 else {
    if (logger.isDebugEnabled()) {
      logger.debug("Aggregation disabled, skipping filter: " + this.filter);
    }
    chain.doFilter(request,response);
  }
}
 

Example 27

From project CampusLifePortlets, under directory /src/main/java/org/jasig/portlet/campuslife/mvc/.

Source file: AggregationAwareFilterBean.java

  15 
vote

@Override public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  if (this.elementsProvider.getIncludedType((HttpServletRequest)request) == Included.AGGREGATED) {
    if (logger.isDebugEnabled()) {
      logger.debug("Aggregation enabled, delegating to filter: " + this.filter);
    }
    this.filter.doFilter(request,response,chain);
  }
 else {
    if (logger.isDebugEnabled()) {
      logger.debug("Aggregation disabled, skipping filter: " + this.filter);
    }
    chain.doFilter(request,response);
  }
}
 

Example 28

From project capedwarf-blue, under directory /appidentity/src/main/java/org/jboss/capedwarf/appidentity/.

Source file: GAEFilter.java

  15 
vote

public void doFilter(ServletRequest req,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  HttpServletRequest request=new CapedwarfHttpServletRequestWrapper((HttpServletRequest)req);
  ApiProxy.Delegate previous=ApiProxy.getDelegate();
  JBossDelegate delegate=JBossDelegate.INSTANCE;
  ApiProxy.setDelegate(delegate);
  try {
    delegate.addRequest(req);
    chain.doFilter(request,response);
  }
  finally {
    delegate.removeRequest();
    ApiProxy.setDelegate(previous);
  }
}
 

Example 29

From project Carolina-Digital-Repository, under directory /access-security/src/main/java/edu/unc/lib/dl/security/access/.

Source file: SpoofShibbolethHeadersFilter.java

  15 
vote

public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  if (request instanceof HttpServletRequest) {
    String members=(String)((HttpServletRequest)request).getHeader("isMemberOf");
    LOG.debug("Unspoofed isMemberOf: " + members);
    if (!(((HttpServletRequest)request).getServletPath().startsWith("/js/") || ((HttpServletRequest)request).getServletPath().startsWith("/css/") || ((HttpServletRequest)request).getServletPath().startsWith("/images/"))) {
      request=new javax.servlet.http.HttpServletRequestWrapper((HttpServletRequest)request){
        @Override public String getHeader(        String name){
          if ("isMemberOf".equals(name)) {
            return isMemberOfHeader;
          }
 else {
            return super.getHeader(name);
          }
        }
        @Override public String getRemoteUser(){
          return remoteUser;
        }
      }
;
      LOG.warn("SpoofShibbolethHeadersFilter: remoteUser = " + remoteUser);
      LOG.warn("SpoofShibbolethHeadersFilter: isMemberOf header = " + isMemberOfHeader);
    }
    chain.doFilter(request,response);
  }
 else {
    throw new RuntimeException("Not an HTTP request.");
  }
}
 

Example 30

From project Coffee-Framework, under directory /coffeeframework-core/src/main/java/coffee/.

Source file: Cafeteria.java

  15 
vote

public static CoffeeRequestContext createRequestContext(ServletRequest request,ServletResponse response,ServletContext servletContext){
  HttpServletRequest httpRequest=(HttpServletRequest)request;
  CoffeeRequestContext context=new CoffeeRequestContext();
  context.setRequest(request);
  context.setResponse(response);
  context.setServletContext(servletContext);
  if (servletContext != null) {
    CoffeeApplicationContext applicationContext=getOrCreateApplicationContext(servletContext);
    context.setApplicationContext(applicationContext);
    context.setRegisteredTagLibs(applicationContext.getRegisteredTagLibs());
  }
  if (httpRequest != null) {
    context.put("contextPath",httpRequest.getContextPath());
    context.put("path",httpRequest.getRequestURI());
  }
  return context;
}
 

Example 31

From project com.idega.content, under directory /src/java/com/idega/content/filter/.

Source file: ContentDispatcher.java

  15 
vote

public void doFilter(ServletRequest srequest,ServletResponse sresponse,FilterChain chain) throws IOException, ServletException {
  HttpServletRequest request=(HttpServletRequest)srequest;
  String jackrabbitBasePath="/repository/default";
  if (contentRepository.equals(CONTENT_REPOSITORY_JACKRABBIT)) {
    String url=getURIMinusContextPath(request);
    String newUrl=jackrabbitBasePath + url;
    RequestDispatcher dispatcher=request.getRequestDispatcher(newUrl);
    dispatcher.include(srequest,sresponse);
  }
 else {
    chain.doFilter(srequest,sresponse);
  }
}
 

Example 32

From project cometd, under directory /cometd-java/cometd-java-server/src/test/java/org/cometd/server/.

Source file: SlowConnectionTest.java

  15 
vote

public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  try {
    chain.doFilter(request,response);
  }
 catch (  EofException x) {
    exceptionLatch.countDown();
    throw x;
  }
}
 

Example 33

From project components-ness-tracking, under directory /src/main/java/com/nesscomputing/tracking/.

Source file: TrackingFilter.java

  15 
vote

@Override public void doFilter(@Nonnull ServletRequest request,@Nonnull ServletResponse response,@Nonnull FilterChain chain) throws IOException, ServletException {
  final HttpServletRequest req=(HttpServletRequest)request;
  final HttpServletResponse res=(HttpServletResponse)response;
  try {
    if (request.getAttribute(ThreadDelegatingScopeFilter.THREAD_DELEGATING_SCOPE_ACTIVE) == null) {
      LOG.warn("Called the tracking filter before the ThreadDelegatingScopeFilter. Tracking will not work. You need to reshuffle your guice modules to bind the filters in the right order!");
    }
 else {
      final TrackingToken trackingToken=scopedProvider.get();
      final UUID trackingUUID=trackingTokenProvider.get(new ServletApiAdapter(req));
      trackingToken.setValue(trackingUUID);
      if (trackingUUID != null) {
        request.setAttribute(X_NESS_TRACK,trackingUUID);
        res.setHeader(X_NESS_TRACK,trackingUUID.toString());
      }
    }
  }
  finally {
    chain.doFilter(request,response);
  }
}
 

Example 34

From project ConferenceProgramPortlet, under directory /src/main/java/org/jasig/portlet/conference/program/mvc/.

Source file: AggregationAwareFilterBean.java

  15 
vote

@Override public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  if (this.elementsProvider.getIncludedType((HttpServletRequest)request) == Included.AGGREGATED) {
    if (logger.isDebugEnabled()) {
      logger.debug("Aggregation enabled, delegating to filter: " + this.filter);
    }
    this.filter.doFilter(request,response,chain);
  }
 else {
    if (logger.isDebugEnabled()) {
      logger.debug("Aggregation disabled, skipping filter: " + this.filter);
    }
    chain.doFilter(request,response);
  }
}
 

Example 35

From project conversation, under directory /spi/src/test/java/org/jboss/seam/conversation/support/.

Source file: RealTestFilter.java

  15 
vote

public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  String cid=request.getParameter("cid");
  System.err.println("Testing ..." + cid + ", sessionId = "+ ((HttpServletRequest)request).getSession().getId());
  Assert.assertNotNull(bean);
  Conversation conversation=bean.getConversation();
  Assert.assertNotNull(conversation);
  if (cid == null) {
    conversation.begin(cId);
  }
 else {
    Assert.assertEquals(cId,conversation.getId());
  }
  try {
    chain.doFilter(request,response);
  }
  finally {
    if (cid != null)     conversation.end();
  }
}
 

Example 36

From project core_4, under directory /impl/src/main/java/org/richfaces/webapp/.

Source file: PushFilter.java

  15 
vote

public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
    HttpServletRequest httpReq=(HttpServletRequest)request;
    HttpServletResponse httpResp=(HttpServletResponse)response;
    if ("GET".equals(httpReq.getMethod()) && httpReq.getQueryString() != null && httpReq.getQueryString().contains("__richfacesPushAsync")) {
      if (pushServlet == null) {
        pushServlet=new PushServlet();
        pushServlet.init(servletConfig);
      }
      pushServlet.doGet(httpReq,httpResp);
      return;
    }
  }
  chain.doFilter(request,response);
}
 

Example 37

From project core_5, under directory /exo.core.component.security.core/src/main/java/org/exoplatform/services/security/j2ee/websphere/.

Source file: WebsphereFilter.java

  15 
vote

/** 
 * Do filter. Remove ltpa token cookie when we are going on public context, nothing to do otherwise.
 */
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  HttpServletRequest httpRequest=(HttpServletRequest)request;
  HttpServletResponse httpResponse=(HttpServletResponse)response;
  if (httpRequest.getQueryString() == null && httpRequest.getRequestURI() != null && httpRequest.getRequestURI().contains("/public")) {
    removeLtpaTokenCookie(httpRequest,httpResponse);
  }
 else   if (httpRequest.getQueryString() != null && httpRequest.getQueryString().contains("UIPortalComponentLogin") && httpRequest.getRequestURI() != null && httpRequest.getRequestURI().contains("/public")) {
    removeLtpaTokenCookie(httpRequest,httpResponse);
  }
  chain.doFilter(request,response);
}
 

Example 38

From project Cours-3eme-ann-e, under directory /Java/tomcat/examples/WEB-INF/classes/filters/.

Source file: ExampleFilter.java

  15 
vote

/** 
 * 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 {
  if (attribute != null)   request.setAttribute(attribute,this);
  long startTime=System.currentTimeMillis();
  chain.doFilter(request,response);
  long stopTime=System.currentTimeMillis();
  filterConfig.getServletContext().log(this.toString() + ": " + (stopTime - startTime)+ " milliseconds");
}
 

Example 39

From project cxf-dosgi, under directory /dsw/cxf-dsw/src/main/java/org/apache/cxf/dosgi/dsw/handlers/.

Source file: SecurityDelegatingHttpContext.java

  15 
vote

public void doFilter(ServletRequest request,ServletResponse response) throws IOException, ServletException {
  if (current < filters.length && !response.isCommitted()) {
    Filter filter=filters[current++];
    LOG.info("doFilter() on " + filter);
    filter.doFilter(request,response,this);
  }
}
 

Example 40

From project demoiselle-contrib, under directory /demoiselle-fuselage/src/main/java/br/gov/frameworkdemoiselle/fuselage/filter/.

Source file: AuthorizerURL.java

  15 
vote

@Override public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  if (!config.isWebfilterEnabled()) {
    chain.doFilter(request,response);
    return;
  }
  this.request=(HttpServletRequest)request;
  String url=this.request.getRequestURI().replaceAll("^/.+?/","/");
  if (isPublicURL(url) || hasPermission(url))   chain.doFilter(request,response);
 else   redirect(response,getContext() + config.getLoginPage());
}
 

Example 41

From project dev-examples, under directory /misc-demo/src/main/java/org/richfaces/demo/.

Source file: TestIdentityFilter.java

  15 
vote

public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  HttpServletRequestWrapper wrapper=new HttpServletRequestWrapper((HttpServletRequest)request){
    private UserBean getUserBean(){
      HttpSession session=getSession(false);
      if (session != null) {
        return (UserBean)session.getAttribute("userBean");
      }
      return null;
    }
    @Override public boolean isUserInRole(    String role){
      UserBean userBean=getUserBean();
      if (userBean != null) {
        return userBean.isUserInRole(role);
      }
      return false;
    }
    @Override public Principal getUserPrincipal(){
      UserBean userBean=getUserBean();
      if (userBean != null) {
        return userBean.getPrincipal();
      }
      return null;
    }
    @Override public String getRemoteUser(){
      UserBean userBean=getUserBean();
      if (userBean != null) {
        return userBean.getRolename();
      }
      return null;
    }
  }
;
  chain.doFilter(wrapper,response);
}
 

Example 42

From project dolphin, under directory /dolphinmaple/src/com/tan/filter/.

Source file: EncodingFilter.java

  15 
vote

public final void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws IOException, ServletException {
  if (encoding != null) {
    req.setCharacterEncoding(encoding);
  }
  chain.doFilter(req,res);
}
 

Example 43

From project EasySOA, under directory /easysoa-registry/easysoa-registry-rest-miner/src/main/java/org/easysoa/records/filters/.

Source file: ExchangeRecordServletFilterImpl.java

  15 
vote

/** 
 * Process the filter 
 */
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  if (exchangeHandler != null) {
    logger.info("Filtering a EasySOA API request");
    if (!(request instanceof CopyHttpServletResponse)) {
      request=new CopyHttpServletRequest((HttpServletRequest)request);
    }
    if (!(response instanceof CopyHttpServletResponse)) {
      response=new CopyHttpServletResponse((HttpServletResponse)response);
    }
  }
  chain.doFilter(request,response);
  if (exchangeHandler != null) {
    if (request instanceof HttpServletRequest) {
      try {
        InMessage inMessage=new InMessage((CopyHttpServletRequest)request);
        OutMessage outMessage=new OutMessage((CopyHttpServletResponse)response);
        this.exchangeHandler.handleMessage(inMessage,outMessage);
      }
 catch (      Exception e) {
        logger.error("An error occurred during the exchange handling",e);
      }
    }
  }
}
 

Example 44

From project egov-data, under directory /easyCompany2/src/main/java/egovframework/rte/tex/com/.

Source file: EgovAccessDeniedHandlerImpl.java

  15 
vote

public void handle(ServletRequest request,ServletResponse response,AccessDeniedException accessDeniedException) throws IOException, ServletException {
  if (errorPage != null) {
    ((HttpServletRequest)request).setAttribute(SPRING_SECURITY_ACCESS_DENIED_EXCEPTION_KEY,accessDeniedException);
    ((HttpServletResponse)response).sendRedirect(errorPage);
  }
  if (!response.isCommitted()) {
    ((HttpServletResponse)response).sendError(HttpServletResponse.SC_FORBIDDEN,accessDeniedException.getMessage());
  }
}
 

Example 45

From project exo-training, under directory /gxt-showcase/src/main/java/com/sencha/gxt/examples/resources/server/.

Source file: EntityManagerFilter.java

  15 
vote

public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  EntityManager em=null;
  try {
    em=factory.createEntityManager();
    EntityManagerUtil.MANAGERS.set(em);
    chain.doFilter(request,response);
    EntityManagerUtil.MANAGERS.remove();
  }
  finally {
    try {
      if (em != null)       em.close();
    }
 catch (    Throwable t) {
      t.printStackTrace();
    }
  }
}
 

Example 46

From project flatpack-java, under directory /demo-server/src/main/java/com/getperka/flatpack/demo/server/.

Source file: DummyAuthenticator.java

  15 
vote

@Override public Authentication validateRequest(ServletRequest request,ServletResponse response,boolean mandatory) throws ServerAuthException {
  HttpServletRequest req=(HttpServletRequest)request;
  DummyPrincipal principal;
  if (req.getParameter("isAdmin") != null) {
    principal=new DummyPrincipal("Hacker T. Admin",Roles.ADMIN);
  }
 else {
    principal=DummyPrincipal.NOBODY;
  }
  return new UserAuthentication(getAuthMethod(),new DefaultUserIdentity(null,principal,new String[]{principal.getRole()}));
}
 

Example 47

From project gatein-sso, under directory /agent/src/main/java/org/gatein/sso/agent/filter/.

Source file: AbstractLogoutFilter.java

  15 
vote

public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  HttpServletRequest httpRequest=(HttpServletRequest)request;
  HttpServletResponse httpResponse=(HttpServletResponse)response;
  boolean isLogoutInProgress=this.isLogoutInProgress(httpRequest);
  if (isLogoutInProgress) {
    if (httpRequest.getSession().getAttribute("SSO_LOGOUT_FLAG") == null) {
      httpRequest.getSession().setAttribute("SSO_LOGOUT_FLAG",Boolean.TRUE);
      String redirectUrl=this.getRedirectUrl(httpRequest);
      redirectUrl=httpResponse.encodeRedirectURL(redirectUrl);
      httpResponse.sendRedirect(redirectUrl);
      return;
    }
 else {
      httpRequest.getSession().removeAttribute("SSO_LOGOUT_FLAG");
    }
  }
  chain.doFilter(request,response);
}
 

Example 48

From project gatein-toolbox, under directory /CoreOrganizationInitializer/src/main/java/org/exoplatform/core/component/organization/initializer/.

Source file: TriggerInitializerFilter.java

  15 
vote

public void doFilter(ServletRequest servletRequest,ServletResponse servletResponse,FilterChain filterChain) throws IOException, ServletException {
  if (log.isTraceEnabled()) {
    log.trace("filter in progress. checkFolders=" + checkFolders + ", TriggerListenersForGroups="+ triggerListenersForGroups);
  }
  HttpServletRequest httpServletRequest=(HttpServletRequest)servletRequest;
  if (httpServletRequest.getRemoteUser() != null && httpServletRequest.getSession().getAttribute(ATTR_FLAG_NAME) == null) {
    ExoContainer container=ExoContainerContext.getCurrentContainer();
    OrganizationListenersInitializerService initializer=(OrganizationListenersInitializerService)container.getComponentInstanceOfType(OrganizationListenersInitializerService.class);
    OrganizationService orgService=(OrganizationService)container.getComponentInstanceOfType(OrganizationService.class);
    RequestLifeCycle.begin(container);
    try {
      String username=httpServletRequest.getRemoteUser();
      User user=orgService.getUserHandler().findUserByName(username);
      initializer.treatUser(user,checkFolders);
      if (triggerListenersForGroups) {
        Collection<Group> groups=orgService.getGroupHandler().findGroupsOfUser(username);
        for (        Group group : groups) {
          initializer.treatGroup(group,checkFolders);
        }
      }
      httpServletRequest.getSession().setAttribute(ATTR_FLAG_NAME,"true");
    }
 catch (    Exception e) {
      log.error("Error occured in TriggerInitializerFilter",e);
    }
 finally {
      RequestLifeCycle.end();
    }
  }
  filterChain.doFilter(servletRequest,servletResponse);
}
 

Example 49

From project gengweibo, under directory /src/com/gengweibo/web/.

Source file: SessionFilter.java

  15 
vote

public void doFilter(ServletRequest request,ServletResponse response,FilterChain filter) throws IOException, ServletException {
  String api=request.getParameter("api");
  if (null == api) {
    String queryString=((HttpServletRequest)request).getQueryString();
    if (queryString.length() > 0) {
      Pattern pattern=Pattern.compile("(\\?|&){0,1}api=(.*?)&{0,1}");
      Matcher matcher=pattern.matcher(queryString);
      if (matcher.matches() && matcher.groupCount() >= 2) {
        api=matcher.group(2);
      }
    }
  }
  if (null != api && !"link".equalsIgnoreCase(api) && !"logout".equalsIgnoreCase(api) && !"flush".equalsIgnoreCase(api) && null == ((HttpServletRequest)request).getSession().getAttribute(Account.ACCOUNT_SESSION_KEY)) {
    ((HttpServletResponse)response).sendRedirect(((HttpServletRequest)request).getContextPath() + "/error.jsp?desc=UnLogin");
    return;
  }
  filter.doFilter(request,response);
}
 

Example 50

From project gmc, under directory /src/org.gluster.storage.management.gateway/src/org/gluster/storage/management/gateway/filters/.

Source file: AuthenticationFailureFilter.java

  15 
vote

@Override public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws IOException, ServletException {
  HttpServletRequest request=(HttpServletRequest)req;
  if (request.getRequestURI().contains("download")) {
    chain.doFilter(req,res);
    return;
  }
  CharResponseWrapper wrapper=new CharResponseWrapper((HttpServletResponse)res);
  chain.doFilter(req,wrapper);
  if (wrapper.getStatus() == Response.Status.UNAUTHORIZED.ordinal()) {
    PrintWriter out=res.getWriter();
    out.println("<status><code>1</code><message>Authentication Failed!</message></status>");
  }
}
 

Example 51

From project GNDMS, under directory /gndms/src/de/zib/gndms/gndms/security/.

Source file: LocalRequestSkippingChannelProcessingFilter.java

  15 
vote

@Override public void doFilter(final ServletRequest req,final ServletResponse res,final FilterChain chain) throws IOException, ServletException {
  final String remoteAddr=req.getRemoteAddr();
  logger.info("request from: " + remoteAddr);
  if (remoteAddr.equals(req.getLocalAddr()))   chain.doFilter(req,res);
 else   super.doFilter(req,res,chain);
}
 

Example 52

From project guice-jit-providers, under directory /extensions/persist/src/com/google/inject/persist/.

Source file: PersistFilter.java

  15 
vote

public void doFilter(final ServletRequest servletRequest,final ServletResponse servletResponse,final FilterChain filterChain) throws IOException, ServletException {
  unitOfWork.begin();
  try {
    filterChain.doFilter(servletRequest,servletResponse);
  }
  finally {
    unitOfWork.end();
  }
}
 

Example 53

From project Guit, under directory /src/main/java/com/guit/server/crawling/.

Source file: CrawlingFilter.java

  15 
vote

@Override public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  HttpServletRequest r=(HttpServletRequest)request;
  String query=r.getQueryString();
  if (query == null || !query.contains("_escaped_fragment_=")) {
    chain.doFilter(request,response);
  }
 else {
    String reqUrl=r.getRequestURL().toString();
    String queryString=r.getQueryString();
    if (queryString != null) {
      reqUrl+="?" + queryString;
    }
    URL fetchUrl=new URL(snapshootService + "/ajaxcrawler?url=" + URLEncoder.encode(reqUrl,"UTF-8"));
    response.setContentType("text/html");
    response.setCharacterEncoding("ISO-8859-1");
    ServletOutputStream out=response.getOutputStream();
    InputStream in=fetchUrl(fetchUrl);
    if (in == null) {
      out.print("<html><head></head><body></body></html>");
      return;
    }
    final byte[] bytes=new byte[4096];
    int bytesRead=in.read(bytes);
    while (bytesRead > -1) {
      out.write(bytes,0,bytesRead);
      bytesRead=in.read(bytes);
    }
  }
}
 

Example 54

From project guj.com.br, under directory /src/br/com/caelum/guj/vraptor/filter/.

Source file: BookmarkableURIFilter.java

  15 
vote

@Override public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws IOException, ServletException {
  HttpServletRequest request=(HttpServletRequest)req;
  HttpServletResponse response=(HttpServletResponse)res;
  ConverterMatcher converters=new ConverterMatcher(AllBookmarkableToCompatibleConverters.get(request.getRequestURI()));
  if (converters.oneMatched()) {
    String compatibleURI=converters.getConverter().convert();
    if (converters.shortBookmarkableURI()) {
      redirectUsingCache(request,response,compatibleURI);
    }
 else {
      setRequestAttributesToCanonicalLink(request,converters);
      request.getRequestDispatcher(compatibleURI).forward(request,response);
    }
  }
 else {
    chain.doFilter(request,response);
  }
}
 

Example 55

From project hadoop_framework, under directory /webapp/src/main/java/org/sleuthkit/web/sampleapp/server/.

Source file: SecurityFilter.java

  15 
vote

@Override public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws IOException, ServletException {
  boolean authorized=false;
  HttpSession session=((HttpServletRequest)req).getSession();
  String authVal=(String)session.getAttribute("SAMPLE_GWT_AUTH");
  if (authVal != null)   authorized=authVal.equals("y");
  if (authorized) {
    chain.doFilter(req,res);
  }
 else {
    String username=req.getParameter("username");
    String password=req.getParameter("password");
    if (username != null && password != null) {
      if (checkCredentials(username,password)) {
        session.setAttribute("SAMPLE_GWT_AUTH","y");
        session.setMaxInactiveInterval(SESSION_TIMEOUT * 60);
        ((HttpServletResponse)res).sendRedirect("/sampleapp/SampleApp.jsp");
      }
 else {
        String loginUrl="/sampleapp/login.jsp?failed=true";
        ((HttpServletResponse)res).sendRedirect(loginUrl);
      }
    }
 else {
      String loginUrl="/sampleapp/login.jsp";
      ((HttpServletResponse)res).sendRedirect(loginUrl);
    }
  }
}
 

Example 56

From project harmony, under directory /harmony.common.serviceinterface/src/main/java/org/opennaas/extensions/idb/serviceinterface/utils/.

Source file: CommonServletFilter.java

  15 
vote

@Override public void doFilter(final ServletRequest arg0,final ServletResponse arg1,final FilterChain arg2) throws IOException, ServletException {
  if (null != this.servletFiler) {
    this.servletFiler.doFilter(arg0,arg1,arg2);
  }
 else {
    arg2.doFilter(arg0,arg1);
  }
}
 

Example 57

From project Hesperid, under directory /server/src/main/java/ch/astina/hesperid/installer/web/services/.

Source file: TapestryDelayedFilter.java

  15 
vote

public final void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  if (!installed) {
    HttpServletRequest httpRequest=(HttpServletRequest)request;
    if (httpRequest.getServletPath().equals(com.spreadthesource.tapestry.installer.InternalConstants.RESTART_URI)) {
      this.start();
      ((HttpServletResponse)response).sendRedirect(httpRequest.getContextPath());
    }
 else {
      try {
        handler.service(httpRequest,(HttpServletResponse)response);
        return;
      }
  finally {
        registry.cleanupThread();
      }
    }
    return;
  }
  chain.doFilter(request,response);
}
 

Example 58

From project http-testing-harness, under directory /server-provider/src/main/java/org/sonatype/tests/http/server/jetty/impl/.

Source file: ProxyTestServlet.java

  15 
vote

@Override public void service(ServletRequest request,ServletResponse res) throws ServletException, IOException {
  HttpServletRequest req=(HttpServletRequest)request;
  Log.debug(req.getPathInfo());
  if (principal != null) {
    String header=req.getHeader("Proxy-Authorization");
    HttpServletResponse response=(HttpServletResponse)res;
    if (header == null) {
      response.setStatus(HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED);
      response.addHeader("Proxy-Authenticate","Basic realm=\"Test Server\"");
      response.sendError(HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED);
      return;
    }
 else {
      String data=header.substring("BASIC ".length());
      data=new String(B64Code.decode(data));
      Log.debug(data);
      String[] creds=data.split(":");
      if (!creds[0].equals(principal) || !creds[1].equals(password)) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
      }
    }
  }
  super.service(request,res);
}
 

Example 59

From project httpobjects, under directory /servlet/src/main/java/org/httpobjects/servlet/.

Source file: ServletFilter.java

  15 
vote

@Override public void doFilter(ServletRequest basicRequest,ServletResponse basicResponse,FilterChain chain) throws IOException, ServletException {
  final HttpServletRequest request=(HttpServletRequest)basicRequest;
  final HttpServletResponse response=(HttpServletResponse)basicResponse;
  final String path=request.getRequestURI();
  final boolean invocationHappened=invoker().invokeFirstPathMatchIfAble(path,request,response);
  if (!invocationHappened) {
    chain.doFilter(basicRequest,basicResponse);
  }
}
 

Example 60

From project https-utils, under directory /src/main/java/org/italiangrid/utils/https/.

Source file: PasswordProtectFilter.java

  15 
vote

/** 
 * {@inheritDoc} 
 */
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  String password=Strings.safeTrimOrNullString(request.getParameter(PASSWORD_PARAM_NAME));
  if (requestPassword != null && !requestPassword.equals(password)) {
    ((HttpServletResponse)response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    return;
  }
  chain.doFilter(request,response);
}
 

Example 61

From project huiswerk, under directory /print/zxing-1.6/zxingorg/src/com/google/zxing/web/.

Source file: DoSFilter.java

  15 
vote

public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  if (isBanned(request)) {
    HttpServletResponse servletResponse=(HttpServletResponse)response;
    servletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
  }
 else {
    chain.doFilter(request,response);
  }
}
 

Example 62

From project iJetty, under directory /console/webapp/src/main/java/org/mortbay/ijetty/console/.

Source file: CacheFilter.java

  15 
vote

public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  try {
    HttpServletRequest httpRequest=(HttpServletRequest)request;
    ((HttpServletResponse)response).setHeader("Cache-Control","no-store");
  }
  finally {
    chain.doFilter(request,response);
  }
}
 

Example 63

From project inspektr, under directory /inspektr-common/src/main/java/com/github/inspektr/common/web/.

Source file: ClientInfoThreadLocalFilter.java

  15 
vote

public void doFilter(final ServletRequest request,final ServletResponse response,final FilterChain filterChain) throws IOException, ServletException {
  try {
    final ClientInfo clientInfo;
    if (otherHeader == null || otherHeader.isEmpty()) {
      clientInfo=new ClientInfo((HttpServletRequest)request);
    }
 else {
      clientInfo=new ClientInfo((HttpServletRequest)request,this.otherHeader);
    }
    ClientInfoHolder.setClientInfo(clientInfo);
    filterChain.doFilter(request,response);
  }
  finally {
    ClientInfoHolder.clear();
  }
}
 

Example 64

From project IOCipherServer, under directory /src/Acme/Serve/.

Source file: Serve.java

  15 
vote

public void forward(ServletRequest _request,ServletResponse _response) throws ServletException, java.io.IOException {
  _request.removeAttribute("javax.servlet.forward.request_uri");
  _response.reset();
  servlet.service(new HttpServletRequestWrapper((HttpServletRequest)_request){
    public java.lang.String getPathInfo(){
      return dispatchLen >= dispatchPath.length() ? null : dispatchPath.substring(dispatchLen);
    }
    public String getRequestURI(){
      return dispatchPath;
    }
    public String getQueryString(){
      return dispatchQuery;
    }
    public String getPathTranslated(){
      return getRequest().getRealPath(getPathInfo());
    }
    public String getServletPath(){
      return dispatchLen <= 0 ? "" : dispatchPath.substring(0,dispatchLen);
    }
    public synchronized java.util.Enumeration getAttributeNames(){
      if (super.getAttribute("javax.servlet.forward.request_uri") == null) {
        setAttribute("javax.servlet.forward.request_uri",super.getRequestURI());
        setAttribute("javax.servlet.forward.context_path",this.getContextPath());
        setAttribute("javax.servlet.forward.servlet_path",super.getServletPath());
        setAttribute("javax.servlet.forward.path_info",super.getPathInfo());
        setAttribute("javax.servlet.forward.query_string",super.getQueryString());
      }
      return super.getAttributeNames();
    }
    public Object getAttribute(    String name){
      getAttributeNames();
      return super.getAttribute(name);
    }
  }
,_response);
}
 

Example 65

From project ipdburt, under directory /iddb-web/src/main/java/iddb/web/security/service/.

Source file: UserServiceFilter.java

  15 
vote

@Override public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  HttpServletResponse resp=(HttpServletResponse)response;
  HttpServletRequest req=(HttpServletRequest)request;
  CommonUserService service=(CommonUserService)UserServiceFactory.getUserService();
  Subject s=service.findUserSession(req);
  if (s == null) {
    log.debug("No authenticated session found");
    service.cleanUp();
    s=new AnonymousSubject();
  }
  if (haveAccess(s,(HttpServletRequest)request,resp)) {
    try {
      chain.doFilter(request,response);
    }
  finally {
      service.cleanUp();
    }
  }
}
 

Example 66

From project java-cas-client, under directory /cas-client-core/src/main/java/org/jasig/cas/client/authentication/.

Source file: AuthenticationFilter.java

  15 
vote

public final void doFilter(final ServletRequest servletRequest,final ServletResponse servletResponse,final FilterChain filterChain) throws IOException, ServletException {
  final HttpServletRequest request=(HttpServletRequest)servletRequest;
  final HttpServletResponse response=(HttpServletResponse)servletResponse;
  final HttpSession session=request.getSession(false);
  final Assertion assertion=session != null ? (Assertion)session.getAttribute(CONST_CAS_ASSERTION) : null;
  if (assertion != null) {
    filterChain.doFilter(request,response);
    return;
  }
  final String serviceUrl=constructServiceUrl(request,response);
  final String ticket=retrieveTicketFromRequest(request);
  final boolean wasGatewayed=this.gateway && this.gatewayStorage.hasGatewayedAlready(request,serviceUrl);
  if (CommonUtils.isNotBlank(ticket) || wasGatewayed) {
    filterChain.doFilter(request,response);
    return;
  }
  final String modifiedServiceUrl;
  log.debug("no ticket and no assertion found");
  if (this.gateway) {
    log.debug("setting gateway attribute in session");
    modifiedServiceUrl=this.gatewayStorage.storeGatewayInformation(request,serviceUrl);
  }
 else {
    modifiedServiceUrl=serviceUrl;
  }
  if (log.isDebugEnabled()) {
    log.debug("Constructed service url: " + modifiedServiceUrl);
  }
  final String urlToRedirectTo=CommonUtils.constructRedirectUrl(this.casServerLoginUrl,getServiceParameterName(),modifiedServiceUrl,this.renew,this.gateway);
  if (log.isDebugEnabled()) {
    log.debug("redirecting to \"" + urlToRedirectTo + "\"");
  }
  response.sendRedirect(urlToRedirectTo);
}
 

Example 67

From project jBilling, under directory /src/java/com/sapienter/jbilling/client/authentication/.

Source file: StaticAuthenticationFilter.java

  15 
vote

/** 
 * Perform authentication using the configured username and password. This filter does not allow anonymous authentication. If a user is already logged in anonymously (if the filter chain puts anonymous authentication before this filter), the token will be removed and a real authentication attempt will be made.
 * @param req servlet request
 * @param res servlet response
 * @param chain filter chain
 * @throws IOException
 * @throws ServletException
 */
public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws IOException, ServletException {
  final HttpServletRequest request=(HttpServletRequest)req;
  final HttpServletResponse response=(HttpServletResponse)res;
  String username=getUsername() != null ? getUsername().trim() : "";
  String password=getPassword() != null ? getPassword() : "";
  if (isAuthenticationRequired(username)) {
    UsernamePasswordAuthenticationToken authRequest=new UsernamePasswordAuthenticationToken(username,password);
    authRequest.setDetails(getAuthenticationDetailsSource().buildDetails(request));
    Authentication authResult;
    try {
      authResult=getAuthenticationManager().authenticate(authRequest);
    }
 catch (    AuthenticationException failed) {
      SecurityContextHolder.getContext().setAuthentication(null);
      getRememberMeServices().loginFail(request,response);
      getAuthenticationEntryPoint().commence(request,response,failed);
      return;
    }
    SecurityContextHolder.getContext().setAuthentication(authResult);
    getRememberMeServices().loginSuccess(request,response,authResult);
  }
  chain.doFilter(request,response);
}
 

Example 68

From project jboss-as-quickstart, under directory /kitchensink-html5-mobile/src/main/java/org/jboss/as/quickstarts/html5_mobile/util/.

Source file: JSONPRequestFilter.java

  15 
vote

@Override public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  if (!(request instanceof HttpServletRequest)) {
    throw new ServletException("Only HttpServletRequest requests are supported");
  }
  final HttpServletRequest httpRequest=(HttpServletRequest)request;
  final HttpServletResponse httpResponse=(HttpServletResponse)response;
  String callback=getCallbackMethod(httpRequest);
  if (!isJSONPRequest(callback)) {
    chain.doFilter(request,response);
  }
 else {
    if (!SAFE_PRN.matcher(callback).matches()) {
      throw new ServletException("JSONP Callback method '" + CALLBACK_METHOD + "' parameter not valid function");
    }
    final ByteArrayOutputStream byteStream=new ByteArrayOutputStream();
    HttpServletResponseWrapper responseWrapper=new HttpServletResponseWrapper(httpResponse){
      @Override public ServletOutputStream getOutputStream() throws IOException {
        return new ServletOutputStream(){
          @Override public void write(          int b) throws IOException {
            byteStream.write(b);
          }
        }
;
      }
      @Override public PrintWriter getWriter() throws IOException {
        return new PrintWriter(byteStream);
      }
    }
;
    chain.doFilter(request,responseWrapper);
    response.setContentType(CONTENT_TYPE);
    response.setCharacterEncoding("UTF-8");
    response.getOutputStream().write((callback + "(").getBytes());
    response.getOutputStream().write(byteStream.toByteArray());
    response.getOutputStream().write(");".getBytes());
  }
}
 

Example 69

From project jboss-servlet-api_spec, under directory /src/main/java/javax/servlet/http/.

Source file: HttpServlet.java

  15 
vote

/** 
 * Dispatches client requests to the protected <code>service</code> method. There's no need to override this method.
 * @param req	the {@link HttpServletRequest} object thatcontains the request the client made of the servlet
 * @param res	the {@link HttpServletResponse} object thatcontains the response the servlet returns to the client				
 * @exception IOException	if an input or output error occurswhile the servlet is handling the HTTP request
 * @exception ServletException	if the HTTP request cannotbe handled
 * @see javax.servlet.Servlet#service
 */
public void service(ServletRequest req,ServletResponse res) throws ServletException, IOException {
  HttpServletRequest request;
  HttpServletResponse response;
  try {
    request=(HttpServletRequest)req;
    response=(HttpServletResponse)res;
  }
 catch (  ClassCastException e) {
    throw new ServletException("non-HTTP request or response");
  }
  service(request,response);
}
 

Example 70

From project jbossportletbridge, under directory /core/portletbridge-impl/src/main/java/org/jboss/portletbridge/bridge/scope/.

Source file: BridgeRequestScopeUtil.java

  15 
vote

public static boolean isExcludedByDefinition(String key,Object value){
  if (null != value && (value instanceof PortletConfig || value instanceof PortletContext || value instanceof PortletRequest|| value instanceof PortletResponse|| value instanceof PortletSession|| value instanceof PortletPreferences|| value instanceof PortalContext|| value instanceof FacesContext|| value instanceof ExternalContext|| value instanceof ServletConfig|| value instanceof ServletContext|| value instanceof ServletRequest|| value instanceof ServletResponse|| value instanceof HttpSession)) {
    return true;
  }
  return isNamespaceMatch(key,"javax.portlet.") || isNamespaceMatch(key,"javax.portlet.faces.") || isNamespaceMatch(key,"javax.faces.")|| isNamespaceMatch(key,"javax.servlet.")|| isNamespaceMatch(key,"javax.servlet.include.")|| isNamespaceMatch(key,AbstractExternalContext.INITIAL_REQUEST_ATTRIBUTES_NAMES);
}
 

Example 71

From project jbpm-plugin, under directory /jbpm/src/main/java/hudson/jbpm/.

Source file: JbpmContextFilter.java

  15 
vote

public void doFilter(ServletRequest servletRequest,ServletResponse servletResponse,FilterChain filterChain) throws IOException, ServletException {
  String actorId=null;
  if (servletRequest instanceof HttpServletRequest) {
    HttpServletRequest httpServletRequest=(HttpServletRequest)servletRequest;
    Principal userPrincipal=httpServletRequest.getUserPrincipal();
    if (userPrincipal != null) {
      actorId=userPrincipal.getName();
    }
  }
  if (actorId == null) {
    Authentication auth=Hudson.getAuthentication();
    if (auth != null) {
      actorId=auth.getName();
    }
  }
  JbpmContext jbpmContext=getJbpmConfiguration().createJbpmContext(jbpmContextName);
  try {
    if (isAuthenticationEnabled) {
      jbpmContext.setActorId(actorId);
    }
    filterChain.doFilter(servletRequest,servletResponse);
  }
  finally {
    jbpmContext.close();
  }
}
 

Example 72

From project jdonframework, under directory /JdonAccessory/src/com/jdon/bussinessproxy/remote/.

Source file: HessianToJdonServlet.java

  15 
vote

/** 
 * Servlet to handle incoming Hessian requests and invoke HessianToJdonRequestProcessor.
 * @param req ServletRequest
 * @param resp ServletResponse
 * @throws javax.servlet.ServletException If errors occur
 * @throws java.io.IOException If IO errors occur
 */
@Override public void service(final ServletRequest req,final ServletResponse resp) throws ServletException, IOException {
  HttpServletRequest request=(HttpServletRequest)req;
  HttpServletResponse response=(HttpServletResponse)resp;
  final String beanName=request.getPathInfo().substring(1);
  htorp.process(beanName,request,response);
}
 

Example 73

From project jetty-project, under directory /jetty-jboss/src/main/java/org/mortbay/jetty/servlet/jsr77/.

Source file: Jsr77ServletHolder.java

  15 
vote

public void handle(Request baseRequest,ServletRequest request,ServletResponse response) throws ServletException, UnavailableException, IOException {
  long startTime=0L;
  long endTime=0L;
  try {
    startTime=System.currentTimeMillis();
    super.handle(baseRequest,request,response);
  }
  finally {
    endTime=System.currentTimeMillis();
    TimeStatisticImpl statistic=(TimeStatisticImpl)_servletStats.getServiceTime();
    statistic.addSample(endTime - startTime,endTime);
  }
}
 

Example 74

From project Jetwick, under directory /src/main/java/de/jetwick/ui/raw/.

Source file: ResourceFilter.java

  15 
vote

@Override public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  HttpServletResponse rsp=(HttpServletResponse)response;
  SimpleDateFormat formatter=new SimpleDateFormat(Helper.cacheDateFormatString);
  formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
  int minutes=30 * 24 * 60;
  rsp.setHeader("Cache-Control","public, max-age=" + minutes * 60);
  chain.doFilter(request,response);
}
 

Example 75

From project jforum2, under directory /src/net/jforum/util/legacy/clickstream/.

Source file: ClickstreamFilter.java

  15 
vote

/** 
 * Processes the given request and/or response.
 * @param request The request
 * @param response The response
 * @param chain The processing chain
 * @throws IOException If an error occurs
 * @throws ServletException If an error occurs
 */
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  if (request.getAttribute(FILTER_APPLIED) == null) {
    request.setAttribute(FILTER_APPLIED,Boolean.TRUE);
    String bot=BotChecker.isBot((HttpServletRequest)request);
    if (bot != null && log.isDebugEnabled()) {
      log.debug("Found a bot: " + bot);
    }
    request.setAttribute(ConfigKeys.IS_BOT,Boolean.valueOf(bot != null));
  }
  chain.doFilter(request,response);
}
 

Example 76

From project jibu, under directory /jibu-web/jibu-core-extjs/src/main/java/org/gaixie/jibu/security/servlet/.

Source file: LoginFilter.java

  15 
vote

public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws IOException, ServletException {
  HttpSession ses=((HttpServletRequest)req).getSession(false);
  boolean allowedRequest=false;
  if (null != ses) {
    if (null != ses.getAttribute("username")) {
      allowedRequest=true;
    }
  }
  if (!allowedRequest) {
    ((HttpServletResponse)res).sendRedirect("Login.x");
    return;
  }
  ((HttpServletResponse)res).setHeader("Pragma","no-cache");
  ((HttpServletResponse)res).setHeader("Cache-Control","no-cache,no-store,max-age=0");
  chain.doFilter(req,res);
}
 

Example 77

From project jira-hudson-integration, under directory /hudson-apiv2-plugin/src/main/java/com/marvelution/hudson/plugins/apiv2/servlet/filter/.

Source file: HudsonAPIV2ServletFilter.java

  15 
vote

/** 
 * {@inheritDoc}
 */
@Override public void doFilter(ServletRequest request,ServletResponse response,FilterChain filterChain) throws IOException, ServletException {
  if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
    final HttpServletRequestWrapper servletRequest=new HttpServletRequestWrapper((HttpServletRequest)request);
    String requestUri=servletRequest.getPathInfo();
    if (StringUtils.isNotBlank(requestUri) && requestUri.startsWith("/")) {
      requestUri=requestUri.substring(1);
    }
    LOGGER.log(Level.FINE,"Got a request from URI: " + requestUri + " with Accept Header: "+ servletRequest.getHeader("Accept"));
    if (StringUtils.isNotBlank(requestUri) && requestUri.startsWith(BaseRestResource.BASE_REST_URI)) {
      validateRuntimeDelegate();
      LOGGER.log(Level.FINE,"Got a REST request, forwarding it to the Wink RestFilter");
      FilteredHttpServletResponse servletResponse=new FilteredHttpServletResponse((HttpServletResponse)response);
      restServlet.service(servletRequest,servletResponse);
      if ((!(servletResponse.isCommitted())) && (servletResponse.getStatusCode() == 404)) {
        LOGGER.log(Level.FINE,"Filter " + this.getClass().getName() + " did not match a resource so letting request continue on FilterChain");
        servletResponse.setStatus(200);
        filterChain.doFilter(request,response);
      }
    }
 else {
      LOGGER.log(Level.FINE,"No REST request, forwarding request to the next ServletFilter");
      filterChain.doFilter(request,response);
    }
  }
 else {
    LOGGER.log(Level.FINE,"No HttpServletRequest and HttpServletResponse, forwarding request to the next ServletFilter");
    filterChain.doFilter(request,response);
  }
}