use of org.zalando.nakadi.util.JsonPathAccess in project nakadi by zalando.
the class HashPartitionStrategy method calculatePartition.
@Override
public String calculatePartition(final EventType eventType, final JSONObject event, final List<String> partitions) throws InvalidPartitionKeyFieldsException {
final List<String> partitionKeyFields = eventType.getPartitionKeyFields();
if (partitionKeyFields.isEmpty()) {
throw new RuntimeException("Applying " + this.getClass().getSimpleName() + " although event type " + "has no partition key fields configured.");
}
try {
final JsonPathAccess traversableJsonEvent = new JsonPathAccess(event);
final int hashValue = partitionKeyFields.stream().map(pkf -> EventCategory.DATA.equals(eventType.getCategory()) ? DATA_PATH_PREFIX + pkf : pkf).map(Try.wrap(okf -> {
final String fieldValue = traversableJsonEvent.get(okf).toString();
return stringHash.hashCode(fieldValue);
})).map(Try::getOrThrow).mapToInt(hc -> hc).sum();
int partitionIndex = abs(hashValue) % partitions.size();
partitionIndex = hashPartitioningCrutch.adjustPartitionIndex(partitionIndex, partitions.size());
final List<String> sortedPartitions = partitions.stream().sorted().collect(Collectors.toList());
return sortedPartitions.get(partitionIndex);
} catch (NakadiRuntimeException e) {
final Exception original = e.getException();
if (original instanceof InvalidPartitionKeyFieldsException) {
throw (InvalidPartitionKeyFieldsException) original;
} else {
throw e;
}
}
}
Aggregations