We can create a resource loader that can be used to load resource bundles that do not follow Wicket's general naming scheme. One use of these would be if your application has a mixture of different frameworks, but you would like to keep your resources in a central location.

Custom Resource Loader Class
public class ExternalResourceLoader implements IStringResourceLoader {
	private static final Logger logger = LoggerFactory.getLogger(ExternalResourceLoader.class);

	private String _resourceBundleName;
	
	public ExternalResourceLoader(String resourceBundleName) {
		_resourceBundleName = resourceBundleName;
	}
	
	public String loadStringResource(Component component, String key) {
		return findResource(component.getLocale(), key);
	}

	public String loadStringResource(Class<?> clazz, String key, Locale locale, String style) {
		return findResource(locale, key);
	}
	
	private String findResource(Locale locale, String key) {
		String string = null;

		ResourceBundle resourceBundle = null;
		try {
			resourceBundle = ResourceBundle.getBundle(_resourceBundleName, locale);
		} catch (MissingResourceException e) {
			if (shouldThrowExceptionForMissingResource()) {
				throw new WicketRuntimeException(String.format("Unable able to locate resource bundle for the specifed base name: %s", _resourceBundleName));
			}
			
			logger.warn("Unable able to locate resource bundle for the specifed base name: {}", _resourceBundleName);
		}
		
		if (resourceBundle != null) {
			boolean caught = false;
			
			try {
				string = resourceBundle.getString(key);
			} catch (MissingResourceException e) {
				caught = true;
			}
			
			if (caught || string == null) {
				if (shouldThrowExceptionForMissingResource()) {
					throw new WicketRuntimeException(String.format("Unable able to locate resource bundle for the specifed base name: %s", _resourceBundleName));
				}				

				logger.warn("No value found key {} in resource bundle {}.", key, _resourceBundleName);
			}
		}
		
		return string;
	}
	
	private boolean shouldThrowExceptionForMissingResource() 
                return turn Application.get().getResourceSettings().getThrowExceptionOnMissingResource();
	}
}
Register the custom resource loader in your application's init() function
protected void init() {  
    getResourceSettings().addStringResourceLoader(new ExternalResourceLoader("baseName")); 
}
  • No labels