Issue when getting value from build.properties in ICEfaces - java

I want to get the value of a property I added from build.properties
dergilik.host=http://172.171.1.155/
with the code below
private final static String PROPERTIES_FILE = "build.properties";
private final static String HOST = "dergilik.host";
private final Properties props = new Properties();
private String getHost() {
try {
InputStream inp = new FileInputStream(PROPERTIES_FILE);
props.load(inp);
return props.getProperty(HOST);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
e.printStackTrace();
return null;
}
}
But the application throws FileNotFoundException when props.load(inp);. I also tried it with ClassLoader class and NullPointerException occured. Furthermore I changed PROPERTIES_FILE as "/ProjectName/build.properties" but it didn't work.
So how can I make the program correctly find build.properties file?
Thanks

If you want to access in web application
and the resource is inside web application and you have access to ServletContext, you should use ServletContext.getResourceAsStream().
and the resource is outside web application, configure the path using context-param in web.xml and try accessing using ServletContext.getInitParameter()
It if is not Web application and present in the classpath use,
Thread.currentThread().getContextClassloader().getResourceAsStream()

Related

Load resource bundle at runtime

Here is what I would like to achieve. We have an application that is running as a servlet on an IBM Domino server.
The application uses resource bundle to get translated messages and labels according to the browser language.
We want to enable customers to override some of the values.
We cannot modify the bundle_lang.properties files in the .jar at runtime.
So the idea was to provide additional bundleCustom_lang.properties files along with the .jar
This bundle could be loaded at runtime using
private static void addToClassPath(String s) throws Exception {
File file = new File(s);
URLClassLoader cl = (URLClassLoader) ClassLoader.getSystemClassLoader();
java.lang.reflect.Method m = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
m.setAccessible(true);
m.invoke(cl, new Object[] { file.toURI().toURL() });
}
So far, so good, this works in Eclipse. Here I had the bundleCustom files in a directory outside the workspace ( /volumes/DATA/Temp/ )
Once the addition ResourceBundle is available, We check this bundle for the key first. If it returns a value than this value is being used for the translation. If no value is returned, or the file does not exist, the value from the bundle inside the .jar is used.
My full code is here
public class BundleTest2 {
static final String CUSTOM_BUNDLE_PATH = "/volumes/DATA/Temp/";
static final String CUSTOM_BUNDLE_MODIFIER = "Custom";
public static void main(String[] args) {
try {
addToClassPath(CUSTOM_BUNDLE_PATH);
System.out.println(_getTranslation("LabelBundle", "OutlineUsersAllVIP"));
} catch (Exception e) {
}
}
private static String _getTranslation(String bundle, String translation) {
return _getTranslation0(bundle, new Locale("de"), translation);
}
private static String _getTranslation0(String bundle, Locale locale, String key) {
String s = null;
try {
try {
ResourceBundle custom = ResourceBundle.getBundle(bundle + CUSTOM_BUNDLE_MODIFIER, locale);
if (custom.containsKey(key)) {
s = custom.getString(key);
}
} catch (MissingResourceException re) {
System.out.println("CANNOT FIND CUSTOM RESOURCE BUNDLE: " + bundle + CUSTOM_BUNDLE_MODIFIER);
}
if (null == s || "".equals(s)) {
s = ResourceBundle.getBundle(bundle, locale).getString(key);
}
} catch (Exception e) {
}
return s;
}
private static void addToClassPath(String s) throws Exception {
File file = new File(s);
URLClassLoader cl = (URLClassLoader) ClassLoader.getSystemClassLoader();
java.lang.reflect.Method m = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
m.setAccessible(true);
m.invoke(cl, new Object[] { file.toURI().toURL() });
}
}
When I try the same from inside the servlet, I get a MissingResourceException.
I also tried to put the .properties files into a customization.jar and provide the full path ( incl. the .jar ) when invoking addToClassPath().
Apparently, the customization.jar is loaded ( it is locked in the file system ), but I still get the MissingResourceException.
We already use the same code in addToClassPath to load a Db2 driver and this is working as expected.
What am I missing?
Why don't you use Database to store the overriden translations? Persisting something crated by client in the local deployment of application is generally not a good idea, what will happen if you redeploy the app, will these resources be deleted? What if you have to run another node of your app, how will you replicate the custom properties file?

Loading Property File from Filesystem in Jboss Fuse / Karaf throws Nullpointer

I try to load a property file in Java running on JBossFuse/karaf.
The file is located at $[karaf.home]/etc/bean.properties
The Code is able to load properties inside the bundle fine, but now I try to exclude the properties from the project itself and the code throws a Nullpointer-Exception.
The Path is properly resolved on my development machine as
C:\Users\someone\devstudio\runtimes\jboss-fuse-6.3.0.redhat-135\etc\bean.properties
The property-File can be loaded in the blueprint-XML to configure beans, but to access the bean my code needs the CamelContext. As I have some static codeblocks that are accessed without an exchange/context/registry, I also wanted to be able to load the properties in Java.
Both the functions throw the NullPointerException and I guess, it is because the code runs in Fuse.
public static Properties getProperties(String location) {
Properties prop = new Properties();
InputStream input = null;
try {
input = PropertyLoader.class.getClassLoader().getResourceAsStream(location);
prop.load(input);
} catch (IOException ex) {
log.error("Error loading properties file from: " + location, ex);
return null;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
log.error(e);
}
}
}
return prop;
}
public static Properties getPropertiesFromFilesystem(String location) {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(location);
prop.load(input);
} catch (IOException ex) {
log.error("Error loading properties file from: " + location, ex);
return null;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
log.error(e);
}
}
}
return prop;
}
The Exception:
java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:434)[:1.8.0_91]
at java.util.Properties.load0(Properties.java:353)[:1.8.0_91]
at java.util.Properties.load(Properties.java:341)[:1.8.0_91]
at com.mycompany.util.PropertyLoader.getProperties(PropertyLoader.java:19)[319:camel-archetype-blueprint:0.0.14]
at com.mycompany.camel.blueprint.MyProcessor.process(MyProcessor.java:21)[319:camel-archetype-blueprint:0.0.14]
at org.apache.camel.processor.DelegateSyncProcessor.process(DelegateSyncProcessor.java:63)[231:org.apache.camel.camel-core:2.17.0.redhat-630135]
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)[231:org.apache.camel.camel-core:2.17.0.redhat-630135]
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:468)[231:org.apache.camel.camel-core:2.17.0.redhat-630135]
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:196)[231:org.apache.camel.camel-core:2.17.0.redhat-630135]
at org.apache.camel.processor.Pipeline.process(Pipeline.java:121)[231:org.apache.camel.camel-core:2.17.0.redhat-630135]
at org.apache.camel.processor.Pipeline.process(Pipeline.java:83)[231:org.apache.camel.camel-core:2.17.0.redhat-630135]
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:196)[231:org.apache.camel.camel-core:2.17.0.redhat-630135]
at org.apache.camel.component.timer.TimerConsumer.sendTimerExchange(TimerConsumer.java:192)[231:org.apache.camel.camel-core:2.17.0.redhat-630135]
at org.apache.camel.component.timer.TimerConsumer$1.run(TimerConsumer.java:76)[231:org.apache.camel.camel-core:2.17.0.redhat-630135]
at java.util.TimerThread.mainLoop(Timer.java:555)[:1.8.0_91]
at java.util.TimerThread.run(Timer.java:505)[:1.8.0_91]
Any help would be highly appreciated.
Do not do that. You are looking for trouble.
Load properties the OSGi way (use .cfg as extension and a blueprint property-placeholder bean)
You have the added benefit of getting notified if the file changes (if you wish)
Inject them in a bean EVEN IF you are using only static methods.
Don't mix managed beans with unmanaged static code unless you know very well what you are doing.
If some "static" code requires properties means that it is stateful, and this class deserves to be instantiated to a bean.
Not sure why you are getting an NPE without a more complete example. If you need to use properties without a route, you should be using Camel's property placeholder facilities:
https://access.redhat.com/documentation/en-us/red_hat_jboss_fuse/6.3/html/apache_camel_development_guide/basicprinciples#BasicPrinciples-PropPlaceholders

Adding logs to wso2 to track logs implemented in custom java code

Below I have a code snippet for a custom API manager mediator, I'm suppose to modify this code for our use. I'm having trouble though getting the logs out of the code when I'm running it in our wso2 environment. What would be the process to be able to the outputs of these logs. This is going to be a jar file I add to the repository/components/lib/ directory of the APIM. The jar file name is com.domain.wso2.apim.extensions. I need to be able to see whats being passed and what parts of the code are being hit for testing
public class IdentifiersLookup extends AbstractMediator implements ManagedLifecycle {
private static Log log = LogFactory.getLog(IdentifiersLookup.class);
private String propertyPrefix = "";
private String netIdPropertyToUse = "";
private DataSource ds = null;
private String DsName = null;
public void init(SynapseEnvironment synapseEnvironment) {
if (log.isInfoEnabled()) {
log.info("Initializing IdentifiersLookup Mediator");
}
if (log.isDebugEnabled())
log.debug("IdentifiersLookup: looking up datasource" + DsName);
try {
this.ds = (DataSource) new InitialContext().lookup(DsName);
} catch (NamingException e) {
e.printStackTrace();
}
if (log.isDebugEnabled())
log.debug("IdentifiersLookup: acquired datasource");
}
Add the below line to log4j.properties file resides wso2am-2.0.0/repository/conf/ folder and restart the server.
log4j.logger.com.domain.wso2.apim.extensions=INFO

Where to best put a variable, in the class or in the method (Android Studio)

I followed in the code in the Android tutorial https://developer.android.com/training/basics/data-storage/files.html
public File getTempFile(Context context, String url) {
File file;
try {
String fileName = Uri.parse(url).getLastPathSegment();
file = File.createTempFile(fileName, null, context.getCacheDir());
} catch (IOException e) {
// Error while creating file
}
return file;
}
When I add this method to my class, there was an error on this code:
return file;
That says "File may not have been initialized"
What I did is I transferred the initialization code
File file;
To the class variable as a class field instead of a local method variable and the error disappeared. Is this the correct way to resolve the issue? Is there no workaround that would keep the variable local in the method and not global in the class?
I would prefer to limit visibility. Fields have a default null initialization. So the equivalent in the method is
File file = null;
The other answers are fine ; especially the one about avoiding the variable completely, but let's answer your question, too:
You put variables where you need them, preferably on the "smallest" scope possible. Meaning that you prefer local variables over class wide fields. In other words: you only use fields when two or more methods need to use the same information!
How about getting rid of it completely
public File getTempFile(Context context, String url) {
try {
String fileName = Uri.parse(url).getLastPathSegment();
return File.createTempFile(fileName, null, context.getCacheDir());
} catch (IOException e) {
// Error while creating file
// well lets say so then
System.err.println ("Error while creating file ");
e.printStackTrace ();
return null;
}
}
public File getTempFile(Context context, String url) {
File file = null;
try {
String fileName = Uri.parse(url).getLastPathSegment();
file = File.createTempFile(fileName, null, context.getCacheDir());
} catch (IOException e) {
// Error while creating file
}
return file;
}
You can get rid of local variable file, or just initialize it with null.

Loading Property file from FileSystem in a Java EE application

I am using EJB 3.0 and CDI to develop a java ee application which will be deployed in Websphere application server.
I have a requirement to have a property file from which i read certain configuration parameters and this property file should reside in the filesystem of the host system where my code will be deployed.
The base path ( directory where the property file will be placed ) for the property file is configured as a Name space binding String resource in Websphere application server.
Currently i have coded a Utility class to retrieve and use the property file which looks as below.
#Singleton
public class AppPropertyUtil {
private static Hashtable apppProperties;
#Resource(name="jndi/basePath",lookup="jndi/basePath")
private static String basePath;
private static final Logger LOGGER = LoggerFactory.getLogger(AppPropertyUtil.class);
protected void loadPropertyBundleFromFileSystem(String path)
{
InputStream inputStream = null;
Properties properties = null;
try {String fullPath=basePath+"/"+path+".properties";
LOGGER.info("Property file path : "+fullPath);
inputStream = new FileInputStream(new File(fullPath));
if (inputStream != null) {
properties = new Properties();
properties.load(inputStream);
LOGGER.info("Properties loaded");
apppProperties = (Hashtable)properties;
}
} catch (FileNotFoundException exception) {
LOGGER.error("Cannot read property bundle ",exception);
}
catch (IOException | IllegalArgumentException exception) {
LOGGER.error("Unable to loadproperties ",
exception);
}
}
public String getProperty(String key)
{
if(apppProperties == null)
{
loadPropertyBundleFromFileSystem("AppProps");
}
Object value = apppProperties.get(key);
if(value != null){
return (String) value;
}
return null;
}
}
But having the #Resource annotation will mandate that the AppPropertyUtil class be injected inside any class that wishes to use it. So, I will not be able to use this in any POJO classes which are not managed.
Please help me understand whether this is the best approach to go with for the above requirement or could this be improved. I would also like to make the getProperty method and loadPropertyBundleFromFileSystem method static to have it being used from a static context, but it is not possible as the class should be injected to be used.
Thanks in advance
Ideally, you shouldn't need to access to your class from any POJO. Use design patterns and separate your concerns. Use your class as a service to load up your property file and serve out a Map or Set of it's contents. POJO Models shouldn't care, but your other classes can read that map/set of properties and pass them to your pojo's or other classes which need it but don't have direct access to it.
The other option is to remove the #Resource and make this just a plain old util class that you pass in the filename to read in it's constructor, then when you call getProperty, you do what you do to check to see if it's been loaded already, if not, load it.
Wrap that in a factory that supplies the #Resource parts and it keeps your EE code from bleeding into your other jars (utils).

Categories

Resources