001/*
002// This software is subject to the terms of the Eclipse Public License v1.0
003// Agreement, available at the following URL:
004// http://www.eclipse.org/legal/epl-v10.html.
005// You must accept the terms of that agreement to use this software.
006//
007// Copyright (C) 2005-2006 Pentaho
008// All Rights Reserved.
009*/
010package mondrian.spi.impl;
011
012import mondrian.spi.CatalogLocator;
013
014import java.net.MalformedURLException;
015import java.net.URL;
016import javax.servlet.ServletContext;
017
018/**
019 * Locates a catalog based upon a {@link ServletContext}.<p/>
020 *
021 * If the catalog URI is an absolute path, it refers to a resource inside our
022 * WAR file, so replace the URL.
023 *
024 * @author Gang Chen, jhyde
025 * @since December, 2005
026 */
027public class ServletContextCatalogLocator implements CatalogLocator {
028    private ServletContext servletContext;
029
030    public ServletContextCatalogLocator(ServletContext servletContext) {
031        this.servletContext = servletContext;
032    }
033
034    public String locate(String catalogPath) {
035        // If the catalog is an absolute path, it refers to a resource inside
036        // our WAR file, so replace the URL.
037        if (catalogPath != null && catalogPath.startsWith("/")) {
038            try {
039                URL url = servletContext.getResource(catalogPath);
040                if (url == null) {
041                    // The catalogPath does not exist, but construct a feasible
042                    // URL so that the error message makes sense.
043                    url = servletContext.getResource("/");
044                    url = new URL(
045                        url.getProtocol(),
046                        url.getHost(),
047                        url.getPort(),
048                        url.getFile() + catalogPath.substring(1));
049                }
050                catalogPath = url.toString();
051            } catch (MalformedURLException ignored) {
052            }
053        }
054        return catalogPath;
055    }
056}
057
058// End ServletContextCatalogLocator.java