File: ClassModel.java

package info (click to toggle)
jboss-logging-tools 2.2.1-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 2,672 kB
  • sloc: java: 9,687; xml: 438; javascript: 38; makefile: 2
file content (364 lines) | stat: -rw-r--r-- 14,368 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2016, Red Hat, Inc., and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.jboss.logging.processor.generator.model;

import static org.jboss.jdeparser.JExprs.$v;
import static org.jboss.jdeparser.JMod.FINAL;
import static org.jboss.jdeparser.JTypes.$t;
import static org.jboss.jdeparser.JTypes.typeOf;

import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.TypeElement;

import org.jboss.jdeparser.FormatPreferences;
import org.jboss.jdeparser.JBlock;
import org.jboss.jdeparser.JCall;
import org.jboss.jdeparser.JClassDef;
import org.jboss.jdeparser.JDeparser;
import org.jboss.jdeparser.JExpr;
import org.jboss.jdeparser.JExprs;
import org.jboss.jdeparser.JFiler;
import org.jboss.jdeparser.JMethodDef;
import org.jboss.jdeparser.JMod;
import org.jboss.jdeparser.JSourceFile;
import org.jboss.jdeparser.JSources;
import org.jboss.jdeparser.JType;
import org.jboss.jdeparser.JVarDeclaration;
import org.jboss.logging.annotations.MessageBundle;
import org.jboss.logging.annotations.MessageLogger;
import org.jboss.logging.processor.apt.ProcessingException;
import org.jboss.logging.processor.model.MessageInterface;
import org.jboss.logging.processor.model.MessageMethod;

/**
 * The basic java class model.
 *
 * @author Kevin Pollet - SERLI - (kevin.pollet@serli.com)
 * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
 */
public abstract class ClassModel {

    private static final String INSTANCE_FIELD_NAME = "INSTANCE";

    private static final String GET_INSTANCE_METHOD_NAME = "readResolve";

    private final JSources sources;

    private final JClassDef classDef;

    private final MessageInterface messageInterface;

    private final String className;
    private final String superClassName;

    private final String format;

    private final Map<String, JMethodDef> messageMethods;


    final JSourceFile sourceFile;
    final ProcessingEnvironment processingEnv;

    /**
     * Construct a class model.
     *
     * @param processingEnv    the processing environment
     * @param messageInterface the message interface to implement.
     * @param superClassName   the super class used for the translation implementations.
     */
    ClassModel(final ProcessingEnvironment processingEnv, final MessageInterface messageInterface, final String className, final String superClassName) {
        this.processingEnv = processingEnv;
        this.messageInterface = messageInterface;
        this.className = messageInterface.packageName() + "." + className;
        this.superClassName = superClassName;
        sources = JDeparser.createSources(JFiler.newInstance(processingEnv.getFiler()), new FormatPreferences(new Properties()));
        sourceFile = sources.createSourceFile(messageInterface.packageName(), className);
        classDef = sourceFile._class(JMod.PUBLIC, className);
        final int idLen = messageInterface.getIdLength();
        if (idLen > 0) {
            format = "%s%0" + messageInterface.getIdLength() + "d: %s";
        } else {
            format = "%s%d: %s";
        }
        messageMethods = new HashMap<>();
    }

    /**
     * Returns the message interface being used.
     *
     * @return the message interface.
     */
    public final MessageInterface messageInterface() {
        return messageInterface;
    }

    /**
     * Writes the generated source file to the file system.
     *
     * @throws java.io.IOException if the file could not be written
     */
    public final void generateAndWrite() throws IOException {
        generateModel();
        sources.writeSources();
        JDeparser.dropCaches();
    }

    /**
     * Generate the code corresponding to this
     * class model
     *
     * @return the generated code
     *
     * @throws IllegalStateException if the class has already been defined.
     */
    JClassDef generateModel() throws IllegalStateException {
        // Add generated annotation if required
        final TypeElement generatedAnnotation = messageInterface.generatedAnnotation();
        if (generatedAnnotation != null) {
            final JType generatedType = typeOf(generatedAnnotation.asType());
            sourceFile._import(generatedType);
            classDef.annotate(generatedType)
                    .value("value", getClass().getName())
                    .value("date", JExprs.str(ClassModelHelper.generatedDateValue()));
        }

        // Create the default JavaDoc
        classDef.docComment().text("Warning this class consists of generated code.");

        // Add extends
        if (superClassName != null) {
            classDef._extends(superClassName);
        }

        // Always implement the interface
        classDef._implements(typeOf(messageInterface.asType()));

        //Add implements
        if (!messageInterface.extendedInterfaces().isEmpty()) {
            for (MessageInterface intf : messageInterface.extendedInterfaces()) {
                final JType interfaceName = typeOf(intf.asType());
                sourceFile._import(interfaceName);
                classDef._implements(interfaceName);
            }
        }
        final JType serializable = $t(Serializable.class);
        sourceFile._import(serializable);
        classDef._implements(serializable);
        classDef.field(JMod.PRIVATE | JMod.STATIC | FINAL, JType.LONG, "serialVersionUID", JExprs.decimal(1L));
        return classDef;
    }

    /**
     * Adds a method to return the message value. The method name should be the
     * method name annotated {@code org.jboss.logging.Message}. This method will
     * be appended with {@code $str}.
     * <p/>
     * <p>
     * If the message method has already been defined the previously created
     * method is returned.
     * </p>
     * <p/>
     *
     * @param messageMethod the message method
     *
     * @return the newly created method.
     *
     * @throws IllegalStateException if this method is called before the generateModel method
     */
    JMethodDef addMessageMethod(final MessageMethod messageMethod) {
        return addMessageMethod(messageMethod, messageMethod.message().value());
    }

    /**
     * Adds a method to return the message value. The method name should be the
     * method name annotated {@code org.jboss.logging.Message}. This method will
     * be appended with {@code $str}.
     * <p/>
     * <p>
     * If the message method has already been defined the previously created
     * method is returned.
     * </p>
     * <p/>
     *
     * @param messageMethod the message method.
     * @param messageValue  the message value.
     *
     * @return the newly created method.
     *
     * @throws IllegalStateException if this method is called before the generateModel method
     */
    JMethodDef addMessageMethod(final MessageMethod messageMethod, final String messageValue) {
        // Values could be null and we shouldn't create message methods for null values.
        if (messageValue == null) {
            return null;
        }

        // Create the method that returns the string message for formatting
        JMethodDef method = messageMethods.get(messageMethod.messageMethodName());
        if (method == null) {
            method = classDef.method(JMod.PROTECTED, String.class, messageMethod.messageMethodName());
            final JBlock body = method.body();
            final String msg;
            if (messageInterface.projectCode() != null && !messageInterface.projectCode().isEmpty() && messageMethod.message().hasId()) {
                // Prefix the id to the string message
                msg = String.format(format, messageInterface.projectCode(), messageMethod.message().id(), messageValue);
            } else {
                msg = messageValue;
            }
            body._return(JExprs.str(msg));
            messageMethods.put(messageMethod.messageMethodName(), method);
        }

        return method;
    }

    /**
     * Get the class name.
     *
     * @return the class name
     */
    public final String qualifiedClassName() {
        return className;
    }


    /**
     * Creates the read resolve method and instance field.
     *
     * @return the read resolve method.
     */
    protected JMethodDef createReadResolveMethod() {
        final JType type = typeOf(classDef);
        final JVarDeclaration instance = classDef.field(JMod.PUBLIC | JMod.STATIC | JMod.FINAL, type, INSTANCE_FIELD_NAME, type._new());
        final JMethodDef readResolveMethod = classDef.method(JMod.PROTECTED, Object.class, GET_INSTANCE_METHOD_NAME);
        readResolveMethod.body()._return($v(instance));
        return readResolveMethod;
    }

    /**
     * Creates the method used to get the locale for formatting messages.
     * <p>
     * If the {@code locale} parameter is {@code null} the {@link MessageLogger#rootLocale()} or
     * {@link MessageBundle#rootLocale()} will be used to determine the {@linkplain Locale locale} to use.
     * </p>
     *
     * @param locale   the locale to use
     * @param override {@code true} if the {@link Override} annotation should be added to the method
     *
     * @return the call to the locale getter
     */
    JCall createLocaleGetter(final String locale, final boolean override) {
        final String methodName = "getLoggingLocale";
        // Create the type and import it
        final JType localeType = typeOf(Locale.class);
        sourceFile._import(localeType);
        final JVarDeclaration defaultInstance = classDef.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, localeType, "LOCALE", determineLocale(locale, localeType));

        // Create the method
        final JMethodDef method = classDef.method(JMod.PROTECTED, localeType, methodName);
        if (override) {
            method.annotate(Override.class);
        }
        method.body()._return($v(defaultInstance));
        return JExprs.call(methodName);
    }

    private JExpr determineLocale(final String locale, final JType localeType) {
        final JExpr initializer;

        if (locale == null) {
            // Create a static instance field for the default locale
            final String bcp47Value;
            if (messageInterface.isAnnotatedWith(MessageBundle.class)) {
                bcp47Value = messageInterface.getAnnotation(MessageBundle.class).rootLocale();
            } else if (messageInterface.isAnnotatedWith(MessageLogger.class)) {
                bcp47Value = messageInterface.getAnnotation(MessageLogger.class).rootLocale();
            } else {
                bcp47Value = "";
            }

            if (bcp47Value.isEmpty()) {
                initializer = localeType.$v("ROOT");
            } else {
                initializer = localeType.call("forLanguageTag").arg(JExprs.str(bcp47Value));
            }
        } else {
            if ("en_CA".equals(locale)) {
                initializer = localeType.$v("CANADA");
            } else if ("fr_CA".equals(locale)) {
                initializer = localeType.$v("CANADA_FRENCH");
            } else if ("zh".equals(locale)) {
                initializer = localeType.$v("CHINESE");
            } else if ("en".equals(locale)) {
                initializer = localeType.$v("ENGLISH");
            } else if ("fr_FR".equals(locale)) {
                initializer = localeType.$v("FRANCE");
            } else if ("fr".equals(locale)) {
                initializer = localeType.$v("FRENCH");
            } else if ("de".equals(locale)) {
                initializer = localeType.$v("GERMAN");
            } else if ("de_DE".equals(locale)) {
                initializer = localeType.$v("GERMANY");
            } else if ("it".equals(locale)) {
                initializer = localeType.$v("ITALIAN");
            } else if ("it_IT".equals(locale)) {
                initializer = localeType.$v("ITALY");
            } else if ("ja_JP".equals(locale)) {
                initializer = localeType.$v("JAPAN");
            } else if ("ja".equals(locale)) {
                initializer = localeType.$v("JAPANESE");
            } else if ("ko_KR".equals(locale)) {
                initializer = localeType.$v("KOREA");
            } else if ("ko".equals(locale)) {
                initializer = localeType.$v("KOREAN");
            } else if ("zh_CN".equals(locale)) {
                initializer = localeType.$v("SIMPLIFIED_CHINESE");
            } else if ("zh_TW".equals(locale)) {
                initializer = localeType.$v("TRADITIONAL_CHINESE");
            } else if ("en_UK".equals(locale)) {
                initializer = localeType.$v("UK");
            } else if ("en_US".equals(locale)) {
                initializer = localeType.$v("US");
            } else {
                final JCall newInstance = localeType._new();
                // Split the locale
                final String[] parts = locale.split("_");
                if (parts.length > 3) {
                    throw new ProcessingException(messageInterface, "Failed to parse %s to a Locale.", locale);
                }
                for (String arg : parts) {
                    newInstance.arg(JExprs.str(arg));
                }
                initializer = newInstance;
            }
        }

        return initializer;
    }
}