// Figure out the translation key name
String name = null;
String fieldName = metaField.getName();
String defaultName = metaField.getDeclaringClass().getFullyQualifiedName() + "." + fieldName;
if (!metaField.getType().isAssignableFrom(String.class)) {
throw new GenerationException("Translation key fields must be of type java.lang.String: " + defaultName);
}
try {
Class<?> asClass = metaField.getDeclaringClass().asClass();
Field field = asClass.getField(fieldName);
Object fieldVal = field.get(null);
if (fieldVal == null) {
throw new GenerationException("Translation key fields cannot be null: " + defaultName);
}
name = fieldVal.toString();
}
catch (Exception e) {
// TODO log this
}
// Figure out the translation key value (for the null locale).
String value = null;
TranslationKey annotation = metaField.getAnnotation(TranslationKey.class);
String defaultValue = annotation.defaultValue();
if (defaultValue != null) {
value = defaultValue;
}
else {
value = "!!" + defaultName + "!!";
}
// Generate code to register the null locale mapping
if (translationKeyFieldMap.containsKey(name)) {
throw new GenerationException("Duplicate translation key found: " + defaultName);
}
translationKeyFieldMap.put(name, value);
ctor.append(Stmt.loadVariable("this").invoke("registerTranslation", name, value, null));
}
// Scan for all @Bundle annotations.
final Collection<MetaClass> bundleAnnotatedClasses = ClassScanner.getTypesAnnotatedWith(Bundle.class, context);
// For each one, generate the code to load the translation and put that generated
// code in the c'tor of the generated class (GeneratedTranslationService)
for (MetaClass bundleAnnotatedClass : bundleAnnotatedClasses) {
String bundlePath = getMessageBundlePath(bundleAnnotatedClass);
// Skip if we've already processed this bundle.
if (processedBundles.contains(bundlePath)) {
continue;
}
// Now get all files in the message bundle (all localized versions)
// TODO optimize this - scan the classpath once and then pull out just the resources we need
MessageBundleScanner scanner = new MessageBundleScanner(
new ConfigurationBuilder()
.filterInputsBy(new FilterBuilder().include(".*json"))
.setUrls(ClasspathHelper.forClassLoader())
.setScanners(new MessageBundleResourceScanner(bundlePath)));
Collection<String> resources = scanner.getStore().get(MessageBundleResourceScanner.class).values();
// If we didn't find at least the specified root bundle file, that's a problem.
if (!resources.contains(bundlePath)) {
throw new GenerationException("Missing i18n bundle (specified in @Bundle): " + bundlePath);
}
// Now generate code to load up each of the JSON files and register them
// with the translation service.
for (String resource : resources) {