Where should I place external xslt file in java web app? - java

I have an external XSLT file that I'm placing in the /WEB-INF/classes/ folder. How should I use relative path to access the file?
File xsltfile = new File("xhtml2fo.xsl");
gives a FileNotFoundException at D:\Softwares\eclipse\xhtml2fo.xsl.
I'm runnning the webapp on a tomcat server.

You can use ServletContext#getRealPath("/") to get the path to the WebContent root
Then Simply use this
String pathToFile = servletContext.getRealPath("/") + "/WEB-INF/classes/ folder/html2fo.xsl";
File file=new File(pathToFile);

The working directory in my tomcat launch configuration was D:/Softwares/eclipse and hence the relative path was being picked up from the same. It worked after I changed the working directory to ${workspace_loc:mywebapp/WebContent/WEB-INF} and file location as "classes/xhtml2fo.xsl"

Related

Trouble reading/writing file from relative path

I've been trying to read and write to a file under my resources directory in my project. However, regardless of what I seem to do it doesn't allow me to do so.
This is my project hierarchy for reference:
Out of all these:
Paths.get("memes.txt")
Paths.get("resources/memes.txt")
Paths.get("/resources/memes.txt")
...
None have worked. What am I doing wrong?
Is it a Maven project ?
Try this :
//Get file from resources folder
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
Ref : https://www.mkyong.com/java/java-read-a-file-from-resources-folder/
Your application can be packed as .jar file - a zip format.
There, or in the built classes directory should be memes.txt. A so-called resource, and in case of a jar not really a file system file. But is located on the class path.
URL url = getClass().getResource("/memes.txt");
InputStream in = getClass().getResourceAsStream("/memes.txt");
The path is relative to the package directory of the class, or absolute as above.
Try it using "../resources/memes.txt" with ".." you go up one directory from your current file (i assume that you are using the code in SwearTest.java)

Get absolute URL of jfx path

This line
URL contexturl = Thread.currentThread().getContextClassLoader().getResource("ClassLoader/Test/someFile.xml");
gives me the following contexturl.toString() string for the resource file someFile.xml:
jfx://ClassLoader/Test/someFile.xml
What does this mean and how can I obtain the absolute file system path of the resource?
The problem is also that contexturl.getPath() returns null.
The someFile.xml file is packaged in some jar file can be loaded as expected. However, I also want to load another file which is in the same folder of the jar but not packaged in the jar, so its external and therefore I need the file system path.
Any hints how to retrieve this path?

File upload to the server directory

I am uploading an excel file to the tomcat server. Which is saving inside my eclipse directory D:\workspace_Eclipse\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\StatusPortal\Job_doc\abc.xls
When ever i am accessing this file its giving me file not found Exception \Job_doc\abc.xls.
Its could not able to find the path which is i am giving while accessing the file like
\Job_doc\abc.xls
I am giving the path \Job_doc\abc.xls while accessing.
This is because you are using a relative path. Eclipse will use the current working directory to be a temp location for deploying the webapp. So the file is uploaded to the folder relative to this path (This happens when you start the app from eclipse Run On Server. Define your paths as static constants(May be you can use absolute paths for testing). After testing you can use the relative paths on production deployment.
Still, you can do alternate way. Dont use the integrated tomcat server of Eclipse. Use a standalone server, use the descriptor file to link the webapp in workspace to tomcat. After the save, just reload the app in tomcat manager and try.
Try reading your file using ClassLoader as below:
InputStream inputStream =
getClass().getClassLoader().getResourceAsStream("/Job_doc/abc.xls");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream ));
If you want to get the File object, then try as below:
URI uri = getClass().getClassLoader().getResource("/Job_doc/abc.xls").toURI();
File file = new File(uri);

Upload file to directory on server using Java and JSP - can't get path right

On my vps, I want to upload a file to the Logos directory.
The directory structure is as follows on my vps -
/home/webadmin/domain.com/html/Logos
When a file is uploaded through my jsp page, that file is renamed, and then I want to put it into the Logos directory.... but I can't seem to get the path right in my servlet code.
Snippet of servlet code -
String upload_directory="/Logos/"; // path to the upload folder
File savedFile = new File(upload_directory,BusinessName+"_Logo."+fileExtension);
//.....
//file saved to directory
//.....
I've tried many variations, but still fail. What is the proper way to specify the path?
Edited
The problem with using getServletContext() is that it returns the path to the directory where Tomcat and my webapp is...whereas I want to reach the directory where my html and image files are - under the root directory of the vps. How do I specify that path?
String server_path = getServletContext().getRealPath("/"); // get server path.
//server_path = /opt/tomcat6/webapps/domain.com/
String upload_directory = "Logos/"; // get path to the upload folder.
String complete_path = server_path + upload_directory; // get the complete path to the upload folder.
//complete_path = /opt/tomcat6/webapps/domain.com/Logos/
File savedFile = new File(complete_path,"NewLogo.jpg");
//savedFile = /opt/tomcat6/webapps/domain.com/Logos/NewLogo.jpg
It's a common practice to make the path for storage configurable - either via some application.properties file, or if you don't have such a properties file - as a context-param in web.xml. There you configure the path to be the absolute path, like:
configuredUploadDir=/home/webadmin/domain.com/html/Logos
Obtain that value in your code (depending on how you stored it), and have:
File uploadDir = new File(configuredUploadDir);
Note: make sure you have the permissions to read and write the target directory.
You can use following code in any jsp or servlet.
1) String serverPath= getServletContext().getRealPath("/");
This will give you full path of the server from root directory to your web application directory.
For me its: "D:\local\tomcat-6.0.29\webapps\myapp" when I sysout from myapp application.
Once you got the whole real path for the server system as above you can get the path relative to your directory. So if I have some data file in myapp\data - I can get it appending \data\filename to the serverPath which we got earlier.
This will work in all situation even you have multiple servers installed on the same system.
2) You can get server home from system properties using
System.getProperty("TOMCAT_HOME")
and then can use this absolute path in your program
3) To pass absolute directory path to any servlet using <init-param>
Hope this will work for you.
Well, the problem is: the File constructor doesn't create the file, only prepares to for the creation, then, after you construct a file instance you must invoke the method createNewFile(), and thats all.
The path "/Logos/" will attempt to create the file in the root of your system, which is not what you want. Look at the ServletContext.getRealPath() method.

Getting the absolute path of a file within a JAR within an EAR?

I have a J2EE app deployed as an EAR file, which in turn contains a JAR file for the business layer code (including some EJBs) and a WAR file for the web layer code. The EAR file is deployed to JBoss 3.2.5, which unpacks the EAR and WAR files, but not the JAR file (this is not the problem, it's just FYI).
One of the files within the JAR file is an MS Word template whose absolute path needs to be passed to some native MS Word code (using Jacob, FWIW).
The problem is that if I try to obtain the File like this (from within some code in the JAR file):
URL url = getClass().getResource("myTemplate.dot");
File file = new File(url.toURI()); // <= fails!
String absolutePath = file.getAbsolutePath();
// Pass the absolutePath to MS Word to be opened as a document
... then the java.io.File constructor throws the IllegalArgumentException "URI is not hierarchical". The URL and URI both have the same toString() output, namely:
jar:file:/G:/jboss/myapp/jboss/server/default/tmp/deploy/tmp29269myapp.ear-contents/myapp.jar!/my/package/myTemplate.dot
This much of the path is valid on the file system, but the rest is not (being internal to the JAR file):
G:/jboss/myapp/jboss/server/default/tmp/deploy/tmp29269myapp.ear-contents
What's the easiest way of getting the absolute path to this file?
My current solution is to copy the file to the server's temporary directory, then use the absolute path of the copy:
File tempDir = new File(System.getProperty("java.io.tmpdir"));
File temporaryFile = new File(tempDir, "templateCopy.dot");
InputStream templateStream = getClass().getResourceAsStream("myTemplate.dot");
IOUtils.copy(templateStream, new FileOutputStream(temporaryFile));
String absolutePath = temporaryFile.getAbsolutePath();
I'd prefer a solution that doesn't involve copying the file.
Unless the code or application you are passing the URI String to accepts a format that specifies a location within a jar/zip file, your solution of copying the file to a temporary location is probably the best one.
If these files are referenced often, you may want to cache the locations of the extract files and just verify their existance each time they are needed.
You should copy the contents to a temporary file (potentially with a cache), because trying to get to internal files of the application container is a dependency you want to avoid. There may not even be an extracted file at all (it can load from the JAR directly).

Categories

Resources