Compare commits

..

No commits in common. '4c2b2a55800b6c768192bb42e967f214c5159650' and '67f4b40989a6d5bfe5fffe542568fc7d9876daba' have entirely different histories.

  1. 5
      src/main/java/de/kreth/property2java/Configuration.java
  2. 11
      src/main/java/de/kreth/property2java/Generator.java
  3. 35
      src/main/java/de/kreth/property2java/config/FreemarkerConfig.java
  4. 9
      src/main/java/de/kreth/property2java/processor/Format.java
  5. 46
      src/main/java/de/kreth/property2java/processor/GenerateResourceBundleProperty2Java.java
  6. 21
      src/main/java/de/kreth/property2java/processor/GenerateResourceBundleProperty2Javas.java
  7. 23
      src/main/java/de/kreth/property2java/processor/ProcessorConfiguration.java
  8. 77
      src/main/java/de/kreth/property2java/processor/Property2JavaGenerator.java
  9. 59
      src/main/resources/template/enum_template_with_initializer.tpl
  10. 48
      src/main/resources/template/enum_template_with_inner_properties.tpl
  11. 48
      src/main/resources/template/enum_template_with_inner_propertyresourcebundle.tpl

@ -12,7 +12,6 @@ import java.util.Map;
import org.apache.commons.text.WordUtils; import org.apache.commons.text.WordUtils;
import de.kreth.property2java.config.Regex; import de.kreth.property2java.config.Regex;
import de.kreth.property2java.processor.Format;
public interface Configuration { public interface Configuration {
@ -24,10 +23,6 @@ public interface Configuration {
*/ */
String getPackage(); String getPackage();
default Format getFormat() {
return Format.WithUnaryOperatorParameter;
}
/** /**
* Filename to InputReader Entries * Filename to InputReader Entries
* *

@ -31,7 +31,7 @@ public class Generator {
public Generator(Configuration config) { public Generator(Configuration config) {
this.config = config; this.config = config;
try { try {
template = FreemarkerConfig.INSTANCE.getTemplate(config.getFormat()); template = FreemarkerConfig.INSTANCE.getTemplate();
} catch (IOException e) { } catch (IOException e) {
throw new IllegalStateException("Unable to load freemarker template", e); throw new IllegalStateException("Unable to load freemarker template", e);
} }
@ -62,7 +62,6 @@ public class Generator {
root.put("generation_date", dateTimeInstance.format(new Date())); root.put("generation_date", dateTimeInstance.format(new Date()));
root.put("package", config.getPackage()); root.put("package", config.getPackage());
root.put("fileName", fileName); root.put("fileName", fileName);
root.put("bundle_base_name", fileName.substring(0, min(fileName.length(), fileName.lastIndexOf('.'))));
root.put("classname", config.mapFilenameToClassName(fileName)); root.put("classname", config.mapFilenameToClassName(fileName));
List<Entry> entries = new ArrayList<>(); List<Entry> entries = new ArrayList<>();
@ -82,14 +81,6 @@ public class Generator {
template.process(root, out); template.process(root, out);
} }
int min(int a, int b) {
int result = Math.min(a, b);
if (result < 0) {
result = Math.max(a, b);
}
return result;
}
public static void main(String[] args) throws IOException, GeneratorException { public static void main(String[] args) throws IOException, GeneratorException {
Generator generator = new Generator(ArgumentConfiguration.parse(args)); Generator generator = new Generator(ArgumentConfiguration.parse(args));
generator.start(); generator.start();

@ -2,36 +2,23 @@ package de.kreth.property2java.config;
import java.io.IOException; import java.io.IOException;
import de.kreth.property2java.processor.Format;
import freemarker.template.Configuration; import freemarker.template.Configuration;
import freemarker.template.Template; import freemarker.template.Template;
public enum FreemarkerConfig { public enum FreemarkerConfig {
INSTANCE; INSTANCE;
private final Configuration cfg; private final Configuration cfg;
public Template getTemplate(Format format) throws IOException {
switch (format) {
case WithInitializer:
return cfg.getTemplate("enum_template_with_initializer.tpl");
case WithInnerPropertyLoader:
return cfg.getTemplate("enum_template_with_inner_properties.tpl");
case WithInnerPropertyResourceBundle:
return cfg.getTemplate("enum_template_with_inner_propertyresourcebundle.tpl");
case WithUnaryOperatorParameter:
return cfg.getTemplate("enum_template.tpl");
default:
throw new IllegalArgumentException("Format " + format + " is not supported.");
}
} public Template getTemplate() throws IOException {
return cfg.getTemplate("enum_template.tpl");
}
private FreemarkerConfig() { private FreemarkerConfig() {
cfg = new Configuration(Configuration.VERSION_2_3_28); cfg = new Configuration(Configuration.VERSION_2_3_28);
cfg.setClassForTemplateLoading(this.getClass(), "/template/"); cfg.setClassForTemplateLoading(this.getClass(), "/template/");
cfg.setDefaultEncoding("UTF-8"); cfg.setDefaultEncoding("UTF-8");
} }
} }

@ -1,9 +0,0 @@
package de.kreth.property2java.processor;
public enum Format {
WithUnaryOperatorParameter,
WithInnerPropertyResourceBundle,
WithInnerPropertyLoader,
WithInitializer
}

@ -1,46 +0,0 @@
package de.kreth.property2java.processor;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(TYPE)
@Retention(RetentionPolicy.SOURCE)
@Repeatable(value = GenerateResourceBundleProperty2Javas.class)
/**
* Für die konfigurierten Resourcen wird jeweils eine Java Klasse erzeugt. Es
* muss nur die Abhängigkeit eingebunden werden und die Annotation in einer
* Klasse verwendet werden, in deren Package die neuen Klassen generiert werden.
* Wenn mehrere Resourcen verarbeitet werden sollen, kann diese Annotation
* mehrfach parallel angegeben werden.
*
* Für die Ausgabe der Prozessornachrichten muss folgendes im maven compiler
* konfiguriert werden:
*
* <pre>
&lt;build&gt;
&lt;plugins&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
&lt;version&gt;3.8.0&lt;/version&gt;
&lt;configuration&gt;
&lt;release&gt;${java.version}&lt;/release&gt;
<b>&lt;showWarnings&gt;true&lt;/showWarnings&gt;</b>
&lt;/configuration&gt;
&lt;/plugin&gt;
&lt;/plugins&gt;
&lt;/build&gt;
* </pre>
*
* @author Markus
*
*/
public @interface GenerateResourceBundleProperty2Java {
String resource();
Format format();
}

@ -1,21 +0,0 @@
package de.kreth.property2java.processor;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Diese Annotation sollte nicht verwendet werden. Sie sammelt nur
* {@link GenerateResourceBundleProperty2Java} wenn diese mehrfach verwendet
* wird.
*
* @author Markus
*
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface GenerateResourceBundleProperty2Javas {
GenerateResourceBundleProperty2Java[] value();
}

@ -9,7 +9,6 @@ import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import javax.annotation.processing.Filer; import javax.annotation.processing.Filer;
import javax.lang.model.element.Element; import javax.lang.model.element.Element;
@ -27,16 +26,17 @@ public class ProcessorConfiguration implements Configuration {
private final Filer filer; private final Filer filer;
private final Element element; private final Element element;
private final Map<String, Reader> input; private final Map<String, Reader> input;
private final Format format;
ProcessorConfiguration(Builder builder) throws IOException { ProcessorConfiguration(Builder builder) throws IOException {
this.filer = builder.filer; this.filer = builder.filer;
this.element = builder.element; this.element = builder.element;
this.format = Objects.requireNonNullElse(builder.format, Format.WithUnaryOperatorParameter);
this.input = new HashMap<>(); this.input = new HashMap<>();
for (String resource : builder.resourcenames) { for (String resource : builder.resourcenames) {
FileObject ressource = filer.getResource(StandardLocation.CLASS_PATH, "", resource);
input.put(resource, ressource.openReader(false)); FileObject ressource = filer.getResource(StandardLocation.CLASS_PATH, "",
resource);
String className = mapFilenameToClassName(resource);
input.put(className, ressource.openReader(false));
} }
} }
@ -52,11 +52,6 @@ public class ProcessorConfiguration implements Configuration {
return packageName; return packageName;
} }
@Override
public Format getFormat() {
return format;
}
@Override @Override
public Map<String, Reader> getInput() { public Map<String, Reader> getInput() {
return input; return input;
@ -72,7 +67,7 @@ public class ProcessorConfiguration implements Configuration {
public Writer outWriter(String fileName) throws IOException { public Writer outWriter(String fileName) throws IOException {
String packageName = getPackage(); String packageName = getPackage();
if (packageName != null && !packageName.isBlank()) { if (packageName != null && !packageName.isBlank()) {
fileName = packageName + "." + mapFilenameToClassName(fileName); fileName = packageName + "." + fileName;
} }
return filer.createSourceFile(fileName, element).openWriter(); return filer.createSourceFile(fileName, element).openWriter();
} }
@ -85,7 +80,6 @@ public class ProcessorConfiguration implements Configuration {
private final Filer filer; private final Filer filer;
private final Element element; private final Element element;
private final List<String> resourcenames; private final List<String> resourcenames;
private Format format = Format.WithUnaryOperatorParameter;
private Builder(Filer filer, Element element) { private Builder(Filer filer, Element element) {
this.filer = filer; this.filer = filer;
@ -93,11 +87,6 @@ public class ProcessorConfiguration implements Configuration {
this.resourcenames = new ArrayList<>(); this.resourcenames = new ArrayList<>();
} }
public Builder withFormat(Format format) {
this.format = format;
return this;
}
public Builder addAll(String[] resourceNames) { public Builder addAll(String[] resourceNames) {
this.resourcenames.addAll(Arrays.asList(resourceNames)); this.resourcenames.addAll(Arrays.asList(resourceNames));
return this; return this;

@ -4,7 +4,6 @@ import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
import java.util.Arrays; import java.util.Arrays;
import java.util.List;
import java.util.Set; import java.util.Set;
import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.AbstractProcessor;
@ -18,9 +17,7 @@ import javax.tools.Diagnostic.Kind;
import de.kreth.property2java.GeneratorException; import de.kreth.property2java.GeneratorException;
@SupportedAnnotationTypes({ "de.kreth.property2java.processor.GenerateProperty2Java", @SupportedAnnotationTypes({ "de.kreth.property2java.processor.GenerateProperty2Java" })
"de.kreth.property2java.processor.GenerateResourceBundleProperty2Javas",
"de.kreth.property2java.processor.GenerateResourceBundleProperty2Java" })
@SupportedSourceVersion(SourceVersion.RELEASE_8) @SupportedSourceVersion(SourceVersion.RELEASE_8)
public class Property2JavaGenerator extends AbstractProcessor { public class Property2JavaGenerator extends AbstractProcessor {
@ -28,63 +25,37 @@ public class Property2JavaGenerator extends AbstractProcessor {
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (!roundEnv.processingOver()) { if (!roundEnv.processingOver()) {
processGenerateProperty2Java(roundEnv); processingEnv.getMessager().printMessage(Kind.NOTE,
processGenerateResourceBundleProperty2Javas(roundEnv); "Processing annotation " + GenerateProperty2Java.class);
Set<? extends Element> elementsAnnotatedWith = roundEnv
.getElementsAnnotatedWith(GenerateProperty2Java.class);
processElements(elementsAnnotatedWith);
} else { } else {
processingEnv.getMessager().printMessage(Kind.NOTE, processingEnv.getMessager().printMessage(Kind.NOTE,
"finished working on annotation " + annotations); "finished working on annotation " + GenerateProperty2Java.class);
} }
return true; return true;
} }
private void processGenerateProperty2Java(RoundEnvironment roundEnv) { private void processElements(Set<? extends Element> elementsAnnotatedWith) {
processingEnv.getMessager().printMessage(Kind.NOTE,
"Processing annotation " + GenerateProperty2Java.class);
Set<? extends Element> elementsAnnotatedWith = roundEnv
.getElementsAnnotatedWith(GenerateProperty2Java.class);
for (Element element : elementsAnnotatedWith) { for (Element element : elementsAnnotatedWith) {
GenerateProperty2Java generateAnnotation = element.getAnnotation(GenerateProperty2Java.class); String[] resources = element.getAnnotation(GenerateProperty2Java.class).resources();
String[] resources = generateAnnotation.resources(); processingEnv.getMessager().printMessage(Kind.NOTE,
generateElementProperties(element, Arrays.asList(resources), Format.WithUnaryOperatorParameter); "Generating Java for " + Arrays.asList(resources));
} try {
} ProcessorConfiguration
.builder(processingEnv.getFiler(), element)
private void processGenerateResourceBundleProperty2Javas(RoundEnvironment roundEnv) { .addAll(resources)
.startGeneration();
processingEnv.getMessager().printMessage(Kind.NOTE, } catch (IOException | GeneratorException e) {
"Processing annotation " + GenerateResourceBundleProperty2Javas.class); StringWriter out = new StringWriter();
e.printStackTrace(new PrintWriter(out));
Set<? extends Element> elementsAnnotatedWith = roundEnv out.flush();
.getElementsAnnotatedWith(GenerateResourceBundleProperty2Javas.class); processingEnv.getMessager().printMessage(Kind.ERROR, "Exception " + e + "\n" + out.toString(),
element);
for (Element element : elementsAnnotatedWith) {
GenerateResourceBundleProperty2Java[] value = element
.getAnnotation(GenerateResourceBundleProperty2Javas.class).value();
for (GenerateResourceBundleProperty2Java generateResourceBundleProperty2Java : value) {
List<String> resources = Arrays.asList(generateResourceBundleProperty2Java.resource());
generateElementProperties(element, resources, generateResourceBundleProperty2Java.format());
} }
} }
} }
private void generateElementProperties(Element element, List<String> resources, Format format) {
processingEnv.getMessager().printMessage(Kind.NOTE,
"Generating Java for " + Arrays.asList(resources));
try {
ProcessorConfiguration
.builder(processingEnv.getFiler(), element)
.addAll(resources)
.withFormat(format)
.startGeneration();
} catch (IOException | GeneratorException e) {
StringWriter out = new StringWriter();
e.printStackTrace(new PrintWriter(out));
out.flush();
processingEnv.getMessager().printMessage(Kind.ERROR, "Exception " + e + "\n" + out.toString(),
element);
}
}
} }

@ -1,59 +0,0 @@
<#if package??>package ${package};
</#if>import java.util.Properties;
import java.util.ResourceBundle;
import java.util.function.UnaryOperator;
import javax.annotation.processing.Generated;
/**
* Property keys from ${fileName}
*/
@Generated(date = "${generation_date}", value = "${generator_name}")
public enum ${classname} {
<#list entries as e>
/**
* ${e.key} = "${e.value}"
*/
${e.constant} ("${e.key}")<#sep>,
</#sep>
</#list>;
private static UnaryOperator<String> function;
private final String value;
private ${classname} (String value) {
this.value = value;
}
public static void init(UnaryOperator<String> resourceFunction) {
function = resourceFunction;
}
/**
* Represented Key in property File.
* @return key
*/
public String getValue() {
return value;
}
/**
* Resolves the value for this key.
* {@link #init(UnaryOperator<String>)} must be called before.
*/
public String getText() {
return function.apply(value);
}
/**
* Resolves the value for this key from the parameter function.
* <p>
* e.g. <code>${classname}.getString(resBundle::getString)</code>
* @param resourceFunction {@link Properties#getProperty(String)} or {@link ResourceBundle#getString(String)}
* @return
*/
public String getString(UnaryOperator<String> resourceFunction) {
return resourceFunction.apply(value);
}
}

@ -1,48 +0,0 @@
<#if package??>package ${package};
</#if>import java.util.Properties;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.function.UnaryOperator;
import javax.annotation.processing.Generated;
/**
* Property keys from ${fileName}
*/
@Generated(date = "${generation_date}", value = "${generator_name}")
public enum ${classname} {
<#list entries as e>
/**
* ${e.key} = "${e.value}"
*/
${e.constant} ("${e.key}")<#sep>,
</#sep>
</#list>;
private final String value;
private ${classname} (String value) {
this.value = value;
}
/**
* Represented Key in property File.
* @return key
*/
public String getValue() {
return value;
}
private static ResourceBundle bundle = PropertyResourceBundle.getBundle("${bundle_base_name}");
/**
* The Text for this Key from PropertyResourceBundle
* @return human readable text
*/
public String getText() {
return bundle.getString(value);
}
}

@ -1,48 +0,0 @@
<#if package??>package ${package};
</#if>import java.util.Properties;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.function.UnaryOperator;
import javax.annotation.processing.Generated;
/**
* Property keys from ${fileName}
*/
@Generated(date = "${generation_date}", value = "${generator_name}")
public enum ${classname} {
<#list entries as e>
/**
* ${e.key} = "${e.value}"
*/
${e.constant} ("${e.key}")<#sep>,
</#sep>
</#list>;
private final String value;
private ${classname} (String value) {
this.value = value;
}
/**
* Represented Key in property File.
* @return key
*/
public String getValue() {
return value;
}
private static ResourceBundle bundle = PropertyResourceBundle.getBundle("${bundle_base_name}");
/**
* The Text for this Key from PropertyResourceBundle
* @return human readable text
*/
public String getText() {
return bundle.getString(value);
}
}
Loading…
Cancel
Save