Test fixes for freemarker template

REL-BRANCH-PropertyToJavaGenerator-0.0.1
Markus Kreth 7 years ago
parent ef5cdbfe4e
commit 9bf094d376
  1. 94
      src/main/java/de/kreth/property2java/Configuration.java
  2. 57
      src/main/java/de/kreth/property2java/FreemarkerConfig.java
  3. 229
      src/main/java/de/kreth/property2java/Generator.java
  4. 19
      src/main/java/de/kreth/property2java/GeneratorException.java
  5. 104
      src/main/java/de/kreth/property2java/cli/CliConfig.java
  6. 103
      src/test/java/de/kreth/property2java/ConfigurationTest.java
  7. 354
      src/test/java/de/kreth/property2java/GeneratorTests.java

@ -1,47 +1,47 @@
package de.kreth.property2java;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Path;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.commons.text.WordUtils;
public interface Configuration {
static final Pattern REGEX = Pattern.compile("_[a-z]{2}(_[A-Z]{2})?\\.");
/**
* Package for generated Java Classes eg. "de.kreth.property2java". If null - no package line is generated.
* @return
*/
String getPackage();
/**
* Filename to InputReader Entries
* @return
*/
Map<String, Reader> getInput();
/**
* Path of java source folder.
* @return
*/
Path getRootPath();
default Writer outWriter(String fileName) throws IOException {
return new FileWriter(new File(getRootPath().toFile(), mapFilenameToClassName(fileName)));
}
default String mapFilenameToClassName(String fileName) {
String path = REGEX.matcher(fileName).replaceAll(".").replaceAll("\\.", "_").replaceAll(" ", "_");
path = WordUtils.capitalize(path, '_');
return path;
}
}
package de.kreth.property2java;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Path;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.commons.text.WordUtils;
public interface Configuration {
static final Pattern REGEX = Pattern.compile("_[a-z]{2}(_[A-Z]{2})?\\.");
/**
* Package for generated Java Classes eg. "de.kreth.property2java". If null - no package line is generated.
* @return
*/
String getPackage();
/**
* Filename to InputReader Entries
* @return
*/
Map<String, Reader> getInput();
/**
* Path of java source folder.
* @return
*/
Path getRootPath();
default Writer outWriter(String fileName) throws IOException {
return new FileWriter(new File(getRootPath().toFile(), mapFilenameToClassName(fileName) + ".java"));
}
default String mapFilenameToClassName(String fileName) {
String path = REGEX.matcher(fileName).replaceAll(".").replaceAll("\\.", "_").replaceAll(" ", "_");
path = WordUtils.capitalize(path, '_');
return path;
}
}

@ -1,33 +1,24 @@
package de.kreth.property2java;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import freemarker.template.Configuration;
import freemarker.template.Template;
public enum FreemarkerConfig {
INSTANCE;
private final Configuration cfg;
public Template getTemplate() throws IOException {
return cfg.getTemplate("enum_template.tpl");
}
private FreemarkerConfig() {
cfg = new Configuration(Configuration.VERSION_2_3_28);
URL url = getClass().getResource("/template/enum_template.tpl");
try {
cfg.setDirectoryForTemplateLoading(new File(url.getFile()).getParentFile());
}
catch (IOException e) {
throw new IllegalStateException("Unable to configure freemarker", e);
}
cfg.setDefaultEncoding("UTF-8");
}
}
package de.kreth.property2java;
import java.io.IOException;
import freemarker.template.Configuration;
import freemarker.template.Template;
public enum FreemarkerConfig {
INSTANCE;
private final Configuration cfg;
public Template getTemplate() throws IOException {
return cfg.getTemplate("enum_template.tpl");
}
private FreemarkerConfig() {
cfg = new Configuration(Configuration.VERSION_2_3_28);
cfg.setClassForTemplateLoading(this.getClass(), "/template/");
cfg.setDefaultEncoding("UTF-8");
}
}

@ -1,108 +1,121 @@
package de.kreth.property2java;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import de.kreth.property2java.cli.ArgumentConfiguration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class Generator {
private static final DateFormat dateTimeInstance = DateFormat.getDateTimeInstance();
private final Configuration config;
private final Template template;
public Generator(Configuration config) {
this.config = config;
try {
template = FreemarkerConfig.INSTANCE.getTemplate();
}
catch (IOException e) {
throw new IllegalStateException("Unable to load freemarker template", e);
}
}
public void start() throws IOException, TemplateException {
for (Map.Entry<String, Reader> entry : config.getInput().entrySet()) {
String fileName = entry.getKey();
Writer out = config.outWriter(fileName);
Properties properties = new Properties();
properties.load(entry.getValue());
generate(properties, out, fileName, config);
}
}
void generate(Properties properties, Writer out, String fileName, Configuration config)
throws IOException, TemplateException {
Map<String, Object> root = new HashMap<>();
root.put("generator_name", getClass().getName());
root.put("generation_date", dateTimeInstance.format(new Date()));
root.put("package", config.getPackage());
root.put("fileName", fileName);
root.put("classname", config.mapFilenameToClassName(fileName));
List<Entry> entries = new ArrayList<>();
root.put("entries", entries);
@SuppressWarnings("unchecked")
Enumeration<String> propertyNames = (Enumeration<String>) properties.propertyNames();
while (propertyNames.hasMoreElements()) {
final String propertyKeyString = propertyNames.nextElement();
final String propertyValue = properties.getProperty(propertyKeyString);
entries.add(new Entry(propertyKeyString.toUpperCase().replaceAll("[\\.-]", "_"), propertyKeyString,
propertyValue));
}
template.process(root, out);
}
public static void main(String[] args) throws IOException, TemplateException {
Generator generator = new Generator(ArgumentConfiguration.parse(args));
generator.start();
}
public class Entry {
public final String constant;
public final String key;
public final String value;
public Entry(String constant, String key, String value) {
super();
this.constant = constant;
this.key = key;
this.value = value;
}
public String getConstant() {
return constant;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
}
}
package de.kreth.property2java;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import de.kreth.property2java.cli.ArgumentConfiguration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class Generator {
private static final DateFormat dateTimeInstance = DateFormat.getDateTimeInstance();
private final Configuration config;
private final Template template;
public Generator(Configuration config) {
this.config = config;
try {
template = FreemarkerConfig.INSTANCE.getTemplate();
}
catch (IOException e) {
throw new IllegalStateException("Unable to load freemarker template", e);
}
}
public void start() throws IOException, GeneratorException {
for (Map.Entry<String, Reader> entry : config.getInput().entrySet()) {
String fileName = entry.getKey();
try (Writer out = config.outWriter(new File(fileName).getName())) {
Properties properties = new Properties();
properties.load(entry.getValue());
try {
generate(properties, out, fileName, config);
}
catch (TemplateException e) {
throw new GeneratorException("Error configuring Engine", e);
}
}
}
}
void generate(Properties properties, Writer out, String fileName, Configuration config)
throws IOException, TemplateException {
Map<String, Object> root = new HashMap<>();
root.put("generator_name", getClass().getName());
root.put("generation_date", dateTimeInstance.format(new Date()));
root.put("package", config.getPackage());
root.put("fileName", fileName);
root.put("classname", config.mapFilenameToClassName(fileName));
List<Entry> entries = new ArrayList<>();
root.put("entries", entries);
@SuppressWarnings("unchecked")
Enumeration<String> propertyNames = (Enumeration<String>) properties.propertyNames();
while (propertyNames.hasMoreElements()) {
final String propertyKeyString = propertyNames.nextElement();
final String propertyValue = properties.getProperty(propertyKeyString);
entries.add(new Entry(propertyKeyString.toUpperCase().replaceAll("[\\.-]", "_"), propertyKeyString,
propertyValue));
}
template.process(root, out);
}
public static void main(String[] args) throws IOException, GeneratorException {
Generator generator = new Generator(ArgumentConfiguration.parse(args));
generator.start();
}
public class Entry {
public final String constant;
public final String key;
public final String value;
public Entry(String constant, String key, String value) {
super();
this.constant = constant;
this.key = key;
this.value = value;
}
public String getConstant() {
return constant;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return "Entry [constant=" + constant + ", key=" + key + ", value=" + value + "]";
}
}
}

@ -0,0 +1,19 @@
package de.kreth.property2java;
public class GeneratorException extends Exception {
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);
}
}

@ -1,52 +1,52 @@
package de.kreth.property2java.cli;
import java.io.IOException;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.MissingOptionException;
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();
private Options options() {
Options retVal = new Options();
retVal.addOption(Option.builder("t").longOpt("targetSourcePath").hasArg().required().build());
retVal.addOption(Option.builder("f").longOpt("files").hasArgs().required().valueSeparator(',').build());
retVal.addOption(Option.builder("p").longOpt("package").hasArg().required(false).build());
return retVal;
}
public void fill(Builder builder, String[] args) throws IOException {
CommandLineParser parser = new DefaultParser();
try {
CommandLine cmd = parser.parse(options, args);
builder.setTarget(cmd.getOptionValue("t", "."));
builder.setPackageName(cmd.getOptionValue("p"));
for (String value : cmd.getOptionValues("f")) {
builder.addPropFile(value);
}
}
catch (MissingOptionException e) {
printHelp();
throw new IllegalStateException(e);
}
catch (ParseException e) {
throw new IOException("Unable to parse Arguments", e);
}
}
public void printHelp() {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("Generator", options);
}
}
package de.kreth.property2java.cli;
import java.io.IOException;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.MissingOptionException;
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();
private Options options() {
Options retVal = new Options();
retVal.addOption(Option.builder("t").longOpt("targetSourcePath").hasArg().required().build());
retVal.addOption(Option.builder("f").longOpt("files").hasArgs().required().valueSeparator(',').build());
retVal.addOption(Option.builder("p").longOpt("package").hasArg().required(false).build());
return retVal;
}
public void fill(Builder builder, String[] args) throws IOException {
CommandLineParser parser = new DefaultParser();
try {
CommandLine cmd = parser.parse(options, args);
builder.setTarget(cmd.getOptionValue("t", "."));
builder.setPackageName(cmd.getOptionValue("p"));
for (String value : cmd.getOptionValues("f")) {
builder.addPropFile(value);
}
}
catch (MissingOptionException e) {
printHelp();
throw new IllegalStateException(e);
}
catch (ParseException e) {
throw new IOException("Unable to parse Arguments", e);
}
}
public void printHelp() {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("Generator", options);
}
}

@ -1,50 +1,53 @@
package de.kreth.property2java;
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;
import java.io.FileWriter;
import java.io.IOException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class ConfigurationTest {
private Configuration config;
@BeforeEach
void initConfig() {
config = Mockito.mock(Configuration.class);
}
@Test
void defaultWriterIsFileWriter() throws IOException {
when(config.outWriter(anyString())).thenCallRealMethod();
when(config.mapFilenameToClassName(anyString())).thenCallRealMethod();
assertTrue(config.outWriter("application.properties") instanceof FileWriter);
}
@Test
void testPathMapping() {
when(config.mapFilenameToClassName(anyString())).thenCallRealMethod();
String className = config.mapFilenameToClassName("application.properties");
assertEquals("Application_Properties", className);
}
@Test
void testPathMappingLocalized() {
when(config.mapFilenameToClassName(anyString())).thenCallRealMethod();
String className = config.mapFilenameToClassName("application_de_DE.properties");
assertEquals("Application_Properties", className);
className = config.mapFilenameToClassName("application_en_US.properties");
assertEquals("Application_Properties", className);
}
}
package de.kreth.property2java;
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;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class ConfigurationTest {
private Configuration config;
@BeforeEach
void initConfig() {
config = Mockito.mock(Configuration.class);
}
@Test
void defaultWriterIsFileWriter() throws IOException {
when(config.outWriter(anyString())).thenCallRealMethod();
when(config.getRootPath()).thenReturn(new File(".").toPath());
when(config.mapFilenameToClassName(anyString())).thenCallRealMethod();
Writer outWriter = config.outWriter("application.properties");
assertTrue(outWriter instanceof FileWriter);
}
@Test
void testPathMapping() {
when(config.mapFilenameToClassName(anyString())).thenCallRealMethod();
String className = config.mapFilenameToClassName("application.properties");
assertEquals("Application_Properties", className);
}
@Test
void testPathMappingLocalized() {
when(config.mapFilenameToClassName(anyString())).thenCallRealMethod();
String className = config.mapFilenameToClassName("application_de_DE.properties");
assertEquals("Application_Properties", className);
className = config.mapFilenameToClassName("application_en_US.properties");
assertEquals("Application_Properties", className);
}
}

@ -1,178 +1,176 @@
package de.kreth.property2java;
import static org.hamcrest.MatcherAssert.assertThat;
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.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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;
import freemarker.template.TemplateException;
class GeneratorTests {
private String path = "application.properties";
private Configuration config;
private Generator generator;
@BeforeEach
void setUp() throws Exception {
Map<String, Reader> input = new HashMap<>();
input.put(path, testProperties());
config = mock(Configuration.class);
when(config.getInput()).thenReturn(input);
when(config.mapFilenameToClassName(anyString())).thenCallRealMethod();
generator = new Generator(config);
}
@Test
void testClassDefinition() throws IOException, TemplateException {
when(config.getPackage()).thenReturn("de.kreth.property2java");
when(config.mapFilenameToClassName(anyString())).thenCallRealMethod();
StringWriter out = new StringWriter();
when(config.outWriter(anyString())).thenReturn(out);
generator.start();
String sourceCode = out.toString().trim();
StringTokenizer sourceTokenizer = new StringTokenizer(sourceCode, "\n");
String linePackage = null;
String lineClass = null;
int countOpenBaces = 0;
int countCloseBaces = 0;
while (sourceTokenizer.hasMoreTokens()) {
String line = sourceTokenizer.nextToken();
if (line.trim().startsWith("package")) {
linePackage = line;
}
else if (line.trim().startsWith("public enum")) {
lineClass = line;
}
if (line.contains("{")) {
countOpenBaces++;
}
if (line.contains("}")) {
countCloseBaces++;
}
}
assertEquals(countCloseBaces, countOpenBaces,
"Count of Braces doesn't match. Open = " + countOpenBaces + ", Close = " + countCloseBaces);
assertNotNull(linePackage);
assertNotNull(lineClass);
assertThat(linePackage,
Matchers.stringContainsInOrder(Arrays.asList("package", "de.kreth.property2java", ";")));
assertThat(lineClass,
Matchers.stringContainsInOrder(Arrays.asList("public", "enum", "Application_Properties")));
}
@Test
void testOneInputGeneratesOneOutput() throws IOException, TemplateException {
Writer out = mock(Writer.class);
Writer nonOut = mock(Writer.class);
when(config.outWriter(anyString())).thenReturn(out, nonOut);
generator.start();
verify(out).close();
verify(nonOut, never()).close();
verify(nonOut, never()).flush();
}
@Test
void testKeys() throws IOException, TemplateException {
StringWriter out = new StringWriter();
when(config.outWriter(anyString())).thenReturn(out);
generator.start();
List<String> lines = out.toString().lines().filter(line -> line.contains(" String "))
.collect(Collectors.toList());
assertEquals(21, lines.size());
assertLineMatch(lines, "label", "label");
assertLineMatch(lines, "label_addarticle", "label.addarticle");
assertLineMatch(lines, "label_user_register", "label.user.register");
assertLineMatch(lines, "message_article_priceerror", "message.article.priceerror");
assertLineMatch(lines, "message_invoiceitem_startbeforeend", "message.invoiceitem.startbeforeend");
assertLineMatch(lines, "message_invoiceitem_allfieldsmustbeset",
"message.invoiceitem.allfieldsmustbeset");
}
private void assertLineMatch(List<String> lines, String key, String expected) {
Optional<String> found = lines.stream().filter(line -> keyMatches(line, key))
.findFirst();
assertTrue(found.isPresent(), "No line found with key = " + key);
final String line = found.get().trim();
int indexEquals = line.indexOf('=');
String value = line.substring(indexEquals + 1).trim().substring(1);
value = value.substring(0, value.length() - 2);
assertEquals(expected, value, "Line \"" + line + "\" don't match expected Value \"" + expected + "\"");
assertEquals(';', line.charAt(line.length() - 1), "Line \"" + line + "\" don't end with ;");
}
private boolean keyMatches(String line, String key) {
line = line.toLowerCase();
key = key.toLowerCase();
return line.contains(" " + key + " ");
}
private StringReader testProperties() {
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" +
"");
}
}
package de.kreth.property2java;
import static org.hamcrest.MatcherAssert.assertThat;
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.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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;
class GeneratorTests {
private String path = "application.properties";
private Configuration config;
private Generator generator;
@BeforeEach
void setUp() throws Exception {
Map<String, Reader> input = new HashMap<>();
input.put(path, testProperties());
config = mock(Configuration.class);
when(config.getInput()).thenReturn(input);
when(config.mapFilenameToClassName(anyString())).thenCallRealMethod();
generator = new Generator(config);
}
@Test
void testClassDefinition() throws IOException, GeneratorException {
when(config.getPackage()).thenReturn("de.kreth.property2java");
when(config.mapFilenameToClassName(anyString())).thenCallRealMethod();
StringWriter out = new StringWriter();
when(config.outWriter(anyString())).thenReturn(out);
generator.start();
String sourceCode = out.toString().trim();
StringTokenizer sourceTokenizer = new StringTokenizer(sourceCode, "\n");
String linePackage = null;
String lineClass = null;
int countOpenBaces = 0;
int countCloseBaces = 0;
while (sourceTokenizer.hasMoreTokens()) {
String line = sourceTokenizer.nextToken();
if (line.trim().startsWith("package")) {
linePackage = line;
}
else if (line.trim().startsWith("public enum")) {
lineClass = line;
}
if (line.contains("{")) {
countOpenBaces++;
}
if (line.contains("}")) {
countCloseBaces++;
}
}
assertEquals(countCloseBaces, countOpenBaces,
"Count of Braces doesn't match. Open = " + countOpenBaces + ", Close = " + countCloseBaces);
assertNotNull(linePackage);
assertNotNull(lineClass);
assertThat(linePackage,
Matchers.stringContainsInOrder(Arrays.asList("package", "de.kreth.property2java", ";")));
assertThat(lineClass,
Matchers.stringContainsInOrder(Arrays.asList("public", "enum", "Application_Properties")));
}
@Test
void testOneInputGeneratesOneOutput() throws IOException, GeneratorException {
Writer out = mock(Writer.class);
Writer nonOut = mock(Writer.class);
when(config.outWriter(anyString())).thenReturn(out, nonOut);
generator.start();
verify(out).close();
verify(nonOut, never()).close();
verify(nonOut, never()).flush();
}
@Test
void testKeys() throws IOException, GeneratorException {
StringWriter out = new StringWriter();
when(config.outWriter(anyString())).thenReturn(out);
generator.start();
List<String> lines = out.toString().lines().filter(line -> line.contains(" (\""))
.collect(Collectors.toList());
assertEquals(21, lines.size());
assertLineMatch(lines, "label", "label");
assertLineMatch(lines, "label_addarticle", "label.addarticle");
assertLineMatch(lines, "label_user_register", "label.user.register");
assertLineMatch(lines, "message_article_priceerror", "message.article.priceerror");
assertLineMatch(lines, "message_invoiceitem_startbeforeend",
"message.invoiceitem.startbeforeend");
assertLineMatch(lines, "message_invoiceitem_allfieldsmustbeset",
"message.invoiceitem.allfieldsmustbeset");
}
private void assertLineMatch(List<String> lines, String key, String expected) {
Optional<String> found = lines.stream().filter(line -> keyMatches(line, key))
.findFirst();
assertTrue(found.isPresent(), "No line found with key = " + key);
final String line = found.get().trim();
int indexEquals = line.indexOf('(');
String value = line.substring(indexEquals + 1).trim().substring(1);
value = value.substring(0, value.length() - 3);
assertEquals(expected, value, "Line \"" + line + "\" don't match expected Value \"" + expected + "\"");
}
private boolean keyMatches(String line, String key) {
line = line.toLowerCase();
key = key.toLowerCase();
return line.contains("\t" + key + " ");
}
private StringReader testProperties() {
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" +
"");
}
}

Loading…
Cancel
Save