001    /*
002    // $Id: //open/mondrian/src/main/mondrian/spi/impl/ServletContextCatalogLocator.java#4 $
003    // This software is subject to the terms of the Common Public License
004    // Agreement, available at the following URL:
005    // http://www.opensource.org/licenses/cpl.html.
006    // Copyright (C) 2005-2006 Julian Hyde
007    // All Rights Reserved.
008    // You must accept the terms of that agreement to use this software.
009    */
010    package mondrian.spi.impl;
011    
012    import mondrian.spi.CatalogLocator;
013    
014    import javax.servlet.ServletContext;
015    import java.net.URL;
016    import java.net.MalformedURLException;
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     * @version $Id: //open/mondrian/src/main/mondrian/spi/impl/ServletContextCatalogLocator.java#4 $
027     */
028    public class ServletContextCatalogLocator implements CatalogLocator {
029        private ServletContext servletContext;
030    
031        public ServletContextCatalogLocator(ServletContext servletContext) {
032            this.servletContext = servletContext;
033        }
034    
035        public String locate(String catalogPath) {
036            // If the catalog is an absolute path, it refers to a resource inside
037            // our WAR file, so replace the URL.
038            if (catalogPath != null && catalogPath.startsWith("/")) {
039                try {
040                    URL url = servletContext.getResource(catalogPath);
041                    if (url == null) {
042                        // The catalogPath does not exist, but construct a feasible
043                        // URL so that the error message makes sense.
044                        url = servletContext.getResource("/");
045                        url = new URL(url.getProtocol(), url.getHost(),
046                                url.getPort(),
047                                url.getFile() + catalogPath.substring(1));
048                    }
049                    catalogPath = url.toString();
050                } catch (MalformedURLException ignored) {
051                }
052            }
053            return catalogPath;
054        }
055    }
056    
057    // End ServletContextCatalogLocator.java