001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     bstefanescu
011 */
012package org.nuxeo.ecm.webengine.jaxrs.servlet.config;
013
014import java.io.IOException;
015import java.net.URL;
016
017import javax.servlet.http.HttpServletRequest;
018import javax.servlet.http.HttpServletResponse;
019
020import org.osgi.framework.Bundle;
021import org.osgi.service.http.HttpContext;
022
023/**
024 * A HttpContext that delegates resource lookup to contributed {@link ResourcesDescriptor} in the inverse order of the
025 * contribution (preserving the ordering imposed by extension mechanism)
026 * <p>
027 * A BundleHttpContext is created for every declated servlet when it is registered against to HttpService. The context
028 * is removed when the servlet is unregistered.
029 *
030 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
031 */
032public class BundleHttpContext implements HttpContext {
033
034    protected Bundle bundle;
035
036    protected ResourceResolver resolver;
037
038    protected volatile ResourcesDescriptor[] resources;
039
040    public BundleHttpContext(Bundle bundle, String resourcesPath) {
041        this.bundle = bundle;
042        if (resourcesPath != null) {
043            if (resourcesPath.startsWith("file:")) {
044                resolver = new FileResourceResolver(resourcesPath.substring("file:".length()));
045            } else {
046                resolver = new BundleResourceResolver(bundle, resourcesPath);
047            }
048        }
049    }
050
051    public void setResources(ResourcesDescriptor[] resources) {
052        this.resources = resources;
053    }
054
055    @Override
056    public String getMimeType(String name) {
057        return null;
058    }
059
060    @Override
061    public URL getResource(String name) {
062        ResourcesDescriptor[] _resources = resources;
063        if (_resources != null) {
064            for (int i = _resources.length - 1; i >= 0; i--) {
065                URL url = _resources[i].getResource(name);
066                if (url != null) {
067                    return url;
068                }
069            }
070        }
071        if (resolver != null) {
072            return resolver.getResource(name);
073        }
074        return null;
075    }
076
077    @Override
078    public boolean handleSecurity(HttpServletRequest request, HttpServletResponse response) throws IOException {
079        // default behaviour assumes the container has already performed authentication
080        return true;
081    }
082}