Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  //
  //  ========================================================================
  //  Copyright (c) 1995-2012 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;
 
 
 
 
 
 /* ------------------------------------------------------------ */
Resource Handler. This handle will serve static content and handle If-Modified-Since headers. No caching is done. Requests for resources that do not exist are let pass (Eg no 404's).

Org.apache.xbean.XBean:
 
 public class ResourceHandler extends HandlerWrapper
 {
     private static final Logger LOG = Log.getLogger(ResourceHandler.class);
 
     String[] _welcomeFiles={"index.html"};
     MimeTypes _mimeTypes = new MimeTypes();
     boolean _aliases;
     boolean _directory;
 
     /* ------------------------------------------------------------ */
     public ResourceHandler()
     {
     	
     }
 
     /* ------------------------------------------------------------ */
     public MimeTypes getMimeTypes()
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
     public void setMimeTypes(MimeTypes mimeTypes)
     {
          = mimeTypes;
     }
 
     /* ------------------------------------------------------------ */
    

Returns:
True if resource aliases are allowed.
 
     public boolean isAliases()
     {
         return ;
     }
 
    /* ------------------------------------------------------------ */
    
Set if resource aliases (eg symlink, 8.3 names, case insensitivity) are allowed. Allowing aliases can significantly increase security vulnerabilities. If this handler is deployed inside a ContextHandler, then the ContextHandler.isAliases() takes precedent.

Parameters:
aliases True if aliases are supported.
    public void setAliases(boolean aliases)
    {
         = aliases;
    }
    /* ------------------------------------------------------------ */
    
Get the directory option.

Returns:
true if directories are listed.
    public boolean isDirectoriesListed()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Set the directory.

Parameters:
directory true if directories are listed.
    public void setDirectoriesListed(boolean directory)
    {
         = directory;
    }
    /* ------------------------------------------------------------ */
    @Override
    public void doStart()
    throws Exception
    {
        Context scontext = ContextHandler.getCurrentContext();
         = (scontext==null?null:scontext.getContextHandler());
        if (!=null)
            =.isAliases();
        if (! && !FileResource.getCheckAliases())
            throw new IllegalStateException("Alias checking disabled");
        super.doStart();
    }
    /* ------------------------------------------------------------ */
    

Returns:
Returns the resourceBase.
    public Resource getBaseResource()
    {
        if (==null)
            return null;
        return ;
    }
    /* ------------------------------------------------------------ */
    

Returns:
Returns the base resource as a string.
    public String getResourceBase()
    {
        if (==null)
            return null;
        return .toString();
    }
    /* ------------------------------------------------------------ */
    

Parameters:
base The resourceBase to set.
    public void setBaseResource(Resource base)
    {
        =base;
    }
    /* ------------------------------------------------------------ */
    

Parameters:
resourceBase The base resource as a string.
    public void setResourceBase(String resourceBase)
    {
        try
        {
            setBaseResource(Resource.newResource(resourceBase));
        }
        catch (Exception e)
        {
            .warn(e.toString());
            .debug(e);
            throw new IllegalArgumentException(resourceBase);
        }
    }
    
    /* ------------------------------------------------------------ */
    

Returns:
Returns the stylesheet as a Resource.
    public Resource getStylesheet()
    {
    	if( != null)
    	{
    	    return ;
    	}
    	else
    	{
    	    if( == null)
    	    {
    	        try
    	        {
    	             =  Resource.newResource(this.getClass().getResource("/jetty-dir.css"));
    	        }
    	        catch(IOException e)
    	        {
    	            .warn(e.toString());
    	            .debug(e);
    	        }	 
    	    }
    	    return ;
    	}
    }
    
    /* ------------------------------------------------------------ */
    

Parameters:
stylesheet The location of the stylesheet to be used as a String.
    public void setStylesheet(String stylesheet)
    {
        try
        {
             = Resource.newResource(stylesheet);
            if(!.exists())
            {
                .warn("unable to find custom stylesheet: " + stylesheet);
                 = null;
            }
        }
    	catch(Exception e)
    	{
    		.warn(e.toString());
            .debug(e);
            throw new IllegalArgumentException(stylesheet.toString());
    	}
    }
    /* ------------------------------------------------------------ */
    

Returns:
the cacheControl header to set on all static content.
    public String getCacheControl()
    {
        return .toString();
    }
    /* ------------------------------------------------------------ */
    

Parameters:
cacheControl the cacheControl header to set on all static content.
    public void setCacheControl(String cacheControl)
    {
        =cacheControl==null?null:new ByteArrayBuffer(cacheControl);
    }
    /* ------------------------------------------------------------ */
    /*
     */
    public Resource getResource(String paththrows MalformedURLException
    {
        if (path==null || !path.startsWith("/"))
            throw new MalformedURLException(path);
        Resource base = ;
        if (base==null)
        {
            if (==null)
                return null;
            base=.getBaseResource();
            if (base==null)
                return null;
        }
        try
        {
            path=URIUtil.canonicalPath(path);
            return base.addPath(path);
        }
        catch(Exception e)
        {
            .ignore(e);
        }
        return null;
    }
    /* ------------------------------------------------------------ */
    protected Resource getResource(HttpServletRequest requestthrows MalformedURLException
    {
        String servletPath;
        String pathInfo;
        Boolean included = request.getAttribute(.) != null;
        if (included != null && included.booleanValue())
        {
            servletPath = (String)request.getAttribute(.);
            pathInfo = (String)request.getAttribute(.);
 
            if (servletPath == null && pathInfo == null)
            {
                servletPath = request.getServletPath();
                pathInfo = request.getPathInfo();
            }
        }
        else
        {
            servletPath = request.getServletPath();
            pathInfo = request.getPathInfo();
        }
        
        String pathInContext=URIUtil.addPaths(servletPath,pathInfo);
        return getResource(pathInContext);
    }
    /* ------------------------------------------------------------ */
    public String[] getWelcomeFiles()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    public void setWelcomeFiles(String[] welcomeFiles)
    {
        =welcomeFiles;
    }
    /* ------------------------------------------------------------ */
    protected Resource getWelcome(Resource directorythrows MalformedURLExceptionIOException
    {
        for (int i=0;i<.;i++)
        {
            Resource welcome=directory.addPath([i]);
            if (welcome.exists() && !welcome.isDirectory())
                return welcome;
        }
        return null;
    }
    /* ------------------------------------------------------------ */
    /*
     * @see org.eclipse.jetty.server.Handler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, int)
     */
    public void handle(String targetRequest baseRequestHttpServletRequest requestHttpServletResponse responsethrows IOExceptionServletException
    {
        if (baseRequest.isHandled())
            return;
        boolean skipContentBody = false;
        if(!..equals(request.getMethod()))
        {
            if(!..equals(request.getMethod()))
            {
                //try another handler
                super.handle(targetbaseRequestrequestresponse);
                return;
            }
            skipContentBody = true;
        }
        
        Resource resource = getResource(request);
        
        if (resource==null || !resource.exists())
        {
            if (target.endsWith("/jetty-dir.css"))
            {	                
                resource = getStylesheet();
                if (resource==null)
                    return;
                response.setContentType("text/css");
            }
            else 
            {
                //no resource - try other handlers
                super.handle(targetbaseRequestrequestresponse);
                return;
            }
        }
            
        if (! && resource.getAlias()!=null)
        {
            .info(resource+" aliased to "+resource.getAlias());
            return;
        }
        // We are going to serve something
        baseRequest.setHandled(true);
        if (resource.isDirectory())
        {
            if (!request.getPathInfo().endsWith(.))
            {
                response.sendRedirect(response.encodeRedirectURL(URIUtil.addPaths(request.getRequestURI(),.)));
                return;
            }
            Resource welcome=getWelcome(resource);
            if (welcome!=null && welcome.exists())
                resource=welcome;
            else
            {
                doDirectory(request,response,resource);
                baseRequest.setHandled(true);
                return;
            }
        }
        // set some headers
        long last_modified=resource.lastModified();
        if (last_modified>0)
        {
            long if_modified=request.getDateHeader(.);
            if (if_modified>0 && last_modified/1000<=if_modified/1000)
            {
                response.setStatus(.);
                return;
            }
        }
        Buffer mime=.getMimeByExtension(resource.toString());
        if (mime==null)
            mime=.getMimeByExtension(request.getPathInfo());
        // set the headers
        doResponseHeaders(response,resource,mime!=null?mime.toString():null);
        response.setDateHeader(.,last_modified);
        if(skipContentBody)
            return;
        // Send the content
        OutputStream out =null;
        try {out = response.getOutputStream();}
        catch(IllegalStateException e) {out = new WriterOutputStream(response.getWriter());}
        // See if a short direct method can be used?
        if (out instanceof AbstractHttpConnection.Output)
        {
            // TODO file mapped buffers
            ((AbstractHttpConnection.Output)out).sendContent(resource.getInputStream());
        }
        else
        {
            // Write content normally
            resource.writeTo(out,0,resource.length());
        }
    }
    /* ------------------------------------------------------------ */
    protected void doDirectory(HttpServletRequest request,HttpServletResponse responseResource resource)
        throws IOException
    {
        if ()
        {
            String listing = resource.getListHTML(request.getRequestURI(),request.getPathInfo().lastIndexOf("/") > 0);
            response.setContentType("text/html; charset=UTF-8");
            response.getWriter().println(listing);
        }
        else
            response.sendError(.);
    }
    /* ------------------------------------------------------------ */
    
Set the response headers. This method is called to set the response headers such as content type and content length. May be extended to add additional headers.

Parameters:
response
resource
mimeType
    protected void doResponseHeaders(HttpServletResponse responseResource resourceString mimeType)
    {
        if (mimeType!=null)
            response.setContentType(mimeType);
        long length=resource.length();
        if (response instanceof Response)
        {
            HttpFields fields = ((Response)response).getHttpFields();
            if (length>0)
                fields.putLongField(.,length);
            if (!=null)
                fields.put(.,);
        }
        else
        {
            if (length>0)
                response.setHeader(.,Long.toString(length));
            if (!=null)
                response.setHeader(.,.toString());
        }
    }
New to GrepCode? Check out our FAQ X