How to load properties file in a JSF application? [duplicate] - jsf

This question already has answers here:
Where to place and how to read configuration resource files in servlet based application?
(6 answers)
Closed 7 years ago.
I'm trying to load a properties file in a JSF application I'm working on, though I can't manage to reference the file.
package com.nivis.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropHandler {
String result = "";
InputStream inputStream;
public void loadProp() {
try {
inputStream = this.getClass().getResourceAsStream("prop.properties");
if (inputStream == null) {
System.err.println("===== Did not load =====");
} else {
System.err.println("===== Loaded =====");
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
PropHandler ph = new PropHandler();
ph.loadProp();
}
}
The file is located in the same package and in the different examples I've found when searching for this, that should work. I've also tried to put the file in every conceivable place in the application and reference it to the best of my knowledge, but it does not work.
(only some of the folders that I've tested to put the file)
What am I doing wrong?
Optimally I'd like to have it in the same folder that I use for the msg.properties file.

As this answer elaborates, com/nivis/prop.properties should be the right way to reference the file nested in your resources folder.
But because you're not using ClassLoader classloader = Thread.currentThread().getContextClassLoader(); to locate the Classloader you have to use an absolute path starting with "/" resulting in /com/nivis/prop.properties.

try something like this
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("prop.properties");

Related

Writing my own image importer, pictures are not recognized as pictures after import

i am writing my own image import for my product catalog. I want to read the images from the local filesystem and store them in the configured assets folder. The import is very simple for now. Its one controller in the admin project and i trigger it by calling an url.
It is creating the files along with the folder structure and the files seem to have the same filesize, but somehow they get messed up along the way and they are not readable as images anymore (picture viewers wont open them). Any ideas why its being messed up ?
here the code:
#Controller("blImageImportController")
#RequestMapping("/imageimport")
public class ImageImportController extends AdminAbstractController {
#Value("${image.import.folder.location}")
private String importFolderLocation;
#Resource(name = "blStaticAssetService")
protected StaticAssetService staticAssetService;
#Resource(name = "blStaticAssetStorageService")
protected StaticAssetStorageService staticAssetStorageService;
#RequestMapping(method = {RequestMethod.GET})
public String chooseMediaForMapKey(HttpServletRequest request,
HttpServletResponse response,
Model model
) throws Exception {
File imageImportFolder = new File(importFolderLocation);
if (imageImportFolder.isDirectory()) {
Arrays.stream(imageImportFolder.listFiles()).forEach(directory ->
{
if (directory.isDirectory()) {
Arrays.stream(directory.listFiles()).forEach(this::processFile);
}
});
}
return "";
}
private void processFile(File file) {
FileInputStream fis = null;
try {
HashMap properties = new HashMap();
properties.put("entityType", "product");
properties.put("entityId", file.getParentFile().getName());
fis = new FileInputStream(file);
StaticAsset staticAsset = this.staticAssetService.createStaticAsset(fis, file.getName(), file.length(), properties);
this.staticAssetStorageService.createStaticAssetStorage(fis, staticAsset);
fis.close();
} catch (Exception e) {
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
There is a check in the StaticAssetService to try to detect this as an image (see https://github.com/BroadleafCommerce/BroadleafCommerce/blob/b55848f/admin/broadleaf-contentmanagement-module/src/main/java/org/broadleafcommerce/cms/file/service/StaticAssetServiceImpl.java#L217-L220). If it detected this correctly, you should get back an ImageStaticAssetImpl in the result to that call.
The flipside of this is the controller that actually reads the file (the StaticAssetViewController that renders a StaticAssetView). One of the things that the StaticAssetView does is set a response header for mimeType which the browser uses to render. This is set by this piece in the StaticAssetStorageService: https://github.com/BroadleafCommerce/BroadleafCommerce/blob/b55848f837f26022a620f0c2c143eed7902ba3f1/admin/broadleaf-contentmanagement-module/src/main/java/org/broadleafcommerce/cms/file/service/StaticAssetStorageServiceImpl.java#L213. I suspect that is the root of your problem.
Also just a note, sending those properties is not necessary when you are uploading the file yourself. That is mainly used in the admin when you are uploading an image for a specific entity (like a product or a category).

Uploading file in JSF (Need correct file pathway) [duplicate]

This question already has an answer here:
How to upload file using JSF 2.2 <h:inputFile>? Where is the saved File?
(1 answer)
Closed 5 years ago.
I am trying to get my JSF site to upload a picture to the server, but am having a time of it. I've found 4 methodologies to do, but I'd like to use h:InputFile as it seems the most direct.
It would seem I just need to supply the upload path correctly.
After adding #MultipartConfig I no longer get an exception, but I can't verify the file is uploaded or see any error.
public void AddPicture()
{
ConnInfo HitIt = new ConnInfo();
try
{
HitIt.save(fileCelebrityToAdd);
}
catch(Exception ex)
{
//?
}
}
#MultipartConfig(location="C:\\local\\pathway\\Netbeans\\project\\web\\Pictures\\items\\")
public class ConnInfo
{
private String uploadLocation;
public ConnInfo()
{
//uploadLocation = ".\\Pictures\\items\\";
uploadLocation = "C:\\local\\pathway\\Netbeans\\project\\web\\Pictures\\items\\";
}
public boolean TryOut(Part file) throws IOException
{
String monkey = uploadLocation+getFilename(file);
try
{
file.write(monkey);
}
catch(Exception ex)
{
return false;
}
return true;
}
}
Hopefully I've copied the necessary information correctly.
After going back and rereading all the articles I had bookmarked, it was actually the from the one Tam had suggested that I was able to strip out some information.
I didn't need the AJAX, or the #MultipartConfig, and my previous attempt was somehow incorrect, but the follow method allowed me to successfully upload a picture where I wanted it:
public boolean SaveHer(Part file)
{
String monkey = getFilename(file);
try (InputStream input = file.getInputStream())
{
Files.copy(input, new File(uploadLocation, monkey).toPath());
}
catch (IOException e)
{
// Show faces message?
return false;
}
return true;
}

Using property files in Web Applications [duplicate]

This question already has answers here:
How to get properties file from /WEB-INF folder in JSF?
(3 answers)
Closed 7 years ago.
I'm developing a web application(this is my first time) and pretty confused about using property files. I don't know where to put the property files.
The problem is that i have put it under the WEB_INF folder. And when i test run it as a Java Application to check whether Database connections are working according to the properties in the property file it is working without any problem.
But when i run it in a Server as a Web Application it fails to load the properties file saying it could not find the file in the path specified. I tried using every possible path i could give and changing the file directories within the whole project. But I kept getting the same error.
Then i changed my class again from scratch thinking there's some kind of a bug withing my code where i load the properties file. And it seems that it could not find the file either when deployed as a Web App. But my test application works fine. Where do i put this file and how do i use it. I have read #BalusC's answer in this thread https://stackoverflow.com/a/2161583/2999358 but i have no idea why this happens. Can someone help me on this?
I'm using Tomcat 8, Eclipse IDE and building on JSF framework.
Class where i load my properties file
public class ConfigCache {
private static final File FILE = new File("./WebContent/WEB-INF/conf/config.properties");
private static final Properties PROPERTIES = new Properties();
public static final String JDBC_DRIVER = ConfigCache.getProperty("db.driverName");
public static final String DATABASE_URL = ConfigCache.getProperty("db.url");
public static final String DATABASE_USERNAME = ConfigCache.getProperty("db.user");
public static final String DATABASE_PASSWORD = ConfigCache.getProperty("db.pass");
public ConfigCache() {
}
public static String getProperty(String key) {
if (PROPERTIES.isEmpty()) {
loadProperties();
}
Object value;
return (value = PROPERTIES.get(key)) == null ? "" : value.toString();
}
private static void loadProperties() {
if (!FILE.exists()) {
throw new IllegalArgumentException("The 'config.properties' has not been found.");
}
try {
FileInputStream fis = null;
try {
fis = new FileInputStream(FILE);
PROPERTIES.load(fis);
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException exp) {
System.out.println("IOException #" + ConfigCache.class + " # loadProperties() : " + exp);
}
}
} catch (Exception exp) {
System.out.println("Exception #" + ConfigCache.class + " # loadProperties() : " + exp);
}
}
}
Folder Structure
Try With this.
put the property in src folder.
Your file is in the WEB-INF directory. This means it's part of the war and reachable as part of the class path. That's perfectly ok, since it makes it portable and independant of the web container installation (e.g. Tomcat).
You can load any file in the class path as a resource:
getClass().getResourceAsStream("/conf/config.properties")
This means you can write your code like this:
private static void loadProperties() {
InputStream is = getClass().getResourceAsStream("/conf/config.properties");
PROPERTIES.load(fis);
}
(Error handling omitted)
You can explode (unzip) your war/ear file and see the contents or folder structure of it and find why your code doesnt work. The reason is that the folder WebContent doesnt exist in your ear/war , but does exist only when run via eclipse. This is the reason why its always better to follow the solution provided in the link posted so that you can retrieve the porperty files from classpath. The below code fetches your property file in eclipse but not in the server.
private static final File FILE = new File("./WebContent/WEB-INF/conf/config.properties");
Contents of WAR file (from JournelDev), it contains WEB-INF directory but there would be no WebContent directory above it

Downloads with JavaFX WebView

my web application offers a download. Javascript creats at the click the url (it depends on the user input) and the browser should open it, so that the page isn't reloaded.
For that, I think I have to alternatives:
// Alt1:
window.open(pathToFile);
// Alt2:
var downloadFrame = document.getElementById('downloads');
if (downloadFrame === null) {
downloadFrame = document.createElement('iframe');
downloadFrame.id = 'downloads';
downloadFrame.style.display = 'none';
document.body.appendChild(downloadFrame);
}
downloadFrame.src = pathToFile;
Both works under Firefox. Problem with open new window method: If the creation of the file at the server needs more time, the new empty tab will be closed late.
Problem with iframe: If there is an error at the server, no feedback is given.
I think at firefox the iframe is the better solution. But the web application must run with an JavaFX WebView, too. JavaFX haven't a download feature, I have to write it. One possible way is to listen on the location property:
final WebView webView = new WebView();
webView.getEngine().locationProperty().addListener(new ChangeListener<String>() {
#Override public void changed(ObservableValue<? extends String> observableValue, String oldLoc, String newLoc) {
if (newLoc.cotains("/download")) {
FileChooser chooser = new FileChooser();
chooser.setTitle("Save " + newLoc);
File saveFile = chooser.showSaveDialog(webView.getEngine().getScene().getWindow());
if (saveFile != null) {
BufferedInputStream is = null;
BufferedOutputStream os = null;
try {
is = new BufferedInputStream(new URL(newLoc).openStream());
os = new BufferedOutputStream(new FileOutputStream(saveFile));
while ((readBytes = is.read()) != -1) {
os.write(b);
}
} finally {
try { if (is != null) is.close(); } catch (IOException e) {}
try { if (os != null) os.close(); } catch (IOException e) {}
}
}
}
}
}
There are some problems:
The download start depends on a part of the url, because JafaFX supports no access to the http headers (that is bearable)
If the user starts the download with the same url two times, only the first download works (the change event only fires, if the url is new). I can crate unique urls (with #1, #2 and so on at the end). But this is ugly.
Only the "window.open(pathToFile);" method works. Loading an iframe don't fire the change location event of the website. That is expectable but I haven't found the right Listener.
Can someone help me to solve 2. or 3.?
Thank you!
PS: Sorry for my bad english.
edit:
For 2. I found a way. I don't know if it is a good one, if it is performant, if the new webview is deleted or is in the cache after download, ....
And the user don't get an feedback, when some a problem is raised:
webView.getEngine().setCreatePopupHandler(new Callback<PopupFeatures, WebEngine>() {
#Override public WebEngine call(PopupFeatures config) {
final WebView downloader = new WebView();
downloader.getEngine().locationProperty().addListener(/* The Listener from above */);
return downloader.getEngine();
}
}
I think you may just need to use copyURLtoFile to get the file...call that when the location changes or just call that using a registered java class. Something like this:
org.apache.commons.io.FileUtils.copyURLToFile(new URL(newLoc), new File(System.getProperty("user.home")+filename));
Using copyURLToFile the current page doesn't have to serve the file. I think registering the class is probably the easiest way to go... something like this:
PHP Code:
Download $filename
Java (in-line class in your javafx class/window... in this case my javafx window is inside of a jframe):
public class JavaApp {
JFrame cloudFrameREF;
JavaApp(JFrame cloudFrameREF)
{
this.cloudFrameREF = cloudFrameREF;
}
public void getfile(String filename) {
String newLoc = "http://your_web_site.com/send_file.php?filename=" + filename;
org.apache.commons.io.FileUtils.copyURLToFile(new URL(newLoc), new File(System.getProperty("user.home")+filename));
}
}
This part would go in the main javafx class:
Platform.runLater(new Runnable() {
#Override
public void run() {
browser2 = new WebView();
webEngine = browser2.getEngine();
appREF = new JavaApp(cloudFrame);
webEngine.getLoadWorker().stateProperty().addListener(
new ChangeListener<State>() {
#Override public void changed(ObservableValue ov, State oldState, State newState) {
if (newState == Worker.State.SUCCEEDED) {
JSObject win
= (JSObject) webEngine.executeScript("window");
// this next line registers the JavaApp class with the page... you can then call it from javascript using "app.method_name".
win.setMember("app", appREF);
}
}
});
You may not need the frame reference... I was hacking some of my own code to test this out and the ref was useful for other things...

jsf 2.2 get the path for a propertie file

i want to read out from a propertie file in my jsf 2.2 project. i use eclipse kepler.
i try to use this in my java-bean in the folder src with the package de.exanple. The file of the bean is called PageServiceBean.java.
The propertie file is in the WEB-INF/resources/prop folder. The propertie file is called config.properties.
I have read that i can change the resouce folder in jsf 2.2 in the web.xml file with the javax.faces.WEBAPP_RESOUCRES_DIRECTORY param name and the param value like /WEB_INF/resoucres
But i don't get the path to the config file.
Can you tell where i can get the path name. I think i must use a relativ path name.
Can you please help me?
Update
I execute the second code fragment from you like:
private Properties getProperties() {
Properties prop = new Properties();
try {
//load a properties file
prop.load(new FileInputStream("config2.properties"));
} catch(Exception e) {
}
return prop;
}
public void setProperty1(Integer value) {
Properties prop = getProperties();
prop.setProperty("ort", value.toString());
try {
prop.store(new FileOutputStream("config2.properties"), null);
Properties prop2 = getProperties();
} catch (IOException ex) {
Logger.getLogger(PageServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
It works! I use the Properties prop3 = getProperties(); to read the the propertie file config2.properties. The File is Store in the eclipse home path ECLIPSE_HOME = C:\elipse_jee\eclipse. Can i change the path into a specific path, like WEB_INF/resources?
I will show you my approach to your need, but I won't try to answer your question.
To use properties files in a JEE application I create a Stateless bean that serves the rest of the application with the getter and setter for the properties. Only this EJB will access the property file in the server and I use the java.util.Properties.
private Properties getProperties() {
Properties prop = new Properties();
try {
//load a properties file
prop.load(new FileInputStream("config.properties"));
} catch(Exception e) {
}
return prop;
}
After I have the access methods for a specifc property:
public Integer getProperty1() {
Properties prop = getProperties();
String value = prop.getProperty("myProperty1Name");
if(value != null) {
return Integer.parseInt(value );
}
return 0;
}
public void setProperty1(Integer value) {
Properties prop = getProperties();
prop.setProperty("myProperty1Name", value.toString());
try {
prop.store(new FileOutputStream("config.properties"), null);
} catch (IOException ex) {
Logger.getLogger(PropertiesManager.class.getName()).log(Level.SEVERE, null, ex);
}
}
In this approach, if the file doesn't exist it will be created. The default value of a property will be hard coded though. For this approach, it doesn't matter where your file is placed. The actual location will depend on your JEE server configuration, domain configuration, application deployment files, etc.
Web content resources are available by ServletContext#getResourceAsStream() and its JSF delegator ExternalContext#getResourceAsStream(). So, this should do:
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
prop.load(ec.getResourceAsStream("/WEB-INF/resources/prop/config2.properties"));
See also:
Where to place and how to read configuration resource files in servlet based application?

Resources