I worked on several projects that had lots of problems with how they handled texts. Especially the problem was more expressed in bigger projects that had several teams working on them. The problem usually comes from process – who defines text key naming convention, do developers follow these convention, who writes and translates texts, how are frequent change requests from customer handled, internationalization etc… Some projects end up having lots of unused text keys, and perhaps some text values are not even defined. The one problem I run into is having almost same key value pairs in same property file, the only difference being case of one letter of text key.

Recently, we started developing on a completely new project from scratch. We decided we will read text values from database, as experience from previous project showed that there will be lots of changes in texts even after project goes live. Although I was skeptical at first, this turned out to be OK, especially as we have good caching mechanism. So to update texts, person responsible for this just has to upload new text file via back-office, and than clear cache.

The problem to have all texts covered in our text properties file exactly one time we solved with a simple unit test. What we did is scan our source files and read all of text keys, and than check if all of them are covered in text property file, and also check if all of property file texts are used in code. This is of course not possible in every case, but worked pretty well in our case.
As we use Stripes Framework we are only setting texts in ActionBeans classes. And of course, we are using them in our jsp files – and as one of our requirement is to support older servers (pre jsp 2.0) we use this workaround to set texts. So this is only 2 packages / folders to scan, and look for two regular expressions. We used Java Scanner to scan all source files.


Scanner scanner = new Scanner(new FileReader(filePath));
try {
	// first use a Scanner to read each line
	while (scanner.hasNextLine()) {
		String textKey = findTextKey(scanner.nextLine());
		if (textKey != null) {
			textKeys.addProperty(textKey, "");
		}
	}
} finally {
	scanner.close();
}


In method we use Regular Expressions and Scanner to check if in selected source line we are using text key. For jsp files in our case the next snippet is used


Scanner scanner = new Scanner(aLine);
Pattern jspTextPattern = Pattern.compile("actionBean.text["(.+)"]");
String found = scanner.findInLine(jspTextPattern);
if (StringUtils.isNotBlank(found)) {
	found = StringUtils.right(found, found.length() - 17);
	found = StringUtils.left(found, found.length() - 2);
	return found;
} else {
	return null;
}



Although this solution will not solve all text problems and couldn`t be used in every project, in our case it turned out to be very useful. If you have any questions or comments please feel free to comment here.

0 comments