Basically I have the model of my project set up this way:
ModelFolder
-----src
-----bin, etc.
-----PropertiesFolder1
--------File1.properties
--------File2.properties, etc.
-----PropertiesFolder2
--------File1.properties
--------File2.properties, etc.
-----MainPropertiesFile1.properties
-----MainPropertiesFile2.properties
I am trying to use it with my View, which is a Dynamic Web Project, and I got the properties files to finally load in my Web Project after changing
foo.load(new FileInputStream("foo.properties"));
to
foo.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("foo.properties"));
and exporting the project to a JAR file, which I then included in WEB-INF/lib. However, I had to add another method to the Model, and when I tried testing that method, the Model was not able to read my properties file. I know that I can use FileInputStream with the full path to get the properties file working in the Model and the View, but are there any alternatives?
I don't want to keep changing the full path every time I switch computers (I use H:\username\...\Java\Workspace at work, whereas at home it's just C:\Java\Workspace).
I also don't want to have to move my properties files to different folders; and finally I don't want to change the way I load the properties file every time I test my Model or my View.
Is there a way to accomplish this?
This is driving me crazy, I've tried all of the following:
try
{
foo.load(this.getClass().getResourceAsStream("foo.properties"));
//foo.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("foo.properties"));
//foo.getClass().getResourceAsStream("foo.properties");
//foo.load(new FileInputStream("foo.properties"));
} catch (IOException ex)
{
al.logIntoProgrammerLog(ex);
}
All of those lines either work in the model or the view. Is there any way I can call those properties files via a relative path in the model, and then somehow properly connect the model with the view so that all the files are found and loaded?
Any help would be greatly appreciated; I am new to Java, so I might be missing something really simple. Thank you.
EDIT:
Sorry for not clarifying this, the Model is a Java Project, whereas the View is a Dynamic Web Project running on local Tomcat Server v6.0.
Better (I hope) explanation:
My View has a LoginServlet with the following doPost method:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String username = request.getParameter("usernameField");
String password = request.getParameter("passwordField");
ActivityLogger al = new ActivityLogger();
LoginController l_c = new LoginController();
//loginUser method will call my UserStorage class and
//will return true if UserStorage finds the User with those credentials in the db
//UserStorage is using a prepared sql statement stored in a properties file to find the User
//That properties file is not being read unless I specify the full path to it.
//Both Login and UserStorage are in the Model
if(l_c.loginUser(username, password))
{
//take user to welcome page
}
else
//display error
}
Thanks again
Take a look at this thread for possible solutions for sharing a .properties file. But I would suggest that you review this approach to see if it's really what you want. More specifically, if your .properties file contains SQL queries, then are you sure you need it in your View? Sounds like you may want to make a clean separation there.
If you are in a web application, you should be able to get the path (relative path in the context of the webapp, so it will work on any machine) by using the ServletContext's getResourceAsStream(). For example, if you wanted to get the path from your servlet's doGet() method:
public void doGet(HttpServletRequest request, HttpServletResponse response) {
InputStream in = getServletContext().getResourceAsStream(<path>);
}
where <path> would be the relative path to your .properties file (i.e. /WEB-INF/foo.properties, or wherever that properties file is located... look in your deployment folder to find out for sure)
But in re-reading your post it seems like perhaps your "Model" is not a webapp and your "View" is a webapp? Maybe you could clarify whether these are two different applications - and possibly one being a webapp running within a servlet container (i.e. Tomcat, Glassfish, etc) and one being a standalone app? If that's the case then this is more of a shared file issue than a 'cannot find resource' issue. A bit of clarification about the nature of your application(s) would help steer the correct response...
Related
I'm new to Spring Boot, so I'm not sure about how to store/manipulate files (use persistance within spring). Use case: Store list of films (title, director...) on a JSON file stored on API server with persistance instead of using a DB.
I have a favorites.json at src/main/resources. This file is updated when request arrives as I said. Code here: GitHub Repo
A kind person has left in the comments what is probably the problem. Changes files in classpath won't work. I still struggling how store data in JSON without a database.
Problem I'm facing:
Files are updated correctly at POST request via OutputStream, but it seems like favorites.json is treated as a static resource, so any update will be ignored until API starts again (I have tried restarting the api when the file is updated, see this but it doesn't change anything. It's still needed to stop and start manually, bash script may help, but I prefer another solution if better-possible.
Maybe I'm looking for a file-based repository, place this file in a specific project path where spring detect updates.
I think I'm skipping some important concepts of spring behaviour.
Here POST Resource
#CrossOrigin(origins = "http://localhost:3000")
#PostMapping(path = TaskLinks.FAVORITES, consumes = "application/json", produces = "application/json")
#ResponseBody
public String updateFavs(#RequestBody List<Show> newFavorites) {
showService.updateFavorites(newFavorites);
return "All right";
}
Methods that modify the file:
public boolean updateFavorites(List<Show> newFavorites) {
if (newFavorites == null)
return false;
setNewFavorites(newFavorites);
return true;
}
private void setNewFavorites(List<Show> newFavorites) {
Gson gson = new Gson();
try {
FileWriter fileW = new FileWriter(FAVORITES_PATH);
String strNewFavs = gson.toJson(newFavorites);
fileW.write(strNewFavs);
fileW.close(); // auto flush
} catch (JsonIOException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
If someone needs to use spring boot persistence system, I will let here what I've found.
The unique solution that I've found to use file persistance on spring-boot (API) is to hard-reload the whole API, which I think is not a clean thing.
So I ended up storing the JSON file on mysql.
Maybe spring have specific tools that I've omitted, but I don't have time to check right now.
The closest approach I got was accessing system temporary file, which is correctly updated because it's allocated outside the application.
I didn't get access to files outside the application other than temporary ones.
Now I'm working with NodeJS express and implemented a png delivery API. I don't really know how I would've done it with spring at all, but there's probably a file focused database or something that may work fine with spring. If I have to face this situation, I will upload the solution that I find most favorable. At the moment express works fine.
We have a web application comprising a client in Angular2 and a server in Play Framework 2.6. This application should allow users to upload their own images. Similarly to many users here, we faced the problem of not being able to access the images in public/assets in production mode, and so we tried the solutions that have been provided to those users, with no success.
We created the following route in the conf/routes file:
GET /files/*file controllers.AdminExerciseCtrl.serve(file)
leading to the following custom action:
public Result serve(String file) {
Boolean DEVELOPMENT = Boolean.parseBoolean(ConfigFactory.load().getString("development"));
String path;
if(DEVELOPMENT) path = "public/";
else path = ConfigFactory.load().getString("root/");
return ok(new java.io.File(path + file));
}
i.e., we are saving the uploaded images to root/files/images.
We tried two way of accessing this route:
Using #routes throws an error because of the # character
Using the route in the src field (where resource.resourcePath is a variable holding the path to the image file, e.g., images/pic.jpg), the route simply isn't found (404).
<img *ngIf="resource" class="thumbnail" [src]="'/files/' + resource.resourcePath">
We are starting to despair since this project is considerably large and uploading images is a core feature. Any ideas of what we could be missing? Anything we should be doing in the client regarding the routes?
Thanks in advance.
I'm working in a web project and I'm having troubles with files(java.io.File). The problem is only when I run as web application(tomcat 7), if I run as Java Application, the problem doesn't exist.
When I instantiate a file, new File("dir");, its path become C://Windows/System32/dir, this way, i can't do anything, maybe cause don't have Windows privilegies.
"I solved the problem" passing new File("C://Users/user/dir"), but I don't like this solution. I wanted to do this automatically, get the app path, for example. I'm coding in my machine, and after the deploy.... i don't know.
Any tips?
That's the part of the project that I'm having the problem, a jsf bean. My view calls the method addFile() to save the file that I receive from my view. It's working, but i have to pass the path like I said before, like is on the code below. The path goes to the Windows dir System32
Bean.java
#ManagedBean
#ViewScoped
public class Bean {
//ATTRIBUTES AND METHODS
public void addFile() {
File temporaryFile = new File("temporary");
//...
//...
//...
}
}
Sorry for my english, i'm brazillian.
There is a method in the File class that does exactly what you're looking for: https://docs.oracle.com/javase/8/docs/api/java/io/File.html#createTempFile-java.lang.String-java.lang.String-
Alternatively you can assemble the file's path yourself:
File myTempFile = new File(System.getProperty("java.io.tmpdir"),"temporary");
you can add folder resources in web folder then add files as you want
i tested it from adding some styles (css) and javascript and call them in jsf page.as example if you create file named x in folder files under web/resources folder
new File("files/x");
wishing the answer helps you .you can tell me if any problem happens again
I am currently migrating an Eclipse 3.0 application to 4.4. The user data was and still should be stored in the folder C:\Users\username\AppData\Roaming\applicationname
The application is using following code to read the directory:
public static String getUserDirectory()
{
String directory = InternalPlatform.getDefault().getUserLocation().getFile();
return directory;
}
I know the code is deprecated, but following code returns the same:
public static String getUserDirectory()
{
String directory = Platform.getUserLocation().getURL().getFile();
return directory;
}
They both return C:\Users\username\user but as I said the user data should be stored at C:\Users\username\AppData\Roaming\applicationname. Did the behaviour of those methods change?
How can I realize that I store my user data under C:\Users\username\AppData\Roaming\applicationname and my application can still find the directory?
I know this has to do something with environment-variables which I don't fully understand.
I don't have a 3.x target platform at hand to compare but C:\Users\username\user looks plain wrong.
If you are interested in the details, the constructor of EquinoxLocations computes the userLocation and adds the literal 'user' the the user's home directory if no default is specified.
Hence, if you start your application with -user #user.home or -Dosgi.user.area=#user.home, the user location will be set to C:\Users\username\. Still not what you are looking for, but at least a sane value.
I think this is a bug in Equinox and recommend to file a bugzilla. If it turns out that there is a good reason for this appraoch the bug entry will still serve as documentation/reasoning.
In the meanwhile you could obtain the home directory on Windows through System.getenv( "APPDATA" ). According to this post it will return the roaming home directory.
I solved the problem by adding three properties in the Configuration tab of my config.ini.product-file:
osgi.configuration.area =
#user.home/AppData/Roaming/ApplicationName/...
osgi.user.area =
#user.home/AppData/Roaming/ApplicationName/...
osgi.instance.area =
#user.home/AppData/Roaming/ApplicationName
Now my method as stated in my question reads the paths that are configured by those properties and the config.ini file which is generated looks exactly like the one of the old build with Eclipse 3.0.
I want to make a blackberry app installable over-the-air (OTA) by deploying it as an OSGi bundle. Any ideas on how to setup the OSGi bundle?
I believe I'll need a way to enable a directory listing at particular URL as well associate the mime type for two file types (*.cod, *.jad)
Any takers?
See Wireless Application Deployment to BlackBerry Smartphones for the details.
In the end I was able to figure it out.
Used the following:
For the most part I followed the steps laid out by Peter Friese (found here)
The tweaking required is as follows:
Tweak1:
In the HttpServiceTracker's addingService() method one needs to invoke:
httpService.registerResources("/blackberry", "/appfiles", new CustomResourceHttpContext());
instead of the servlet registration to map a URL to the location of your files.
Tweak2:
You'll need to create a folder called appfiles at the root of your eclipse project in which you place your blackberry binaries.
Tweak3:
You'll need to implement your own custom HttpContext class inside the HTTPServiceTracker to associate the required mime types
e.g
public String getMimeType(String name) {
if (name.endsWith(".jad")) {
return "text/vnd.sun.j2me.app-descriptor";
} else if (name.endsWith(".cod")) {
return "application/vnd.rim.cod";
} else {
return null;
}
}
Caveat: In order to install the app over the air you'll need to specify the jad file name as there is no support for a directory listing using this approach.