So I'm trying to add some ability to my project to allow user-defined properties in my deployment artifact - a simple key:value .properties file. I place the service.properties file in
war/WEB-INF/my-service.properties
And in my ServiceImpl.java constructor I have the following:
String propertiesFileName = "my-service.properties";
URL propertyURL = ClassLoader.getSystemResource(propertiesFileName);
URL propertyURL2 = this.getClass().getClassLoader().getResource(propertiesFileName);
URL propertyURL3 = this.getClass().getClassLoader().getResource( "WEB-INF/" + propertiesFileName);
URL propertyURL6 = this.getClass().getClassLoader().getResource(
"E:/Projects/eclipse-workspace/projectName/war/WEB-INF/" + propertiesFileName);
All instances of Property URL are null. I know I'm missing something absolutely obvious, but I need a second pair of eyes. Regards.
EDIT:
Ah, it seems I was confused as the default GAE project creates a logging.properties file in /war. From the Google App Engine documentation:
The App Engine Java SDK includes a template logging.properties file, in the appengine-java-sdk/config/user/ directory. To use it, copy the file to your WEB-INF/classes directory (or elsewhere in the WAR), then the system property java.util.logging.config.file to "WEB-INF/classes/logging.properties" (or whichever path you choose, relative to the application root). You can set system properties in the appengine-web.xml file, as follows:
Try putting the service.properties in WEB-INF/classes. Then it should be accessible just with :
this.getClass().getClassLoader().getResourceAsStream("/filename.properties");
As Mike mentioned in his comment to jsights answer, it worked for me if I used
this.getClass().getClassLoader().getResourceAsStream("filename.properties");
(removed the first slash) after placing the file in WEB-INF/classes.
I think what you will need is something like this:
String filePath = servletContext.getRealPath("/WEB-INF/views/") + "/" + mav.getViewName() + ".vm";
FileInputStream in = new FileInputStream(filePath);
I get the servletContext from spring: #Autowire ServletContext.
Related
I have a spring application, and i'm trying to access a json file with the following code :
try (FileReader reader = new FileReader("parameters.json")) {
Object obj = jsonParser.parse(reader);
parameterList = (JSONArray) obj;
}
I have put the parameter.json file in the project folder and I'm accesing the file data from an angular app through a rest api, and that works fine when I run the application on local machine, but when I deploy the war file on tomcat, my application can't load the file, should I put parameter.json file somewhere else on tomcat or what is the best solution for it.
Your question states you are attempting to access a file called parameter.json, while your code excerpt shows parameters.json. Perhaps that discrepancy indicates a typo in your source code?
If not, there are various ways to access a file from the classpath in Spring, with the first step for each being to ensure the file is in the project's src/main/resources directory.
You can then use one of the Spring utility classes ClassPathResource, ResourceLoader or ResourceUtils to get to the file. The easiest approach, though, may be to put your properties in a .properties file (default file name application.properties) and access the values using Spring's #Value annotation:
#Value("${some.value.in.the.file}")
private String myValue;
You can use other file names as well by utilizing #PropertySource:
#Configuration
#PropertySource(value = {"classpath:application.properties",
"classpath:other.properties"})
public class MyClass {
#Value("${some.value.in.the.file}")
private String myValue;
...
}
Make sure your parameters.josn filename is exactly same in the code.
Move you parameters.json file in the resources folder and then use the classpath with the filename.
try (FileReader reader = new FileReader("classpath:parameters.json")) {
Object obj = jsonParser.parse(reader);
parameterList = (JSONArray) obj;
}
Try to put the file under resources folder in your spring project. You should be able to access the file from that location.
FileReader is looking for a full-fledged file system like the one on your computer, but when your WAR is deployed, there just isn't one, so you have to use a different approach. You can grab your file directly from your src/main/resources folder like this
InputStream inputStream = getClass().getResourceAsStream("/parameters.json");
I have a little problem with Struts 2 when I try to get the context path :
ServletActionContext.getServletContext().getRealPath("\\WebContent\\resources\\img\\");
I got this path:
C:\Users\killian\workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SiteWebAdministrable\WebContent\resources\imgicone.jpg
Why the exact source path ?
Because i need to upload and save images for an admin website to control background and without the actual path i cannot save images in the resources path...
So i save the path with the name and extension in the database (no problem), and i need to save the image in the resource directory (image problem...)
Can someone help me please ? Did i forgot something ?
This question is the answer ?
How do you get the project path in Struts 2?
servletContext.getServletContext().getRealPath("/resources/img/name_of_image.png")
So, passing the "/" to getRealPath() would return you the absolute disk file system path of the /web folder of the expanded WAR file of the project. Something like /path/to/server/work/folder/demo.war/ which you should be able to further use in File or FileInputStream.
Note that most starters don't seem to see/realize that you can actually pass the whole web content path to it and that they often use
String absolutePathToIndexJSP = servletContext.getRealPath("/") + "demo.png";
instead of
String absolutePathToIndexJSP = servletContext.getRealPath("/demo.png");
getRealPath() is unportable; you'd better never use it
Use getRealPath() carefully.
If all you actually need is to get an InputStream of the web resource, better use ServletContext#getResourceAsStream() instead, this will work regardless of the way how the WAR is expanded. So, if you for example want an InputStream of index.jsp, then do not do:
InputStream input = new FileInputStream(servletContext.getRealPath("/demo.png")); // Wrong!
But instead do:
InputStream input = servletContext.getResourceAsStream("/demo.png"); // Right!
Or if you intend to obtain a list of all available web resource paths, use ServletContext#getResourcePaths() instead.
Set<String> resourcePaths = servletContext.getResourcePaths("/");
I know there are many topics out there for this but I have seem to have tried everything. I can put my file name in there and it finds it if there is a src folder,
InputStream is = context.class.getClassLoader().getResourceAsStream("file.props");
but when we put it on an apache server, a src folder is not automatically created, so it isn't finding it. I have tried placing it directly in the web-inf folder and
InputStream is = context.class.getClassLoader().getResourceAsStream("/WEB-INF" + File.separator + "file.props");
But this is always returned as null. What is the reason for this? The file exists there, why can't it find it?
You appear to be using the wrong ClassLoader. Invoking context.class.getClassLoader() provides the ClassLoader with which the ServletContext class (context.class) was loaded. What you want is the ClassLoader for the web application's classes, which would be context.getClassLoader().
Don't use the ClassLoader if you want to load your file from /WEB-INF. Instead, use the ServletContext's method for just that purpose:
// In your servlet e.g. doGet method
ServletContext app = super.getServletContext();
InputStream in = app.getResourceAsStream("/WEB-INF/file.props");
Note that using / is okay regardless of the OS, filesystem, etc.
If you really want to use the ClassLoader, take #rickz's advice and move your file.props into WEB-INF/classes.
I am trying to read a properties file in my java web application. I have tried these solution:
Where to place and how to read configuration resource files in servlet based application?
Howto access properties file from Java EE web application?
But none of them worked for me.
Here is the structure of my app:
The code that reads the properties file is placed in the A class and it did not work even I put the absolute path. A is a normal Java class.
But everything worked like a charm if the reading properties code is place in the servlet class (ProcessRequest.java)
Here is the code I have used:
public class A {
public A() {
try {
Properties p = new Properties();
p.load(this.getClass().getClassLoader().getResourceAsStream("/a.properties"));
String n = p.getProperty("name");
System.out.println("name: " + n);
} catch (Exception ex) {
Logger.getLogger(A.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Any idea?
You've put it in the servlets package, however you're trying it to get from the classpath root. The leading / makes the path relative to the classpath root.
Fix the path accordingly:
p.load(this.getClass().getClassLoader().getResourceAsStream("/servlets/a.properties"));
or, assuming that the current class is in servlets package already:
p.load(this.getClass().getClassLoader().getResourceAsStream("a.properties"));
Unrelated to the concrete problem, might it later happen that you move the properties file outside the WAR to an external location which allows easy editing of the file without the need to rebuild/redeploy everytime, then I'd suggest to use the thread's context class loader instead of the current class' class loader. It'll work in all circumstances:
p.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("servlets/a.properties"));
(note that the path doesn't need to start with / here, because it's always relative to classpath root)
Do you see the properties file under WEB-INF/servlets after building the application. If yes then try using following line.
p.load(getServletContext().getResourceAsStream("/WEB-INF/servlets/a.properties"));
instead of this
p.load(this.getClass().getClassLoader().getResourceAsStream("/a.properties"));
I need to get real path for file in my WebContent directory, so that framework that I use can access that file. It only takes String file as attribute, so I need to get the real path to this file in WebContent directory.
I use Spring Framework, so solution should be possible to make in Spring.
If you need this in a servlet then use getServletContext().getRealPath("/filepathInContext")!
getServletContext().getRealPath("") - This way will not work if content is being made available from a .war archive. getServletContext() will be null.
In this case we can use another way to get real path. This is example of getting a path to a properties file C:/Program Files/Tomcat 6/webapps/myapp/WEB-INF/classes/somefile.properties:
// URL returned "/C:/Program%20Files/Tomcat%206.0/webapps/myapp/WEB-INF/classes/"
URL r = this.getClass().getResource("/");
// path decoded "/C:/Program Files/Tomcat 6.0/webapps/myapp/WEB-INF/classes/"
String decoded = URLDecoder.decode(r.getFile(), "UTF-8");
if (decoded.startsWith("/")) {
// path "C:/Program Files/Tomcat 6.0/webapps/myapp/WEB-INF/classes/"
decoded = decoded.replaceFirst("/", "");
}
File f = new File(decoded, "somefile.properties");
you must tell java to change the path from your pc into your java project so
if you use spring use :
#Autowired
ServletContext c;
String UPLOAD_FOLDEdR=c.getRealPath("/images");
but if you use servlets just use
String UPLOAD_FOLDEdR = ServletContext.getRealPath("/images");
so the path will be /webapp/images/ :)
In situations like these I tend to extract the content I need as a resource (MyClass.getClass().getResourceAsStream()), write it as a file to a temporary location and use this file for the other call.
This way I don't have to bother with content that is only contained in jars or is located somewhere depending on the web container I'm currently using.
Include the request as a parameter. Spring will then pass the request object when it calls the mapped method
#RequestMapping .....
public String myMethod(HttpServletRequest request) {
String realPath = request.getRealPath("/somefile.txt");
...
You could use the Spring Resource interface (and especially the ServletContextResource): http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/core/io/Resource.html
This approach uses the resource loader to get the absolute path to a file in your app, and then goes up a few folders to the app's root folder. No servlet context required! This should work if you have a "web.xml" in your WEB-INF folder. Note that you may want to consider using this solely for development, as this type of configuration is usually best stored externally from the app.
public String getAppPath()
{
java.net.URL r = this.getClass().getClassLoader().getResource("web.xml");
String filePath = r.getFile();
String result = new File(new File(new File(filePath).getParent()).getParent()).getParent();
if (! filePath.contains("WEB-INF"))
{
// Assume we need to add the "WebContent" folder if using Jetty.
result = FilenameUtils.concat(result, "WebContent");
}
return result;
}
my solve for: ..../webapps/mydir/ (..../webapps/ROOT/../mydir/)
String dir = request.getSession().getServletContext().getRealPath("/")+"/../mydir";
Files.createDirectories(Paths.get(dir));
try to use this when you want to use arff.txt in your development and production level too
String path=getServletContext().getRealPath("/WEB-INF/files/arff.txt");