/*******************************************************************************
 * Copyright (c) 2014 IBH SYSTEMS GmbH.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBH SYSTEMS GmbH - initial API and implementation
 *******************************************************************************/
package de.dentrassi.osgi.web;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.io.ByteStreams;

import de.dentrassi.osgi.web.util.Requests;
import de.dentrassi.osgi.web.util.Responses;

public class ResourceRequestHandler implements RequestHandler
{
    private final URL url;

    private final long lastModified;

    public ResourceRequestHandler ( final URL url, final long lastModified )
    {
        this.url = url;
        this.lastModified = lastModified;
    }

    @Override
    public void process ( final HttpServletRequest request, final HttpServletResponse response ) throws IOException
    {
        boolean isGet = request.getMethod ().equalsIgnoreCase ( "get" );

        if ( !isGet && request.getMethod ().equalsIgnoreCase ( "head" ) )
        {
            if ( Requests.isNotModified ( request, this.lastModified ) )
            {
                return;
            }
            isGet = true; // handle as GET
        }

        if ( !isGet )
        {
            Responses.methodNotAllowed ( request, response );
            return;
        }

        response.setDateHeader ( Responses.LAST_MODIFIED, this.lastModified );

        try ( InputStream in = this.url.openStream () )
        {
            ByteStreams.copy ( in, response.getOutputStream () );
        }
    }
}

@@ -551,16 +551,54 @@
 i.web;%0A%0A
+import java.io.FileNotFoundException;%0A
 import j
@@ -1769,32 +1769,102 @@
 urn;%0A        %7D%0A%0A
+        try ( InputStream in = this.url.openStream () )%0A        %7B%0A    
         response
@@ -1926,25 +1926,28 @@
 fied );%0A
-%0A
+    
         
 try ( In
@@ -1942,128 +1942,227 @@
     
-try ( InputStream in = this.url.openStream () )%0A        %7B%0A            ByteStreams.copy ( in, response.getOutputStream ()
+ByteStreams.copy ( in, response.getOutputStream () );%0A        %7D%0A        catch ( final FileNotFoundException e )%0A        %7B%0A            // caused by accessing a directory%0A            Responses.notFound ( request, response
  );%0A
@@ -2167,20 +2167,21 @@
 ;%0A        %7D%0A
+%0A
     %7D%0A%7D%0A

send out a 404 when the entry found is a directory