OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 80 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
73 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.utils.i18n;
15
 
16
import org.openconcerto.utils.Log;
156 ilm 17
import org.openconcerto.utils.ReflectUtils;
73 ilm 18
import org.openconcerto.utils.Tuple2;
19
import org.openconcerto.utils.Value;
20
 
21
import java.io.IOException;
22
import java.lang.reflect.Constructor;
23
import java.lang.reflect.InvocationTargetException;
24
import java.lang.reflect.Method;
25
import java.lang.reflect.Modifier;
26
import java.util.ArrayList;
27
import java.util.List;
28
import java.util.Locale;
29
import java.util.ResourceBundle.Control;
30
import java.util.logging.Level;
31
 
32
import net.jcip.annotations.ThreadSafe;
33
 
34
/**
35
 * Allow to create a list of instances from classes and other files ending with a language tag.
36
 *
37
 * @author Sylvain
38
 * @param <T> type of instances.
39
 * @see #createInstances(String, Locale)
40
 */
41
@ThreadSafe
42
public class LocalizedInstances<T> {
43
 
44
    private final Class<T> clazz;
45
    private final Control cntrl;
46
    private String staticMethodName;
47
 
48
    public LocalizedInstances(Class<T> clazz, Control cntrl) {
49
        super();
50
        this.clazz = clazz;
51
        this.cntrl = cntrl;
52
        this.staticMethodName = null;
53
    }
54
 
55
    public final Class<T> getClassToUse() {
56
        return this.clazz;
57
    }
58
 
59
    public final Control getControl() {
60
        return this.cntrl;
61
    }
62
 
63
    public final Tuple2<Locale, List<T>> createInstances(final Locale locale) {
64
        return this.createInstances(this.getClassToUse().getName(), locale);
65
    }
66
 
67
    public final Tuple2<Locale, List<T>> createInstances(final String baseName, final Locale locale) {
68
        return createInstances(baseName, locale, this.getClassToUse());
69
    }
70
 
71
    /**
72
     * Create instances of the same language. For each candidate locale, this method first looks for
80 ilm 73
     * {@link #getInstance(Class) a class} and then for
74
     * {@link #createInstance(String, Locale, Class) other files}.
73 ilm 75
     *
76
     * @param baseName the base name of the classes, e.g. "org.acme.MyClass".
77
     * @param locale the desired locale, e.g. fr_FR.
78
     * @param cl the class to use as context for loading
79
     *        {@link Class#forName(String, boolean, ClassLoader) classes} and
80
     *        {@link Class#getResourceAsStream(String) resources}.
81
     * @return the used locale and the instances, e.g. if no classes ending in fr were found, this
82
     *         method will use the {@link Control#getFallbackLocale(String, Locale) fallback} and if
83
     *         this also doesn't exist, then the locale will be <code>null</code> and the list
84
     *         empty.
85
     */
86
    public final Tuple2<Locale, List<T>> createInstances(final String baseName, final Locale locale, final Class<?> cl) {
87
        final List<T> l = new ArrayList<T>();
88
        Locale localeRes = null;
89
        // test emptiness to not mix languages
90
        for (Locale targetLocale = locale; targetLocale != null && l.isEmpty(); targetLocale = this.cntrl.getFallbackLocale(baseName, targetLocale)) {
91
            localeRes = targetLocale;
156 ilm 92
            // e.g. "fr_FR", "fr"
73 ilm 93
            for (final Locale candidate : this.cntrl.getCandidateLocales(baseName, targetLocale)) {
156 ilm 94
                // e.g. org.acme.MyClass_fr
73 ilm 95
                final String bundleName = this.cntrl.toBundleName(baseName, candidate);
96
 
97
                // code first
156 ilm 98
                final Class<? extends T> subclazz = ReflectUtils.getSubclass(bundleName, this.clazz, cl.getClassLoader());
99
                if (subclazz != null) {
73 ilm 100
                    try {
101
                        final Value<? extends T> instance = this.getInstance(subclazz);
102
                        if (instance.hasValue())
103
                            l.add(instance.getValue());
104
                        else
156 ilm 105
                            Log.get().warning(subclazz + " exists but the constructor wasn't found");
73 ilm 106
                    } catch (Exception e) {
107
                        Log.get().log(Level.WARNING, "Couldn't create an instance using " + subclazz, e);
108
                    }
109
                }
110
 
111
                try {
112
                    final T newInstance = this.createInstance(bundleName, candidate, cl);
113
                    if (newInstance != null)
114
                        l.add(newInstance);
115
                } catch (IOException e) {
116
                    Log.get().log(Level.WARNING, "Couldn't create an instance using " + bundleName, e);
117
                }
118
            }
119
        }
120
        return Tuple2.create(localeRes, l);
121
    }
122
 
123
    /**
124
     * The no-arg static method to use.
125
     *
126
     * @param staticMethodName a static method name, <code>null</code> meaning the constructor.
127
     * @return this.
128
     * @see #getInstance(Class)
129
     */
130
    public final synchronized LocalizedInstances<T> setStaticMethodName(String staticMethodName) {
131
        this.staticMethodName = staticMethodName;
132
        return this;
133
    }
134
 
135
    public final synchronized String getStaticMethodName() {
136
        return this.staticMethodName;
137
    }
138
 
139
    /**
140
     * Get an instance of the passed class. In this implementation, if
141
     * {@link #getStaticMethodName()} isn't <code>null</code> then it is used, otherwise the no-arg
142
     * constructor is used.
143
     *
144
     * @param subclass the class to use.
145
     * @return an instance or {@link Value#getNone()} if the method or constructor doesn't exist.
146
     * @exception IllegalAccessException if the method or constructor is inaccessible.
147
     * @exception InstantiationException if the class that declares the constructor represents an
148
     *            abstract class.
149
     * @exception InvocationTargetException if the method or constructor throws an exception.
150
     */
151
    protected <U extends T> Value<U> getInstance(final Class<U> subclass) throws InstantiationException, IllegalAccessException, InvocationTargetException {
152
        final String staticMethodName = this.getStaticMethodName();
153
        try {
154
            if (staticMethodName != null) {
155
                final Method method = subclass.getMethod(staticMethodName);
156
                if (Modifier.isStatic(method.getModifiers()) && subclass.isAssignableFrom(method.getReturnType())) {
157
                    return Value.getSome(subclass.cast(method.invoke(null)));
158
                } else {
159
                    return Value.getNone();
160
                }
161
            } else {
162
                final Constructor<U> ctor = subclass.getConstructor();
163
                return Value.getSome(ctor.newInstance());
164
            }
165
        } catch (NoSuchMethodException e) {
166
            return Value.getNone();
167
        }
168
    }
169
 
170
    /**
171
     * Create an instance for the passed bundle and locale.
172
     *
173
     * @param bundleName the bundle.
174
     * @param candidate the locale.
175
     * @param cl the class to use as context.
176
     * @return a new instance using a resource at <code>bundleName</code>, or <code>null</code>.
177
     * @throws IOException if an error occur while reading the resource.
178
     * @see Control#toResourceName(String, String)
179
     */
180
    protected T createInstance(final String bundleName, final Locale candidate, final Class<?> cl) throws IOException {
181
        return null;
182
    }
183
}