001 /* 002 * Copyright (C) 2006-2007 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017 package org.codehaus.gmaven.runtime.support.util; 018 019 import org.codehaus.gmaven.runtime.support.stubgen.parser.SourceType; 020 import org.codehaus.gmaven.runtime.util.ResourceLoader; 021 import org.slf4j.Logger; 022 import org.slf4j.LoggerFactory; 023 024 import java.net.MalformedURLException; 025 import java.net.URL; 026 027 /** 028 * Basic {@link ResourceLoader} implemenation. 029 * 030 * @version $Id: ResourceLoaderImpl.java 76 2009-12-05 12:04:30Z user57 $ 031 * @author <a href="mailto:jason@planet57.com">Jason Dillon</a> 032 */ 033 public class ResourceLoaderImpl 034 implements ResourceLoader 035 { 036 protected final Logger log = LoggerFactory.getLogger(getClass()); 037 038 protected ClassLoader classLoader; 039 040 public ResourceLoaderImpl(final ClassLoader classLoader) { 041 assert classLoader != null; 042 043 this.classLoader = classLoader; 044 } 045 046 public URL loadResource(final String name) throws MalformedURLException { 047 return resolve(name, classLoader); 048 } 049 050 protected String toResourceName(final String className) { 051 assert className != null; 052 053 // Figure out what resource to load 054 String resource = className; 055 056 if (!resource.startsWith("/")) { 057 resource = "/" + resource; 058 } 059 060 if (!resource.endsWith(SourceType.GROOVY_EXT)) { 061 resource = resource.replace('.', '/'); 062 resource += SourceType.GROOVY_EXT; 063 } 064 065 return resource; 066 } 067 068 protected URL resolve(final String className, final ClassLoader classLoader) throws MalformedURLException { 069 assert className != null; 070 assert classLoader != null; 071 072 // log.debug("Resolve; class name: {}", className); 073 074 String resource = toResourceName(className); 075 076 // log.debug("Resolve; resource name {}", resource); 077 078 URL url = classLoader.getResource(resource); 079 080 // log.debug("From CL: {}", url); 081 082 if (url == null) { 083 // Not sure if this is necessary or not... 084 url = Thread.currentThread().getContextClassLoader().getResource(resource); 085 086 // log.debug("From TCL: {}", url); 087 } 088 089 return url; 090 } 091 }