com.crabshue.commons.properties.PropertiesUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of commons-properties Show documentation
Show all versions of commons-properties Show documentation
Library for properties files operations.
package com.crabshue.commons.properties;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import com.crabshue.commons.exceptions.SystemException;
import com.crabshue.commons.properties.exceptions.PropertiesErrorContext;
import com.crabshue.commons.properties.exceptions.PropertiesErrorType;
/**
* @author vinh
*/
public class PropertiesUtils {
protected PropertiesUtils() {
}
/**
* Read a properties file.
*
* @param propertiesFile the file.
* @return the properties.
*/
public static Properties readPropertiesFile(final File propertiesFile) {
Validate.notNull(propertiesFile);
return readPropertiesFile(propertiesFile.toURI());
}
/**
* Read a properties file.
*
* @param propertiesFilePath the file.
* @return the properties.
*/
public static Properties readPropertiesFile(final Path propertiesFilePath) {
Validate.notNull(propertiesFilePath);
return readPropertiesFile(propertiesFilePath.toUri());
}
/**
* Read a properties file.
*
* @param propertiesFileUri the file.
* @return the properties.
*/
public static Properties readPropertiesFile(final URI propertiesFileUri) {
Validate.notNull(propertiesFileUri);
final Properties ret = new Properties();
try (InputStream is = propertiesFileUri.toURL().openStream()) {
ret.load(is);
} catch (IOException e) {
throw new SystemException(PropertiesErrorType.CANNOT_READ_PROPERTIES, "Cannot read properties file.")
.addContextValue(PropertiesErrorContext.PROPERTIES, propertiesFileUri);
}
return ret;
}
/**
* Filter the properties whose key matches prefix.
*
* @param properties the properties.
* @param prefix the prefix to filter with.
* @return the matching properties.
*/
public static Map collectPropertiesForPrefix(final Properties properties, final String prefix) {
Validate.notNull(properties);
Validate.notNull(prefix);
final Map ret = new HashMap<>();
for (final Map.Entry