Properties file reset when modifying or adding value - java

What I need is a simple way to read and write certain values to a XML file? I want it to be simple something like this:
Configuration config = new Configuration();
config.setValue("WIDTH", 1000);
int WIDTH = config.getValue("WIDTH");
It needs to be writable and readable at all times. This is what I have so far:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
public class Configuration {
Properties config;
public Configuration() {
config = new Properties();
}
public void setValue(String name, String value) {
try {
config.setProperty(name, value);
config.storeToXML(new FileOutputStream("MyXmlConfig.xml"), null);
} catch (Exception e) {
e.printStackTrace();
}
}
public String getValue(String name) {
try {
config.loadFromXML(new FileInputStream("MyXmlConfig.xml"));
} catch (Exception e) {
e.printStackTrace();
}
return config.getProperty(name);
}
}
The problem with what I have is that it resets the created file when a variable is updated or added.

The built-in class java.util.Properties supports this use case:
Properties config = new Properties();
config.loadFromXML(new FileInputStream("c:/MyXmlConfig.xml"));
config.setProperty("WIDTH", "1000");
int WIDTH = Integer.parseInt(config.getProperty("WIDTH"));
config.storeToXML(new FileOutputStream("c:/MyXmlConfig.xml"), "My config file");

Related

Got an error that attribute value is missing

I have base class that have an Url url without instantiation, than I have and class that inherit it and in the before method of it (TestNG) I have statement :
url = new URL(props.getProperty(“appiumURL”));
the URL is 127.0.0.0
afterwards I have :
desiredCapabilities.setCapability(“automationName”, props.getProperty(“iOSAutomationName”));
String iOSAppUrl = getClass().getResource(props.getProperty(“iOSAppLocation”)).getFile();
utils.log().info(“appUrl is” + iOSAppUrl);
desiredCapabilities.setCapability(“bundleId”, props.getProperty(“iOSBundleId”));
desiredCapabilities.setCapability(“wdaLocalPort”, wdaLocalPort);
desiredCapabilities.setCapability(“webkitDebugProxyPort”, webkitDebugProxyPort);
//desiredCapabilities.setCapability(“app”, iOSAppUrl);
driver = new IOSDriver(url, desiredCapabilities);
the value of the url is : http://0.0.0.0:4723/wd/hub
than after the line of the “driver = new IOSDriver(url, desiredCapabilities);” I get an exception that the url is null,
than BuildInfo class is opened :
package org.openqa.selenium;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
/**
* Reads information about how the current application was built from the Build-Info section of
the
* manifest in the jar file, which contains this class.
*/
public class BuildInfo {
private static final Properties BUILD_PROPERTIES = loadBuildProperties();
private static Properties loadBuildProperties() {
Properties properties = new Properties();
Manifest manifest = null;
JarFile jar = null;
try {
URL url = BuildInfo.class.getProtectionDomain().getCodeSource().getLocation();
File file = new File(url.toURI());
jar = new JarFile(file);
ZipEntry entry = jar.getEntry("META-INF/build-stamp.properties");
if (entry != null) {
try (InputStream stream = jar.getInputStream(entry)) {
properties.load(stream);
}
}
manifest = jar.getManifest();
} catch (
IllegalArgumentException |
IOException |
NullPointerException |
URISyntaxException ignored) {
} finally {
if (jar != null) {
try {
jar.close();
} catch (IOException e) {
// ignore
}
}
}
if (manifest == null) {
return properties;
}
try {
Attributes attributes = manifest.getAttributes("Build-Info");
Set<Entry<Object, Object>> entries = attributes.entrySet();
for (Entry<Object, Object> e : entries) {
properties.put(String.valueOf(e.getKey()), String.valueOf(e.getValue()));
}
attributes = manifest.getAttributes("Selenium");
entries = attributes.entrySet();
for (Entry<Object, Object> e : entries) {
properties.put(String.valueOf(e.getKey()), String.valueOf(e.getValue()));
}
} catch (NullPointerException e) {
// Fall through
}
return properties;
}
/** #return The embedded release label or "unknown". */
public String getReleaseLabel() {
return BUILD_PROPERTIES.getProperty("Selenium-Version", "unknown").trim();
}
/** #return The embedded build revision or "unknown". */
public String getBuildRevision() {
return BUILD_PROPERTIES.getProperty("Build-Revision", "unknown");
}
/** #return The embedded build time or "unknown". */
public String getBuildTime() {
return BUILD_PROPERTIES.getProperty("Build-Time", "unknown");
}
#Override
public String toString() {
return String.format("Build info: version: '%s', revision: '%s', time: '%s'",
getReleaseLabel(), getBuildRevision(), getBuildTime());
}
the thing is that :
attributes = manifest.getAttributes("Selenium");
entries = attributes.entrySet();
the attribute is null .
what I’m doing wrong?
Thank you

How to read properties file in java, which has value in key-value pair

if properties file contains below type values how to read it directly into map
user={'name':'test','age':'23','place':'london'}.
Thanks in advance!
You can inject values into a Map from the properties file using the #Value annotation like this.
#Value("#{${user}}")
private Map<String, String> user;
Entry in your application.properties must be:
user = {"name":"test","age":"23","place":"London"}
test.properties file
name=test
age=23
place=london
code
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
public class ReadPropertiesFile {
public static void main(String[] args) {
try {
File file = new File("test.properties");
FileInputStream fileInput = new FileInputStream(file);
Properties properties = new Properties();
properties.load(fileInput);
fileInput.close();
Enumeration enuKeys = properties.keys();
while (enuKeys.hasMoreElements()) {
String key = (String) enuKeys.nextElement();
String value = properties.getProperty(key);
System.out.println(key + ": " + value);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Hope, this would help.. :)
This will read a property file and put it in Properties object.
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesConfig {
private Properties prop;
private PropertiesConfig() {
super();
init();
}
private static class PropertiesInstance {
private static PropertiesConfig instance = null;
public static PropertiesConfig getInstance() {
if (null == instance) {
instance = new PropertiesConfig();
}
return instance;
}
}
public static PropertiesConfig getInstance() {
return PropertiesInstance.getInstance();
}
private void init() {
prop = new Properties();
try (InputStream input = getClass().getResourceAsStream("/sample_config.properties")) {
// load a properties file
prop.load(input);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public String getProperty(String key) {
return prop.getProperty(key);
}
}
Now you can use any library to convert a value to Map as your value looks like a JSON.
Code example to achieve this through Jackson:
public static Map < String, Object > covertFromJsonToMap(String json) throws JsonTransformException {
try {
return mapper.readValue(json, new TypeReference < HashMap < String, Object >> () {});
} catch (Exception e) {
LOGGER.error("Error " + json, e);
throw new JsonTransformException("Error in json parse", e);
}
}
So something like this will do:
covertFromJsonToMap(PropertiesConfig.getInstance().get("user"));
Looks like you have a JSON representation of your map as a value. Once you read the value as a String in Java you can use Gson to convert it to map
Gson gson = new Gson();
String json = <YOUR_STRING>
Map<String,Object> map = new HashMap<String,Object>();
map = (Map<String,Object>) gson.fromJson(json, map.getClass());

Retrieving properties from the Classpath rather than from resources/config.properties

I currently have the following method which allows me to pick properties that have been defined in my resources/config.properties file
private final Properties properties = new Properties();
{
final ClassLoader loader = getClass().getClassLoader();
try(InputStream config = loader.getResourceAsStream("Resources/config.properties")){
properties.load(config);
} catch(IOException e){
throw new IOError(e);
}
}
But I now want to pick my properties from the classpath so I have moved my config.properties from resources and placed it directly under src. But I'm struggling to know what changes I now need to make to my method to enable me to read from classpath.
Check example here
import java.io.IOError;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ReaderProp {
public final Properties properties = new Properties();
public ReaderProp()
{
final ClassLoader loader = getClass().getClassLoader();
try(InputStream config = loader.getResourceAsStream("error.properties")){
properties.load(config);
} catch(IOException e){
throw new IOError(e);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ReaderProp readerProp = new ReaderProp();
System.out.println(readerProp.properties.get("E1000_SE_ERROR-CODE"));// output E1000
}
}
Check error.properties
======================
E1000_SE_ERROR-CODE = E1000
//Find another answer
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ReaderProp {
private final Properties configProp = new Properties();
/**
* read property file
*
* #param propertyName
* #param path
*
* #throws IOException
*/
public ReaderProp(String propertyName, String path) {
try {
InputStream in;
File file;
if (path.equals("")) {
in = this.getClass().getClassLoader().getResourceAsStream(propertyName);
}
else {
file = new File(path + propertyName);
in = new FileInputStream(file);
}
configProp.load(in);
}
catch (IOException e) {
}
}
public static void main(String[] args) {
ReaderProp readerProp = new ReaderProp("error.properties",new File("").getAbsolutePath()+"\\src\\");
System.out.println(readerProp.configProp.get("E1000_SE_ERROR-CODE"));// output E1000
}
}

How to read properties file from meta-inf folder from a POJO

How to read properties file from meta-inf folder in a web application from plain java class.
The simplest you can do is :-
InputStream propertiesIs = this.getClass().getClassLoader().getResourceAsStream("META-INF/your.properties");
Properties prop = new Properties();
prop.load(propertiesIs);
System.out.println(prop.getProperty(YourPropertyHere));
OR
you can try loading your properties using FileInputStream also :-
input = new FileInputStream("META-INF/your.properties");
When reading resources, one should take care of closing them properly.
InputStream streamOrNull = getClass().getClassLoader().getResourceAsStream(
"META-INF/your.properties");
if (streamOrNull == null) {
// handle no such file
}
else {
try (InputStream stream = streamOrNull) { // close stream eventually
Properties properties = new Properties();
properties.load(stream);
// access properties
}
}
package net.bounceme.doge.json;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PropertiesReader {
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(PropertiesReader.class.getName());
public Properties tryGetProps(String propertiesFileName) {
log.fine(propertiesFileName);
Properties properties = new Properties();
try {
properties = getProps(propertiesFileName);
} catch (IOException ex) {
Logger.getLogger(PropertiesReader.class.getName()).log(Level.SEVERE, null, ex);
}
log.info(properties.toString());
return properties;
}
private Properties getProps(String propertiesFileName) throws IOException {
log.fine(propertiesFileName);
Properties properties = new Properties();
properties.load(PropertiesReader.class.getResourceAsStream("/META-INF/" + propertiesFileName + ".properties"));
log.fine(properties.toString());
return properties;
}
}
this works for me.

properties file is returning null

i am trying to read values from properties file and
when i tried to run this program
its giving the output as
null
import java.io.FileInputStream;
import java.util.Properties;
public class JavaApplication1 {
final private static String osName = System.getProperty("os.name");
static final Properties configFile = new Properties() {
{
try {
configFile.load(new FileInputStream("config.properties"));
} catch (Exception e) {
}
}
};
private static String DIR = osName.equals("Linux") ? configFile.getProperty("tempDirForLinux") : configFile.getProperty("tempDirForWindows");
public static void main(String[] args) {
System.out.println(DIR);
}
}
The part that is a bit odd in your example is where you create an anonymous Properties class and then load the properties into that same class in an initialization statement. I'm not sure how that is meant to work (and I'm guessing doesn't)
This is probably what you want rather
public class JavaApplication1 {
final private static String osName = System.getProperty("os.name");
static final Properties configFile = new Properties();
static {
try {
configFile.load(new FileInputStream("config.properties"));
} catch (Exception e) {
e.printStackTrace();
}
};
private static String DIR = osName.equals("Linux") ? configFile.getProperty("tempDirForLinux") : configFile.getProperty("tempDirForWindows");
public static void main(String[] args) throws IOException {
System.out.println(DIR);
}
}

Categories

Resources