org.simpleflatmapper.map.context.impl.BreakDetector Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of sfm-map Show documentation
Show all versions of sfm-map Show documentation
Java library to map flat record - ResultSet, csv - to java object with minimum configuration and low footprint.
package org.simpleflatmapper.map.context.impl;
import org.simpleflatmapper.map.MappingException;
import org.simpleflatmapper.map.context.Key;
import org.simpleflatmapper.map.context.KeyDefinition;
public class BreakDetector {
private final KeyDefinition definition;
private final KeyObjectStore cache;
private Key currentKey;
public BreakDetector(KeyDefinition definition) {
this.definition = emptyToNull(definition);
if (this.definition == null) {
cache = null;
} else {
cache = new KeyObjectStore();
}
}
private static KeyDefinition emptyToNull(KeyDefinition definition) {
if (definition == null || definition.isEmpty()) {
return null;
}
return definition;
}
public boolean broke(S source) throws MappingException {
if (definition == null) {
return true;
}
Key oldKey = currentKey;
currentKey = definition.getValues(source);
return oldKey == null || !oldKey.equals(currentKey);
}
public Key getKey(S source) {
return definition.getValues(source);
}
public Key getCurrentKey() {
return currentKey;
}
public void handleSource(S source) throws MappingException {
if (definition == null) {
return;
}
currentKey = definition.getValues(source);
}
public void setValue(Object value) {
if (definition != null) {
setValue(value, this.currentKey);
}
}
public void setValue(Object value, Key key) {
if (key == null)
throw new IllegalStateException("Invalid state currentKey is null");
if (key != KeyDefinition.NOT_EQUALS) {
cache.put(key, value);
}
}
public Object getValue() {
if (definition != null) {
return getValue(currentKey);
}
return null;
}
public Object getValue(Key key) {
if (key == null)
throw new IllegalStateException("Invalid state currentKey is null");
if (key == KeyDefinition.NOT_EQUALS) return null;
return cache.get(key);
}
public void markRootAsBroken() {
if (definition != null) {
currentKey = null;
cache.clear();
}
}
public boolean hasKeyDefinition() {
return definition != null;
}
}