refactor: Changes to make Abstract-Document and Adapter better. (#2872)

* Added new test case for error handling

* Added new test cases for error handling

* Refactored Abstract Document

* Changes updated
This commit is contained in:
drishtii7
2024-03-31 04:47:04 -03:00
committed by GitHub
parent d3e7401f70
commit 44a9766656
2 changed files with 81 additions and 13 deletions
@@ -36,41 +36,67 @@ import java.util.stream.Stream;
*/
public abstract class AbstractDocument implements Document {
private final Map<String, Object> properties;
private final Map<String, Object> documentProperties;
protected AbstractDocument(Map<String, Object> properties) {
Objects.requireNonNull(properties, "properties map is required");
this.properties = properties;
this.documentProperties = properties;
}
@Override
public Void put(String key, Object value) {
properties.put(key, value);
documentProperties.put(key, value);
return null;
}
@Override
public Object get(String key) {
return properties.get(key);
return documentProperties.get(key);
}
@Override
public <T> Stream<T> children(String key, Function<Map<String, Object>, T> constructor) {
public <T> Stream<T> children(String key, Function<Map<String, Object>, T> childConstructor) {
return Stream.ofNullable(get(key))
.filter(Objects::nonNull)
.map(el -> (List<Map<String, Object>>) el)
.findAny()
.stream()
.flatMap(Collection::stream)
.map(constructor);
.filter(Objects::nonNull)
.map(el -> (List<Map<String, Object>>) el)
.findAny()
.stream()
.flatMap(Collection::stream)
.map(childConstructor);
}
@Override
public String toString() {
return buildStringRepresentation();
}
private String buildStringRepresentation() {
var builder = new StringBuilder();
builder.append(getClass().getName()).append("[");
properties.forEach((key, value) -> builder.append("[").append(key).append(" : ").append(value)
.append("]"));
// Explaining variable for document properties map
Map<String, Object> documentProperties = this.documentProperties;
// Explaining variable for the size of document properties map
int numProperties = documentProperties.size();
// Explaining variable for tracking the current property index
int currentPropertyIndex = 0;
// Iterate over document properties map
for (Map.Entry<String, Object> entry : documentProperties.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// Append key-value pair
builder.append("[").append(key).append(" : ").append(value).append("]");
// Add comma if not last property
if (++currentPropertyIndex < numProperties) {
builder.append(", ");
}
}
builder.append("]");
return builder.toString();
}