Skip to content

Instantly share code, notes, and snippets.

@Tzrlk
Created December 3, 2014 01:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tzrlk/82d74c074e63955a8a35 to your computer and use it in GitHub Desktop.
Save Tzrlk/82d74c074e63955a8a35 to your computer and use it in GitHub Desktop.
A ResourceBundle Control for reading files off a ServletContext.
package nz.co.aetheric.web.servlet;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.ServletContext;
import java.io.IOException;
import java.io.InputStream;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Locale;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
/**
* This class controls the way that resource bundles are loaded from the servlet context instead of the class loader.
* <p>Author: <a href="http://gplus.to/tzrlk">Peter Cummuskey</a></p>
*/
@Slf4j
@RequiredArgsConstructor
public class ServletContextBundleControl extends ResourceBundle.Control {
protected final ServletContext context;
@Override
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
throws IllegalAccessException, InstantiationException, IOException {
final String path = toBundleName(baseName, locale) + ".properties";
final PrivilegedResourceLoad privileged = new PrivilegedResourceLoad(path);
try (InputStream stream = privileged.perform()) {
return stream != null
? new PropertyResourceBundle(stream)
: null;
}
}
@RequiredArgsConstructor
public class PrivilegedResourceLoad implements PrivilegedExceptionAction<InputStream> {
protected final String resource;
@Override
public InputStream run() throws IOException {
return context.getResourceAsStream(resource);
}
public InputStream perform() throws IOException {
try {
return AccessController.doPrivileged(this);
} catch (PrivilegedActionException error) {
throw (IOException) error.getCause();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment