I am trying to deploy a REST web service. I use glassfish as a web server.
I have a problem when i try to open an external file. in other words I want to read a file that is in the web-inf folder named "config.xml".
When I used a Java application (not web application), I used the following code to open the file but now it does not work
String path = new File (".") GetCanonicalPath () + "/ config.xml".
Cordially
I guess this line can be useful to you:
File image = new File(req.getServletContext().getRealPath("/") + "/carrousel/"+ req.getParameter("fileName"));
I use it to create a new File in the server.
Related
I tried to upload an image to tomcat and glassfish servers, Path I tried to set is as bellow System.getProperty("user.dir")+ File.separator+"images"+File.separator;
It takes System.getProperty("user.dir") as tomcat C:\Apache\Tomcat\bin and glassfish 'C:\Apache\glassfish4\glassfish\domains\domain1\config` directory. I am using Intellij to develop the system.
I want to upload an image to out/artifacts/CopywriteProtector_war)exploded/Resources/images folder so that I can access the images using http://localhost/Resources/images/msg.jpg, how to do this? I have spent days of time googling but couldn't able to find useful thing
You can get the root of your deployed application with
String root = getServletContext().getRealPath("/");
This will be the equivalent of the resources directory of your source code.
Add the filepath of where you want your image to be. i.e.
String filePath = root + "images/msg.jpg";
Then you can created your writer from that path
BufferedWriter writer = new BufferedWriter(new FileWriter(filepath);
writer.write(objectToWrite);//or similar
You can then access the resulting file with
getServletContext().getResource(filePath); // as URL or
getServletContext().getResourceAsStream(filePath); // as InputStream
-- Tested and worked on Payara (an application server derived from Glassfish)
I am trying to generate a XML file and save it in /WEB-INF/pages/.
Below is my code which uses a relative path:
File folder = new File("src/main/webapp/WEB-INF/pages/");
StreamResult result = new StreamResult(new File(folder, fileName));
It's working fine when running as an application on my local machine (C:\Users\userName\Desktop\Source\MyProject\src\main\webapp\WEB-INF\pages\myFile.xml).
But when deploying and running on server machine, it throws the below exception:
javax.xml.transform.TransformerException:
java.io.FileNotFoundException
C:\project\eclipse-jee-luna-R-win32-x86_64\eclipse\src\main\webapp\WEB INF\pages\myFile.xml
I tried getServletContext().getRealPath() as well, but it's returning null on my server. Can someone help?
Never use relative local disk file system paths in a Java EE web application such as new File("filename.xml"). For an in depth explanation, see also getResourceAsStream() vs FileInputStream.
Never use getRealPath() with the purpose to obtain a location to write files. For an in depth explanation, see also What does servletcontext.getRealPath("/") mean and when should I use it.
Never write files to deploy folder anyway. For an in depth explanation, see also Recommended way to save uploaded files in a servlet application.
Always write them to an external folder on a predefined absolute path.
Either hardcoded:
File folder = new File("/absolute/path/to/web/files");
File result = new File(folder, "filename.xml");
// ...
Or configured in one of many ways:
File folder = new File(System.getProperty("xml.location"));
File result = new File(folder, "filename.xml");
// ...
Or making use of container-managed temp folder:
File folder = (File) getServletContext().getAttribute(ServletContext.TEMPDIR);
File result = new File(folder, "filename.xml");
// ...
Or making use of OS-managed temp folder:
File result = File.createTempFile("filename-", ".xml");
// ...
The alternative is to use a (embedded) database or a CDN host (e.g. S3).
See also:
Recommended way to save uploaded files in a servlet application
Where to place and how to read configuration resource files in servlet based application?
Simple ways to keep data on redeployment of Java EE 7 web application
Store PDF for a limited time on app server and make it available for download
What does servletcontext.getRealPath("/") mean and when should I use it
getResourceAsStream() vs FileInputStream
just use
File relpath = new File(".\pages\");
as application cursor in default stay into web-inf folder.
I'm creating a REST webservice that uses keyczar for encryption. I've generated both public and private keys and placed them under src/main/resources/RSA.
To instantiate the encrypter I need to pass to it the location of the files like Crypter crypterPrivate = new Crypter(PATH_RSA + "/private"); but I'm having problems with the RSA folder location when I deploy the war file.
I've tried some stuff I've googled like InputStream but it is not this case since I don't want to pass any file but the RSA folder location. Also have tried several different folders like /WEB-INF/classes/RSA (it's where is located in war file).
Any tips? Thank you
If keyczar can take a URL for its key location then this.getClass().getResource("/RSA/private") will give you a suitable URL. If it requires a native file path then you'll have to use
ServletContext ctx = // ...
String pathToKey = ctx.getRealPath("/WEB-INF/classes/RSA/private");
Exactly how you get hold of the ServletContext depends on your toolkit. Note that this will only work if the WAR file is expanded on disk when you deploy it, it won't work if the app is running directly from the compressed WAR file.
You can access this file via the classpath.
URL resourceUrl = URL.class.getResource("/WEB-INF/classes/RSA");
File resourceFile = new File(resourceUrl.toURI());
I'm pretty sure the Java version of Keyczar doesn't support this functionality, but I believe someone submitted a small patch in their issue tracker to add it:
http://code.google.com/p/keyczar/issues/detail?id=55
KeyczarClassLoaderReader reader = new KeyczarClassLoaderReader(PATH_RSA + "/private");
Crypter crypterPrivate = new Crypter(reader);
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.
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);