Skip to content

Instantly share code, notes, and snippets.

@svenmeier
Created February 9, 2016 08:32
Show Gist options
  • Save svenmeier/9024f7563bc68ce7dfdf to your computer and use it in GitHub Desktop.
Save svenmeier/9024f7563bc68ce7dfdf to your computer and use it in GitHub Desktop.
package org.apache.wicket.examples.compref;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.wicket.Component;
import org.apache.wicket.resource.loader.IStringResourceLoader;
public class NestedStringResourceLoader implements IStringResourceLoader
{
private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\{\\{([^ ]*?)\\}\\}");
private List<IStringResourceLoader> loaders;
public NestedStringResourceLoader(List<IStringResourceLoader> loaders)
{
this.loaders = new ArrayList<>(loaders);
}
@Override
public String loadStringResource(Component component, String key, Locale locale, String style,
String variation)
{
Iterator<IStringResourceLoader> iter = loaders.iterator();
String value = null;
while (iter.hasNext() && (value == null))
{
IStringResourceLoader loader = iter.next();
value = loader.loadStringResource(component, key, locale, style, variation);
}
if (value != null) {
StringBuffer output = new StringBuffer();
Matcher matcher = PLACEHOLDER_PATTERN.matcher(value);
// Search for other nested keys to replace
while (matcher.find())
{
String replacedPlaceHolder = loadStringResource(component, matcher.group(1), locale, style, variation);
matcher.appendReplacement(output, replacedPlaceHolder);
}
matcher.appendTail(output);
value = output.toString();
}
return value;
}
@Override
public String loadStringResource(Class<?> clazz, String key, Locale locale, String style,
String variation)
{
Iterator<IStringResourceLoader> iter = loaders.iterator();
String value = null;
while (iter.hasNext() && (value == null))
{
IStringResourceLoader loader = iter.next();
value = loader.loadStringResource(clazz, key, locale, style, variation);
}
if (value != null) {
StringBuffer output = new StringBuffer();
Matcher matcher = PLACEHOLDER_PATTERN.matcher(value);
// Search for other nested keys to replace
while (matcher.find())
{
String replacedPlaceHolder = loadStringResource(clazz, key, locale, style, variation);
matcher.appendReplacement(output, replacedPlaceHolder);
}
matcher.appendTail(output);
value = output.toString();
}
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment