External properties files in Webshpere Application server - filenotfoundexception

I placed an properties file in the PROFILE_ROOT/properties folder of the WAS server. But when the application searches for the file I get a FileNotFound Exception. On the other hand, it is able to search for an existing properties file. Should anything be changed in the server once a property file has been added.
Properties properties = new Properties();
properties.load(new FileInputStream(new File("C:\\websphere\\appserver\\profiles\\appsrv01\\properties\\example.properties")));
System.out.println(properties.getProperty("en"));

Related

How can i refer one property file from another property file in spring cloud config

I have to implement spring cloud config for an existing project where i have an use case to handle
Here Some property files are referred by other property files like
logging.propFile=classpath:/cfg/xyz.properties and these property files are used in multiple places like
Properties property = new Properties();
property.load(new FileInputStream(propsPath));
logger = somefactory.createfactory(property.get("logging.propFile")); and this factory creation is defined in a different jar.
If i move all property files in git repo files i mentioned will not be available in class path and if i go for code change a lot of code change is involved.What is the best way to handle this situation.
Is there any way to refer one property file to another in spring cloud config .
Spring Cloud Config server allows for reading static files through HTTP. So you can put your references properties file into the configuration git repository and reference them through http://<configserver_url>/*/*/<branch_name>/xyz.properties. This only works when your code can handle URLs, so the FileInputStream in your example would not do it.
See https://cloud.spring.io/spring-cloud-config/multi/multi__serving_alternative_formats.html and https://cloud.spring.io/spring-cloud-config/multi/multi__serving_plain_text.html.
Also note the resolvePlaceholders query parameter that defaults to true.
We are using this for keeping our logback.xml configuration in the config server by setting logging.config: http://<configserver_url/*/*/master/logback.xml?resolvePlaceholders=false

Spring Reload Properties on Demand

I am looking to load properties from file On Demand in my spring boot application.
I have a requirement to load the properties from the file when there is a change in the properties file.
I am using #Configuration properties to load the properties, by setting the spring.config.location=file:/../test-properties.yml.
Bean class that holds the data
#Configuration
#ConfigurationProperties
public class GetValues {
List<String> values = new ArrayList<String>();
//getters and setters
}
test-properties.yml
values:
- X1
- X2
- X3
I have a rest service to load the data loaded from properties file to backend, within which I am Autowiring the GetValues Bean.
Whenever there is a change in the property file, I will call this service which would load the properties to the Backend.
Right Now, It is loading the same properties everytime, as the properties are already loaded in to the context.
Is there a way to reload the properties from the file everytime I hit the service? I don't want to use the Spring-Cloud, #RefreshScope.
There are two solutions
Using spring devtools you can achieve auto restart when config file change. Only desirable in development environment.
Make that when you hit the service the properties file get loaded, and update your config class attributes. Abstract:
Properties prop = new Properties();
InputStream input = null;
input = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileNameProperties);
prop.load(input);
bean.setValue(prop.getProperty("attribute1"));
If you don't want to use Spring Cloud Config / #RefreshScope, one option would be to the usage of a FileChangeListener / WatchService found in Apache commons (or similar library) or JDK 7 and reload the properties. Make sure you synchronize the usage of the loaded properties and updating them when the file changes, maybe through a ReentrantReadWriteLock.

Java EE 7: How to load JDBC connection info from properties file / any file on file system

I am working on a Java EE 7 application. I am using Payara micro to deploy my WAR files. Now, I need JDBC connectivity in my application, but I need to keep the database IP/username/password somewhere I can change later on, without re-uploading and deploying WAR file again.
Could anybody please tell me how can I achieve this?
EDIT:
I came accross a solution to that on SO:
https://stackoverflow.com/a/6296375/1931698
But, I am looking for a solution without all that plumbing. Inheriting DataSource just to have connection info in some external file looks like overkill.
EDIT:
Also, it would be really helpful if I can just provide a configuration panel to the user, where he / she can enter JDBC connection info. Is there a way to change that info at runtime (effectively discarding existing connection pool and creating a new one)?
Payara Micro should allow system property replacement in Datasource definitions using the syntax ${system.property.name} you can use that to define the database user name and password as well as the connect strings.
There is also environment variable support in 171.1 onwards using the syntax ${ENV=env.name} where env.name is the environment variable name.
Make use of java.utils.Properties with a seperate myproperties.properties file in your src folder (in classpath).
Properties prop = null;
try {
prop = new Properties();
InputStream inputStream = getClass().getClassLoader()
.getResourceAsStream("myProperty.‌​properties");
if (inputStream != null) {
prop.load(inputStream);
}
} catch (IOException e) {
errorLog.error("Property file not found in classpath:
ClientChecking Class.");
}
String userName = prop.getProperty("USERNAME");
myproperties.properties file must contain:
USERNAME=user123
If you are using Apache tomcat for hosting, then you can find and edit the propertyfile from path WebContent(Root dir)/WEB-INF/classes/

How to maintain, update application properties dynamically in Spring? [duplicate]

This question already has answers here:
How can I reload properties file in Spring 4 using annotations?
(3 answers)
Closed 6 years ago.
I would like to maintain a list of application properties like service endpoints, application variables, etc. in a Spring application. These properties should be able to updated dynamically (possibly through an web page by system administrator).
Does spring has an inbuilt feature to accomplish this requirement?
I am not sure spring has an implementation for updating the properties file dynamically.
You can do something like reading the properties file using FileInputStream into a Properties object. Then you will be able to update the properties. Later you can write back the properties to the same file using the FileOutputStream.
// reading the existing properties
FileInputStream in = new FileInputStream("propertiesFile");
Properties props = new Properties();
props.load(in);
in.close();
// writing back the properties after updation
FileOutputStream out = new FileOutputStream("propertiesFile");
props.setProperty("property", "value");
props.store(out, null);
out.close();
Externalizing properties, take a look here
Spring loads these properties which can be configured at runtime and accessed in your application in different ways.
Add your own implementation of a PropertySource to your Environment.
Warning: Properties used by #ConfigurationProperties and #Value annotations are only read once on application startup, so changing the actual property values at runtime will have no effect (until restarted).
I am not sure, but check if you can make use #ConfigurationProperties of Spring boot framework.
#ConfigurationProperties(locations = "classpath:application.properties", ignoreUnknownFields = false, prefix = "spring.datasource")
You can keep this application.properties file in you classpath
Change the properties in this file without redeploying the application
Java Experts - I am just trying to explore my view. Corrections are always welcome.
Edit - I read a good examples on #PropertySource here

Spring FreeMarkerConfiguration Template Loader Path overwritten by Configuration

I have a Java based web app running with Spring 4. I'm using FreeMarker for my web templates. My WebConfig class uses a FreeMarkerConfigurer object to set up my template loader path and some other settings as so:
#Bean
public FreeMarkerConfigurer freemarkerConfig() throws IOException {
FreeMarkerConfigurer fmc = new FreeMarkerConfigurer();
fmc.setTemplateLoaderPath("/WEB-INF/templates");
fmc.setDefaultEncoding("UTF-8");
Properties settings = new Properties();
settings.setProperty("date_format", "dd MMM yyyy");
fmc.setFreemarkerSettings(settings);
return fmc;
}
This works fine: views resolve correctly, including any <#import 'spring.ftl' as spring> directives which can be loaded from the jar.
Now I want to customise my application more, for example setting a custom template exception handler. I've created a FreeMarker Configuration object and added this to the FreeMarkerConfigurer:
Configuration cfg = new Configuration();
cfg.setTemplateExceptionHandler(new MyTemplateExceptionHandler());
fmc.setConfiguration(cfg);
But this stops my views resolving - it seems to overwrite the TemplateLoaderPath from the FreeMarkerConfigurer object and I have to explicitly set the path in the Configuration instance instead for my templates to be located by the project:
cfg.setDirectoryForTemplateLoading(new File("C:/myProject/WEB-INF/templates"));
Additionally, spring.ftl is no longer loaded from the jar and I have to put a copy in my template directory for it to be loaded.
Why does adding a Configuration to a FreeMarkerConfigurer overwrite my template loader path? Is my setup incorrect or does a Configuration have greater priority?
FreeMarkerConfigurer is just a factory that helps to build a freemarker.template.Configuration and exposes it with its method getConfiguration().
If you want to further configurate the configuration, extract it first from your configurer, because there will be only one Configuration used by FreeMarker.

Resources