Compare commits

..

No commits in common. '8e9671bec5169855a4769f4c680ccc07aef867dd' and 'b00bb1a1d607dac1c1711bd5acc9e5e0acf9125e' have entirely different histories.

  1. 2
      .github/workflows/maven.yml
  2. 1
      .gitignore
  3. 1
      Application_Properties.java
  4. 40
      pom.xml
  5. 7
      src/main/java/de/kreth/property2java/Configuration.java
  6. 6
      src/main/java/de/kreth/property2java/Generator.java
  7. 11
      src/main/java/de/kreth/property2java/GeneratorException.java
  8. 8
      src/main/java/de/kreth/property2java/GeneratorOptions.java
  9. 5
      src/main/java/de/kreth/property2java/cli/ArgumentConfiguration.java
  10. 4
      src/main/java/de/kreth/property2java/cli/CliConfig.java
  11. 4
      src/main/java/de/kreth/property2java/config/FreemarkerConfig.java
  12. 5
      src/main/java/de/kreth/property2java/config/Regex.java
  13. 1
      src/main/java/de/kreth/property2java/processor/GenerateProperty2Java.java
  14. 3
      src/main/java/de/kreth/property2java/processor/GenerateResourceBundleProperty2Java.java
  15. 11
      src/main/java/de/kreth/property2java/processor/ProcessorConfiguration.java
  16. 13
      src/main/java/de/kreth/property2java/processor/Property2JavaGenerator.java
  17. 7
      src/test/java/de/kreth/property2java/ConfigurationTest.java
  18. 48
      src/test/java/de/kreth/property2java/GeneratorTests.java
  19. 24
      src/test/java/de/kreth/property2java/GeneratorWithInnerPropertiesTest.java
  20. 52
      src/test/java/de/kreth/property2java/TestPropertiesSource.java
  21. 3
      src/test/java/de/kreth/property2java/generated/GenerateTheTest.java
  22. 1
      src/test/java/de/kreth/property2java/generated/Property_Loader_Format_Properties.java
  23. 27
      src/test/java/de/kreth/property2java/parts/ReplaceLogicForTemplate.java
  24. 9
      src/test/java/de/kreth/property2java/parts/ReplaceLogicForTemplateTest.java
  25. 38
      src/test/java/de/kreth/property2java/processor/Property2JavaGeneratorTest.java

@ -19,6 +19,6 @@ jobs:
- name: Set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 17
java-version: 11
- name: Build with Maven
run: mvn -B package --file pom.xml

1
.gitignore vendored

@ -2,5 +2,4 @@
.project
.factorypath
.settings
.idea
target

@ -10,7 +10,7 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>17</java.version>
<java.version>11</java.version>
<org.junit.jupiter>5.3.0-M1</org.junit.jupiter>
<org.slf4j>1.7.36</org.slf4j>
<org.apache.logging.log4j>2.17.2</org.apache.logging.log4j>
@ -47,12 +47,6 @@
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j}</version>
</dependency>
<dependency>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>
<version>1.3.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
@ -146,42 +140,12 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.1</version>
<version>3.8.0</version>
<configuration>
<release>${java.version}</release>
<compilerArgs>-proc:none</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.openrewrite.maven</groupId>
<artifactId>rewrite-maven-plugin</artifactId>
<version>6.15.0</version>
<configuration>
<activeRecipes>
<recipe>org.openrewrite.java.migrate.UpgradeToJava17</recipe>
<recipe>org.openrewrite.staticanalysis.JavaApiBestPractices</recipe>
<recipe>org.openrewrite.staticanalysis.CommonStaticAnalysis</recipe>
<recipe>org.openrewrite.staticanalysis.CodeCleanup</recipe>
<recipe>org.openrewrite.recipes.rewrite.OpenRewriteRecipeBestPractices</recipe>
</activeRecipes>
<exclusions>
<exclusion>**/generated/**</exclusion>
</exclusions>
</configuration>
<dependencies>
<dependency>
<groupId>org.openrewrite.recipe</groupId>
<artifactId>rewrite-migrate-java</artifactId>
<version>3.14.1</version>
</dependency>
<dependency>
<groupId>org.openrewrite.recipe</groupId>
<artifactId>rewrite-rewrite</artifactId>
<version>0.5.0</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<scm>

@ -10,9 +10,9 @@ import java.nio.file.Path;
import java.util.EnumSet;
import java.util.Map;
import org.apache.commons.text.WordUtils;
import de.kreth.property2java.config.Regex;
import org.apache.commons.text.WordUtils;
public interface Configuration {
@ -45,7 +45,7 @@ public interface Configuration {
default EnumSet<GeneratorOptions> getOptions() {
return EnumSet.noneOf(GeneratorOptions.class);
}
default Writer outWriter(String fileName) throws IOException {
return new FileWriter(new File(getRootPath().toFile(), mapFilenameToClassName(fileName) + ".java"),
outputCharset());
@ -59,7 +59,8 @@ public interface Configuration {
String path = Regex.PATTERN.matcher(fileName).replaceAll(".").replaceAll("\\.", "_").replaceAll(" ", "_")
.replaceAll("/", "_");
return WordUtils.capitalize(path, '_');
path = WordUtils.capitalize(path, '_');
return path;
}
}

@ -17,10 +17,8 @@ import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import de.kreth.property2java.cli.ArgumentConfiguration;
import de.kreth.property2java.config.FreemarkerConfig;
import freemarker.template.Template;
import freemarker.template.TemplateException;
@ -77,13 +75,13 @@ public class Generator {
root.put("fileName", fileName);
root.put("bundle_base_name", fileName.substring(0, min(fileName.length(), fileName.lastIndexOf('.'))));
root.put("classname", config.mapFilenameToClassName(fileName));
if (!config.getOptions().isEmpty()) {
if (config.getOptions().isEmpty() == false) {
root.put("options", config.getOptions());
List<String> imports = config.getOptions().stream()
.map(GeneratorOptions::getAdditionalImport)
.flatMap(Arrays::stream)
.collect(Collectors.toList());
if (!imports.isEmpty()) {
if (imports.isEmpty() == false) {
root.put("imports", imports);
}
}

@ -1,14 +1,19 @@
package de.kreth.property2java;
import java.io.Serial;
public class GeneratorException extends Exception {
@Serial
private static final long serialVersionUID = -7319030228448260990L;
public GeneratorException(String message, Throwable cause) {
super(message, cause);
}
public GeneratorException(String message) {
super(message);
}
public GeneratorException(Throwable cause) {
super(cause);
}
}

@ -11,13 +11,13 @@ public enum GeneratorOptions {
* Add a format Method, which uses and supports {@link MessageFormat}.
*/
WithMessageFormatter("java.text.MessageFormat");
private final String[] additionalImport;
GeneratorOptions(String... additionalImport) {
this.additionalImport = additionalImport!= null ? additionalImport : new String[]{};
private GeneratorOptions(String... additionalImport) {
this.additionalImport = additionalImport!= null ? additionalImport : new String[] {};
}
String[] getAdditionalImport() {
return additionalImport;
}

@ -12,10 +12,9 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import de.kreth.property2java.Configuration;
public final class ArgumentConfiguration implements Configuration {
public class ArgumentConfiguration implements Configuration {
private final String packageName;
@ -52,7 +51,7 @@ public final class ArgumentConfiguration implements Configuration {
@Override
public Writer outWriter(String fileName) throws IOException {
File dir;
if (packageName != null && !packageName.isBlank()) {
if (packageName != null && packageName.isBlank() == false) {
dir = new File(rootPath.toFile(), packageName.replace('.', File.separatorChar));
} else {
dir = rootPath.toFile();

@ -2,8 +2,6 @@ package de.kreth.property2java.cli;
import java.io.IOException;
import de.kreth.property2java.cli.ArgumentConfiguration.Builder;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
@ -13,6 +11,8 @@ import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import de.kreth.property2java.cli.ArgumentConfiguration.Builder;
public class CliConfig {
private final Options options = options();

@ -2,9 +2,7 @@ package de.kreth.property2java.config;
import java.io.IOException;
import de.kreth.property2java.Format;
import freemarker.template.Configuration;
import freemarker.template.Template;
@ -30,7 +28,7 @@ public enum FreemarkerConfig {
}
FreemarkerConfig() {
private FreemarkerConfig() {
cfg = new Configuration(Configuration.VERSION_2_3_28);
cfg.setClassForTemplateLoading(this.getClass(), "/template/");
cfg.setDefaultEncoding("UTF-8");

@ -2,10 +2,7 @@ package de.kreth.property2java.config;
import java.util.regex.Pattern;
public final class Regex {
public class Regex {
public static final Pattern PATTERN = Pattern.compile("_[a-z]{2}(_[A-Z]{2})?\\.");
private Regex() {
}
}

@ -6,7 +6,6 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import de.kreth.property2java.Format;
import de.kreth.property2java.GeneratorOptions;

@ -7,7 +7,6 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import de.kreth.property2java.Format;
import de.kreth.property2java.GeneratorOptions;
@ -47,6 +46,6 @@ public @interface GenerateResourceBundleProperty2Java {
String resource();
Format format();
GeneratorOptions[] options() default {};
}

@ -11,6 +11,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.annotation.processing.Filer;
import javax.lang.model.element.Element;
import javax.lang.model.element.PackageElement;
@ -18,7 +19,6 @@ import javax.lang.model.element.TypeElement;
import javax.tools.FileObject;
import javax.tools.StandardLocation;
import de.kreth.property2java.Configuration;
import de.kreth.property2java.Format;
import de.kreth.property2java.Generator;
@ -49,7 +49,8 @@ public class ProcessorConfiguration implements Configuration {
public String getPackage() {
String packageName = "";
if (element instanceof TypeElement typeElement) {
if (element instanceof TypeElement) {
TypeElement typeElement = (TypeElement) element;
PackageElement packageElement = (PackageElement) typeElement.getEnclosingElement();
packageName = packageElement.getQualifiedName().toString();
}
@ -70,7 +71,7 @@ public class ProcessorConfiguration implements Configuration {
public EnumSet<GeneratorOptions> getOptions() {
return EnumSet.copyOf(Arrays.asList(options));
}
@Override
public Path getRootPath() {
throw new UnsupportedOperationException(
@ -90,7 +91,7 @@ public class ProcessorConfiguration implements Configuration {
return new Builder(filer, element);
}
static final class Builder {
static class Builder {
public GeneratorOptions[] options;
private final Filer filer;
private final Element element;
@ -112,7 +113,7 @@ public class ProcessorConfiguration implements Configuration {
this.options = options;
return this;
}
public Builder addAll(String[] resourceNames) {
this.resourcenames.addAll(Arrays.asList(resourceNames));
return this;

@ -4,9 +4,9 @@ import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
@ -16,14 +16,13 @@ import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic.Kind;
import de.kreth.property2java.Format;
import de.kreth.property2java.GeneratorException;
import de.kreth.property2java.GeneratorOptions;
@SupportedAnnotationTypes({"de.kreth.property2java.processor.GenerateProperty2Java",
@SupportedAnnotationTypes({ "de.kreth.property2java.processor.GenerateProperty2Java",
"de.kreth.property2java.processor.GenerateResourceBundleProperty2Javas",
"de.kreth.property2java.processor.GenerateResourceBundleProperty2Java"})
"de.kreth.property2java.processor.GenerateResourceBundleProperty2Java" })
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class Property2JavaGenerator extends AbstractProcessor {
@ -65,14 +64,14 @@ public class Property2JavaGenerator extends AbstractProcessor {
GenerateResourceBundleProperty2Java[] value = element
.getAnnotation(GenerateResourceBundleProperty2Javas.class).value();
for (GenerateResourceBundleProperty2Java generateResourceBundleProperty2Java : value) {
List<String> resources = Collections.singletonList(generateResourceBundleProperty2Java.resource());
List<String> resources = Arrays.asList(generateResourceBundleProperty2Java.resource());
generateElementProperties(element, resources, generateResourceBundleProperty2Java.format(), generateResourceBundleProperty2Java.options());
}
}
}
private void generateElementProperties(Element element, List<String> resources, Format format, GeneratorOptions[] options) {
processingEnv.getMessager().printMessage(Kind.NOTE, "Generating Java for " + Collections.singletonList(resources));
processingEnv.getMessager().printMessage(Kind.NOTE, "Generating Java for " + Arrays.asList(resources));
try {
ProcessorConfiguration
.builder(processingEnv.getFiler(), element)
@ -84,7 +83,7 @@ public class Property2JavaGenerator extends AbstractProcessor {
StringWriter out = new StringWriter();
e.printStackTrace(new PrintWriter(out));
out.flush();
processingEnv.getMessager().printMessage(Kind.ERROR, "Exception " + e + "\n" + out, element);
processingEnv.getMessager().printMessage(Kind.ERROR, "Exception " + e + "\n" + out.toString(), element);
}
}

@ -1,7 +1,7 @@
package de.kreth.property2java;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
@ -10,7 +10,6 @@ import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
@ -31,7 +30,7 @@ class ConfigurationTest {
when(config.outputCharset()).thenCallRealMethod();
Writer outWriter = config.outWriter("application.properties");
assertInstanceOf(FileWriter.class, outWriter);
assertTrue(outWriter instanceof FileWriter);
}
@Test

@ -6,21 +6,19 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
@ -30,8 +28,6 @@ import java.util.Optional;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
import org.apache.commons.cli.MissingOptionException;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -49,7 +45,7 @@ import freemarker.template.TemplateException;
@MockitoSettings(strictness = Strictness.LENIENT)
class GeneratorTests {
private final String path = "application.properties";
private String path = "application.properties";
@Mock
private Configuration config;
@ -113,7 +109,7 @@ class GeneratorTests {
assertFalse(root.containsKey("imports"));
}
@Test
void testClassDefinition() throws IOException, GeneratorException {
@ -193,38 +189,6 @@ class GeneratorTests {
assertLineMatch(lines, "message_invoiceitem_allfieldsmustbeset", "message.invoiceitem.allfieldsmustbeset");
}
@Test
void testTemplateException() throws TemplateException, IOException {
Template template = mock(Template.class);
when(config.outWriter(anyString())).thenReturn(mock(Writer.class));
doThrow(new TemplateException(null)).when(template).process(any(Map.class), any(Writer.class));
Generator generator = new Generator(config, template);
GeneratorException ex = assertThrows(GeneratorException.class, generator::start);
assertThat(ex.getCause()).isInstanceOf(TemplateException.class);
}
@Test
void testMainMethod() throws IOException, GeneratorException {
Path source = Files.createTempFile(getClass().getSimpleName(), ".properties");
Generator.main(new String[]{"-t", "target", "-f", source.toString()});
}
@Test
void testMainMethodMissingOption() throws IOException, GeneratorException {
IllegalStateException e = assertThrows(IllegalStateException.class, () -> Generator.main(new String[]{}));
assertThat(e.getCause()).isInstanceOf(MissingOptionException.class);
}
@Test
void testGenerateFor() throws IOException, GeneratorException {
Class<?> locationClass = getClass();
List<URL> rescources = new ArrayList<>();
String relativeTargetDir = "target";
Generator.generateFor(locationClass, rescources, relativeTargetDir);
}
private void assertLineMatch(List<String> lines, String key, String expected) {
Optional<String> found = lines.stream().filter(line -> keyMatches(line, key)).findFirst();

@ -2,9 +2,14 @@ package de.kreth.property2java;
import static de.kreth.property2java.TestPropertiesSource.testProperties;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.IOException;
@ -20,7 +25,6 @@ import java.util.Optional;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -34,7 +38,7 @@ import org.mockito.quality.Strictness;
@MockitoSettings(strictness = Strictness.LENIENT)
public class GeneratorWithInnerPropertiesTest {
private final String path = "application.properties";
private String path = "application.properties";
@Mock
private Configuration config;
@ -119,11 +123,11 @@ public class GeneratorWithInnerPropertiesTest {
String load = null;
while (sourceTokenizer.hasMoreTokens()) {
String line = sourceTokenizer.nextToken();
if (line.contains("Properties") &&
!line.contains("import") &&
!line.contains("enum") &&
!line.contains("@link") &&
!line.contains("class")) {
if (line.contains("Properties")
&& !line.contains("import")
&& !line.contains("enum")
&& !line.contains("@link")
&& !line.contains("class")) {
declaration = line;
} else if (line.contains(".load")) {
load = line;
@ -139,7 +143,7 @@ public class GeneratorWithInnerPropertiesTest {
Matchers.containsString("properties.load(Application_Properties.class.getResourceAsStream(\"/application.properties\"));"));
}
@Test
void testOneInputGeneratesOneOutput() throws IOException, GeneratorException {

@ -5,42 +5,30 @@ import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import de.kreth.property2java.generated.GenerateTheTest;
public class TestPropertiesSource {
public static StringReader testProperties() {
return new StringReader("""
label =
label.addarticle = Add Article
label.cancel = Cancel
label.close = Close
label.delete = Delete
label.discart = Discart
label.loggedin = Logged in:
label.logout = Logout
label.ok = OK
label.store = Store
label.preview = Preview
label.open = Open
label.user.register = Register
message.article.priceerror = Please set the price.
message.delete.text = Delete {0}?
message.delete.title = Really delete?
message.invoiceitem.allfieldsmustbeset = Start, end and article must not be \\r\\n\
empty!
message.invoiceitem.startbeforeend = End must be later than start.
message.user.create.success = Thanks {0} created!
message.user.loginfailure = Login Error! Wrong user or password?
message.user.passwordmissmatch = Passwords don't match.
message.with.five.placeholders = Third is first{2}, then last "{4}", second={1}, fourth={3} and first is last={0}
""");
return new StringReader("\r\n" + "label = \r\n" + "\r\n" + "label.addarticle = Add Article\r\n"
+ "label.cancel = Cancel\r\n" + "label.close = Close\r\n"
+ "label.delete = Delete\r\n" + "label.discart = Discart\r\n"
+ "label.loggedin = Logged in:\r\n" + "label.logout = Logout\r\n"
+ "label.ok = OK\r\n" + "label.store = Store\r\n"
+ "label.preview = Preview\r\n" + "label.open = Open\r\n"
+ "label.user.register = Register\r\n" + "\r\n"
+ "message.article.priceerror = Please set the price.\r\n"
+ "message.delete.text = Delete {0}?\r\n"
+ "message.delete.title = Really delete?\r\n"
+ "message.invoiceitem.allfieldsmustbeset = Start, end and article must not be \\r\\n"
+ " empty!\r\n"
+ "message.invoiceitem.startbeforeend = End must be later than start.\r\n"
+ "message.user.create.success = Thanks {0} created!\r\n"
+ "message.user.loginfailure = Login Error! Wrong user or password?\r\n"
+ "message.user.passwordmissmatch = Passwords don't match.\r\n"
+ "message.with.five.placeholders = Third is first{2}, then last \"{4}\", second={1}, fourth={3} and first is last={0}\r\n");
}
public static void main(String[] args) throws IOException {
File dir = new File("D:\\Markus\\programmierung\\workspace_clubhelper\\PropertyToJavaGenerator\\src\\test\\resources");
@ -48,7 +36,7 @@ public class TestPropertiesSource {
testProperties().transferTo(out);
System.out.println("Generated: " + GenerateTheTest.PROPERTY_LOADER_PROPERTIES);
}
try (FileWriter out = new FileWriter(new File(dir, GenerateTheTest.UNARY_OPERATOR_PROPERTIES))) {
testProperties().transferTo(out);
System.out.println("Generated: " + GenerateTheTest.UNARY_OPERATOR_PROPERTIES);
@ -61,6 +49,6 @@ public class TestPropertiesSource {
testProperties().transferTo(out);
System.out.println("Generated: " + GenerateTheTest.PROPERTY_LOADER_OPTIONS_PROPERTIES);
}
}
}

@ -3,6 +3,7 @@ package de.kreth.property2java.generated;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
@ -24,7 +25,7 @@ public class GenerateTheTest {
public static final String RESOURCE_BUNDLE = "resource_bundle.properties";
public static void main(String[] args) throws IOException, GeneratorException {
Path current = Path.of(".", "src", "test", "java", "de", "kreth", "property2java", "generated").toAbsolutePath().normalize();
Path current = Paths.get(".", "src", "test", "java", "de", "kreth", "property2java", "generated").toAbsolutePath().normalize();
System.out.println(current);
withUnaryOperatorParameter(current);

@ -5,6 +5,7 @@ import java.util.ResourceBundle;
import javax.annotation.processing.Generated;
import java.text.MessageFormat;
;
/**
* Property keys from property_loader_format.properties

@ -1,12 +1,12 @@
package de.kreth.property2java.parts;
public final class ReplaceLogicForTemplate {
public class ReplaceLogicForTemplate {
static String doReplacements(String property, Object...objects) {
StringBuilder text = new StringBuilder();
int index = property.indexOf('{');
text.append(property, 0, index);
text.append(property.substring(0, index));
while (index >= 0) {
index++;
int endIndex = withEndIndex(index, property);
@ -14,19 +14,19 @@ public final class ReplaceLogicForTemplate {
String theIndex = property.substring(index, endIndex);
int withIndex = Integer.valueOf(theIndex);
if (withIndex+1> objects.length) {
throw new IllegalStateException("No Argument for Index {" + theIndex +
"}" + " at Position=" + (index - 1) + " in \"" + property + "\"");
throw new IllegalStateException("No Argument for Index {" + theIndex
+ "}" + " at Position=" + (index - 1) + " in \"" + property + "\"");
}
text.append(objects[withIndex].toString());
index = property.indexOf('{', endIndex);
if (index <0) {
text.append(property.substring(endIndex + 1));
} else {
text.append(property, endIndex + 1, index);
text.append(property.substring(endIndex + 1, index));
}
} else {
endIndex = index;
index = property.indexOf('{', index);
if (index <0) {
text.append('{');
@ -36,7 +36,7 @@ public final class ReplaceLogicForTemplate {
}
return text.toString();
}
/**
* extracts the end index, if (and only if) the closing } exists and
* between the indicee an integer value exists.
@ -45,15 +45,15 @@ public final class ReplaceLogicForTemplate {
* @return -1 if invalid or not existing
*/
private static int withEndIndex(int index, String property) {
int result = -1;
int endIndex = property.indexOf('}', index);
if (endIndex >index) {
String between = property.substring(index, endIndex);
if (between.length() > 0) {
result = endIndex;
for (int i = 0; i < between.length(); i++) {
if (!Character.isDigit(between.charAt(i))) {
for(int i=0; i<between.length(); i++) {
if (Character.isDigit(between.charAt(i)) == false) {
return -1;
}
}
@ -62,7 +62,4 @@ public final class ReplaceLogicForTemplate {
return result;
}
private ReplaceLogicForTemplate() {
}
}
}

@ -1,14 +1,11 @@
package de.kreth.property2java.parts;
import static org.assertj.core.api.Assertions.*;
import static de.kreth.property2java.parts.ReplaceLogicForTemplate.doReplacements;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.jupiter.api.Test;
public class ReplaceLogicForTemplateTest {
@Test
void testPlaceholderOnly() {
String property = "{0}";
@ -81,5 +78,5 @@ public class ReplaceLogicForTemplateTest {
.hasMessageContaining("Position=5") // Index of missing Placeholder
.hasMessageContaining(property); // Orignal Text
}
}

@ -1,19 +1,15 @@
package de.kreth.property2java.processor;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -42,40 +38,10 @@ public class Property2JavaGeneratorTest {
when(processingEnv.getMessager()).thenReturn(messanger);
}
@SuppressWarnings({"unchecked", "rawtypes"})
@SuppressWarnings("unchecked")
@Test
void testGeneratorInitializedCorrectly() {
GenerateProperty2Java an = mock(GenerateProperty2Java.class);
when(an.resources()).thenReturn(new String[]{});
TypeElement element = mock(TypeElement.class);
when(element.getAnnotation(GenerateProperty2Java.class)).thenReturn(an);
annotations.add(element);
when(roundEnv.getElementsAnnotatedWith(ArgumentMatchers.any(Class.class))).thenReturn(annotations);
Element annotatedElement = mock(Element.class);
GenerateResourceBundleProperty2Javas value = new GenerateResourceBundleProperty2Javas() {
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
@Override
public GenerateResourceBundleProperty2Java[] value() {
return new GenerateResourceBundleProperty2Java[0];
}
};
when(annotatedElement.getAnnotation(GenerateResourceBundleProperty2Javas.class)).thenReturn(value);
Set<Element> elements = new HashSet<>(List.of(annotatedElement));
when(roundEnv.getElementsAnnotatedWith(GenerateResourceBundleProperty2Javas.class))
.thenReturn((Set) elements);
processor.process(annotations, roundEnv);
}
}

Loading…
Cancel
Save