01 /*
02 * Copyright 2008-2014 the original author or authors.
03 *
04 * Licensed under the Apache License, Version 2.0 (the "License");
05 * you may not use this file except in compliance with the License.
06 * You may obtain a copy of the License at
07 *
08 * http://www.apache.org/licenses/LICENSE-2.0
09 *
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.griffon.runtime.groovy.util;
17
18 import griffon.core.resources.ResourceHandler;
19 import griffon.util.ConfigReader;
20 import groovy.lang.Script;
21 import org.codehaus.griffon.runtime.util.DefaultCompositeResourceBundleBuilder;
22
23 import javax.annotation.Nonnull;
24 import javax.inject.Inject;
25 import java.net.URL;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.List;
29 import java.util.ResourceBundle;
30
31 import static java.util.Objects.requireNonNull;
32
33 /**
34 * @author Andres Almiray
35 * @since 2.0.0
36 */
37 public class GroovyAwareCompositeResourceBundleBuilder extends DefaultCompositeResourceBundleBuilder {
38 protected static final String GROOVY_SUFFIX = ".groovy";
39 private final ConfigReader configReader;
40
41 @Inject
42 public GroovyAwareCompositeResourceBundleBuilder(@Nonnull ResourceHandler resourceHandler, @Nonnull ConfigReader configReader) {
43 super(resourceHandler);
44 this.configReader = requireNonNull(configReader, "Argument 'reader' must not be null");
45 }
46
47 @Nonnull
48 @Override
49 @SuppressWarnings("unchecked")
50 protected Collection<ResourceBundle> loadBundleFromClass(@Nonnull String fileName) {
51 List<ResourceBundle> bundles = new ArrayList<>();
52 URL resource = getResourceAsURL(fileName, GROOVY_SUFFIX);
53 if (null != resource) {
54 bundles.add(new GroovyScriptResourceBundle(configReader, resource));
55 return bundles;
56 }
57
58 resource = getResourceAsURL(fileName, CLASS_SUFFIX);
59 if (null != resource) {
60 String className = fileName.replace('/', '.');
61 try {
62 Class<?> klass = loadClass(className);
63 if (Script.class.isAssignableFrom(klass)) {
64 bundles.add(new GroovyScriptResourceBundle(configReader, (Class<? extends Script>) klass));
65 return bundles;
66 }
67 } catch (ClassNotFoundException e) {
68 // ignore
69 }
70 }
71
72 return super.loadBundleFromClass(fileName);
73 }
74 }
|