001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.velocity;
016    
017    import com.liferay.portal.kernel.log.Log;
018    import com.liferay.portal.kernel.log.LogFactoryUtil;
019    
020    import java.io.InputStream;
021    
022    import org.apache.velocity.exception.ResourceNotFoundException;
023    
024    /**
025     * @author Brian Wing Shun Chan
026     */
027    public class ClassLoaderVelocityResourceListener
028            extends VelocityResourceListener {
029    
030            @Override
031            public InputStream getResourceStream(String source)
032                    throws ResourceNotFoundException {
033    
034                    try {
035                            return doGetResourceStream(source);
036                    }
037                    catch (Exception e) {
038                            throw new ResourceNotFoundException(source);
039                    }
040            }
041    
042            protected InputStream doGetResourceStream(String source) throws Exception {
043                    if (source.contains(JOURNAL_SEPARATOR) ||
044                            source.contains(SERVLET_SEPARATOR) ||
045                            source.contains(THEME_LOADER_SEPARATOR)) {
046    
047                            return null;
048                    }
049    
050                    ClassLoader classLoader = getClass().getClassLoader();
051    
052                    if (_log.isDebugEnabled()) {
053                            _log.debug("Loading " + source);
054                    }
055    
056                    return classLoader.getResourceAsStream(source);
057            }
058    
059            private static Log _log = LogFactoryUtil.getLog(
060                    ClassLoaderVelocityResourceListener.class);
061    
062    }