I'm currently building a RESTful API using Jersey. So far, all has been going well, however, all of the configuration entries have been hard coded in. (i.e. Database Host, Database Username, etc...).
I'd like to be able to setup a config.properties
file that exists in my WEB-INF
folder to contain all of these configuration specs.
I'm concerned that if I do it the "classic" way of reading the file on the Classpath, I'm performing file I/O for every request. I want to be able to read once on startup (which I know involves a ServletListener
in my web.xml
file.
Here's what I have below:
web.xml:
<listener>
<listener-class>com._1834Software.Config</listener-class>
</listener>
I'd like to do something like this (which I found here on StackOverflow) but I don't think it works necessarily with Jersey:
Config.java
public class Config implements ServletContextListener {
private static final String ATTRIBUTE_NAME = "config";
private Properties config = new Properties();
@Override
public void contextInitialized(ServletContextEvent event) {
try {
config.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));
} catch (IOException err) {
err.printStackTrace();
}
event.getServletContext().setAttribute(ATTRIBUTE_NAME, this);
}
@Override
public void contextDestroyed(ServletContextEvent event) { /**/ }
public static Config getInstance(ServletContext context) {
return (Config) context.getAttribute(ATTRIBUTE_NAME);
}
public String getProperty(String key) {
return config.getProperty(key);
}
}
I try to call it like such:
Config config = Config.getInstance(getServletContext());
String property = config.getProperty("HEROKU_DATABASE_URL");
But I get the following error:
Error:(32, 40) java: cannot find symbol
symbol: method getServletContext()
location: class com._1834Software.database.DatabaseHandler
And here is the file (DatabaseHandler.java
where I'm trying to call it):
public class DatabaseHandler {
public Connection connection = null;
Config config = Config.getInstance(getServletContext());
String property = config.getProperty("somekey");
/* Database Parameters */
private String DRIVER = "org.postgresql.Driver";
private String host = "XXXXX";
private String userName = "XXXXX";
private String password = "XXXXX";
public void connect() throws SQLException {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException err) {
err.printStackTrace();
}
try {
connection = DriverManager.getConnection(host, userName, password);
} catch (SQLException err) {
err.printStackTrace();
}
}
public void disconnect() throws SQLException { connection.close(); }
}
java: cannot find symbol
.