Changeable parameter file for Java program - java

I made a program for my employer, with one of the abilities being that non-software employees can change properties in several different parameter files. For example (something that isn't actually in the program), I put a "volume" parameter that the user can change in volume.txt.
However, it appears that when running the actual jar file, changing these values doesn't affect the program. Am I safe to assume that when I create the artifact, java builds the file into the jar file? I changed values for the parameter file in both source and the artifact production, but nothing changed. How should I fix this so that changes in the file will be read? Should I build the artifact without the files in the source folder and instead put them in the location of the executable jar? Thanks!

Properties files that can be edited by your users should be on a directory where your users have access to and where they cannot do much harm.
It is not clear in your question but i assume that the properties can be modified while your application is running. To detect file changes you can use a java.nio.file.WatchService.
I have created a small demo program for you. Hope this helps.
import java.io.IOException;
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
public class Main {
private static String WATCH_DIR = "c:/temp";
private static String WATCH_FILE_NAME = "volume.txt";
public static void main(String[] args) {
FileSystem fileSystem = FileSystems.getDefault();
try (final WatchService watchService = fileSystem.newWatchService()) {
fileSystem.getPath(WATCH_DIR).register(watchService, ENTRY_MODIFY);
while (true) {
final WatchKey watchKey = watchService.take();
for (WatchEvent<?> event : watchKey.pollEvents()) {
// "ENTRY_MODIFY" so context will be an instance of Path.
final Path changed = (Path) event.context();
if (changed.endsWith(WATCH_FILE_NAME)) {
System.out.println("Volume.txt was changed");
}
}
if (!watchKey.reset()) {
System.out.println("Key invalid");
}
}
} catch (IOException | InterruptedException e) {
System.out.println("Oops, something is not working");
e.printStackTrace();
}
}
}

Related

Where to put Java Resource Bundle in Project Environment

I am trying to use resource bundle in my project. i am new for development. is it professional way to put property files inside src/ folder i mean inside jar.
Also i have tried by placing my propert [AppProp] outside of the src folder [/resources/properties/AppProp]. I have added Add Class Folder from build path eclipse. I am trying to run this in eclipse. But it says Can't find bundle for base name. Please see my below code. Please provide any suggestion.
public class PropertyReader {
private String bundleName = null;
ResourceBundle resourceBundle = null;
public PropertyReader(String bundle){
this.bundleName = bundle;
loadProperty();
}
public void loadProperty(){
try{
resourceBundle = ResourceBundle.getBundle(bundleName);
} catch(Exception e){
e.printStackTrace();
}
}
public static void main(String a[]){
try{
PropertyReader pr = new PropertyReader("resources/properties/AppProp");
} catch(Exception e){
e.printStackTrace();
}
}
}
You don't need to change the code. But make sure following
1) You are providing the correct file path.
2) File type must be .properties in your case it should be be like AppProp.properties
There are lot of techniques/standards to organize your source files and code.
But for now above points are the solution of your problem.

Creating File & Directories not working properly

I am currently working on a method that will create files and directories. Bellow is the use case & problem explained.
1) When a user specifies a path e.g "/parent/sub folder/file.txt", the system should be able to create the directory along with the file.txt. (This one works)
2) When a user specifies a path e.g "/parent/sub-folder/" or "/parent/sub-folder", the system should be able to create all directories. (Does not work), Instead of it creating the "/sub-folder/" or /sub-folder" as a folder, it will create a file named "sub-folder".
Here is the code I have
Path path = Paths.get(rootDir+"test/hello/");
try {
Files.createDirectories(path.getParent());
if (!Files.isDirectory(path)) {
Files.createFile(path);
} else {
Files.createDirectory(path);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
You need to use createDirectories(Path) instead of createDirectory(path). As explained in the tutorial:
To create a directory several levels deep when one or more of the
parent directories might not yet exist, you can use the convenience
method, createDirectories(Path, FileAttribute). As with the
createDirectory(Path, FileAttribute) method, you can specify an
optional set of initial file attributes. The following code snippet
uses default attributes:
Files.createDirectories(Paths.get("foo/bar/test"));
The directories
are created, as needed, from the top down. In the foo/bar/test
example, if the foo directory does not exist, it is created. Next, the
bar directory is created, if needed, and, finally, the test directory
is created.
It is possible for this method to fail after creating some, but not
all, of the parent directories.
Not sure of which File API you are using. But find below the simplest code to create file along with folders using java.io package.
import java.io.File;
import java.io.IOException;
public class FileTest {
public static void main(String[] args) {
FileTest fileTest = new FileTest();
fileTest.createFile("C:"+File.separator+"folder"+File.separator+"file.txt");
}
public void createFile(String rootDir) {
String filePath = rootDir;
try {
if(rootDir.contains(File.separator)){
filePath = rootDir.substring(0, rootDir.lastIndexOf(File.separator));
}
File file = new File(filePath);
if(!file.exists()) {
System.out.println(file.mkdirs());
file = new File(rootDir);
System.out.println(file.createNewFile());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}

Eclipse not finding file?

I am using eclipse and I have my text file in the correct directory (src folder). I just want to read the file and count all the words in it. For some reason I am getting a file not found exception being thrown.
here is my code.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Tester {
public static int getSizeOfDictionary(File dictionary)
throws FileNotFoundException {
int count = 0;
Scanner reader = new Scanner(dictionary);
while (reader.hasNextLine()) {
reader.nextLine();
count++;
}
reader.close();
return count;
}
public static void main(String[] args) throws FileNotFoundException {
File test = new File("words.txt");
System.out.println(getSizeOfDictionary(test));
}
}
You could use this.getClass().getResource("words.txt") which will find that file on the current classpath.
From the main method you could use: Tester.class.getResource("words.txt")
when eclipse launches jvm it sets current directory to project base directory generally (unless you modify the default current directory)
${workspace_loc}/project_name
so you need to change your File initialization to
File test = new File("src/words.txt");
Note:
It will just be limited to this project structure, if you export it to jar it will not work any more, I assume you just need it as part of exercise
You have to use property class to access your file within class-path and source folder
you can try like:
this.getClass().getResourceAsFile("words.txt")

Eliminate hardcoded file paths and urls in web development

I'm currently developing a web site using servlets & spring framework. As usual it contains lots of files (jsp, js, css, images, various resources etc).
I'm trying to avoid writing any hardcoded path, or domain in any file ...
For example as you may know when a request is handled you 'forward' it to a jsp page (it's path probably will be hardcoded). Other examples are imports images/css/js etc in jsp files ...
Is there any general way (or tools) to avoid hardcoded paths/urls so any refactorings won't cause troubles?
EDIT
I use netbeans 7.1.2 ... Unfortunately netbeans only helps with pure java code. When working with jsp files things are limited, and if you add custom tag files and Jsp 2.0 EL is like programming in console mode :p
In the JSP files themselves, you can avoid nearly all hardcoded domain / urls by using JSTL
For example, when creating a link to another page, you would do it like this:
Refer an Entrepreneur!
This means that, regardless of where your webapp is, the link will always have the right url. For example, in my development box this link would be:
http://localhost:8080/accounts/referrals/send.html
But on my production server, it resolves correctly to:
http://wwww.mydomain.com/referrals/send.html
You can see that in my dev server, the webapp context is under /accounts, but on the production machine, it's just under / as the webapp is under the root context.
You can read a small tutorial here
Properties file is always a good option so that you have to make changes if any only at one point.
If you are referencing any static contents (js, images, css, etc), you don't have to hardcode the entire file path. Instead, you can do this:-
<img src="${pageContext.request.contextPath}/resources/images/test.jpg"/>
The rest of the file paths (Hibernate domain mappings, forwarded page in Spring controller, etc) should be relative to your project structure, and most IDEs are smart enough to refactor them without problem... or at least in my case, IntelliJ seems to handle of all that for me.
At some point of time, you need to ask yourself, how much of hardcoding is acceptable vs not acceptable? Further, I wouldn't try to stray too far away from the Spring/Hibernate recommended solutions. If you make everything too abstract, you have a different set of problem to deal with and it becomes counterproductive to other peers that may be inheriting your project in the future.
Actually I just came up with an idea. Since netbeans does analysis and shows dependencies on java code, maybe it's better to handle all paths & domains as java variables.
I've created a package on my project named FileResolver and inside I have one class for each file type on my project (eg one class for Jsp files, one for Css files etc). Inside those files I'll record & hardcode all paths of all files in public static final String variables. Sample:
public class Jsps {
public class layouts{
public static final String main = "layouts/main.jsp";
}
public class pages{
public static final String error = "pages/error.jsp";
public static final String login = "pages/login.jsp";
public static final String register = "pages/register.jsp";
}
...
}
All over my project I should use the variables instead of paths. Then anytime I refactor a file, I'll have only one file to change is the mapping value in those variables ...
And if somethime I need to change the variable, netbeans will refactor all of them in the project at once ...
I think this will work just fine since I keep my project clean from file paths and the only thing I have to worry about is the mapping in that file of the variables to appropriate file paths.
EDIT
I'll write a simple parser to create those java files instead of writting by hand for all files ... I'll update when I finish it
UPDATE
Here is my FileResolverGenerator
public class FileResolverGenerator {
private static final String newFilePath = "C:/Users/Foo/Desktop/Jsps.java";
private static final String scanRootFolder = "C:/Users/Foo/Desktop/myProject/web/WEB-INF/jsp";
private static final String varValueReplaceSource = "C:/Users/Foo/Desktop/myProject/web/WEB-INF/jsp/";
private static final String varValueReplaceTarget = "";
private static final boolean valueAlign = true;
private static final int varNameSpaces = 15;
public static void main(String[] args){
try {
// Create file and a writer
File f = new File(newFilePath);
f.createNewFile();
bw = new BufferedWriter( new FileWriter(f) );
// Execute
filesParser( new File(scanRootFolder) );
// 'Burn' file
bw.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(ResolverGenerator.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ResolverGenerator.class.getName()).log(Level.SEVERE, null, ex);
}
}
// ================================================================================================ //
// ============================================= WORK ============================================= //
// ================================================================================================ //
private static void filesParser(File rootFolder) throws FileNotFoundException, IOException{
folderIn(rootFolder);
// Files first
if(!rootFolder.exists()) throw new FileNotFoundException();
for(File f : rootFolder.listFiles()){
if(f==null){ return; }
if(f.isDirectory()){ continue; }
else if(f.isFile()){ writeFileVariable(f); }
}
// Folders next
for(File f : rootFolder.listFiles()){
if(f==null){ return; }
if(f.isDirectory()){ filesParser(f); }
else if(f.isFile()){ continue; }
}
folderOut(rootFolder);
}
// ================================================================================================ //
// ============================================ PRINTS ============================================ //
// ================================================================================================ //
private static BufferedWriter bw;
private static int tabCount = 0;
private static void folderIn(File f) throws IOException{
bw.append("\n\n");
for(int i=0; i<tabCount; i++)
bw.append("\t");
bw.append("public class "+f.getName()+"{\n");
tabCount++;
}
private static void folderOut(File f) throws IOException{
tabCount--;
for(int i=0; i<tabCount; i++)
bw.append("\t");
bw.append("}\n");
}
private static void writeFileVariable(File f) throws IOException{
String varName = f.getName().split("\\.")[0].replaceAll("-", "");
String varValue = f.getPath().replaceAll("\\\\","/")
.replace(varValueReplaceSource.replaceAll("\\\\","/"),varValueReplaceTarget.replaceAll("\\\\","/"));
for(int i=0; i<tabCount; i++)
bw.append("\t");
bw.append("public static final String "+varName+" = ");
if(valueAlign){
for(int i=0; i<varNameSpaces-varName.length(); i++) bw.append(" ");
bw.append("\t"); }
bw.append("\""+varValue+"\";\n");
}
}
Just to be specific ... This scans all files under "/WEB-INF/jsp/" and creates a java file having all jsp files 'registered' to public static final String variables with each path ... The idea is to use the generated java file as reference for all jsps are in project ... always use these variables instead of hardcoded paths ..
This has nothing to do with the project or any project. It's just a tool which saves you
time, instead of doing this by hand for every file in the project.
I also created another class ResolverConsistencyChecker, which takes all variables and checks if the filepath is correct (file exists) ... since we didn't made any changes to filenames and filepaths all tests are passed.
This method should run when testing project for 'errors'
public class ResolverConsistencyChecker {
private static Class checkClass = Jsps.class;
private static String fullPathPrefix = "C:/Users/Foo/Desktop/myProject/web/WEB-INF/jsp/";
public static void main(String[] args){
try {
filesChecker( checkClass );
System.out.println( "Tests passed. All files locations are valid" );
} catch (FileNotFoundException ex) {
Logger.getLogger(ResolverConsistencyChecker.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ResolverConsistencyChecker.class.getName()).log(Level.SEVERE, null, ex);
}
}
// ================================================================================================ //
// ============================================= WORK ============================================= //
// ================================================================================================ //
private static void filesChecker(Class rootClass) throws FileNotFoundException, IOException{
// Check file paths in current class depth
for(Field f : rootClass.getFields()){
try {
String fullFilePath = fullPathPrefix+f.get(f.getName()).toString();
File file = new File( fullFilePath );
if( !file.exists() )
throw new FileNotFoundException("Variable: '"+f.getName()+"'\nFile "+fullFilePath);
} catch (IllegalArgumentException ex) {
Logger.getLogger(ResolverConsistencyChecker.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(ResolverConsistencyChecker.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Check for embedded classes
for(Class c : rootClass.getClasses()){
filesChecker(c);
}
}
}

better way to point to folders and files in a properties file?

I was wondering if there is a better way to have a point to PATH in a properties file. Consider the following code:
public class Properties
{
//MIKE
public final static String PATH_TO_FILE_A = "C:\\programmer_MIKE\fileA.txt";
public final static String PATH_TO_FILE_B = "C:\\programmer_MIKE\fileB.txt";
//BILL
//public final static String PATH_TO_FILE_A = "/Users/BILL/Desktop/fileA.txt";
//public final static String PATH_TO_FILE_B = "/Users/BILL/Desktop/fileB.txt";
}
when any developer need to invoke FILE_A he simply does:
File file = new File(Properties.PATH_TO_FILE_A);
this works ok for BILL if he commented out MIKE's PATH_TO_FILE_A.
Q: is there a better design? If BILL committed his work including the Properties file - he will cause a problem to MIKE (no worries, he'll get a Coffee Latte later on).
the FILES are big (2-4Gb) and we don't want to put them in our repository (svn) and sometimes there are simply temporary folder to create a PDF so we don't want to put them in a "./docs" path.
Thanks for any pointer!
If for whatever reason you really must have hardcoded paths, then you could store them in some kind of map indexed by username. Something like:
public class Properties {
private static Map<String, DeveloperPaths> properties = create();
private static Map<String, DeveloperPaths> create() {
Map<String, DeveloperPaths> properties = new HashMap<String, DeveloperPaths>();
properties.put("mike", new DeveloperPaths(
"C:\\programmer_MIKE\fileA.txt",
"C:\\programmer_MIKE\fileB.txt")
);
properties.put("bill", new DeveloperPaths(
"/Users/BILL/Desktop/fileA.txt",
"/Users/BILL/Desktop/fileB.txt")
);
return properties;
}
public static File FileA()
{
String user = System.getProperty("user.name");
return properties.get(user).fileA;
}
public static File FileB()
{
String user = System.getProperty("user.name");
return properties.get(user).fileB;
}
}
class DeveloperPaths {
public File fileA;
public File fileB;
public DeveloperPaths(String pathA, String pathB) {
fileA = new File(pathA);
fileB = new File(pathB);
}
}
Then, the code to access each path would be identical regardless of developer, for example:
File myFile = Properties.fileA();
Normally paths are configurable entites and should be stored in property file.
Property files has a build in support in java and it uses Properties object for storing that information.
You can read the property file at startup or init (or similar) method of your application and read the proeprties from property file. This will make your configuration dynamic and anyone would be able to change it.
You can create a static method and call it on startup like:
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class GetProperties {
public static Properties prop = new Properties();
public static void init() {
InputStream inputStream = GetProperties.class.getClassLoader().getResourceAsStream("application.properties");
try {
prop.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Things like this should be configured externally and/or passed in via parameter, system parameter, or environment variable. Alternatively you could use DI/IoC, but when there's no attached behavior, IMO a config value is plenty.
It's fine to have a hard-coded default, but otherwise stuff like this doesn't belong in code.

Categories