I want to open the xsd file in the web-inf/xsd/output.xsd
This is what I am trying to do
URL url = portletContext.getResource("WEB-INF/xsd/output.xsd");
getResource returns URL but in my case I am getting NullPointerException and I need to supply this to the newFile to open the file.
File newFile = new File("");
I am confused how to get this working.
UPDATE
Please bear with my english. I got this working. I have a question, I have another file *.xsl file which would be used to generate the PDF. I cannot delete this file after opening, what would be the effect on the JVM if a file is left open I mean >100 users trying to create the PDF i.e., *.xsl file will be opened 100 times, in future application is used heavily by the users, does the GC automatically clear all the file descriptors opened?
From the API doc of javax.portlet.PortletContext it describes that:
... The path must begin with a slash (/) and is interpreted as relative to the current context root (which usually is the WebContent or web directory of your web application)
This method allows the portlet container to make a resource available to portlets from any source. Resources can be located on a local or remote file system, in a database, or in a .war file.
Related
Ok, Here is my Web project. I built it in eClipse with the following structure:
workspace3\MyProject\war\images\uploaded
workspace3\MyProject\war\WEB-INF\classes
Ok, I want to store the uploaded images into workspace3\MyProject\war\images\unloaded, so here is the code at service side & it works fine in Eclipse
String absolutePath = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
absolutePath=absolutePath.replace("WEB-INF/classes/", "images/uploaded");
File file = File.createTempFile("upload-", "."+extName, new File(absolutePath));
Ok, now I compiled my project & put it into VPS with Tomcat server and it has the following structure
tomcat7\webapps\ROOT\images\uploaded
tomcat7\webapps\ROOT\WEB-INF\classes
However, somehow when run the website via internet, it couldn't find the images\uploaded location.
Did i do anything wrong here?
Why getClass().getProtectionDomain().getCodeSource().getLocation().getPath() doesn't work in final product after compiled?
You should rather use ServletContext#getRealPath(...) to determine the file system path of your web application:
String absolutePath = request.getServletContext().getRealPath("/images/uploaded");
// File uploaded to this directory will be accessible via
// `http://<yourserver>/<web-app>/images/uploaded/`
But be careful! The servlet specification does not guarantee, that getRealPath will return a path to a writable directory. And it may return null in case the virtual path cannot be translated to a real path!
If you want to be sure, that the destination is a writable directory, and you just want to upload files into a temporary directory for processing, consider using the web application's private temp directory:
File tempDir = (File)request.getServletContext().getAttribute(ServletContext.TEMPDIR);
// Files uploaded to that directory will NOT be automatically published to WWW.
Note that this directory is temporary only and may not survive a server restart! So it is not thought for durable persistance.
The most sensible and durable solution is to write the file into a database, or any other repository (e.g. JCR like Jackrabbit), or into a file directory that is NOT controlled by your web server (and is specified from outside, e.g. via system property or in web.xml).
I need to be able to access my web application's css files, that are stored under src/main/resources/styles, from the backend java controller. I want to use them for creating PDF output with iText.
In other words, I want to do something like this:
CssFile cssFile1 = XMLWorkerHelper.getCSS(new FileInputStream("src/main/resources/styles/my.css"));
However, I'm clearly not going about this correctly, as I am receiving Exceptions like this:
java.io.FileNotFoundException: styles\standard.css (The system cannot find the path specified)
How can a retrieve these files in the controller?
I tried this, but it did not work, same error:
String rcp = econtext.getRequestContextPath();
CssFile cssFile1 = XMLWorkerHelper.getCSS(new FileInputStream(rcp + "src/main/resources/styles/my.css"));
The FileInputStream operates on the local disk file system and all relative paths are relative to the current working directory, which is the local disk file system folder which is been opened at exactly the moment the JVM is started. This is definitely not the root of src/main/resources folder.
Given that the /src/main/resources is recognizable as a Maven folder structure for root of classpath resources, then you just need to obtain it as classpath resource by ClassLoader#getResourceAsStream() instead.
InputStream input = getClass().getResourceAsStream("/styles/standard.css");
// ...
Or if the class is possibly packaged in a JAR loaded by a different classloader.
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("styles/standard.css");
// ...
See also:
getResourceAsStream() vs FileInputStream
Thats because the JSF is a web app.
Now move the styles/my.css to WEB-INF/styles/my.css this ensures the files your accessing within the controller are part of the WebApp
and now you can access the resource using
XMLWorkerHelper.class.getResourceAsStream("styles/my.css")
I have a simple java class in my web application in which i have written the below code but its not working
File test= new File("/templates/xmdForModel.xsd");
templates folder is inside the root folder of the application.
the location of the file is ----> application-root/package/test.java
location of the file is --------> application-root/testRoot/template/xmdForModel.xsd
Error
Failed to read schema document 'file:/templates/xmdForModel.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not .
If you want to look up the file name for files inside of your web application, you can use ServletContext#getRealPath.
However, I would recommend loading your resources using the classloader with Class#getResourceAsStream. This way, it even works if the file does not really exist as a file (for example only inside of a jar).
If this is a file that a user is supposed to edit (or that you write to), I would place it outside of the web application, and then specify an absolute path (for example "/etc/myapp/conf/xmd.xsd") with a configurable prefix.
Path in the File constructor can be absolute or relative. When you start the path with '/' (in a linux based os), it is going to consider that path as an absolute path and create a file/folder in the root of your file structure (not in the root of the project). It will be like specifying c:\templates in windows machine.
Try removing the first slash and running your program. Removing first slash will make the part relative from your .java file. So you can use ../ to switch to parent folder.
java: application-root/package/test.java
file: application-root/testRoot/template/xmdForModel.xsd
So from your java file you will need to change directory to application root folder and then select template folder. Like following.
File x = new File("../testRoot/template/xmdForModel.xsd");
src:http://docs.oracle.com/javase/tutorial/essential/io/path.html
/home/sally/statusReport is an absolute path. All of the information
needed to locate the file is contained in the path string.
A relative path needs to be combined with another path in order to
access a file. For example, joe/foo is a relative path. Without more
information, a program cannot reliably locate the joe/foo directory in
the file system.
I need to access the resource files in my web project from a class. The problem is that the paths of my development environment are different from the ones when the project is deployed.
For example, if I want to access some css files while developing I can do like this:
File file = new File("src/main/webapp/resources/styles/some.css/");
But this may not work once it's deployed because there's no src or main directories in the target folder. How could I access the files consistently?
You seem to be storing your CSS file in the classpath for some unobvious reason. The folder name src is typical as default name of Eclipse's project source folder. And that it apparently magically works as being a relative path in the File constructor (bad, bad), only confirms that you're running this in the IDE context.
This is indeed not portable.
You should not be using File's constructor. If the resource is in the classpath, you need to get it as resource from the classpath.
InputStream input = getClass().getResourceAsStream("/main/webapp/resources/styles/some.css");
// ...
Assuming that the current class is running in the same context, this will work regardless of the runtime environment.
See also:
getResourceAsStream() vs FileInputStream
Update: ah, the functional requirement is now more clear.
Actually I want to get lastModified from the file. Is it possible with InputStream? –
Use getResource() instead to obtain it as an URL. Then you can open the connection on it and request for the lastModified.
URL url = getClass().getResource("/main/webapp/resources/styles/some.css");
long lastModified = url.openConnection().getLastModified();
// ...
If what you're looking to do is open a file that's within the browser-visible part of the application, I'd suggest using ServletContext.getRealPath(...)
Thus:
File f = new File(this.getServletContext().getRealPath("relative/path/to/your/file"));
Note: if you're not within a servlet, you may have to jump through some additional hoops to get the ServletContext, but it should always be available to you in a web environment. This solution also allows you to put the .css file where the user's browser can see it, whereas putting it under /WEB-INF/ would hide the file from the user.
Put your external resources in a sub-directory of your project's WEB-INF folder. E.g., put your css resources in WEB-INF/styles and you should be able to access them as:
new File("styles/some.css");
Unless you're not using a standard WAR for deployment, in which case, you should explain your setup.
Typically resource files are placed in your war along with your class files. Thus they will be on the classpath and can be looked up via
getClass.getResource("/resources/styles/some.css")
or by opening a File as #ig0774 mentioned.
If the resource is in a directory that is not deployed in the WAR (say you need to change it without redeploying), then you can use a VM arg to define the path to your resource.
-Dresource.dir=/src/main/webapp/resources
and do a lookup via that variable to load it.
In Java web project, the standard directory like:
{WEB-ROOT} /
/WEB-INF/
/WEB-INF/lib/
/WEB-INF/classes
So, if you can get the class files path in file system dynamic,
you can get the resources file path.
you can get the path ( /WEB-INF/classes/ ) by:
this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath()
so, then the next ...
This question already has answers here:
How to save generated file temporarily in servlet based web application
(2 answers)
Closed 6 years ago.
I have recently created a web project in Java using eclipse. I have a servlet which includes a timer task. This timer tasks calls the "writeList" method of an XML Writing class that I have created. This all works fine, and I have verified that it runs every minute using System.out.
When I run my XML Writing class from within eclipse as an application, it works fine. The file is outputted to 'WebContent/test.rdf' without any problems.
However, when it is called by the timer task in my servlet, I am getting the following error:
java.io.FileNotFoundException: WebContent/Test.rdf(No such file or directory)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:179)
at java.io.FileOutputStream.<init>(FileOutputStream.java:70)
at com.XMLWriter.writeList(XMLWriter.java:58)
at com.ServerTimer$1.run(ServerTimer.java:30)
at java.util.TimerThread.mainLoop(Timer.java:512)
at java.util.TimerThread.run(Timer.java:462)
The code at line 58 of XMLWriter is as follows:
fileOut = new FileOutputStream("WebContent/TEST.rdf");
model.write(fileOut);
fileOut is a FileOutputStream, and model is an instance of a Jena model, as I am working with RDF.
Any help would be appreciated, I have been stuck with this for days now! Any questions just let me know!
EDIT: So it is working now, but I want to write the file to the 'WebContent' directory of my Web Project. Is there any way of doing this automatically? I can't get the system to dynamically find that directory.
You should never rely on relative paths that way. Using relative paths in Java IO is asking for portability trouble. The java.io.File knows nothing about the web application context it is running in. The actual path would be dependent on the current working directory, which is not per se the same in all environments and depends on the way how you started the server/application. It may become relative to for example C:/Tomcat/bin and your TEST.rdf is obviously not there. Always use absolute paths, i.e. use the full disk file system path.
In case of a JSP/Servlet webapplication you can use ServletContext#getRealPath() to convert a relative web path to an absolute disk file system path which you can use further in Java IO stuff. A relative web path is rooted in the public webcontent. Assuming that /TEST.rdf is located in the root of the public webcontent, then you can get an absolute disk file system path for /TEST.rdf inside a servlet the following way:
String relativeWebPath = "/TEST.rdf";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
It's because the directory does not exist. Either create the directory (programatically or offline) or create the folder on the base path.