Reputation: 114
I want to use app_config file in my code and want to load it when starting the project in server.
package test.controller;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.mysql.cj.core.util.StringUtils;
import test.config.AppConfig;
import test.connection.jdbc.JDBCConnection;
@ApplicationPath("webapp")
public class RestApplication extends Application{
public static final String CONFIG_FILE = "C:\\Users\\chakrabo\\eclipse-workspace\\HelloWorld\\config\\src\\main\\resources\\app-config.xml";
private static ObjectMapper objectMapper = new XmlMapper();
public static AppConfig appConfig = getConfig();
public static Connection con = JDBCConnection.getConnection(appConfig.getDbUrl(),
appConfig.getUsername(), appConfig.getPassword());
private static AppConfig getConfig() {
try {
AppConfig config = objectMapper.readValue(
StringUtils.toString(Files.readAllBytes(Paths.get(CONFIG_FILE))), AppConfig.class);
return config;
} catch(Exception e) {
System.out.println("RestApplication : getConfig " +e.getMessage());
return null;
}
}
}
With actual path i am able to read this app-config file. but i dont know how to read it based on relative path.
Context should be HelloWorld(project name) but it does not work. even if i put this config folder inside webcontent and WEB-INF still it says file not found exception.
can anyone help me.
Upvotes: 0
Views: 1087
Reputation: 1
You can use the following:
RestApplication.getClass().getClassLoader().getResourceAsStream("app-config.xml")));
With this you can load files from src/main/resources
folder
Upvotes: 0
Reputation: 1042
To get the path to a file, try using the ServletContext.
Make a field (global instance variable) in the Application as such:
@Context
ServletContext servletContext;
Then use
String path = servletContext.getRealPath("/WEB-INF/app-config.xml");
This makes use of JAX-RS's built-in Dependency Injection mechanism.
You need the Servlet API as such
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
Upvotes: 1