Getting the path to current dynamic web project JAVA - java

How can I access an XML file while my application is already deployed?
I'm running a Dynamic Web Application with several classes and a simple rest service, but I don't have any actual servlets, so accessing the ServletContext is not possible, (as far as I know) so using getRealPath() won't work.
An example:
I have a class DBcon which connects to a database, but has to load the properties from an XML file, which are located at /xml/db/oracle-properties.xml
In a normal Java project you can simply use a file input stream, but it won't work for a dynamic web application.
How can I still load the xml file?

If the file is in the classpath, you can get it as input stream with something like this:
InputStream in = this.getClass().getResourceAsStream("xml/db/oracle-properties.xml");

I figured out by reading this: Where to place and how to read configuration resource files in servlet based application?
I've put the xml files in WEB-INF/classes and then used this code to load it:
InputStream xmlFile = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
prop.loadFromXML(xmlFile);

Related

Storing credentials in a Google App Engine Java server

I have a Java Server running on Google App Engine, with integrations with third-party services (eg. SendGrid).
What's the best way to store credentials (usernames/passwords, API keys) for these third-party services? In the Java code, or through a configuration file such as web.xml or appengine-web.xml, or elsewhere? How would I access the credentials through code?
If you are using Java in GAE then,
You can save the credentials in file under src/main/resources/ or if you are not using this structure, put the file in src package.
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("credentials.json");
or
InputStream is = AnyClassName.class.getResourceAsStream("credentials.json");
How to read is answered in this, How do I load a file from resource folder?
then you can convert the inputStream to Map or any pojo using any Json libraries, popular ones are,
Gson
Jackson
Also make sure the file is not tracked in version control (if you use any), so that the file not available for others, and only during deployment you can inject that file.
Same kind of solution applies for other languages also, just not the same folder structure like java.
In my opinion it is good to save sensitive data in external files in WEB-INF folder. A lot of keys from third-party services can be downloaded like file and you need just paste it, like
And you can access it in code like
getServletContext().getResourceAsStream("/WEB-INF/credentials.json")

Java: Universally accessing resource files regardless of application server

I'm looking for the 'best practice' way to access resource files (for example a bunch of .xml files) as well as the folder structure in which they reside, regardless of the application server used.
Right now I'm using Wildfly 8 server and I access all src/main/resources/xxxx by getting the application real path then using Paths.get(resourcePath) as well as Files.walk(Paths.get(folderPath)) if I want to access a folder's files.
However, I faced a problem when I tried to deploy to Weblogic 12c, because this app server actually takes everything under WEB-INF/classes and creates a .jar file and adds it to WEB-INF/lib. I can still access singular resources using classLoader.getResource(resourcePath) but for some reason when I try to create a new File(Paths.get(resourcePath) or use Files.walk(Paths.get(folderPath)) it doesn't seem to be working. It throws an exception saying to file doesn't exist which I'm guessing is because it is not accessible since it is packaged inside a jar file.
I could potentially use classLoader.getResource(resourcePath) to access all my resources but unfortunately in my case I cannot know what resources will be available at compile time. I specifically NEED to be able to go through a selected folder's files and subfolders but I haven't found a common way to do it on both app servers, or ALL app servers for that matter.
Bonus points if the solution uses the new File api instead of creating a bunch of FileReaders but I'm ok with that too.
You could place the XML files in a folder /WEB-INF/xml and then use the ServletContext to obtain a File or Path for that location.
Variant 1:
call servletContext.getResourceUrl("/WEB-INF/xml") to obtain a URL and convert this URL to a File or Path. But depending on the server this might return a non-file resource URL, e.g. a jndi:/ url.
Variant 2:
call servletContext.getRealPath("/WEB-INF/xml") to obtain a file string and convert this URL to a File or Path.

where to keep an XML that should be editable and downloadable?

So I have a web app (using apache tomcat server,servlets,eclipse IDE). I wrote code to allow user to edit the XML file via UI. So I used the following code to access the XML through java
String fileName = "/MyXML.xml";
String path = this.getClass().getResource(fileName).toString();
This works fine. I am able to edit the file through UI.
Now I want to let the client download the file. But I am not able to access the file while I am trying to download.
However, if I keep the file inside webapps folder, then I can access the file using the following
ServletContext ctx = getServletContext();
InputStream is = ctx.getResourceAsStream("/MyXML.xml");
(Thanku Mr.MK Yong- http://www.mkyong.com/servlet/servlet-code-to-download-text-file-from-website-java/)
But then If i keep it inside webapp folder, how do I access the file for editing the XML ?
So basically I am either able to edit the file, or I am able to download the file(from webapp folder), or I am able to do both on two different copies of the file. I want to edit the XMl file and be able to download the same. So where do I keep the file and how do I access it?
You should store it in the local resource folder as it is essentially a dynamic resource.
The other thing i recommend is if you know the parameters that will be changed then have a template in resource folder and store the changes in database.
Personally i have it the second way.
e.g.
/yourapp/resource/config_file/xmltemplate.xml
Parameters that can change:
userLocation
folderLocation
colorBase
Stored them in the table:
Table: UserCongifStorage
Columns: userLocation, folderLocation, colorBase
So when i need to use the data from row 1 the logic is:
read in the xml file into a string, replace the variables with data retrieved from database, output it as xml to resource folder.
Then you read for usage.
Hope that helps
If the file is in your 'webapp' folder (I think you mean your application root), then it is already accessiable to everyone by calling hxxp://domainname/appname/MyXML.xml. I would suggest you not to store files that can be edited, inside your app folders, since they will be overwritten if you redeploy your application.
Put them in an external directory and load the contents like you would do with all other files. Doing this you can take control over file permissions easily, too.

How to read data from local XML file in Flex

I have a java web application which contains a flash part.Currently the .swf file is reading the xml file from project src folder. I want to access the xml file from local file system(in C:/ drive ).How to access XML data from C:/ drive.Currently my java web application is accessing the same xml file from C:/ drive.Can i pass the xml data through javascript to .swf file.
Is it a best practice.Which is the best practice for accessing XML file from local file system in Flex.
Any help is appreciated.
If your swf is in a web application, you can't access freely the hard drive. There are nevertheless two options:
FileReference
With the command FileReference.browse(), you can allow the user to choose a file from the local system and load it, or upload it.
If you choose to load it, you'll have access to its data as a ByteArray.
ExternalInterface
ExternalInterface allows you to communicate via javascript with the browser. You can set a responder with ExternalInterface.addCallback(). Check the reference for some example.
You say this is a Java web application. So one way would be to put the XML file on server and then make a service call to read it in Flex.
var httpService:HTTPService = new HTTPService();
httpService.url = path; //The URL of the XML file goes here
httpService.resultFormat = "e4x";
httpService.addEventListener(FaultEvent.FAULT, onFaultHttpService);
httpService.addEventListener(ResultEvent.RESULT, onResultHttpService);
httpService.send();
You will have to define the onFaultHttpService and onResultHttpService methods.
AFAIK, there is no way to access the filesystem directly in Flex, unless you are using AIR.

JSP: FileReader with relative path throws FileNotFoundException

I have some embedded Java code in which I'm trying to load a properties file that is located in the same folder as the JSP file:
Properties titles = new Properties();
titles.load(new FileReader("titles.txt"));
The code above throws a FileNotFoundException.
How exactly does one refer to the 'current folder' in this situation?
Two things:
JSPs should not contain java code. use an mvc framework (spring mvc, stripes etc) as controller and use the JSP as view only. That makes life a lot easier
You are not supposed to access resource files through the file system in a web app, use classloader access as suggested by redlab. The problem is that a web app may or may not be unpacked on the file system, that's up to the servlet container
The main problem I see is that you can't make any valid assumptions as to what the path is, as you don't know where your compiled JSPs are
So: create a controller class, put the properties file in the same folder and load it from the controller class via getClass().getClassLoader().getResourceAsStream("titles.txt");
FileReader requires absolute path, or relative the where the java is run. But for web applications this is usually done via /etc/init.d/tomcat startup and you can't rely on what is the current dir.
You can obtain the absolute path of your application by calling servletContext.getRealPath("/relative/path/to/file.txt")
You can get the relative part of the URL by calling request.getRequestURL().
That said, you'd better use this code in a servlet, not a JSP - JSP is a view technology and logic should not be placed in it.
By using the classloader that loads your class you can get the file easily.
getClass().getClassLoader().getResourceAsStream("titles.txt");
However I don't know if it will work with JSP
You could also use ServletContext.getResourceAsStream(""), but then you have to give the full webcontent-relative path.

Categories

Resources