Getting Properties Object from config.properties file after deployment - java

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".

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);
}

Copy all files from Source to Destination Java

I have to code a java method public void public void copyTo(Path rSource, Path rDest) that copies all files from existing directory rSource to a new directory rDest with the same name. rSource must exist and rDest must not exist, runtime exception if not true. I can't seem to make it work, help!
What I tried :
public void copyTo(Path rSource, Path rDest){
if(!(Files.exists(rSource) && Files.isDirectory(rSource)) || (Files.exists(rDest))){
throw new RuntimeException();
}
try {
Files.createDirectory(rDest);
if(Files.exists(rDest)){
try(DirectoryStream<Path> stream = Files.newDirectoryStream(rSource)) {
for(Path p : stream) {
System.out.println(p.toString());
Files.copy(p, rDest);
}
} catch( IOException ex) {
}
}
} catch (IOException e) {
}
}
Files.copy() at least takes two parameters, source and destination files path or stream. The problem in your case is that you are passing rDest folder Path, not the actual file Path. Just modify the code inside your for loop to append the files name from the source to the destination folder Path:
Path newFile = Paths.get(rDest.toString() + "/" + p.getFileName());
Files.copy(p, newFile);
Correct me if I'm wrong

Create method name based on values in configuration file in Java

I have this in my config.properties file.
DBServerName=SomeServer
DBUserId=myId
I know how to create a Configuration java class so that this works
Configuration.get("DBServerName");
However, I am trying to create a Configuration file where I can make the following call.
Configuration.getDBServerName() ;
I do not actually want to write the getDBServerName() method. I want to Configuration class to read the properties file and create the corresponding getXXX() methods automagically.
Please help.
Before anyone points out, I have read the following, and I am looking for answers beyond what have been mentioned here.
create java classes based on values defined in .properties file
Update 1
The lombok folks seem to have solved this. Trying out http://notatube.blogspot.in/2010/12/project-lombok-creating-custom.html
I think you should read properties file as text file and push data into array
Example
public class ReadPropertiesFile {
public static void main(String[] args) {
try {
File file = new File("test.properties");
FileInputStream fileInput = new FileInputStream(file);
Properties properties = new Properties();
properties.load(fileInput);
fileInput.close();
Enumeration enuKeys = properties.keys();
while (enuKeys.hasMoreElements()) {
String key = (String) enuKeys.nextElement();
String value = properties.getProperty(key);
System.out.println(key + ": " + value);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}

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 file deletion fails

I need to delete files from within a java program and have written this code. It fails to delete the file and I can't figure why. The File is not in use and not write protected.
public static void delfile(String filetodel) {
try {
File file = new File("filetodel");
if (file.delete()) {
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed." + filetodel);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I guess the issue is this:
File file = new File("filetodel");
This should possibly be (inferred from the parameter filetodel passed in the method):
File file = new File(filetodel);
Everything else seems fine, and is working on my machine.
If you just want to delete the file, there is no need for loading it.
java.nio.file.Files.deleteIfExists(filetodel); (where filetodel contains the path to the file)
Returns true if the file was deleted, so you can even put it in your if-clause.
hey buddy you should use a path as parameter in delete
static void delete(Path path)
Deletes a file.
static boolean deleteIfExists(Path path)
Deletes a file if it exists.
search here: http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html
so in your case
File file = new File("c://user//filetodel");
file.delete();
or use getAbsolutePath(filename) and use it in file path
Here is my code to delete file.
public class deletef
{
public static void main(String[] args)
{
try{
File file = new File("/home/rahul/Downloads/ou.txt");
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
your code is also right but you have to put extension also in your file
File file = new File("filetodel");
here add extension also of file other wise your code will not delete file

Categories