Reading properties file in JSF2.0 which can work in war also - jsf-2

To read a properties file in JSF2.0 with Glassfishv3 webserver, which is located at root directory of my web application, I am using below code-
ServletContext ctx = (ServletContext) FacesContext
.getCurrentInstance().getExternalContext().getContext();
String deploymentDirectoryPath = ctx.getRealPath("/");
Properties prop = new Properties();
prop.load(new FileInputStream(deploymentDirectoryPath
+ File.separator + "portal-config.properties"));
Below is the screenshot of web portal-
While running the portal I am getting FileNotFound Error, since the file is not present in glassfish domain.
Is there any way to read properties file which can work in both the situations, at development stage and in war file also?

You should never use java.io.File to refer web resources. It knows nothing about the context it is sitting in. You should also never use ServletContext#getRealPath() as it may return null when the server is configured to expand WAR file in memory instead of on disk, which is beyond your control in 3rd party hosts.
Just use ExternalContext#getResourceAsStream() to get the web resource directly in flavor of an InputStream. It takes a path relative to the webcontent root.
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
properties.load(ec.getResourceAsStream("/portal-config.properties"));
See also:
getResourceAsStream() vs FileInputStream
What does servletcontext.getRealPath("/") mean and when should I use it
Where to place and how to read configuration resource files in servlet based application?
Update it does not seem to be a web resource at all. You should move the file into the "WebContent" folder as shown in the screenshot. Or, better, the /WEB-INF folder so that nobody can access it by URL.
properties.load(ec.getResourceAsStream("/WEB-INF/portal-config.properties"));
An alternative would be to put it in the classpath, the "Java source" folder as shown in the screenshot. You don't need to put it in a package, that's optional. Assuming that you didn't put it in a package, then do so:
ClassLoader cl = Thread.currentThread().getContextClassLoader();
properties.load(cl.getResourceAsStream("portal-config.properties"));
(note that the path may not start with a slash!)

Related

Using Grails to store image but could not store outside CATALINA_HOME in production

I'm using Grails 2.5.6 to store uploaded images to folder on a server.
The following are my code to store the image
mpr.multiFileMap.file.each{fileData->
CommonsMultipartFile file = fileData
File convFile = new File(file.getOriginalFilename());
file.transferTo(convFile);
/** Processing File **/
File uploadedFile = new File("${directory}${generatedFileName}.${extension}")
convFile.renameTo(uploadedFile)
}
I have no problem running on development (MacOSX High Sierra)
But when i deployed on production (Ubuntu 14.04 server), i could not save the file outside CATALINA_HOME directory.
I have checked the permission and ownership of the destination directory, but still, the directory was created but the file was never stored.
For Example, i've tried to store the file on /home/tomcat/ directory (/home directory was in separate partition with tomcat which stored it /var), the directory was created, but the file was never stored.
When i put the destination directory within CATALINA_HOME folder, everything works fine. But this was not the scenario i want to do.
You say your destination directory is on another partition, so maybe another filesystem is used on this partition.
Or if you look on the javadoc of the renameTo method it is said :
Many aspects of the behavior of this method are inherently
platform-dependent: The rename operation might not be able to move a
file from one filesystem to another, it might not be atomic, and it
might not succeed if a file with the destination abstract pathname
already exists. The return value should always be checked to make
sure that the rename operation was successful.
...
#return true if and only if the renaming succeeded;
false otherwise
Thus I think the renameTo method is not able to move the file, don't know why but you can rewrite your code like this :
mpr.multiFileMap.file.each{fileData->
CommonsMultipartFile file = fileData
File uploadedFile = new File("${directory}${generatedFileName}.${extension}")
// String originalFilename = file.getOriginalFilename()
// you can store originalFilename in database for example
if(!uploadedFile.getParentFile().exists()) {
uploadedFile.getParentFile().mkdirs()
// You can set permissions on the target directory if you desired, using PosixFilePermission
}
file.transferTo(uploadedFile)
}

read file from res folder blackberry

I want to read file from "res" folder on blackberry. The file that i used is a file javascript.
I used this code InputStream in = classs.getResourceAsStream("file.js");. But i get "could not find this path" and I use also
String srcFile = "/res/ressourcesWeb/file.js";
FileConnection srcConn = (FileConnection) Connector.open(srcFile, Connector.READ);
InputStream in = srcConn.openInputStream();
but i got an exception.
Can any one help me to read the file and give me the right path that should I use?
Your res folder has to be inside src folder to be accessed from your code.
src folder is the root folder of your project package. And all folders outside of src folder are invisible for the code at runtime.
Check this post for more details: Blackberry runtime error: FRIDG: could not find img/logo.png
There's file location principle described.
You actually do not need to put your resources under the src folder for them to be accessible from your code.
That is one way to do it, but I don't think it's the best way. Files under the src folder should really be source code, not images, or other resources. For JavaScript resources, it's debatable whether those should be under src or not. Most projects I've seen have used the src folder for only Java source code.
In any case, if you would like to keep your file (or other resources, like images) outside the src folder, you can do so. The BlackBerry plugin for Eclipse actually sets it up like this by default, when you create a new project. There is a res folder at the top level, next to (not under) src.
If you have
src\
src\com\mycompany\myapp\
res\
res\resourcesWeb\
res\resourcesWeb\file.js
Then, you can open the file like this:
String jsPath = "/resourcesWeb/file.js";
InputStream input = getClass().getResourceAsStream(jsPath);
byte [] content = IOUtilities.streamToBytes(input);
String contentAsString = new String(content);
P.S. You also can probably do this:
String jsPath = "/file.js";
InputStream input = getClass().getResourceAsStream(jsPath);
and not specify the path to the resource. Obviously, this will only work if there are no naming conflicts in your resource folders (e.g. you don't have /res/resourcesWeb/file.js and also /res/otherPath/file.js)

How do I derive physical path of a relative directory inside Config.groovy?

I am trying to set up Weceem using the source from GitHub. It requires a physical path definition for the uploads directory, and for a directory for appears to be used for writing searchable indexes. The default setting for uploads is:
weceem.upload.dir = 'file:/var/www/weceem.org/uploads/'
I would like to define those using relative paths like WEB-INF/resources/uploads. I tried a methodology I have used previously for accessing directories with relative path like this:
File uploadDirectory = ApplicationHolder.application.parentContext.getResource("WEB-INF/resources/uploads").file
def absoluteUploadDirectory = uploadDirectory.absolutePath
weceem.upload.dir = 'file:'+absoluteUploadDirectory
However, 'parentContext' under ApplicationHolder.application is NULL. Can anyone offer a solution to this that would allow me to use relative paths?
look at your Config.groovy you should have (maybe it is commented)
// locations to search for config files that get merged into the main config
// config files can either be Java properties files or ConfigSlurper scripts
// "classpath:${appName}-config.properties", "classpath:${appName}-config.groovy",
grails.config.locations = [
"file:${userHome}/.grails/${appName}-config.properties",
"file:${userHome}/.grails/${appName}-config.groovy"
]
Create Conig file in deployment server
"${userHome}/.grails/${appName}-config.properties"
And define your prop (even not relative path) in that config file.
To add to Aram Arabyan's response, which is correct, but lacks an explanation:
Grails apps don't have a "local" directory, like a PHP app would have. They should be (for production) deployed in a servlet container. The location of that content is should not be considered writable, as it can get wiped out on the next deployment.
In short: think of your deployed application as a compiled binary.
Instead, choose a specific location somewhere on your server for the uploads to live, preferably outside the web server's path, so they can't be accessed directly. That's why Weceem defaults to a custom folder under /var/www/weceem.org/.
If you configure a path using the externalized configuration technique, you can then have a path specific to the server, and include a different path on your development machine.
In both cases, however, you should use absolute paths, or at least paths relative to known directories.
i.e.
String base = System.properties['base.dir']
println "config: ${base}/web-app/config/HookConfig.grooy"
String str = new File("${base}/web-app/config/HookConfig.groovy").text
return new ConfigSlurper().parse(str)
or
def grailsApplication
private getConfig() {
String str = grailsApplication.parentContext.getResource("config/HookConfig.groovy").file.text
return new ConfigSlurper().parse(str)
}

Is it possible to have a dynamic resource path for import?

I have a Spring.NET program with a configuration file. To smooth the transition from test to prod I'd like to have an environment variable that gives the path to a shared config file, and use that to import a resource, however it appears the <import resource="path"/> is not being resolved. For example if I try to load the file <import resource="\\server\share\${computername}\SpringConfig.xml"/> I get a file not found exception as below:
System.Configuration.ConfigurationErrorsException: Error creating context 'spring.root': file [\server\share\${computername}\SpringConfig.xml] cannot be resolved to local file path - resource does not use 'file:' protocol. ---> Spring.Objects.Factory.ObjectDefinitionStoreException: IOException parsing XML document from file [\server\share\${computername}\SpringConfig.xml] ---> System.IO.FileNotFoundException: file [\server\share\${computername}\SpringConfig.xml] cannot be resolved to local file path - resource does not use 'file:' protocol.
Is there a way I can have a dynamic import path in Spring.NET, preferably without writing code?
You can do that anyway with some extra code:
Create your own FileSystemResource that will replace placeholders in the resource name. Start from overriding the existing FileSystemResource (In Spring.Core.IO namespace)
Register your new IResource implementation in the container using your own protocol name (ex: myfile://) See ref docs here for an example :
In .NET configuration file (app.config/web.config)
http://www.springframework.net/doc-latest/reference/html/resources.html#d4e2911
In Spring configuration files
http://www.springframework.net/doc-latest/reference/html/objects.html#context-custom-resourcehandler
Use it!
resource="myfile://\server\share\${computername}\SpringConfig.xml"
I don't think we can do that with the current version.
Latest Java version supports it, so we can expect this feature in a future version (Using variables environnement by default)

Looking for image in HDD rather in context

I have multimodule project
Project
|--src
|-JavaFile.java
Web-Project
|-Web-Content
|-images
| |-logo.PNG
|-pages
|-WEB-INF
regular java module - contains src with all java files
dynamic web project module - contains all web related stuff
eventually regular java module goes as a jar file in dynamic web module in lib folder
Problem
java file after compilation looks for an image file in c:\ibm\sdp\server completepath\logo.png rather in context. File is defined in java file as below for iText:
Image logo = Image.getInstance("/images/logo.PNG");
Please suggest how can I change my java file to refer to image. I am not allowed to change my project structure.
You need to use ServletContext#getResource() or, better, getResourceAsStream() for that. It returns an URL respectively an InputStream of the resource in the web content.
InputStream input = getServletContext().getResourceAsStream("/images/logo.PNG");
// ...
This way you're not dependent on where (and how!) the webapp is been deployed. Relying on absolute disk file system paths would only end up in portability headache.
See also:
getResourceAsStream() vs FileInputStream
Update: as per the comments, you seem to be using iText (you should have clarified that a bit more in the question, I edited it). You can then use the Image#getInstance() method which takes an URL:
URL url = getServletContext().getResource("/images/logo.PNG");
Image image = Image.getInstance(url);
// ...
Update 2: as per the comments, you turn out to be sitting in the JSF context (you should have clarified that as well in the question). You should use ExternalContext#getResource() instead to get the URL:
URL url = FacesContext.getCurrentInstance().getExternalContext().getResource("/images/logo.PNG");
Image image = Image.getInstance(url);
// ...

Resources