Get resource folder in java war file - java

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);

Related

retrieve value from servlet and store in xml file [duplicate]

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.

Why getClass().getProtectionDomain().getCodeSource().getLocation().getPath() doesn't work in final product after compiled?

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).

How do I get a resource using Class, ClassLoader, and URL

I am writing a simple JSF application and am trying to get a resource (database.properties file) using Class, ClassLoader, and URL that is not working. url is null and I don't know why. I have done a lot of research but without success.
Code:
Class cls = Class.forName("<packagename>.SimpleDataSource");
ClassLoader cLoader = cls.getClassLoader();
URL url = cLoader.getResource(fileName); // fileName = "database.properties" w/o the double quote
FileInputStream in = new FileInputStream(url.getFile());
Thanks for your comment Sandeep, it was helpful. I found out that my properties file was in the wrong place. I then moved it inside my src folder under the java resources folder and now my properties file gets loaded in. I have a new problem now but will start a new thread if I can't figure it out.
Once you have a URL you can get an InputStream from it using url.openStream(), or you can simply use cLoader.getResourceAsStream(...) in the first place. Your current approach of
FileInputStream in = new FileInputStream(url.getFile());
will work on some platforms but not all, and only when your application is running from a directory on disk. It will fail if your classes and resources are packed up into a JAR, but if you use getResourceAsStream it will work from a JAR as well as an unpacked directory.

Adding and accessing resource files to Play Framework application

I am running a PlayFramework 2 application. The application builds a client authenticated SSL session to a 2nd server. To accomplish this I am storing a Java Keystore file in a resource directory. Everything runs fine on my local box. Next I create a dist package for upload to Cloud Foundry which essentially builds a war file with a buch of Jars. Any idea how I can access the Keystore from my java code once its compiled into a Jar and uploaded to CloudFoundry? Any direction would be greatly appreciated. Here is current code snippet.
Best,
SR
//READS THE JAVA KEYSTORE FILE FROM A RELATIVE LOCATION
File clientKS = new File("resource/devportal.jks");
//SET CONNECTION PARAMS
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type","application/json");
con.setDoOutput(true);
con.setSSLSocketFactory(getFactory(clientKS, passphrase.toCharArray()));
Assuming there is no other way than to use a java.io.File, you may want to try getting ahold of it by putting it in the classpath of your app and do something like
AnyClassOfYourApp.class.getResource("devportal.jks").getFile()
Its been a while but try this:
//TESTING BY USING INCLUDED KEYSTORE IN JAR FILE
String ksPath = "/res/devportal.jks";
URL jksURL = PostNvp.class.getResource(ksPath);
File jksStore = new File(jksURL.toURI());
//TESTING
Where PostNvp is my java class PostNvp.java where this code snippet lives.

Classpath Resource in Tomcat6 (Works in Jetty)

I'm having trouble with a legacy Web Application that I'm migrating to Maven3.
I need to obtain a file from the Classpath that in the directory structure is located in:
/src/main/resources/com/thinkglish/geoip/GeoIP.dat
When I create the .war file with the Maven build, I can confirm that this .dat file is located (as it should be) in:
WEB-INF/classes/com/thinkglish/geoip/GeoIP.dat
I'm trying two different approaches to get the resource from one of my classes, which implements javax.servlet.Filter:
ClassPathResource resource = new ClassPathResource("com/thinkglish/geoip/GeoIp.dat");
and
URL resource = getClass().getResource("/com/thinkglish/geoip/GeoIp.dat");
If I start the application using Maven's Jetty plugin, that works fine in both ways. However, when I deploy the application in a Tomcat and start the server, the resource cannot be located.
In the first case I get a java.io.FileNotFoundException: class path resource [com/thinkglish/geoip/GeoIp.dat] cannot be resolved to URL because it does not exist and in the second case the resource is null.
A curious thing about all this is that if I use one method or the other trying to obtain another resource from the Classpath (e.g. com/thinkglish/struts/i18n/MessageResources.properties or com/thinkglish/filter/LanguageFilter.class) it works without any problems.
Do you have any guess about this? Is it possible that the .dat extension has anything to do with this?
Edited - More data!
I added a new .properties mock file to the exact same directory in which the .dat file lives:
/src/main/resources/com/thinkglish/geoip/mock.properties
I tried to obtain it in Tomcat6 and it worked!
ClassPathResource resource = new ClassPathResource("com/thinkglish/geoip/mock.properties");
I'm starting to think that I need to do something else configuration-wise to make Tomcat6 accept the .dat file as a Classpath resource.
Thanks in advance!
I might be barking up completely the wrong tree here... but have you checked the capitalisation of GeoIP.dat / GeoIp.dat? Is Tomcat running on a case-sensitive OS?
Following should work:
String classpathLocation = "com/thinkglish/geoip/GeoIp.dat";
URL classpathResource = Thread.currentThread().getContextClassLoader().getResource(classpathLocation);
// Or:
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(classpathLocation);

Categories

Resources