unable to access outside xml config file in spring boot jar - java

am trying to use an xml file from outside jar.now its getting null pointer exception
private static String getRequestConfigurationLocation() throws UnsupportedEncodingException
{
URL resourceURL = ConfigurationFactory.class.getResource(Configuration.XML_CONF);
//Assert.notNull(resourceURL, "Resource url is null : ");
String urlFilePath = resourceURL.getFile();
String actualFilePath = java.net.URLDecoder.decode(urlFilePath, StandardCharsets.UTF_8.name());
return actualFilePath;
}
Configuration
public class ConfigurationFactory
{
public static final String XML_CONF = "D:/DEV//X/X1/Service/target/conf/rConfiguration.xml";
}
how can i use external file in an executable jar
error log
Caused by: java.lang.NullPointerException

You should use java.util.Properties to access external file,
refer to this answer to load xml properties file

In your property file try :
external.config=D:/DEV//X/X1/Service/target/conf/rConfiguration.xml
Or
annotate your configuration file with following
#configuration
#ImportResource("D:/DEV//X/X1/Service/target/conf/rConfiguration.xml")

Related

Not able to read resource files from src/test/resources in STS

I created folder src/test/resources/ in root project directory, and inside this I added a file in folder jsons as jsons/server_request.json.
Now I am trying to read this file by calling a the static function in CommonTestUtilityclass given as:
public class CommonTestUtility {
public static String getFileAsString(String fileName) throws IOException {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
String content = new String(Files.readAllBytes(file.toPath()));
return content;
}
}
Now while calling this function as
class ServerTest {
#Test
void test_loadResource() {
String content = CommonTestUtility.getFileAsString("jsons/server_request.json");
}
}
, It's giving me the error as:
CommonTestUtility - Cannot invoke "java.net.URL.getFile()" because the return value of "java.lang.ClassLoader.getResource(String)" is null.
I tried to include the src/test/resources/ in the run configuration
of Junit ServerTest.java, but still it's not able to find out the
resource
How to resolve this issue?
https://mkyong.com/java/java-read-a-file-from-resources-folder/
This above link might be helpful.
The getResource() method return an URI you need to change
.getFile() function to. toURI().
Simple code
private File getFileFromResource(String fileName) throws URISyntaxException{
ClassLoader classLoader = getClass().getClassLoader();
URL resource = classLoader.getResource(fileName);
if (resource == null) {
throw new IllegalArgumentException("file not found! " + fileName);
} else {
// failed if files have whitespaces or special characters
//return new File(resource.getFile());
return new File(resource.toURI());
}
}
I recreated the same scenario you describe and your code works for me.
Could you double-check that your project looks like mine below? If so, I suspect it might be something with your environment.

java.io.FileNotFoundException: resourceedge-config.xml (The system cannot find the file specified)

I was using jboss server to deploy my applications and it works fine. My jboss server is corrupted, and I'm changing to tomcat 7.0.55 and its giving me error on my console
"java.io.FileNotFoundException: resourceedge-config.xml (The system cannot find the file specified)"
The resourceedge-config.xml is readingfrom this method:
public static Properties loadSystemConfiguration() throws FileNotFoundException, IOException{
return loadSystemConfiguration(ConfigReader.getFile_Prefix() + "-config.xml");
}
And it's also calling from my application filter class too which is:
//get the application context
ServletContext context = filterConfig.getServletContext();
String configFilePrefix = context.getInitParameter(ApplicationFilter.APPLICATION_CONFIG_FILE_PREFIX);
if(configFilePrefix != null){
ConfigReader.setFile_Prefix(configFilePrefix);
}
try{
configuration = ConfigReader.loadSystemConfiguration();
}catch(Exception e){
e.printStackTrace();
configuration = null;
}
The resourceedge-config.xml is place inside C:\apache-tomcat-7.0.55\bin
Please I need help on this to enable to read the file resourceedge-config.xml.
Thanks

reading config file from different folder java

I am trying to read a config file based on the code here:
http://www.opencodez.com/java/read-config-file-in-java.htm
So I found that if the config.cfg is in same directory as of where I am running the code, then everything is fine but if the config is at different directory
example: /path/to/config.cfg
I get this error:
java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:418)
at java.util.Properties.load0(Properties.java:337)
at java.util.Properties.load(Properties.java:325)
at packagename.conf.Config.<init>(Config.java:14)
at packagename.conf.Config.main(Config.java:30)
My guess is it is not able to find the file.
But how do I modify the above code to read config file from a different folder?
Thanks
Edit: Code from the link:
import java.util.*;
import java.util.Properties;
public class Config
{
Properties configFile;
public Config()
{
configFile = new java.util.Properties();
try {
configFile.load(this.getClass().getClassLoader().
getResourceAsStream("myapp/config.cfg"));
}catch(Exception eta){
eta.printStackTrace();
}
}
public String getProperty(String key)
{
String value = this.configFile.getProperty(key);
return value;
}
}
The code that you posted expects the configuration-file to be on the classpath (that is, in the same sorts of places that Java looks for your .class files). So, you can either include the directory containing the configuration-file in the classpath:
java -classpath .:/path/to packagename.conf.Config
Or else you can modify the code to expect the configuration-file to be a regular filesystem file:
final InputStream cfg = new FileInputStream("/path/to/config.cfg");
try
{ configFile.load(cfg); }
finally
{ cfg.close(); }

Where to keep `java.util.Properties` file and how to access it?

I am adding email sending capability to my web app. SMTP server settings will be read from a java.util.Properties file. I wouldn't like to hardcode path to this file.
Where should I keep this file?
How should I access this file?
A good pattern to follow is to keep your static resources (like property files) under your WEB-INF/classes/ directory.
That way they can be read from the classpath and not accessed by the browser:
for example, put your settings file under WEB-INF/classes/mail-settings.properties, and use the following to read it:
InputStream is = MyClass.class.getResourceAsStream("mail-settings.properties");
Properties p = new Properties();
p.load(is);
is.close();
Keep property file in classpath location like in folder : WEB-INF/classes/mail.properties
Here property file is - mail.properties. To read this file you can use below code
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class EmailPropertyReader {
private static ResourceBundle myResources;
public static String FILENAME = "mail";
static{
initialize(FILENAME);
}
public static void initialize(String propertyFile) throws MissingResourceException
{
try{
myResources = ResourceBundle.getBundle(FILENAME, Locale.getDefault());
}catch(Exception ex){
//Logger
}
}
private static String getParameter(String parmName)
{
String param = null;
try
{
param = myResources.getString(parmName) ;
}catch(Exception e){
param = null;
//Logger
}
if (param != null)
return param.trim();
else
return param;
}
}
You just create object and enter code here use method getParameter() ->
For example:
mail.properties :
EMAILID=a#a.com
then
String strEmailid=EmailPropertyReader.getParameter("EMAILID");
if you want to keep it with your code you may just as well create the Properties instance programmatically.
Properties mailProperties = new Properties();
mailProperties.setProperty("mail.transport.protocol", "smtp");
mailProperties.setProperty("mail.smtp.host", "localhost");
mailProperties.setProperty("mail.smtp.port", "587");
mailProperties.setProperty("mail.smtp.auth", "false");
javax.mail.Session.getInstance(mailProperties);
If you want to have it in a properties file anyway you can load it as a classpath resource. Have a look at getResourceAsStream in java.lang.Class. Update: see epochs answer for how to do this!
Here is a solution:
I have placed EmailSettings.properties file into WebContent\WEB-INF\classes. This code now works:
InputStream inputFile = this.getClass().getClassLoader().getResourceAsStream("EmailSettings.properties");
Properties emailConfig = new Properties();
emailConfig.load( inputFile );
.
.
.
If the settings are stage dependent ,you could set the path to the File via a vm Enviorment varibable.
-DmyPropertyFilePath=....
Also there is a good artikel about loading property files (even so it is a bit Dated) on Java World

java.util.Properties$LineReader.readLine

I need to read a config file
I get this error while running the following code:
java.util.Properties$LineReader.readLine
The file config.cfg is present and has r/w permissions.
import java.util.*;
import java.util.Properties;
public class Config
{
Properties configFile;
public Config()
{
configFile = new java.util.Properties();
try {
configFile.load(this.getClass().getClassLoader().
getResourceAsStream("config.cfg"));
}catch(Exception eta){
eta.printStackTrace();
}
}
public String getProperty(String key)
{
String value = this.configFile.getProperty(key);
return value;
}
}
EDIT - Full Error
[java] java.lang.NullPointerException
[java] at java.util.Properties$LineReader.readLine(Properties.java:418)
[java] at java.util.Properties.load0(Properties.java:337)
[java] at java.util.Properties.load(Properties.java:325)
[java] at Config.<init>(Unknown Source)
[java] at ClosureBuilder.<clinit>(Unknown Source)
EDIT - Directory Structure
src
-> config.java
-> config.cfg
You have to put your config.cfg in the same folder where your .class file lies.
The resource stream is being returned as null. The resource isn't where you think it is in the classpath.
It seems your program is not able to find the config.cfg file.
this.getClass().getClassLoader().getResourceAsStream("config.cfg")
The above call is returning null.
Try the below:
InputStream is = this.getClass().getClassLoader().getResourceAsStream("config.cfg")
if(is !=null){
configFile.load(is);
}
This change will not let your program fail. But also, if the file is not located, your property object configFile will not have any property from the file.
Check the path what you are getting for your config using this.getClass().getResource("/");

Categories