Created
July 12, 2016 13:33
-
-
Save bademux/8af228eed3a6370e49148f7040bb5ecb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class InitDynamoDBConfig{ | |
{ | |
ConversionSchema schema = v2CompatibleBuilder("v2CompatibleWithUuidAsByteBuffer") | |
.addFirstType(UUID.class, UUIDToByteBuffer.Marshaller.instance(), UUIDToByteBuffer.Unmarshaller.instance()) | |
.build() | |
DynamoDBMapperConfig config = new DynamoDBMapperConfig.Builder() | |
.withConversionSchema(schema) | |
.withTableNameResolver(tableNameResolver) | |
.build(); | |
DynamoDBMapper mapper = new DynamoDBMapper(amazonDynamoDB, config) | |
} | |
} | |
public final class UUIDToByteBuffer { | |
private static final int UUID_BYTE_SIZE = 16; | |
public static class Marshaller implements ArgumentMarshaller.BinaryAttributeMarshaller { | |
private static final Marshaller INSTANCE = new Marshaller(); | |
public static Marshaller instance() { | |
return INSTANCE; | |
} | |
private Marshaller() { | |
} | |
@Override | |
public AttributeValue marshall(Object obj) { | |
ByteBuffer uuid = toByteBuffer((UUID) obj); | |
return new AttributeValue().withB(uuid); | |
} | |
} | |
public static class Unmarshaller implements ArgumentUnmarshaller { | |
private static final Unmarshaller INSTANCE = new Unmarshaller(); | |
public static Unmarshaller instance() { | |
return INSTANCE; | |
} | |
@Override | |
public void typeCheck(AttributeValue value, Method setter) { | |
if (value.getB() == null) { | |
throw new DynamoDBMappingException("Expected B in value " + value + " when invoking " + setter); | |
} | |
} | |
@Override | |
public Object unmarshall(AttributeValue value) { | |
return toUuid(value.getB()); | |
} | |
} | |
static UUID toUuid(ByteBuffer buffer) { | |
try { | |
return new UUID(buffer.getLong(), buffer.getLong()); | |
} catch (BufferUnderflowException ex) { | |
throw new IllegalArgumentException("Buffer needs to have at least 16 bytes"); | |
} finally { | |
buffer.position(buffer.position() - UUID_BYTE_SIZE); | |
} | |
} | |
static ByteBuffer toByteBuffer(UUID uuid) { | |
return (ByteBuffer) ByteBuffer.allocate(UUID_BYTE_SIZE) | |
.putLong(uuid.getMostSignificantBits()) | |
.putLong(uuid.getLeastSignificantBits()) | |
.position(0); | |
} | |
private UUIDToByteBuffer() { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment