View Javadoc
1   /*
2    * Copyright (c) 2006-present the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.codehaus.gmaven.plugin;
17  
18  import java.net.MalformedURLException;
19  import java.net.URL;
20  
21  import javax.annotation.Nullable;
22  
23  import org.codehaus.gmaven.adapter.ResourceLoader;
24  import org.slf4j.Logger;
25  import org.slf4j.LoggerFactory;
26  
27  import static com.google.common.base.Preconditions.checkNotNull;
28  
29  /**
30   * Basic {@link ResourceLoader} implementation.
31   *
32   * @since 2.0
33   */
34  public class BasicResourceLoader
35      implements ResourceLoader
36  {
37    protected static final String DOT_GROOVY = ".groovy";
38  
39    protected final Logger log = LoggerFactory.getLogger(getClass());
40  
41    protected final ClassLoader classLoader;
42  
43    public BasicResourceLoader(final ClassLoader classLoader) {
44      this.classLoader = checkNotNull(classLoader);
45    }
46  
47    @Nullable
48    public URL loadResource(final String name) throws MalformedURLException {
49      return resolve(name, classLoader);
50    }
51  
52    @Nullable
53    protected URL resolve(final String className, final ClassLoader classLoader) throws MalformedURLException {
54      log.trace("Resolve; class-name: {}, class-loader: {}", className, classLoader);
55  
56      String name = resourceName(className);
57  
58      log.trace("Resolve; resource: {}", name);
59  
60      boolean tcl = false;
61      URL resource = classLoader.getResource(name);
62  
63      // try from tcl if given CL does not resolve
64      if (resource == null) {
65        resource = Thread.currentThread().getContextClassLoader().getResource(name);
66        tcl = true;
67      }
68  
69      log.trace("Resource: {}, tcl: {}", resource, tcl);
70  
71      return resource;
72    }
73  
74    /**
75     * Translate class-name into resource-name.
76     */
77    protected String resourceName(final String className) {
78      String name = className;
79  
80      if (!name.startsWith("/")) {
81        name = "/" + name;
82      }
83  
84      if (!name.endsWith(DOT_GROOVY)) {
85        name = name.replace('.', '/');
86        name += DOT_GROOVY;
87      }
88  
89      return name;
90    }
91  }