Skip to content

Instantly share code, notes, and snippets.

@josefbetancourt
Last active October 12, 2016 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save josefbetancourt/22c1060d261118ffa5c8 to your computer and use it in GitHub Desktop.
Save josefbetancourt/22c1060d261118ffa5c8 to your computer and use it in GitHub Desktop.
package com.octodecillion.util;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
/**
* Detect duplicate properties when loading Properties from stream.
* <p>
*
* @author jbetancourt
* @since
*/
@RunWith(Enclosed.class)
public class DuplicatePropDetectWithCommonsConfig {
/**
* Detect duplicate keys in Properties resource.
* <p>
* <a href="">Commons Config</a> is used.
* {@link Properties} class.
*
* @see Properties#load(Reader)
*
* @param reader The reader is NOT closed.
* @param delimiterParsingDisabled
* @return Map of keys that are duplicated with a list value of each value of duplicate.
* @throws ConfigurationException
*/
@SuppressWarnings("unchecked")
public Map<String, List<String>> loadWithConfig(Reader reader, boolean delimiterParsingDisabled) throws ConfigurationException {
PropertiesConfiguration config = new PropertiesConfiguration();
final Map<String, List<String>> results = new HashMap<>();
config.setDelimiterParsingDisabled(delimiterParsingDisabled);
config.load(reader);
Iterator<String> keys = config.getKeys();
while (keys.hasNext()) {
String theKey = keys.next();
List<?> valueObject = config.getList(theKey);
if(valueObject.size() > 1){
results.put(theKey, (List<String>) valueObject);
}
}
return results;
}
/**
* @author jbetancourt
*
*/
public static class DuplicatePropDetectWithCommonsConfigTest {
private static final String DATA1_PROPERTIES = "/Data1.properties";
/**
* @throws ConfigurationException
*/
@Test
public void testLoadFileWithConfig() throws ConfigurationException {
System.out.println("*********************** running test ");
InputStream is = this.getClass().getResourceAsStream(DATA1_PROPERTIES);
Assert.assertNotNull(is);
DuplicatePropDetectWithCommonsConfig detector = new DuplicatePropDetectWithCommonsConfig();
Map<String, List<String>> map = detector.loadWithConfig(new InputStreamReader(is), true);
Assert.assertEquals(1, map.size());
Assert.assertTrue(map.containsKey("three"));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment