Eclipse won't read a config file - java

I have an Eclipse web project. I have a file called deploy.properties in the root directory which doesn't seem to get read. I have a feeling that I may need to add the file to the "build path" (like a jar), but this is just a guess, when I try to do this there is no option for adding files to the build path so that makes me think I am wrong about that.
Line 89 is this one props.load(stream);
My stack trace looks like this:
java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:365)
at java.util.Properties.load(Properties.java:293)
at sempedia.dao.Dao.getConfigFile(Dao.java:89)
at sempedia.dao.Dao.<clinit>(Dao.java:17) 89
And the class looks like this:
public class Dao {
private static final String configFileLocation = "/deploy.properties";
private static final Properties configFile = getConfigFile(configFileLocation);
private static final String host = configFile.getProperty("mysql.host");
private static final String port = configFile.getProperty("mysql.port");
private static final String db = configFile.getProperty("mysql.db");
private static final String user = configFile.getProperty("mysql.user");
private static final String pwd = configFile.getProperty("mysql.pwd");
public static String getHost() { return host; }
public static String getPort() { return port; }
public static String getDb() { return db; }
public static String getUser() { return user; }
public static String getPwd() { return pwd; }
public static Connection getCon() {
Connection con = null;
try {
String url = "jdbc:mysql://" + host + ":" + port + "/" + db;
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(url, user, pwd);
} catch (SQLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return con;
}
private static Properties getConfigFile(String fileName) {
Properties props = new Properties();
try {
InputStream stream = Dao.class.getResourceAsStream(fileName);
props.load(stream);
} catch (IOException e) {
System.err.println("Error opening configuration file");
System.exit(1);
}
return props;
}
}

Keep in mind that when you read files in your eclipse project, the default location is in your source directory (if this is a web application, that translates to your classes directory later). So my advice is to try moving the file from the project root directory to your "src" directory and retrying.

Method Dao.class.getResourceAsStream(fileName) returns null as the inputstream if the target file doesn't exist in the classpath - that's why the NullPointerException.
You should either catch it (now you only catch IOException) or test input stream before calling props.load(stream) for null;
Now what root directory do you mean? System root, app source root, app working directory? System root would be a rather bad place to put your config files.
Address it with "deploy.properties" (without the slash at the beginning) and place it in the root of your classpath ("classes", "bin" - or whatever you call it).
If you place it in the default package level of your source directory - either in the source, or a directory that you have added as a source directory, it will be copied to the classpath during compile like this:
/app
/src
/config
deploy.properties
and now add config directory to the project as a source directory.

Related

how to read property files from external storage

I have a jar file that I run from the console. In the program itself, I have to read data from the property file, which should be in the same folder as my jar file. How can i do this ?
my code which does not work correctly:
public class ReadProperties {
String propPath = System.getProperty("app.properties");
private String message;
private String userName;
ReadProperties() {
readProperties();
}
private void readProperties() {
final FileInputStream in;
try {
in = new FileInputStream(propPath);
Properties myProps = new Properties();
myProps.load(in);
message = myProps.getProperty(Constants.MESSAGE);
userName = myProps.getProperty(Constants.USERNAME);
} catch (Exception e) {
e.printStackTrace();
}
}
public String getMessage() {
return message;
}
public String getUserName() {
return userName;
}
}
Note that the way you have coded above requires a system property to mark the file to load, passed as:
java -Dapp.properties=somefile.properties
If you intended a file called "app.properties" this requires a change to the declaration of propPath without System.getProperty
Your file handling should use try with resources to clean up afterwards with automatic close, and not hide any exception:
try (FileInputStream in = new FileInputStream(propPath)) {
// load here
}
You could provide default property values after exception, or handle by add throws IOException to the method, or append code to adapt as a runtime exception so that is is reported:
catch (Exception e) {
throw new UncheckedIOException(e);
}

Java file copy fails

I have written a very simple Java program to copy a file passed as an argument to the /tmp directory. The program produces several Java exceptions.
public class CopyFile {
public static void main(String[] args) throws IOException {
String fqp2File = "";
if (new File(args[0]).isFile()) {
fqp2File = args[0];
}
else {
System.out.println("Passed argument is not a file");
}
copy(fqp2File, "/tmp");
}
private static boolean copy(String from, String to) throws IOException{
Path src = Paths.get(from);
Path dest = Paths.get(to);
try {
Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);
return true;
} catch (IOException ioe) {
System.err.format("I/O Error when copying file");
ioe.printStackTrace();
return false;
}
}
}
When I run this program I get these errors:
java -jar CopyFile.jar /home/downloads/dfA485MVSZ.ncr.pwgsc.gc.ca.1531160874.13500750
I/O Error when copying filejava.nio.file.FileSystemException: /tmp:
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:103)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:114)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:119)
at sun.nio.fs.UnixCopyFile.copy(UnixCopyFile.java:578)
at sun.nio.fs.UnixFileSystemProvider.copy(UnixFileSystemProvider.java:265)
at java.nio.file.Files.copy(Files.java:1285)
at ca.gc.ssc.gems.esnap.cipo.CopyFile.copy(CopyFile.java:39)
at ca.gc.ssc.gems.esnap.cipo.CopyFile.main(CopyFile.java:31)
To test your code I used C:/tmp/test.txt; as your args[0]. I fixed the issue by giving the output a filename to write to shown below:
Path dest = Paths.get(to);
to
Path dest = Paths.get(to, "test2.txt");
And it now successfully copied the file into that name, you can modify the filename however you want or add logic to change filename automatically.

Store execution result in java in properties file

I wrote a code in java to run some scripts which can return different result depending on the environment setup. I would like to store the result of every execution. I try with properties file but every time it executes, it overwrites the previous result in config.properties. I did a research but not find any most likely example. This is my code to return properties file. The value which will be different are TCpassed and TCfailed on every execution.
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
public class ExecutionProperties {
public void setConfigProperties(int tcPassed, int tcFailed){
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream("config.properties");
// set the properties value
prop.setProperty("TCpassed", ""+ tcPassed);
prop.setProperty("TCfailed", ""+ tcFailed);
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Is it possible to get the execution time and store it in config.properties in order to differentiate with the previous result?
Thanks before
You can use append mode using constructor FileOutputStream("config.properties", true)
Sample properties file after couple of execution
#Mon May 04 13:03:29 IST 2015
TCpassed=1
TCfailed=1
#Mon May 04 13:04:03 IST 2015
TCpassed=1
TCfailed=1
Property file are usually key value pairs, e.g.
TCpassed=9
TCfailed=1
So if you want to store the result of every execution, you need a different key for every execution.
And if you want to append to the property file, you can:
Load the property file as Properties object;
Add new entry to the Properties object;
Write the Properties Object back to the file;
Here is an example:
public static void appendTestResult(File propertyFile, int tcPassed, int tcFailed) {
try {
Properties properties = loadProperties(propertyFile);
String testId = getTestID();
properties.setProperty("TCpassed_" + testId, String.valueOf(tcPassed));
properties.setProperty("TCfailed_" + testId, String.valueOf(tcFailed));
saveProperties(propertyFile, properties);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void saveProperties(File propertyFile, Properties properties) throws IOException {
OutputStream outputStream = null;
try {
outputStream = FileUtils.openOutputStream(propertyFile);
properties.store(outputStream, "new test");
} finally {
IOUtils.closeQuietly(outputStream);
}
}
public static Properties loadProperties(File propertyFile) throws IOException {
InputStream inputStream = null;
try {
inputStream = FileUtils.openInputStream(propertyFile);
Properties properties = new Properties();
properties.load(inputStream);
return properties;
} finally {
IOUtils.closeQuietly(inputStream);
}
}
public static String getTestID() {
return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
}

Java getResource return null mac

I am very new to StackOverflow and I've done my best to fix this problem before posting this question here. I'm faced with the problem of getResource() returning null. I have a hunch that this is because I'm on a mac and the pathing is different here than on a PC (where this code seems to work fine). This is the code:
public class SampleClass
{
static String imgpath = "/theimage.png";
public static void main(String[] args)
{
System.out.println(imgpath);
System.out.println(SampleClass.class.getResource(imgpath));
try
{
BufferedImage image = ImageIO.read(SampleClass.class.getResource(imgpath));
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
src, res and bin are all in the same directory and theimage.png is inside of res.
System.out.println(SampleClass.class.getResource("imgpath")); gives me null.
I had the same issue on my mac using spring boot :
the file is located on properties/report/example.jasper
when the path was : "report/example.jasper" i got nullPointerException
So i changed to : "./report/example.jasper" and It works fine without any bug.
InputStream inStream = null;
try {
inStream = ExportController.class.getClassLoader().getResourceAsStream(path);
final JasperReport jasperReport = (JasperReport) JRLoader.loadObject(inStream);
jasperReport.setWhenNoDataType(WhenNoDataTypeEnum.ALL_SECTIONS_NO_DETAIL);
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);
} catch (final JRException jre) {
throw new TechnicalException("Error when export jasper");
} finally {
if (inStream != null) {
inStream.close();
}
}
you get nullpointer exception because there is no image named imgpath in that folder
public class SampleClass
{
static String imgpath = "/theimage.png";
public static void main(String[] args)
{
System.out.println(imgpath);
System.out.println(SampleClass.class.getResource(imgpath));
try
{
BufferedImage image = ImageIO.read(SampleClass.class.getResource(imgpath));
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
I faced the same issue on Mac. Here how I now get files from resources. For example, I have a common Maven project with resource folder in src/main. In resource folder I have a file "test.txt".
To get a path to the file:
public class Utils {
public static String getFilePathInResources() {
URL url = Utils.class.getClassLoader().getResource("test.txt");
return url.getPath();
}
}
Here the filename is hardcored just for clearity, of course, really it is a parameter in the method.
If set a filename as "/test.txt" with "/" - this will give null.
URL url = Utils.class.getClassLoader().getResource("/test.txt"); // url == null

Getting Properties Object from config.properties file after deployment

I have a config file containing server information such as FTP URL's and their credentials. I am trying to, on deployment of my web app, reference the config.properties file to assign the stored values to local variables but for whatever reason cannot find the file.
I have a getConfigProperties class:
public class getConfigProperties {
public Properties getConfig(String fileName) {
// load config file
Properties prop = new Properties();
InputStream input = null;
try {
// grab config file from destination
input = getConfigProperties.class.getClass().getResourceAsStream(
fileName);
// check if input is null
if (input == null) {
System.out.println("Sorry, unable to find "
+ "config.properties");
return null;
}
// load content
prop.load(input);
// start to declare variables
// Prod vars
System.out.println(prop.getProperty("prismUrlProd"));
System.out.println(prop.getProperty("prismUserProd"));
System.out.println(prop.getProperty("prismPassProd"));
System.out.println(prop.getProperty("cardUrlProd"));
System.out.println(prop.getProperty("cardUserProd"));
System.out.println(prop.getProperty("cardPassProd"));
System.out.println(prop.getProperty("pwcProd"));
System.out.println(prop.getProperty("esdSignInProd"));
System.out.println(prop.getProperty("emailProd"));
// used to catch possible errors
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return prop;
}
public static void main(String[] args) {
getConfigProperties a = new getConfigProperties();
a.getConfig("/config/config.properties");
}
}
And I use this in another class to assign the variables. Inside my method, I set a Properties object to what is returned from getConfig(String filename):
public static void initialize() {
// load config file
getConfigProperties config = new getConfigProperties();
Properties prop = config.getConfig("/config/config.properties");
}
It's explained in properties file in web app that on deplyoment, our location of the config.properties changes, but when trying "/WEB-INF/classes/config/config.properties", I can't find the file. Using the main in my getConfigProperties class, I am able to find config.properties no problem and reference the text in my config file by printing it to console. Any possible suggestions as to where this file may be on deployment? Do I have to reference it a certain way? Any help would much be appreciated.
I got this to work by putting config.properties in my src folder and referencing it by "config.properties".

Categories