IndexLengthRestrictionEnforcer { public Optional<JsonValue> enforce(final JsonPointer pointer, final JsonValue value) { final int keyOverhead = jsonPointerBytes(pointer) + thingIdNamespaceOverhead; if (keyOverhead > MAX_INDEX_CONTENT_LENGTH - DEFAULT_VALUE_LENGTH) { return Optional.empty(); } else if (value.isString()) { return Optional.of(fixViolation(value, keyOverhead)); } else if (isNonEmptyComposite(value)) { throw new IllegalArgumentException("value should not be an array or object but it is"); } else { return Optional.of(value); } } private  IndexLengthRestrictionEnforcer(final String thingId); static IndexLengthRestrictionEnforcer newInstance(final String thingId); Optional<JsonValue> enforce(final JsonPointer pointer, final JsonValue value);  }
@Test public void enforceRestrictionsOnViolation() { final String key = "/attributes/enforceRestrictionsOnViolation"; final int maxAllowedValueForKey = MAX_INDEX_CONTENT_LENGTH - OVERHEAD - key.length(); final String value = TestStringGenerator.createStringOfBytes(maxAllowedValueForKey + 1); final String enforcedValue = indexLengthRestrictionEnforcer.enforce(JsonPointer.of(key), JsonValue.of(value)) .orElseThrow() .asString(); final int enforcedValueBytes = enforcedValue.getBytes(StandardCharsets.UTF_8).length; assertThat(value).startsWith(enforcedValue); assertThat(enforcedValueBytes).isLessThanOrEqualTo(maxAllowedValueForKey); final int maxUtf8Bytes = 4; assertThat(enforcedValueBytes).isCloseTo(maxAllowedValueForKey, Offset.offset(maxUtf8Bytes)); }
@Test public void doNotTruncateWithoutViolation() { final String key = "/attributes/doesNotTruncateWithoutViolation"; final int maxAllowedValueForKey = MAX_INDEX_CONTENT_LENGTH - OVERHEAD - key.length(); final String value = TestStringGenerator.createStringOfBytes(maxAllowedValueForKey); assertThat(indexLengthRestrictionEnforcer.enforce(JsonPointer.of(key), JsonValue.of(value))) .contains(JsonValue.of(value)); }
@Test public void giveUpIfKeyIsTooLong() { final String value = "value"; final String baseKey = "/attributes/giveUpIfKeyIsTooLong/"; final int maxAllowed = MAX_INDEX_CONTENT_LENGTH - OVERHEAD - baseKey.length(); final String key = baseKey + TestStringGenerator.createStringOfBytes(maxAllowed + 1); assertThat(indexLengthRestrictionEnforcer.enforce(JsonPointer.of(key), JsonValue.of(value))) .isEmpty(); }