package lombok.core.configuration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import lombok.core.configuration.ConfigurationParser.Collector;
public class StringConfigurationSource implements ConfigurationSource {
private final Map<ConfigurationKey<?>, Result> values;
public static ConfigurationSource forString(CharSequence content, ConfigurationProblemReporter reporter, String contentDescription) {
final Map<ConfigurationKey<?>, Result> values = new HashMap<ConfigurationKey<?>, Result>();
new ConfigurationParser(reporter).parse(content, contentDescription, new Collector() {
@Override public void clear(ConfigurationKey<?> key, String contentDescription, int lineNumber) {
values.put(key, new Result(null, true));
}
@Override public void set(ConfigurationKey<?> key, Object value, String contentDescription, int lineNumber) {
values.put(key, new Result(value, true));
}
@Override public void add(ConfigurationKey<?> key, Object value, String contentDescription, int lineNumber) {
modifyList(key, value, true);
}
@Override public void remove(ConfigurationKey<?> key, Object value, String contentDescription, int lineNumber) {
modifyList(key, value, false);
}
@SuppressWarnings("unchecked")
private void modifyList(ConfigurationKey<?> key, Object value, boolean add) {
Result result = values.get(key);
List<ListModification> list;
if (result == null || result.getValue() == null) {
list = new ArrayList<ConfigurationSource.ListModification>();
values.put(key, new Result(list, result != null));
} else {
list = (List<ListModification>) result.getValue();
}
list.add(new ListModification(value, add));
}
});
return new StringConfigurationSource(values);
}
private StringConfigurationSource(Map<ConfigurationKey<?>, Result> values) {
this.values = new HashMap<ConfigurationKey<?>, Result>();
for (Entry<ConfigurationKey<?>, Result> entry : values.entrySet()) {
Result result = entry.getValue();
if (result.getValue() instanceof List<?>) {
this.values.put(entry.getKey(), new Result(Collections.unmodifiableList((List<?>) result.getValue()), result.isAuthoritative()));
} else {
this.values.put(entry.getKey(), result);
}
}
}
@Override
public Result resolve(ConfigurationKey<?> key) {
return values.get(key);
}
}