I have a static array list in my code. Now I want that should be moved to the properties file so that if there is any change or modification in future I have simply change the values in properties file and it will be reflected everywhere where it is used.
As of now static code is like this:
ArrayList dataList = new ArrayList();
dataList.add("A");
dataList.add("B");
dataList.add("E");
dataList.add("G");
dataList.add("H");
dataList.add("P");
dataList.add("W");
ArrayList TypeList = new ArrayList();
TypeList.add(new Brand("A", "Test1"));
TypeList.add(new Brand("B", "Test2"));
TypeList.add(new Brand("E", "Test3"));
TypeList.add(new Brand("G", "Test4"));
I have tried this but this is not working:
Properties prop = new Properties();
prop.load(new FileInputStream("/displayCategerization.properties"));
I want both of them to be dynamic and the values should be picked from properties file. How can I do this?
You can try below code:
private static Properties props = null;
public static void load(String configFilePath) {
InputStream is = ClassLoader.getSystemResourceAsStream(configFilePath);
props = new Properties();
props.load(is);
is.close();
}
public static String getValueByKey(String key) {
String propertyValue=null;
if(props.containsKey(key)) {
propertyValue = props.getProperty(key);
}
return propertyValue;
}
Call this function during start of your program. You need to restart your program in case of properties file update
You can use in this way :-
Properties prop = new Properties();
prop.load(new FileInputStream("Test.properties"));
String name = prop.getProperty("name");
String city = prop.getProperty("city");
Test.properties
name=xyz
city=AAA
Related
I am using this example to read from configuration file (data such as host name, password, etc) . But they did not include the Configurations class itself.
So I am not really sure how that should be implemented.
Here is how I am trying to read the properties from Main class:
Configurations configs = new Configurations(); // Error: cannot find symbol symbol: class Configurations location: class Main
try {
Configuration config = configs.properties(new File("database.properties"));
String dbHost = config.getString("database.host");
int dbPort = config.getInt("database.port");
String dbUser = config.getString("database.user");
String dbPassword = config.getString("database.password", "secret"); // provide a default
long dbTimeout = config.getLong("database.timeout");
} catch (ConfigurationException cex) {
cex.printStackTrace();
}
And this is how my database.properties file looks:
database.host = "dbname";
datatabase.port = 5005;
datatabase.user = "root";
datatabase.password = "";
database.timeout = 60000
P.S. Sorry for my stupidity, I am very new to Java.
You can use the properties class in java, which has a load method that specifies an inputstream.
Then, you can read your properties file via FileInputStream.
example:
public class Test {
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
InputStream inputStream =
new FileInputStream("D:\\work_space\\java_workspace\\test-mq\\src\\main\\resources\\database.properties");
properties.load(inputStream);
String host = properties.getProperty("database.host");
// get more properties......
System.out.println(host);
}
}
The following program successfully prints 4 properties as expected
public class TestingStringProps {
public static void main(String[] args) throws IOException {
String s = "name=file\npath=/var/log/mine/\nhost=localhost:9092\nport=9999";
Properties props = new Properties();
props.load(new StringReader(s));
System.out.println("Number of Props: " + props.stringPropertyNames().size());
for (final String name : props.stringPropertyNames()) {
System.out.println(props.getProperty(name));
}
}
}
Now, if i pass the same string as Program Argument in eclipse, it considers the whole String as one property.
How to pass a string of properties in eclipse?
Requirement: I have simplified the question here. In our project a program gets a string of properties like the above from another program and it is working fine. I wanted to test the second program independently.
You need to change the code a bit. Then need to set the program arguments as below (need to add space in between each property)
public static void main(String[] args) throws IOException {
String str = String.join("\n", args);
Properties props = new Properties();
props.load(new StringReader(str));
System.out.println("Number of Props: " + props.stringPropertyNames().size());
for (final String name : props.stringPropertyNames()) {
System.out.println(props.getProperty(name));
}
}
program argument: name=file path=/var/log/mine host=localhost:9092 port=9999
If I have a set of properties, I understand that Springboot's relaxed data binder will read in a list of properties (or yaml) and populate the matching object. Like so:
Properties props = new Properties();
props.put("devices.imports[0]","imp1");
props.put("devices.imports[1]","imp2");
props.put("devices.definitions[0].id","first");
props.put("devices.definitions[1].id", "second");
DeviceConfig conf = new DeviceConfig();
PropertiesConfigurationFactory<DeviceConfig> pcf = new PropertiesConfigurationFactory<>(conf);
pcf.setProperties(props);
conf = pcf.getObject();
assertThat(conf.getDefinitions()).hasSize(2); //Definitions is coming in as 0 instead of the expected 2
DeviceConfig looks like this:
#ConfigurationProperties(prefix="devices")
public class DeviceConfig {
private List<String> imports = new ArrayList<>();
private List<DeviceDetailsProperties> definitions = new ArrayList<>();
public List<String> getImports() {
return this.imports;
}
public List<DeviceDetailsProperties> getDefinitions() {
return definitions;
}
public void setImports(List<String> imports) {
this.imports = imports;
}
public void setDefinitions(List<DeviceDetailsProperties> definitions) {
this.definitions = definitions;
}
}
DeviceDetailsProperties just has an id field with getters/setters.
Strangely neither the definitions (objects) or imports (Strings) are getting populated.
Using SpringBoot 1.2.0.RELEASE
When using the PropertiesConfigurationFactory in a manual way like this, it won't automatically use the prefix value in the annotation.
Add a targetName like so:
pcf.setTargetName("devices");
The corrected code would be:
Properties props = new Properties();
props.put("devices.imports[0]","imp1");
props.put("devices.imports[1]","imp2");
props.put("devices.definitions[0].id","first");
props.put("devices.definitions[1].id", "second");
DeviceConfig conf = new DeviceConfig();
PropertiesConfigurationFactory<DeviceConfig> pcf = new PropertiesConfigurationFactory<>(conf);
pcf.setProperties(props);
pcf.setTargetName("devices"); // <--- Add this line
conf = pcf.getObject();
assertThat(conf.getDefinitions()).hasSize(2);
I tried best couldn't find a complete instructions on how to config a properties file with Maven,Testng.
Here are what I did and the exception I got:
from TestNG for suite, added
content of the config file:
user=testuser
password=pswd
pom.xml
src/test/resources
true
in code:
#BeforeTest #Parameters(value = { "config-file" })
public void initFramework(String configfile) throws Exception
{
InputStream stream = Config.class.getResourceAsStream("/config.properties");
Properties properties = new Properties();
try {
properties.load(stream);
String user = properties.getProperty("user");
String password = properties.getProperty("password");
System.out.println("\nGot User FirstName+LastName shows as:"+ user +"\n" + password + "===========");
} catch (IOException e) {
e.printStackTrace();
// You will have to take some action here...
}
}
Here is what I got when compile:
org.testng.TestNGException:
Parameter 'config-file' is required by #Configuration on method initFramework but has not been marked #Optional or defined
Question:
I think I got all options mixed but really wanted a working way to read the parameter for Java/Selenium/TestNG/Maven.
Properties CONFIG= new Properties();
FileInputStream ip = new FileInputStream("C://config.properties");
CONFIG.load(ip);
//Now simply read through property file:-
String user = CONFIG.getProperty("user");
String password = CONFIG.getProperty("password");
//To write property file:-
CONFIG.setProperty("user","newbie1");
CONFIG.setProperty("password","secret123");
I'm pretty new to java so bear with me. I'm trying to retrieve the properties of a child node. For instance I'm trying to retrieve all the properties associated with the image property:
/content
/foo
/jcr:content
/page
/page_child
/image <-----
Currently my script is retrieving all the properties from page_child but how do I get the properties of "image"
public void setPageContext(PageContext context) {
ValueMap properties = (ValueMap) context.getAttribute("properties");
closeText = properties.get("closeText", "");
imageURL = properties.get("fileReference", "");
}
public String getCloseText() { return closeText; }
public String getCloseText() { return imageURL; }
Take a look at /libs/foundation/components/adaptiveimage
In the JSP, they are creating a new Resource using the jcr:content of the image file.
Resource fileJcrContent = resource.getChild("file").getChild("jcr:content");
if (fileJcrContent != null) {
ValueMap fileProperties = fileJcrContent.adaptTo(ValueMap.class);
String mimeType = fileProperties.get("jcr:mimeType", "jpg");
extension = mimeType.substring(mimeType.lastIndexOf("/") + 1);
}
From there, all properties will be accessible through fileProperties.