How Or where Do I access my properties file - java

I have a properties file myprops.properties as follows:
Wsdl=someurl
UserName=user
UserPassword=pasword
Application=appName
And inside my controller I'm trying to access to set values in my service as follows
Properties prop = new Properties();
prop.load(new FileInputStream("resources/myprops.properties"));
myService.setWsdl(prop.getProperty("Wsdl"));
myService.setUserName(prop.getProperty("UserName"));
myService.setUserPassword(prop.getProperty("UserPassword"));
myService.setApplication(prop.getProperty("Application"));
my Issue is I just do not know what path to use. Its a Spring project if that makes any difference. and Idealy I would like to have the properties file in my "src/main/resources" folder
I realise this may be very simple to some but I have tried searching for the solution both here and on Google and I cannot seem to find a solution that has helped. I've tried moving the file around the project but cannot seem to figure it out
The Error I get is
java.io.FileNotFoundException: resources\drm.properties (The system cannot find the path specified)
any advice/explanation or even a link that clearly explains it would be great

well, src/main/resources are on the classpath, you just need to do.
Properties properties = PropertiesLoaderUtils.loadAllProperties("your properties file name");

If you are using spring, you could set your property placeholder.
<context:property-placeholder location="classpath:resources/myprops.properties" />
and in your beans you can inject the values from the properteis using the #Value annotation
#Autowired
public Foo(#Value("${Wsdl}") String wsdl) {
...
}
in the case above I used in the constructor, but its possible to use by Autowired field/setter.
So in your service you could have something like:
#Service
public class MyService {
private final String wsdl;
private final String username;
private final String password;
private final String application;
#Autowired
public MyService(
#Value("${Wsdl}") String wsdl,
#Value("${UserName}") String username,
#Value("${UserPassword}") String password,
#Value("${Application}") String application
) {
// set it to each field.
}
}

Given that src/main/resources is on the classpath, you could do:
Resource resource = new ClassPathResource("/myprops.properties");
Properties props = PropertiesLoaderUtils.loadProperties(resource);

Don't use a FileInputStream; use getResourceAsStream() to read it from the servlet context.

You can always count on mkyong. This is an example/tutorial on how to load and read property files.
http://www.mkyong.com/java/java-properties-file-examples/
This question should be marked as a duplicate:
Loading a properties file from Java package
How to use Java property files?
Load a property file in Java
Java Properties File not loading
Java NullPointerException on loading properties file
Not able to load properties file in Java

Related

Spring Profiling

I have 2 URLs among which 1 is specific to Dev and the other to Prod.
I am also using Spring profiling where i have seperate file for dev and prod application-dev.properties and application-prod.properties and my
appication.properties file look like this for Dev env
spring.profiles.active=dev
Now in my java code i want to have one property which will bind to the appropriate value depending on the spring profile i am using. How can i do it.
Current Java Class:-
//DEV
private static final String WIND_RESOURCE_EXTRACTOR_URL = "https://localhost:9090/dev";
//FOR PROD
//private static final String WIND_RESOURCE_EXTRACTOR_URL = "https://localhost:9090/prod";
SO i want to mention this properties in my application-dev.properties or application-prod.properties file and my java class should pick the correct value based on the current spring profile.
You just need to inject the value from your properties file. Assuming all the setup has already been done to read from the properties to the enviroment, i assume it has been.
public class MyClazz {
private final String myUrl;
#Autowired
public MyClazz(#Value("${my.url.property.name}") String myUrl){
this.myUrl = myUrl;
}
and within your two properties files place a my.url.property.name=WhateverValueIwant.

Getting properties object in spring

I have a properties file called xyz.properties. Right now, I am able to load individual property of this file in my class annotated with #Component which is working perfectly fine.
However, I am thinking of making my project more modular, for which I need to read the whole xyz.properties file as one properties object so that i can pass it along. How can I do so ?
Update
Right now, I am loading individual property from the file like this
my applicationContext.xml has following entry
<context:property-placeholder location="classpath:xyz.properties" order="2" ignore-unresolvable="true"/>
and then i have the respective class as
#Component
public class XyzConfiguration {
#Value("${client.id}")
private String clientId;
#Value("${client.secret}")
private String clientSecret;
...
}
What I mean by pass it along
Right now, for each individual property I have to create a respective field in a class and then annotate it with respective property name. By doing so, I am making my nested module very spring framework specific. I might someday put this module on github for others as well and they may or may not use spring framework. For them it would be easier to create an object of this module by passing required parameters (ideally in case of a Properties object) so that my module will fetch the properties by itself.
You can try below code.
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.core.io.ResourceLoader;
import java.util.Properties;
private String fileLocator;
private Properties prop;
private ResourceLoader resourceLoader;
public void init() throws IOException {
//"fileLocator" must be set as a path of file.
final Resource resource = resourceLoader.getResource(fileLocator);
prop = PropertiesLoaderUtils.loadProperties(resource);
}
prop will have all values from your property file and then you can get any value by calling prop.getProperty() method.

load properties in mule munit

I have some placeholders in my flow. Values for these placeholders are specified in a properties file (in classpath). I am doing munit using java. Currently, these placeholders are not getting replaced by values in property file. Any idea how do I load this file while running munit?
My munit is like this:
Class MyClass extends FunctionalMunitSuite{
#Override
protected String getConfigResources() {
//try 1[gave give value pairs directly]: didnt worked
System.getProperties().put("prop.key", "value");
//try2[load prop files]:didn't worked
prop.load(this.getClass().getResourceAsStream("mypropertyfile.properties"));
System.setProperties(prop);
}
}
In Overriding getConfigResources() specify a test-config.xml which has your mock connector and context property placeholder of properties file. Store that test properties file in src/test/resources
#Override
protected String getConfigResources() {
return "mule-config-test.xml" + ",actual-flow-to-test.xml";
}
Inside mule-config-test.xml, define test property file like this:
<context:property-placeholder ignore-resource-not-found="true" location="wmo-mule-app.properties,wmo-mule-app-unit-test.properties" />
In this case, wmo-mule-app.properties is my actual app property file while wmo-mule-app-unit-test.properties is the over-riding unit-test property file. This unit-test property file will take precedence over wmo-mule-app.properties
Currently you might be having your files in /src/main/resources
try to put it in /src/test/resources

Reading config resource from relative path for a Java app

--myjar.jar
--config
----appconfig.xml
I'm trying create maven based java application which can read configuration file from a relative path config\appconfig.xml
The idea here is that, the configuration can be modified without recompiling the application.
My implementation is something like this:
#Service
public class JooxXmlConfigurationServiceImpl implements XmlConfigurationService {
#Value("${configuration.xml}")
private String path;
}
Where the value is fetched from a properties file that is uder src/main/java/app-defaults.properties
It works when the String path is defined as the complete address like: C:/myprojects/myapp/config/appconfig.xml
but I need to set the path to be something like config/appconfig.xml

How do I read a .properties file without calling its absolute path

I have my .properties file in
com.someOtherpage
-somefolder
--theProperties.java `<--- This guy needs it`
com.somepackage
WEB-INF
-config
--project.properties `<--- Here is where he sits`
when deployed how can I call the properties file with out calling its absolute path like below
public class theProperties
{
private static Properties properties = new Properties();
public theProperties()
{
}
public String get(String attribute) throws Exception
{
//what do I need to set up to be able to call this file this way
//notice there is no '../../project.properties'
// -----
InputStream is = theProperties.class.getResourceAsStream("project.properties");
properties.load(is);
is.close();
return properties.getProperty(attribute);
}
}
The above isn't working, why?
If you put the properties file in the same package as the Class that reads it you specify its path relative to that class, that is if the properties file is in the exact same package as the class loading it you specify the path as project.properties.
If you put the properties file in the default package and the loading class isn't in the default package, you have to specify an absolute path like, /project.properties. Just a reminder no classes should be in the default class path as a general rule.
Either way, your properties file has to be on the classpath which yours isn't. In other words it has to be somewhere in WEB-INF/classes/.
A better solution, but more complex is to use Guice to inject properties and not write your own reader.
here is a nice explanation of how...
http://jaitechwriteups.blogspot.com/2007/01/how-to-read-properties-file-in-web.html
Assuming you want to avoid the absolute filepath, not the absolute path within the classpath, you need to do:
theProperties.class.getResourceAsStream("/WEB-INF/config/project.properties")
The forward slash at the front is important. Without it the path is relative to the loading class's package location.

Categories

Resources