这是indexloc提供的服务,不要输入任何密码
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions core-java-modules/core-java-properties/pom.xml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-properties</artifactId>
<version>0.1.0-SNAPSHOT</version>
Expand All @@ -14,4 +14,21 @@
<version>0.0.1-SNAPSHOT</version>
</parent>

</project>
<properties>
<apache.commons.version>2.11.0</apache.commons.version>
<commons.beanutils.version>1.10.1</commons.beanutils.version>
</properties>

<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-configuration2</artifactId>
<version>${apache.commons.version}</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>${commons.beanutils.version}</version>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package com.baeldung.core.java.properties;

import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.FileBasedConfiguration;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.ex.ConfigurationException;

public class ApacheCommonsPropertyMutator implements PropertyMutator {

private final String propertyFileName;

public ApacheCommonsPropertyMutator(String propertyFileName) {
this.propertyFileName = propertyFileName;
}

@Override
public String getProperty(String key) throws ConfigurationException {
FileBasedConfigurationBuilder<FileBasedConfiguration> builder = getAppPropertiesConfigBuilder();
Configuration properties = builder.getConfiguration();

return (String) properties.getProperty(key);
}

@Override
public void addOrUpdateProperty(String key, String value) throws ConfigurationException {
FileBasedConfigurationBuilder<FileBasedConfiguration> builder = getAppPropertiesConfigBuilder();
Configuration configuration = builder.getConfiguration();

configuration.setProperty(key, value);
builder.save();
}

private FileBasedConfigurationBuilder<FileBasedConfiguration> getAppPropertiesConfigBuilder() {
Parameters params = new Parameters();

return new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class).configure(params.properties()
.setFileName(propertyFileName));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package com.baeldung.core.java.properties;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

public class FileAPIPropertyMutator {

private final String propertyFileName;
private final PropertyLoader propertyLoader;

public FileAPIPropertyMutator(String propertyFileName, PropertyLoader propertyLoader) {
this.propertyFileName = propertyFileName;
this.propertyLoader = propertyLoader;
}

public String getPropertyKeyWithValue(int lineNumber) throws IOException {
List<String> fileLines = getFileLines();
// depending on the system, sometimes the first line will be a comment with a timestamp of the file read
// the next line will make this method compatible with all systems
if (fileLines.get(0).startsWith("#")) {
lineNumber++;
}

return fileLines.get(lineNumber);
}

public String getLastPropertyKeyWithValue() throws IOException {
List<String> fileLines = getFileLines();

return fileLines.get(fileLines.size() - 1);
}

public void addPropertyKeyWithValue(String keyAndValue) throws IOException {
File propertiesFile = new File(propertyLoader.getFilePathFromResources(propertyFileName));
List<String> fileContent = getFileLines(propertiesFile);

fileContent.add(keyAndValue);
Files.write(propertiesFile.toPath(), fileContent, StandardCharsets.UTF_8);
}

public int updateProperty(String oldKeyValuePair, String newKeyValuePair) throws IOException {
File propertiesFile = new File(propertyLoader.getFilePathFromResources(propertyFileName));
List<String> fileContent = getFileLines(propertiesFile);
int updatedIndex = -1;

for (int i = 0; i < fileContent.size(); i++) {
if (fileContent.get(i)
.replaceAll("\\s+", "")
.equals(oldKeyValuePair)) {
fileContent.set(i, newKeyValuePair);
updatedIndex = i;
break;
}
}
Files.write(propertiesFile.toPath(), fileContent, StandardCharsets.UTF_8);

// depending on the system, sometimes the first line will be a comment with a timestamp of the file read
// the next line will make this method compatible with all systems
if (fileContent.get(0).startsWith("#")) {
updatedIndex--;
}

return updatedIndex;
}

private List<String> getFileLines() throws IOException {
File propertiesFile = new File(propertyLoader.getFilePathFromResources(propertyFileName));
return getFileLines(propertiesFile);
}

private List<String> getFileLines(File propertiesFile) throws IOException {
return new ArrayList<>(Files.readAllLines(propertiesFile.toPath(), StandardCharsets.UTF_8));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.baeldung.core.java.properties;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class FileStreamsPropertyMutator implements PropertyMutator {

private final String propertyFileName;
private final PropertyLoader propertyLoader;

public FileStreamsPropertyMutator(String propertyFileName, PropertyLoader propertyLoader) {
this.propertyFileName = propertyFileName;
this.propertyLoader = propertyLoader;
}

@Override
public String getProperty(String key) throws IOException {
Properties properties = propertyLoader.fromFile(propertyFileName);

return properties.getProperty(key);
}

@Override
public void addOrUpdateProperty(String key, String value) throws IOException {
Properties properties = propertyLoader.fromFile(propertyFileName);
properties.setProperty(key, value);

FileOutputStream out = new FileOutputStream(propertyLoader.getFilePathFromResources(propertyFileName));
properties.store(out, null);
out.close();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.baeldung.core.java.properties;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Objects;
import java.util.Properties;

public class PropertyLoader {

public Properties fromFile(String filename) throws IOException {
String appPropertiesFileName = getFilePathFromResources(filename);
FileInputStream in = new FileInputStream(appPropertiesFileName);
Properties properties = new Properties();

properties.load(in);
in.close();

return properties;
}

public String getFilePathFromResources(String filename) {
URL resourceUrl = getClass().getClassLoader()
.getResource(filename);
Objects.requireNonNull(resourceUrl, "Property file with name [" + filename + "] was not found.");

return resourceUrl.getFile();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.baeldung.core.java.properties;

import java.io.IOException;

import org.apache.commons.configuration2.ex.ConfigurationException;

public interface PropertyMutator {

String getProperty(String key) throws IOException, ConfigurationException;

void addOrUpdateProperty(String key, String value) throws IOException, ConfigurationException;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.baeldung.core.java.properties;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.Properties;

public class XMLFilePropertyMutator implements PropertyMutator {

private final String propertyFileName;

public XMLFilePropertyMutator(String propertyFileName) {
this.propertyFileName = propertyFileName;
}

@Override
public String getProperty(String key) throws IOException {
Properties properties = loadProperties();

return properties.getProperty(key);
}

@Override
public void addOrUpdateProperty(String key, String value) throws IOException {
String filePath = getXMLAppPropertiesWithFileStreamFilePath();
Properties properties = loadProperties(filePath);

try (OutputStream os = Files.newOutputStream(Paths.get(filePath))) {
properties.setProperty(key, value);
properties.storeToXML(os, null);
}
}

private Properties loadProperties() throws IOException {
return loadProperties(getXMLAppPropertiesWithFileStreamFilePath());
}

private Properties loadProperties(String filepath) throws IOException {
Properties props = new Properties();
try (InputStream is = Files.newInputStream(Paths.get(filepath))) {
props.loadFromXML(is);
}

return props;
}

String getXMLAppPropertiesWithFileStreamFilePath() {
URL resourceUrl = getClass().getClassLoader()
.getResource(propertyFileName);
Objects.requireNonNull(resourceUrl, "Property file with name [" + propertyFileName + "] was not found.");

return resourceUrl.getFile();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package com.baeldung.core.java.properties;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import org.apache.commons.configuration2.ex.ConfigurationException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class ApacheCommonsPropertyMutatorUnitTest {

private static final String PROPERTY_FILE_NAME = "app.properties";
private final PropertyLoader propertyLoader = new PropertyLoader();
private Properties initialProperties;

private final ApacheCommonsPropertyMutator propertyMutator = new ApacheCommonsPropertyMutator(PROPERTY_FILE_NAME);

@BeforeEach
public void loadInitialPropertiesFromFile() throws IOException {
initialProperties = propertyLoader.fromFile(PROPERTY_FILE_NAME);
}

@AfterEach
public void restoreInitialPropertiesToFile() throws IOException {
FileOutputStream out = new FileOutputStream(propertyLoader.getFilePathFromResources(PROPERTY_FILE_NAME));
initialProperties.store(out, null);
out.close();
}

@Test
public void givenApacheCommons_whenAddNonExistingProperty_thenNewPropertyWithoutAffectingOtherProperties() throws ConfigurationException {
assertNull(propertyMutator.getProperty("new.property"));
assertEquals("TestApp", propertyMutator.getProperty("name"));

propertyMutator.addOrUpdateProperty("new.property", "new-value");

assertEquals("new-value", propertyMutator.getProperty("new.property"));
assertEquals("TestApp", propertyMutator.getProperty("name"));
}

@Test
public void givenApacheCommons_whenUpdateExistingProperty_thenUpdatedPropertyWithoutAffectingOtherProperties() throws ConfigurationException {
assertEquals("1.0", propertyMutator.getProperty("version"));
assertEquals("TestApp", propertyMutator.getProperty("name"));

propertyMutator.addOrUpdateProperty("version", "2.0");

assertEquals("2.0", propertyMutator.getProperty("version"));
assertEquals("TestApp", propertyMutator.getProperty("name"));
}
}
Loading