Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  //
  //  ========================================================================
  //  Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd.
  //  ------------------------------------------------------------------------
  //  All rights reserved. This program and the accompanying materials
  //  are made available under the terms of the Eclipse Public License v1.0
  //  and Apache License v2.0 which accompanies this distribution.
  //
  //      The Eclipse Public License is available at
 //      http://www.eclipse.org/legal/epl-v10.html
 //
 //      The Apache License v2.0 is available at
 //      http://www.opensource.org/licenses/apache2.0.php
 //
 //  You may elect to redistribute this code under either of these licenses.
 //  ========================================================================
 //
 
 package org.eclipse.jetty.server.handler;
 
 import java.util.Set;
 
 
 
 /* ------------------------------------------------------------ */
GZIP Handler This handler will gzip the content of a response if:
  • The filter is mapped to a matching path
  • The response status code is >=200 and <300
  • The content length is unknown or more than the minGzipSize initParameter or the minGzipSize is 0(default)
  • The content-type is in the comma separated list of mimeTypes set in the mimeTypes initParameter or if no mimeTypes are defined the content-type is not "application/gzip"
  • No content-encoding is specified by the resource

Compressing the content can greatly improve the network bandwidth usage, but at a cost of memory and CPU cycles. If this handler is used for static content, then use of efficient direct NIO may be prevented, thus use of the gzip mechanism of the org.eclipse.jetty.servlet.DefaultServlet is advised instead.

 
 public class GzipHandler extends HandlerWrapper
 {
     private static final Logger LOG = Log.getLogger(GzipHandler.class);
 
     protected Set<String_mimeTypes;
     protected Set<String_excluded;
     protected int _bufferSize = 8192;
     protected int _minGzipSize = 256;
     protected String _vary = "Accept-Encoding, User-Agent";
 
     /* ------------------------------------------------------------ */
    
Instantiates a new gzip handler.
 
     public GzipHandler()
     {
     }
 
     /* ------------------------------------------------------------ */
    
Get the mime types.

Returns:
mime types to set
 
     public Set<StringgetMimeTypes()
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
    
Set the mime types.

Parameters:
mimeTypes the mime types to set
 
     public void setMimeTypes(Set<StringmimeTypes)
    {
         = mimeTypes;
    }
    /* ------------------------------------------------------------ */
    
Set the mime types.

Parameters:
mimeTypes the mime types to set
    public void setMimeTypes(String mimeTypes)
    {
        if (mimeTypes != null)
        {
             = new HashSet<String>();
            StringTokenizer tok = new StringTokenizer(mimeTypes,",",false);
            while (tok.hasMoreTokens())
            {
                .add(tok.nextToken());
            }
        }
    }
    /* ------------------------------------------------------------ */
    
Get the excluded user agents.

Returns:
excluded user agents
    public Set<StringgetExcluded()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Set the excluded user agents.

Parameters:
excluded excluded user agents to set
    public void setExcluded(Set<Stringexcluded)
    {
         = excluded;
    }
    /* ------------------------------------------------------------ */
    
Set the excluded user agents.

Parameters:
excluded excluded user agents to set
    public void setExcluded(String excluded)
    {
        if (excluded != null)
        {
             = new HashSet<String>();
            StringTokenizer tok = new StringTokenizer(excluded,",",false);
            while (tok.hasMoreTokens())
                .add(tok.nextToken());
        }
    }
    /* ------------------------------------------------------------ */
    

Returns:
The value of the Vary header set if a response can be compressed.
    public String getVary()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Set the value of the Vary header sent with responses that could be compressed.

By default it is set to 'Accept-Encoding, User-Agent' since IE6 is excluded by default from the excludedAgents. If user-agents are not to be excluded, then this can be set to 'Accept-Encoding'. Note also that shared caches may cache many copies of a resource that is varied by User-Agent - one per variation of the User-Agent, unless the cache does some normalization of the UA string.

Parameters:
vary The value of the Vary header set if a response can be compressed.
    public void setVary(String vary)
    {
         = vary;
    }
    /* ------------------------------------------------------------ */
    
Get the buffer size.

Returns:
the buffer size
    public int getBufferSize()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Set the buffer size.

Parameters:
bufferSize buffer size to set
    public void setBufferSize(int bufferSize)
    {
         = bufferSize;
    }
    /* ------------------------------------------------------------ */
    
Get the minimum reponse size.

Returns:
minimum reponse size
    public int getMinGzipSize()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Set the minimum reponse size.

Parameters:
minGzipSize minimum reponse size
    public void setMinGzipSize(int minGzipSize)
    {
         = minGzipSize;
    }
    /* ------------------------------------------------------------ */
    
    @Override
    public void handle(String targetRequest baseRequestHttpServletRequest requestHttpServletResponse responsethrows IOExceptionServletException
    {
        if (!=null && isStarted())
        {
            String ae = request.getHeader("accept-encoding");
            if (ae != null && ae.indexOf("gzip")>=0 && !response.containsHeader("Content-Encoding")
                    && !..equalsIgnoreCase(request.getMethod()))
            {
                if (!=null)
                {
                    String ua = request.getHeader("User-Agent");
                    if (.contains(ua))
                    {
                        .handle(target,baseRequestrequestresponse);
                        return;
                    }
                }
                final CompressedResponseWrapper wrappedResponse = newGzipResponseWrapper(request,response);
                
                boolean exceptional=true;
                try
                {
                    .handle(targetbaseRequestrequestwrappedResponse);
                    exceptional=false;
                }
                finally
                {
                    Continuation continuation = ContinuationSupport.getContinuation(request);
                    if (continuation.isSuspended() && continuation.isResponseWrapped())   
                    {
                        continuation.addContinuationListener(new ContinuationListener()
                        {
                            public void onComplete(Continuation continuation)
                            {
                                try
                                {
                                    wrappedResponse.finish();
                                }
                                catch(IOException e)
                                {
                                    .warn(e);
                                }
                            }
                            public void onTimeout(Continuation continuation)
                            {}
                        });
                    }
                    else if (exceptional && !response.isCommitted())
                    {
                        wrappedResponse.resetBuffer();
                        wrappedResponse.noCompression();
                    }
                    else
                        wrappedResponse.finish();
                }
            }
            else
            {
                .handle(target,baseRequestrequestresponse);
            }
        }
    }

    
Allows derived implementations to replace ResponseWrapper implementation.

Parameters:
request the request
response the response
Returns:
the gzip response wrapper
    {
        return new CompressedResponseWrapper(request,response)
        {
            {
                super.setMimeTypes(GzipHandler.this.);
                super.setBufferSize(GzipHandler.this.);
                super.setMinCompressSize(GzipHandler.this.);
            }
            
            @Override
            protected AbstractCompressedStream newCompressedStream(HttpServletRequest request,HttpServletResponse responsethrows IOException
            {
                return new AbstractCompressedStream("gzip",request,this,)
                {
                    @Override
                    protected DeflaterOutputStream createStream() throws IOException
                    {
                        return new GZIPOutputStream(.getOutputStream(),);
                    }
                };
            }
            
            @Override
            protected PrintWriter newWriter(OutputStream out,String encodingthrows UnsupportedEncodingException
            {
                return GzipHandler.this.newWriter(out,encoding);
            }
        };
    }
    
    
Allows derived implementations to replace PrintWriter implementation.

Parameters:
out the out
encoding the encoding
Returns:
the prints the writer
Throws:
java.io.UnsupportedEncodingException
    protected PrintWriter newWriter(OutputStream out,String encodingthrows UnsupportedEncodingException
    {
        return encoding==null?new PrintWriter(out):new PrintWriter(new OutputStreamWriter(out,encoding));
    }
New to GrepCode? Check out our FAQ X