index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/aws-lambda-builders/tests/integration/workflows/java_maven/testdata/single-build/java11/no-deps/src/main/java/aws
Create_ds/aws-lambda-builders/tests/integration/workflows/java_maven/testdata/single-build/java11/no-deps/src/main/java/aws/lambdabuilders/Main.java
package aws.lambdabuilders; public class Main { public static void main(String[] args) { System.out.println("Hello AWS Lambda Builders!"); } }
4,200
0
Create_ds/personalize-kafka-connector/src/test/java/com/aws
Create_ds/personalize-kafka-connector/src/test/java/com/aws/converter/DataConverterTest.java
package com.aws.converter; import com.amazonaws.services.personalizeevents.model.Event; import com.amazonaws.services.personalizeevents.model.Item; import com.amazonaws.services.personalizeevents.model.User; import com.aws.util.Constants; import com.aws.util.TestConstants; import org.apache.kafka.connect.sink.SinkRecord; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; public class DataConverterTest { @Test public void testEventDataConverter(){ SinkRecord sinkRecord = createRecord(TestConstants.sampleValsForEventData); Map<String, String> additionalValues = new HashMap<>(); Event eventInfo = DataConverter.convertSinkRecordToEventInfo(sinkRecord, additionalValues); Assertions.assertTrue(eventInfo.getEventType().equals(TestConstants.TEST_EVENT_TYPE_VALUE)); Assertions.assertTrue(additionalValues.get(Constants.FIELD_SESSION_ID).equals(TestConstants.TEST_SESSION_ID_VALUE)); Assertions.assertTrue(additionalValues.get(Constants.FIELD_USER_ID).equals(TestConstants.TEST_USER_ID_VALUE)); Assertions.assertTrue(eventInfo.getItemId().equals(TestConstants.TEST_ITEM_ID_VALUE)); Assertions.assertTrue(eventInfo.getSentAt().getTime() == TestConstants.TEST_EVENT_TIME_VALUE); } @Test public void testItemDataConverter(){ SinkRecord sinkRecord = createRecord(TestConstants.sampleValsForItemData); Item item = DataConverter.convertSinkRecordToItemInfo(sinkRecord); Assertions.assertTrue(item.getItemId().equals(TestConstants.TEST_ITEM_ID_VALUE)); Assertions.assertTrue(item.getProperties().equals(TestConstants.TEST_PROPERTIES_VALUE)); } @Test public void testUserDataConverter(){ SinkRecord sinkRecord = createRecord(TestConstants.sampleValsForUserData); User user = DataConverter.convertSinkRecordToUserInfo(sinkRecord); Assertions.assertTrue(user.getUserId().equals(TestConstants.TEST_USER_ID_VALUE)); Assertions.assertTrue(user.getProperties().equals(TestConstants.TEST_PROPERTIES_VALUE)); } private SinkRecord createRecord(Map<String, Object> valueMap) { return new SinkRecord("topic", 0, null, null, null, valueMap, 1); } }
4,201
0
Create_ds/personalize-kafka-connector/src/test/java/com/aws
Create_ds/personalize-kafka-connector/src/test/java/com/aws/util/TestConstants.java
package com.aws.util; import com.aws.transform.CombineFieldsToJSONTransformation; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class TestConstants { public static final Map<String, String> configVals; public static final Map<String, String> itemconfigVals; public static final Map<String, String> userconfigVals; public static final Map<String, String> invalidConfigVals; public static final Map<String, Object> validTransformationConfig; public static final Map<String, Object> inValidTransformationConfig; public static final Map<String, Object> sampleValsForEventData; public static final Map<String, Object> sampleValsForUserData; public static final Map<String, Object> sampleValsForItemData; public static final Map<String, Object> sampleValsForTransformation; public static final String TEST_USER_ID_VALUE= "test-user1"; public static final String TEST_ITEM_ID_VALUE = "test-item1"; public static final String TEST_SESSION_ID_VALUE = "test-session1"; public static final String TEST_EVENT_TYPE_VALUE = "test-event1"; public static final Long TEST_EVENT_TIME_VALUE = 123456789L; public static final String TEST_EVENT_TRACKING_ID ="test-tracking-id"; public static final String TEST_AWS_REGION ="test-region"; public static final String VALID_ITEM_DATASET_ARN = "arn:aws:personalize:<REGION>:<ACCOUNT_ID>:dataset/<DATASET_GROUP_NAME>/ITEMS"; public static final String VALID_USER_DATASET_ARN = "arn:aws:personalize:<REGION>:<ACCOUNT_ID>:dataset/<DATASET_GROUP_NAME>/USERS"; public static final String TEST_PROPERTIES_VALUE = "{}"; public static final String FIELD_1 ="field1"; public static final String FIELD_2 ="field2"; public static final String PROPERTIES_FIELD_WITH_FIELDS = "{\"field1\":\"field1\",\"field2\":\"field2\"}"; static { Map<String, String> configMap = new HashMap<String, String>(); configMap.put(Constants.AMAZON_PERSONALIZE_EVENT_TRACKING_ID,TEST_EVENT_TRACKING_ID); configMap.put(Constants.AWS_REGION_NAME,TEST_AWS_REGION); configMap.put(Constants.AMAZON_PERSONALIZE_DATA_TYPE,Constants.PUT_EVENTS_REQUEST_TYPE); configVals = Collections.unmodifiableMap(configMap); configMap = new HashMap<String, String>(); configMap.put(Constants.AMAZON_PERSONALIZE_DATASET_ARN, VALID_ITEM_DATASET_ARN); configMap.put(Constants.AWS_REGION_NAME,TEST_AWS_REGION); configMap.put(Constants.AMAZON_PERSONALIZE_DATA_TYPE,Constants.PUT_ITEMS_REQUEST_TYPE); itemconfigVals = Collections.unmodifiableMap(configMap); configMap = new HashMap<String, String>(); configMap.put(Constants.AMAZON_PERSONALIZE_DATASET_ARN, VALID_USER_DATASET_ARN); configMap.put(Constants.AWS_REGION_NAME,TEST_AWS_REGION); configMap.put(Constants.AMAZON_PERSONALIZE_DATA_TYPE,Constants.PUT_USERS_REQUEST_TYPE); userconfigVals = Collections.unmodifiableMap(configMap); Map transformConfig = new HashMap<String, Object>(); transformConfig.put(CombineFieldsToJSONTransformation.FIELDS_TO_INCLUDE, Arrays.asList("field1", "field2")); transformConfig.put(CombineFieldsToJSONTransformation.TARGET_FIELD_NAME, CombineFieldsToJSONTransformation.DEFAULT_FIELD_NAME); validTransformationConfig = Collections.unmodifiableMap(transformConfig); transformConfig = new HashMap<String, Object>(); transformConfig.put(Constants.AWS_SECRET_KEY, Arrays.asList("field1", "field2")); transformConfig.put(CombineFieldsToJSONTransformation.TARGET_FIELD_NAME, CombineFieldsToJSONTransformation.DEFAULT_FIELD_NAME); inValidTransformationConfig = Collections.unmodifiableMap(transformConfig); Map<String, Object> valuesMap = new HashMap<String, Object>(); valuesMap.put(Constants.FIELD_USER_ID, TEST_USER_ID_VALUE); valuesMap.put(Constants.FIELD_ITEM_ID, TEST_ITEM_ID_VALUE); valuesMap.put(Constants.FIELD_EVENT_TYPE,TEST_EVENT_TYPE_VALUE); valuesMap.put(Constants.FIELD_SESSION_ID,TEST_SESSION_ID_VALUE); valuesMap.put(Constants.FIELD_EVENT_TIME,TEST_EVENT_TIME_VALUE); sampleValsForEventData = Collections.unmodifiableMap(valuesMap); valuesMap = new HashMap<String, Object>(); valuesMap.put(Constants.FIELD_ITEM_ID,TEST_ITEM_ID_VALUE); valuesMap.put(Constants.FIELD_PROPERTIES,TEST_PROPERTIES_VALUE); sampleValsForItemData = Collections.unmodifiableMap(valuesMap); valuesMap = new HashMap<String, Object>(); valuesMap.put(Constants.FIELD_USER_ID,TEST_USER_ID_VALUE); valuesMap.put(Constants.FIELD_PROPERTIES,TEST_PROPERTIES_VALUE); sampleValsForUserData = Collections.unmodifiableMap(valuesMap); valuesMap = new HashMap<String, Object>(); valuesMap.put(Constants.FIELD_USER_ID,TEST_USER_ID_VALUE); valuesMap.put(FIELD_1,FIELD_1); valuesMap.put(FIELD_2,FIELD_2); sampleValsForTransformation = Collections.unmodifiableMap(valuesMap); Map<String, String> invalidConfigMap = new HashMap<String, String>(); invalidConfigMap.put("amazon.personalize.event.tracking.id.invalid","test-tracking-id"); invalidConfigMap.put("amazon.region.name","test-region"); invalidConfigMap.put("amazon.personalize.data.type","invalidAction"); invalidConfigVals = Collections.unmodifiableMap(invalidConfigMap); } public static final String INVALID_ARN_INVALID_SERVICE = "arn:aws:ec2:<REGION>:<ACCOUNT_ID>:dataset/<DATASET_GROUP_NAME>/ITEMS"; public static final String INVALID_ARN_INVALID_RESOURCE = "arn:aws:personalize:<REGION>:<ACCOUNT_ID>:test/<DATASET_GROUP_NAME>/ITEMS"; public static final String INVALID_ARN_INVALID_DATASET = "arn:aws:personalize:<REGION>:<ACCOUNT_ID>:dataset/<DATASET_GROUP_NAME>/INTERACTIONS"; public static final String VALID_USER_DATASET_TYPE = "users"; public static final String VALID_EVENT_DATASET_TYPE = "events"; public static final String VALID_ITEMS_DATASET_TYPE = "items"; public static final String INVALID_DATASET_TYPE = "invalid"; }
4,202
0
Create_ds/personalize-kafka-connector/src/test/java/com/aws
Create_ds/personalize-kafka-connector/src/test/java/com/aws/config/PersonalizeSinkConfigTest.java
package com.aws.config; import com.aws.util.Constants; import com.aws.util.TestConstants; import org.apache.commons.lang3.StringUtils; import org.apache.kafka.common.config.ConfigException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class PersonalizeSinkConfigTest { @Test public void testEventConfig(){ PersonalizeSinkConfig config = new PersonalizeSinkConfig(TestConstants.configVals); Assertions.assertTrue(StringUtils.isNotBlank(config.getName())); Assertions.assertTrue(config.getName().equals(Constants.DEFAULT_CONNECTOR_NAME)); Assertions.assertTrue(config.getDataType().equals(Constants.PUT_EVENTS_REQUEST_TYPE)); Assertions.assertTrue(config.getEventTrackingId().equals(TestConstants.TEST_EVENT_TRACKING_ID)); Assertions.assertTrue(config.getAwsRegionName().equals(TestConstants.TEST_AWS_REGION)); Assertions.assertFalse(config.getDataSetArn().equals(TestConstants.VALID_ITEM_DATASET_ARN)); } @Test public void testItemConfig(){ PersonalizeSinkConfig config = new PersonalizeSinkConfig(TestConstants.itemconfigVals); Assertions.assertTrue(config.getDataType().equals(Constants.PUT_ITEMS_REQUEST_TYPE)); Assertions.assertFalse(StringUtils.isNotBlank(config.getEventTrackingId())); Assertions.assertFalse(config.getEventTrackingId().equals(TestConstants.TEST_EVENT_TRACKING_ID)); Assertions.assertTrue(config.getAwsRegionName().equals(TestConstants.TEST_AWS_REGION)); Assertions.assertTrue(config.getDataSetArn().equals(TestConstants.VALID_ITEM_DATASET_ARN)); } @Test public void testUserConfig(){ PersonalizeSinkConfig config = new PersonalizeSinkConfig(TestConstants.userconfigVals); Assertions.assertTrue(config.getDataType().equals(Constants.PUT_USERS_REQUEST_TYPE)); Assertions.assertFalse(StringUtils.isNotBlank(config.getEventTrackingId())); Assertions.assertFalse(config.getEventTrackingId().equals(TestConstants.TEST_EVENT_TRACKING_ID)); Assertions.assertTrue(config.getAwsRegionName().equals(TestConstants.TEST_AWS_REGION)); Assertions.assertTrue(config.getDataSetArn().equals(TestConstants.VALID_USER_DATASET_ARN)); } @Test public void testInvalidConfig(){ Assertions.assertThrows(ConfigException.class,() -> new PersonalizeSinkConfig(TestConstants.invalidConfigVals)); } }
4,203
0
Create_ds/personalize-kafka-connector/src/test/java/com/aws/config
Create_ds/personalize-kafka-connector/src/test/java/com/aws/config/validators/PersonalizeDataTypeValidatorTest.java
package com.aws.config.validators; import com.aws.util.TestConstants; import org.apache.kafka.common.config.ConfigException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; public class PersonalizeDataTypeValidatorTest { private static final String DATA_TYPE_CONFIG_NAME = "amazon.personalize.data.type"; private static PersonalizeDataTypeValidator personalizeDataTypeValidator; @BeforeAll public static void setUp(){ personalizeDataTypeValidator= new PersonalizeDataTypeValidator(); } @Test public void testValidUsersDataType(){ // Testing by passing valid User DataSet Type value Assertions.assertDoesNotThrow(() -> personalizeDataTypeValidator.ensureValid(DATA_TYPE_CONFIG_NAME, TestConstants.VALID_USER_DATASET_TYPE)); } @Test public void testValidItemsDataType(){ // Testing by passing valid Items DataSet Type value Assertions.assertDoesNotThrow(() -> personalizeDataTypeValidator.ensureValid(DATA_TYPE_CONFIG_NAME, TestConstants.VALID_ITEMS_DATASET_TYPE)); } @Test public void testValidEventsDataType(){ // Testing by passing valid Event DataSet Type value Assertions.assertDoesNotThrow(() -> personalizeDataTypeValidator.ensureValid(DATA_TYPE_CONFIG_NAME, TestConstants.VALID_EVENT_DATASET_TYPE)); } @Test public void testInvalidDataType(){ // Testing by passing Invalid DataSet Type value which is not supported Assertions.assertThrows(ConfigException.class,() -> personalizeDataTypeValidator.ensureValid(DATA_TYPE_CONFIG_NAME, TestConstants.INVALID_DATASET_TYPE)); } }
4,204
0
Create_ds/personalize-kafka-connector/src/test/java/com/aws/config
Create_ds/personalize-kafka-connector/src/test/java/com/aws/config/validators/ArnValidatorTest.java
package com.aws.config.validators; import com.aws.util.TestConstants; import org.apache.kafka.common.config.ConfigException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; public class ArnValidatorTest { private static final String ARN_CONFIG_NAME = "amazon.personalize.dataset.arn"; private static ArnValidator arnValidator; @BeforeAll public static void setUp(){ arnValidator= new ArnValidator(); } @Test public void testValidItemsDataSetArn(){ //Testing with passing valid Item DataSet ARN Assertions.assertDoesNotThrow(() -> arnValidator.ensureValid(ARN_CONFIG_NAME, TestConstants.VALID_ITEM_DATASET_ARN)); } @Test public void testValidUsersDataSetArn(){ //Testing with passing valid User DataSet ARN Assertions.assertDoesNotThrow(() -> arnValidator.ensureValid(ARN_CONFIG_NAME, TestConstants.VALID_USER_DATASET_ARN)); } @Test public void testInValidArnWithService(){ //Testing with passing invalid service name Assertions.assertThrows(ConfigException.class ,() ->arnValidator.ensureValid(ARN_CONFIG_NAME, TestConstants.INVALID_ARN_INVALID_SERVICE)); } @Test public void testInValidArnWithResource(){ //Testing with passing invalid resource name Assertions.assertThrows(ConfigException.class ,() ->arnValidator.ensureValid(ARN_CONFIG_NAME, TestConstants.INVALID_ARN_INVALID_RESOURCE)); } @Test public void testInValidArnWithDataSetType(){ //Testing with passing invalid dataset name Assertions.assertThrows(ConfigException.class ,() ->arnValidator.ensureValid(ARN_CONFIG_NAME, TestConstants.INVALID_ARN_INVALID_DATASET)); } }
4,205
0
Create_ds/personalize-kafka-connector/src/test/java/com/aws/config
Create_ds/personalize-kafka-connector/src/test/java/com/aws/config/validators/PersonalizeCredentialsProviderValidatorTest.java
package com.aws.config.validators; import com.aws.auth.AssumeRoleCredentialsProvider; import com.aws.util.TestConstants; import org.apache.kafka.common.config.ConfigException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; public class PersonalizeCredentialsProviderValidatorTest { private static final String CREDENTIALS_PROVIDER_CONFIG_NAME = "amazon.personalize.credentials.provider.class"; private static PersonalizeCredentialsProviderValidator personalizeCredentialsProviderValidator; @BeforeAll public static void setUp() { personalizeCredentialsProviderValidator = new PersonalizeCredentialsProviderValidator(); } @Test public void testValidClass() { //Testing with valid class with implements AWSCredentialsProvider Assertions.assertDoesNotThrow(() -> personalizeCredentialsProviderValidator.ensureValid(CREDENTIALS_PROVIDER_CONFIG_NAME, AssumeRoleCredentialsProvider.class)); } @Test public void testInValidClass() { //Testing with invalid class by passing String constant instead of class which implements AWSCredentialsProvider Assertions.assertThrows(ConfigException.class, () -> personalizeCredentialsProviderValidator.ensureValid(CREDENTIALS_PROVIDER_CONFIG_NAME, TestConstants.INVALID_DATASET_TYPE)); } }
4,206
0
Create_ds/personalize-kafka-connector/src/test/java/com/aws
Create_ds/personalize-kafka-connector/src/test/java/com/aws/writer/DataWriterTest.java
package com.aws.writer; import com.amazonaws.services.personalizeevents.AmazonPersonalizeEvents; import com.amazonaws.services.personalizeevents.model.*; import com.aws.config.PersonalizeSinkConfig; import com.aws.util.TestConstants; import org.apache.kafka.connect.sink.SinkRecord; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.verify; @ExtendWith(MockitoExtension.class) public class DataWriterTest { @Mock AmazonPersonalizeEvents client; @Captor ArgumentCaptor<PutEventsRequest> putEventsRequestArgumentCaptor; @Captor ArgumentCaptor<PutItemsRequest> putItemsRequestArgumentCaptor; @Captor ArgumentCaptor<PutUsersRequest> putUsersRequestArgumentCaptor; @Test public void testWriterForEventData() throws Exception { PersonalizeSinkConfig config = new PersonalizeSinkConfig(TestConstants.configVals); DataWriter dataWriter = new DataWriter(config, client); SinkRecord sinkRecord = createRecord(TestConstants.sampleValsForEventData); dataWriter.write(Collections.singletonList(sinkRecord)); verify(client).putEvents(putEventsRequestArgumentCaptor.capture()); PutEventsRequest putEventsRequest = putEventsRequestArgumentCaptor.getValue(); assertTrue(putEventsRequest.getSessionId().equals(TestConstants.TEST_SESSION_ID_VALUE)); assertTrue(putEventsRequest.getUserId().equals(TestConstants.TEST_USER_ID_VALUE)); assertTrue(!putEventsRequest.getEventList().isEmpty()); Event event = putEventsRequest.getEventList().get(0); assertTrue(event.getEventType().equals(TestConstants.TEST_EVENT_TYPE_VALUE)); assertTrue(event.getItemId().equals(TestConstants.TEST_ITEM_ID_VALUE)); assertTrue(event.getSentAt().getTime() == TestConstants.TEST_EVENT_TIME_VALUE); assertTrue(putEventsRequest.getTrackingId().equals(TestConstants.TEST_EVENT_TRACKING_ID)); } @Test public void testWriterForItemData() throws Exception { PersonalizeSinkConfig config = new PersonalizeSinkConfig(TestConstants.itemconfigVals); DataWriter dataWriter = new DataWriter(config, client); SinkRecord sinkRecord = createRecord(TestConstants.sampleValsForItemData); dataWriter.write(Collections.singletonList(sinkRecord)); verify(client).putItems(putItemsRequestArgumentCaptor.capture()); PutItemsRequest putItemsRequest = putItemsRequestArgumentCaptor.getValue(); assertTrue(putItemsRequest.getDatasetArn().equals(TestConstants.VALID_ITEM_DATASET_ARN)); assertTrue(!putItemsRequest.getItems().isEmpty()); Item item = putItemsRequest.getItems().get(0); assertTrue(item.getItemId().equals(TestConstants.TEST_ITEM_ID_VALUE)); assertTrue(item.getProperties().equals(TestConstants.TEST_PROPERTIES_VALUE)); } @Test public void testWriterForUserData() throws Exception { PersonalizeSinkConfig config = new PersonalizeSinkConfig(TestConstants.userconfigVals); DataWriter dataWriter = new DataWriter(config, client); SinkRecord sinkRecord = createRecord(TestConstants.sampleValsForUserData); dataWriter.write(Collections.singletonList(sinkRecord)); verify(client).putUsers(putUsersRequestArgumentCaptor.capture()); PutUsersRequest putUsersRequest = putUsersRequestArgumentCaptor.getValue(); assertTrue(putUsersRequest.getDatasetArn().equals(TestConstants.VALID_USER_DATASET_ARN)); assertTrue(!putUsersRequest.getUsers().isEmpty()); User user = putUsersRequest.getUsers().get(0); assertTrue(user.getUserId().equals(TestConstants.TEST_USER_ID_VALUE)); assertTrue(user.getProperties().equals(TestConstants.TEST_PROPERTIES_VALUE)); } private SinkRecord createRecord(Object value) { return new SinkRecord("topic", 0, null, null, null, value, 1); } }
4,207
0
Create_ds/personalize-kafka-connector/src/test/java/com/aws
Create_ds/personalize-kafka-connector/src/test/java/com/aws/transfrom/CombineFieldsToJSONTransformationTest.java
package com.aws.transfrom; import com.aws.transform.CombineFieldsToJSONTransformation; import com.aws.util.TestConstants; import org.apache.kafka.common.config.ConfigException; import org.apache.kafka.connect.connector.ConnectRecord; import org.apache.kafka.connect.sink.SinkRecord; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class CombineFieldsToJSONTransformationTest { @Test public void testValidTransformationConfiguration(){ CombineFieldsToJSONTransformation.Value value = new CombineFieldsToJSONTransformation.Value(); Assertions.assertDoesNotThrow(() -> value.configure(TestConstants.validTransformationConfig)); } @Test public void testInValidTransformationConfiguration(){ CombineFieldsToJSONTransformation.Value value = new CombineFieldsToJSONTransformation.Value(); Assertions.assertThrows(ConfigException.class, () -> value.configure(TestConstants.inValidTransformationConfig)); } @Test public void testValueTransformation(){ CombineFieldsToJSONTransformation.Value value = new CombineFieldsToJSONTransformation.Value(); value.configure(TestConstants.validTransformationConfig); ConnectRecord record = value.apply(createRecord(null, TestConstants.sampleValsForTransformation)); Map<String, Object> valueMap = (Map<String, Object>) record.value(); assertFalse(valueMap.containsKey(TestConstants.FIELD_1)); assertFalse(valueMap.containsKey(TestConstants.FIELD_2)); assertTrue(valueMap.containsKey(CombineFieldsToJSONTransformation.DEFAULT_FIELD_NAME)); assertTrue(valueMap.get(CombineFieldsToJSONTransformation.DEFAULT_FIELD_NAME).equals(TestConstants.PROPERTIES_FIELD_WITH_FIELDS)); } @Test public void testKeyTransformation(){ CombineFieldsToJSONTransformation.Key key = new CombineFieldsToJSONTransformation.Key(); key.configure(TestConstants.validTransformationConfig); ConnectRecord record = key.apply(createRecord(TestConstants.sampleValsForTransformation, null)); Map<String, Object> keyMap = (Map<String, Object>) record.key(); assertFalse(keyMap.containsKey(TestConstants.FIELD_1)); assertFalse(keyMap.containsKey(TestConstants.FIELD_2)); assertTrue(keyMap.containsKey(CombineFieldsToJSONTransformation.DEFAULT_FIELD_NAME)); assertTrue(keyMap.get(CombineFieldsToJSONTransformation.DEFAULT_FIELD_NAME).equals(TestConstants.PROPERTIES_FIELD_WITH_FIELDS)); } private ConnectRecord<SinkRecord> createRecord(Object key, Object value) { return new SinkRecord("topic", 0, null, key, null, value, 1); } }
4,208
0
Create_ds/personalize-kafka-connector/src/test/java/com/aws
Create_ds/personalize-kafka-connector/src/test/java/com/aws/task/PersonalizeSinkTaskTest.java
package com.aws.task; import com.aws.util.TestConstants; import org.apache.kafka.common.config.ConfigException; import org.apache.kafka.connect.sink.ErrantRecordReporter; import org.apache.kafka.connect.sink.SinkRecord; import org.apache.kafka.connect.sink.SinkTaskContext; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.Map; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class PersonalizeSinkTaskTest { private final static Map<String, Object> VALUE = TestConstants.sampleValsForEventData; private final static String KEY = "key"; @Test void testTask() { final PersonlizeSinkTask task = createSinkTask(); Assertions.assertDoesNotThrow(() -> task.start(TestConstants.configVals)); Assertions.assertDoesNotThrow(() -> task.put(Collections.singletonList(createRecord()))); Assertions.assertDoesNotThrow(() -> task.stop()); } @Test void testValidConfig(){ final PersonlizeSinkTask task = createSinkTask(); Assertions.assertDoesNotThrow(() ->task.start(TestConstants.configVals)); Assertions.assertDoesNotThrow(() -> task.stop()); } @Test void testInValidConfig(){ final PersonlizeSinkTask task = createSinkTask(); Assertions.assertThrows(ConfigException.class, () ->task.start(TestConstants.invalidConfigVals)); Assertions.assertDoesNotThrow(() -> task.stop()); } private SinkRecord createRecord() { return new SinkRecord("topic", 0, null, KEY, null, VALUE, 1); } private PersonlizeSinkTask createSinkTask() { final PersonlizeSinkTask sinkTask = new PersonlizeSinkTask(); SinkTaskContext mockContext = mock(SinkTaskContext.class); ErrantRecordReporter reporter = mock(ErrantRecordReporter.class); when(mockContext.errantRecordReporter()).thenReturn(reporter); sinkTask.initialize(mockContext); return sinkTask; } }
4,209
0
Create_ds/personalize-kafka-connector/src/test/java/com/aws
Create_ds/personalize-kafka-connector/src/test/java/com/aws/connector/PersonalizeSinkConnectorTest.java
package com.aws.connector; import com.aws.util.TestConstants; import org.apache.kafka.connect.connector.Connector; import org.apache.kafka.connect.connector.ConnectorContext; import org.apache.kafka.connect.sink.SinkConnector; import org.junit.jupiter.api.Test; import org.mockito.Mock; import static com.aws.util.TestConstants.configVals; import static com.aws.util.Constants.AMAZON_PERSONALIZE_EVENT_TRACKING_ID; import static com.aws.util.Constants.AWS_REGION_NAME; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.data.MapEntry.entry; import static org.junit.jupiter.api.Assertions.*; public class PersonalizeSinkConnectorTest { @Mock private ConnectorContext context; @Test void testStartAndStop() { final PersonalizeSinkConnector connector = createConnector(); connector.start(configVals); assertThat(connector.taskConfigs(1)).hasSize(1); assertThat(connector.taskConfigs(10)).hasSize(10); } @Test void testConfig() { final PersonalizeSinkConnector connector = createConnector(); connector.start(configVals); assertThat(connector.taskConfigs(1).get(0)).contains( entry(AWS_REGION_NAME, TestConstants.TEST_AWS_REGION), entry(AMAZON_PERSONALIZE_EVENT_TRACKING_ID, TestConstants.TEST_EVENT_TRACKING_ID)); } @Test public void testVersion() { String version = new PersonalizeSinkConnector().version(); System.out.println(version); assertNotNull(version); assertFalse(version.isEmpty()); } @Test public void connectorType() { Connector connector = new PersonalizeSinkConnector(); assertTrue(SinkConnector.class.isAssignableFrom(connector.getClass())); } private PersonalizeSinkConnector createConnector() { final PersonalizeSinkConnector connector = new PersonalizeSinkConnector(); connector.initialize(context); return connector; } }
4,210
0
Create_ds/personalize-kafka-connector/src/main/java/com/aws
Create_ds/personalize-kafka-connector/src/main/java/com/aws/converter/DataConverter.java
package com.aws.converter; import com.amazonaws.services.personalizeevents.model.Event; import com.amazonaws.services.personalizeevents.model.Item; import com.amazonaws.services.personalizeevents.model.MetricAttribution; import com.amazonaws.services.personalizeevents.model.User; import com.aws.util.Constants; import org.apache.kafka.connect.data.Struct; import org.apache.kafka.connect.errors.DataException; import org.apache.kafka.connect.sink.SinkRecord; import java.util.Collection; import java.util.Date; import java.util.Map; /************* * This class is used for Mapping Kafka records to Personalize Event Model Objects */ public class DataConverter { /************ * This methods used to convert Sink Kafka Record into Event Model object. * @param record * @return */ public static Event convertSinkRecordToEventInfo(SinkRecord record, Map<String, String> additionalValues) { Event eventInfo = null; if(record.value() instanceof Struct) eventInfo = prepareEventDataFromStruct((Struct) record.value(), additionalValues); else eventInfo = prepareEventDataFromMap((Map<String, Object>) record.value(), additionalValues); return eventInfo; } private static Event prepareEventDataFromStruct(Struct recordValue, Map<String, String> additionalValues) { Event eventInfo = new Event(); //Processing required fields in request try { eventInfo.setEventType(recordValue.getString(Constants.FIELD_EVENT_TYPE)); additionalValues.put(Constants.FIELD_SESSION_ID,recordValue.getString(Constants.FIELD_SESSION_ID)); String eventTimeStr = null; if (recordValue.get(Constants.FIELD_EVENT_TIME) instanceof String) { eventTimeStr = recordValue.getString(Constants.FIELD_EVENT_TIME); eventInfo.setSentAt(new Date(Long.parseLong(eventTimeStr))); } else if (recordValue.get(Constants.FIELD_EVENT_TIME) instanceof Long) { eventInfo.setSentAt(new Date((Long) recordValue.get(Constants.FIELD_EVENT_TIME))); } } catch (DataException exception) { throw new DataException("Missing Required Data"); } //Optional field for Event Object eventInfo.setEventId(null != getValueForOptionalField(recordValue, Constants.FIELD_EVENT_ID) ? (String) getValueForOptionalField(recordValue, Constants.FIELD_EVENT_ID) : null); eventInfo.setEventValue(null != getValueForOptionalField(recordValue, Constants.FIELD_EVENT_VALUE) ? (Float) getValueForOptionalField(recordValue, Constants.FIELD_EVENT_VALUE) : null); eventInfo.setImpression(null != getValueForOptionalField(recordValue, Constants.FIELD_EVENT_IMPRESSION) ? (Collection<String>) getValueForOptionalField(recordValue, Constants.FIELD_EVENT_IMPRESSION) : null); eventInfo.setItemId(null != getValueForOptionalField(recordValue, Constants.FIELD_ITEM_ID) ? (String) getValueForOptionalField(recordValue, Constants.FIELD_ITEM_ID) : null); if(null != getValueForOptionalField(recordValue, Constants.FIELD_EVENT_METRIC_ATTRIBUTION_SOURCE)) { MetricAttribution metricAttribution = new MetricAttribution(); metricAttribution.setEventAttributionSource((String) getValueForOptionalField(recordValue, Constants.FIELD_EVENT_METRIC_ATTRIBUTION_SOURCE)); } eventInfo.setProperties(null != getValueForOptionalField(recordValue, Constants.FIELD_PROPERTIES) ? (String) getValueForOptionalField(recordValue, Constants.FIELD_PROPERTIES) : null); eventInfo.setRecommendationId(null != getValueForOptionalField(recordValue, Constants.FIELD_EVENT_RECOMMENDATION_ID) ? (String) getValueForOptionalField(recordValue, Constants.FIELD_EVENT_RECOMMENDATION_ID) : null); //Another optional field in request if(null != getValueForOptionalField(recordValue, Constants.FIELD_USER_ID)) additionalValues.put(Constants.FIELD_USER_ID , (String) getValueForOptionalField(recordValue, Constants.FIELD_USER_ID)); return eventInfo; } private static Event prepareEventDataFromMap(Map<String, Object> recordValue, Map<String, String> additionalValues) { Event eventInfo = new Event(); //Processing required fields in request if(recordValue.containsKey(Constants.FIELD_EVENT_TYPE)) eventInfo.setEventType((String)recordValue.get(Constants.FIELD_EVENT_TYPE)); else throw new DataException("Missing Required Data"); if(recordValue.containsKey(Constants.FIELD_EVENT_TYPE)) additionalValues.put(Constants.FIELD_SESSION_ID, (String) recordValue.get(Constants.FIELD_SESSION_ID)); else throw new DataException("Missing Required Data"); if(recordValue.containsKey(Constants.FIELD_EVENT_TIME)){ String eventTimeStr = null; if (recordValue.get(Constants.FIELD_EVENT_TIME) instanceof String) { eventTimeStr = (String) recordValue.get(Constants.FIELD_EVENT_TIME); eventInfo.setSentAt(new Date(Long.parseLong(eventTimeStr))); } else if (recordValue.get(Constants.FIELD_EVENT_TIME) instanceof Long) { eventInfo.setSentAt(new Date((Long) recordValue.get(Constants.FIELD_EVENT_TIME))); } }else throw new DataException("Missing Required Data"); //Optional field for Event Object eventInfo.setEventId(null != getValueForOptionalFieldFromMap(recordValue, Constants.FIELD_EVENT_ID) ? (String) getValueForOptionalFieldFromMap(recordValue, Constants.FIELD_EVENT_ID) : null); eventInfo.setEventValue (null != getValueForOptionalFieldFromMap(recordValue, Constants.FIELD_EVENT_VALUE) ? (Float) getValueForOptionalFieldFromMap(recordValue, Constants.FIELD_EVENT_VALUE) : null); eventInfo.setImpression(null != getValueForOptionalFieldFromMap(recordValue, Constants.FIELD_EVENT_IMPRESSION) ? (Collection<String>) getValueForOptionalFieldFromMap(recordValue, Constants.FIELD_EVENT_IMPRESSION) : null); eventInfo.setItemId(null != getValueForOptionalFieldFromMap(recordValue, Constants.FIELD_ITEM_ID) ? (String) getValueForOptionalFieldFromMap(recordValue, Constants.FIELD_ITEM_ID) : null); if(null != getValueForOptionalFieldFromMap(recordValue, Constants.FIELD_EVENT_METRIC_ATTRIBUTION_SOURCE)) { MetricAttribution metricAttribution = new MetricAttribution(); metricAttribution.setEventAttributionSource((String) getValueForOptionalFieldFromMap(recordValue, Constants.FIELD_EVENT_METRIC_ATTRIBUTION_SOURCE)); } eventInfo.setProperties(null != getValueForOptionalFieldFromMap(recordValue, Constants.FIELD_PROPERTIES) ? (String) getValueForOptionalFieldFromMap(recordValue, Constants.FIELD_PROPERTIES) : null); eventInfo.setRecommendationId(null != getValueForOptionalFieldFromMap(recordValue, Constants.FIELD_EVENT_RECOMMENDATION_ID) ? (String) getValueForOptionalFieldFromMap(recordValue, Constants.FIELD_EVENT_RECOMMENDATION_ID) : null); //Another optional field in request if(null != getValueForOptionalFieldFromMap(recordValue, Constants.FIELD_USER_ID)) additionalValues.put(Constants.FIELD_USER_ID, (String) getValueForOptionalFieldFromMap(recordValue, Constants.FIELD_USER_ID)); return eventInfo; } private static Object getValueForOptionalFieldFromMap(Map<String, Object> recordValue, String fieldName) { Object valueForField = null; if(recordValue != null){ try{ valueForField = recordValue.get(fieldName); }catch (DataException e){ valueForField = null; } } return valueForField; } private static Object getValueForOptionalField(Struct recordValue, String fieldName) { Object valueForField = null; if(recordValue != null){ try{ valueForField = recordValue.get(fieldName); }catch (DataException e){ valueForField = null; } } return valueForField; } /************** * This method is used to convert Sink record to Item Model object * @param record * @return */ public static Item convertSinkRecordToItemInfo(SinkRecord record) { Item itemInfo = null; if(record.value() instanceof Struct) itemInfo = prepareItemDataFromStruct((Struct) record.value()); else itemInfo = prepareItemDataFromMap((Map<String, Object>) record.value()); return itemInfo; } private static Item prepareItemDataFromStruct(Struct recordValue) { Item itemInfo = new Item(); try { itemInfo.setItemId(recordValue.getString(Constants.FIELD_ITEM_ID)); } catch (DataException exception) { throw new DataException("Missing Required Data"); } itemInfo.setProperties((String) getValueForOptionalField(recordValue, Constants.FIELD_PROPERTIES)); return itemInfo; } private static Item prepareItemDataFromMap(Map<String,Object> recordValue) { Item itemInfo = new Item(); try { itemInfo.setItemId( (String) recordValue.get(Constants.FIELD_ITEM_ID)); } catch (Throwable exception) { throw new DataException("Missing Required Data"); } itemInfo.setProperties((String) getValueForOptionalFieldFromMap(recordValue, Constants.FIELD_PROPERTIES)); return itemInfo; } /*************** * This method is used to convert Sink record to User Model object * @param record * @return */ public static User convertSinkRecordToUserInfo(SinkRecord record) { User userInfo = null; if(record.value() instanceof Struct) userInfo = prepareUserDataFromStruct((Struct) record.value()); else userInfo = prepareUserDataFromMap((Map<String, Object>) record.value()); return userInfo; } private static User prepareUserDataFromMap(Map<String, Object> recordValue) { User userInfo = new User(); try { userInfo.setUserId( (String) recordValue.get(Constants.FIELD_USER_ID)); } catch (Throwable exception) { throw new DataException("Missing Required Data"); } userInfo.setProperties((String) getValueForOptionalFieldFromMap(recordValue, Constants.FIELD_PROPERTIES)); return userInfo; } private static User prepareUserDataFromStruct(Struct recordValue) { User userInfo = new User(); try { userInfo.setUserId(recordValue.getString(Constants.FIELD_USER_ID)); }catch (DataException exception) { throw new DataException("Missing Required Data"); } userInfo.setProperties( (String) getValueForOptionalField(recordValue, Constants.FIELD_PROPERTIES)); return userInfo; } }
4,211
0
Create_ds/personalize-kafka-connector/src/main/java/com/aws
Create_ds/personalize-kafka-connector/src/main/java/com/aws/util/Version.java
package com.aws.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Properties; /************ * This is used for providing version for Connector */ public class Version { private static final Logger log = LoggerFactory.getLogger(Version.class); public static final String version; static { String versionProperty = "unknown"; try { Properties prop = new Properties(); prop.load(Version.class.getResourceAsStream(Constants.CONNECTOR_VERSION_PROPERTIES_FILE_NAME)); System.out.println(prop); versionProperty = prop.getProperty(Constants.CONNECTOR_VERSION_PROPERTY_NAME, versionProperty).trim(); } catch (Exception e) { log.warn("Error in loading connector version"); versionProperty = "unknown"; } version = versionProperty; } public static String getVersion() { return version; } }
4,212
0
Create_ds/personalize-kafka-connector/src/main/java/com/aws
Create_ds/personalize-kafka-connector/src/main/java/com/aws/util/Constants.java
package com.aws.util; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import org.apache.kafka.common.config.types.Password; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /*********** * This class consists of Constants used. */ public class Constants { //Event Related Fields public static final String FIELD_EVENT_TYPE ="eventType"; public static final String FIELD_EVENT_ID ="eventId"; public static final String FIELD_EVENT_VALUE ="eventValue"; public static final String FIELD_EVENT_IMPRESSION ="impression"; public static final String FIELD_ITEM_ID ="itemId"; public static final String FIELD_EVENT_METRIC_ATTRIBUTION_SOURCE ="eventAttributionSource"; public static final String FIELD_PROPERTIES = "properties"; public static final String FIELD_EVENT_RECOMMENDATION_ID = "recommendationId"; public static final String FIELD_EVENT_TIME ="sentAt"; public static final String FIELD_SESSION_ID ="sessionId"; public static final String FIELD_USER_ID ="userId"; public static final Set<String> VALID_DATA_TYPE = new HashSet<String>(Arrays.asList("events", "items","users")); public static final String PUT_EVENTS_REQUEST_TYPE = "events"; public static final String PUT_ITEMS_REQUEST_TYPE = "items"; public static final String PUT_USERS_REQUEST_TYPE = "users"; public static final String PERSONALIZE_SERVICE_NAME = "personalize"; public static final String PERSONALIZE_DATASET_RESOURCE = "dataset"; public static final String PERSONALIZE_USERS_DATASET_RESOURCE_NAME = "USERS"; public static final String PERSONALIZE_ITEMS_DATASET_RESOURCE_NAME = "ITEMS"; public static final Class<? extends AWSCredentialsProvider> AWS_PERSONALIZE_CREDENTIALS_PROVIDER_CLASS_DEFAULT = DefaultAWSCredentialsProviderChain.class; public static final String AWS_ACCESS_KEY = "aws.access.key"; public static final String DEFAULT_STRING_VALUE = ""; public static final String AWS_ACCESS_KEY_DOC = "AWS Access key"; public static final String AWS_ACCESS_KEY_DISPLAY = "AWS Access key"; public static final String AWS_SECRET_KEY = "aws.secret.key"; public static final Password AWS_SECRET_KEY_DEFAULT_VALUE = new Password(null); public static final String AWS_SECRET_KEY_DOC = "AWS Secret Access Key"; public static final String AWS_SECRET_KEY_DISPLAY = "AWS Secret Access Key"; public static final String AWS_REGION_NAME = "aws.region.name"; public static final String DEFAULT_AWS_REGION_NAME = "us-east-1"; public static final String AWS_REGION_NAME_DOC = "AWS Region"; public static final String AWS_REGION_NAME_DISPLAY = "AWS Region"; public static final String AMAZON_PERSONALIZE_EVENT_TRACKING_ID = "amazon.personalize.event.tracking.id"; public static final String AMAZON_PERSONALIZE_EVENT_TRACKING_ID_DOC = "Amazon Personalize Event tracking ID"; public static final String AMAZON_PERSONALIZE_EVENT_TRACKING_ID_DISPLAY = "Amazon Personalize Event tracking ID"; public static final String AMAZON_PERSONALIZE_DATA_TYPE = "amazon.personalize.data.type"; public static final String AMAZON_PERSONALIZE_EVENT_TYPE_DISPLAY = "Amazon Personalize Data Type"; public static final String AMAZON_PERSONALIZE_EVENT_TYPE_DOC = "Valid data types are events,items and users corresponding to interactions, items and users datasets."; public static final String AMAZON_PERSONALIZE_DATASET_ARN = "amazon.personalize.dataset.arn"; public static final String AMAZON_PERSONALIZE_DATASET_ARN_DISPLAY = "ARN for Users/Items dataset"; public static final String AMAZON_PERSONALIZE_DATASET_ARN_DOC = "The Amazon Resource Name (ARN) of the Users/Items dataset you are adding the user(s)/item(s) to."; public static final String AMAZON_PERSONALIZE_CREDENTIALS_PROVIDER_CLASS = "amazon.personalize.credentials.provider.class"; public static final String AMAZON_PERSONALIZE_CREDENTIALS_PROVIDER_CLASS_PREFIX = AMAZON_PERSONALIZE_CREDENTIALS_PROVIDER_CLASS.substring(0, AMAZON_PERSONALIZE_CREDENTIALS_PROVIDER_CLASS.lastIndexOf(".")+1); public static final String AMAZON_PERSONALIZE_CREDENTIALS_PROVIDER_CLASS_DOC = "AWS Credential Provider Class"; public static final String AMAZON_PERSONALIZE_CREDENTIALS_PROVIDER_CLASS_DISPLAY = "AWS Credential Provider Class"; public static final String AWS_ACCOUNT_DETAILS_GROUP = "AWS Account Details"; public static final String MAX_RETRIES = "max.retries"; public static final String NAME_PROPERTY = "name"; public static final String DEFAULT_CONNECTOR_NAME = "Personalize-sink"; public static final String CONNECTOR_VERSION_PROPERTIES_FILE_NAME ="/kafka-connect-personalize-version.properties"; public static final String CONNECTOR_VERSION_PROPERTY_NAME ="version"; public static final String RECORD_RATE_LIMIT_PROPERTY_NAME ="record.rate.limit"; public static final String MAX_TASKS_PROPERTY_NAME ="tasks.max"; public static final Integer DEFAULT_VALUE_FOR_EVENT_RECORD_RATE = 1000; public static final Integer DEFAULT_VALUE_FOR_ITEM_AND_USER_RECORD_RATE = 10; }
4,213
0
Create_ds/personalize-kafka-connector/src/main/java/com/aws
Create_ds/personalize-kafka-connector/src/main/java/com/aws/config/PersonalizeSinkConfig.java
package com.aws.config; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.aws.config.validators.ArnValidator; import com.aws.config.validators.PersonalizeCredentialsProviderValidator; import com.aws.config.validators.PersonalizeDataTypeValidator; import org.apache.commons.lang3.StringUtils; import org.apache.kafka.common.Configurable; import org.apache.kafka.common.config.AbstractConfig; import org.apache.kafka.common.config.ConfigDef; import org.apache.kafka.common.config.types.Password; import org.apache.kafka.common.config.ConfigException; import org.apache.kafka.connect.errors.ConnectException; import java.util.Map; import static com.aws.util.Constants.*; /**************** * This class is used for connector specific configuration. */ public class PersonalizeSinkConfig extends AbstractConfig { private final String awsAccessKey; private final String awsSecretKey; private final String awsRegionName; private final String eventTrackingId; private final String dataSetArn; private final String dataType; private final int maxRetries; private final String name; public static final ConfigDef CONFIG_DEF = new ConfigDef().define( AWS_ACCESS_KEY, ConfigDef.Type.STRING, DEFAULT_STRING_VALUE, ConfigDef.Importance.HIGH, AWS_ACCESS_KEY_DOC, AWS_ACCOUNT_DETAILS_GROUP, 1, ConfigDef.Width.LONG, AWS_ACCESS_KEY_DISPLAY ).define( AWS_SECRET_KEY, ConfigDef.Type.PASSWORD, AWS_SECRET_KEY_DEFAULT_VALUE, ConfigDef.Importance.HIGH, AWS_SECRET_KEY_DOC, AWS_ACCOUNT_DETAILS_GROUP, 2, ConfigDef.Width.LONG, AWS_SECRET_KEY_DISPLAY ).define( AWS_REGION_NAME, ConfigDef.Type.STRING, ConfigDef.NO_DEFAULT_VALUE, ConfigDef.Importance.HIGH, AWS_REGION_NAME_DOC, AWS_ACCOUNT_DETAILS_GROUP, 3, ConfigDef.Width.LONG, AWS_REGION_NAME_DISPLAY ).define( AMAZON_PERSONALIZE_DATA_TYPE, ConfigDef.Type.STRING, PUT_EVENTS_REQUEST_TYPE, new PersonalizeDataTypeValidator(), ConfigDef.Importance.HIGH, AMAZON_PERSONALIZE_EVENT_TYPE_DOC, AWS_ACCOUNT_DETAILS_GROUP, 4, ConfigDef.Width.LONG, AMAZON_PERSONALIZE_EVENT_TYPE_DISPLAY ).define( AMAZON_PERSONALIZE_DATASET_ARN, ConfigDef.Type.STRING, DEFAULT_STRING_VALUE, new ArnValidator(), ConfigDef.Importance.HIGH, AMAZON_PERSONALIZE_DATASET_ARN_DOC, AWS_ACCOUNT_DETAILS_GROUP, 6, ConfigDef.Width.LONG, AMAZON_PERSONALIZE_DATASET_ARN_DISPLAY ).define( AMAZON_PERSONALIZE_EVENT_TRACKING_ID, ConfigDef.Type.STRING, DEFAULT_STRING_VALUE, ConfigDef.Importance.HIGH, AMAZON_PERSONALIZE_EVENT_TRACKING_ID_DOC, AWS_ACCOUNT_DETAILS_GROUP, 5, ConfigDef.Width.LONG, AMAZON_PERSONALIZE_EVENT_TRACKING_ID_DISPLAY ).define( MAX_RETRIES, ConfigDef.Type.INT, 2, ConfigDef.Importance.HIGH, MAX_RETRIES, null, 8, ConfigDef.Width.LONG, MAX_RETRIES ).define( AMAZON_PERSONALIZE_CREDENTIALS_PROVIDER_CLASS, ConfigDef.Type.CLASS, AWS_PERSONALIZE_CREDENTIALS_PROVIDER_CLASS_DEFAULT, new PersonalizeCredentialsProviderValidator(), ConfigDef.Importance.LOW, AMAZON_PERSONALIZE_CREDENTIALS_PROVIDER_CLASS_DOC, AWS_ACCOUNT_DETAILS_GROUP, 7, ConfigDef.Width.LONG, AMAZON_PERSONALIZE_CREDENTIALS_PROVIDER_CLASS_DISPLAY ); public String awsAccessKey() { return getString(AWS_ACCESS_KEY); } public Password awsSecretKey() { return getPassword(AWS_SECRET_KEY); } public PersonalizeSinkConfig(Map<?, ?> props) { super(CONFIG_DEF, props); awsAccessKey =awsAccessKey(); awsSecretKey = awsSecretKey().value(); awsRegionName = getString(AWS_REGION_NAME); maxRetries = getInt(MAX_RETRIES); dataType = getString(AMAZON_PERSONALIZE_DATA_TYPE); if(dataType.equals(PUT_EVENTS_REQUEST_TYPE)) { eventTrackingId = getVaildConfigValue(props, AMAZON_PERSONALIZE_EVENT_TRACKING_ID); dataSetArn = getString(AMAZON_PERSONALIZE_DATASET_ARN); }else { dataSetArn = getVaildConfigValue(props,AMAZON_PERSONALIZE_DATASET_ARN); eventTrackingId = getString(AMAZON_PERSONALIZE_EVENT_TRACKING_ID); } name = getConnectorName(props); } /******* * This method is used for getting name for connector which is configured * @param props * @return */ private String getConnectorName(Map<?, ?> props) { String connectorName = null; if (props.containsKey(NAME_PROPERTY)) { String nameProp = (String) props.get(NAME_PROPERTY); connectorName = null != nameProp ? nameProp : DEFAULT_CONNECTOR_NAME; } else { connectorName = DEFAULT_CONNECTOR_NAME; } return connectorName; } private String getVaildConfigValue(Map<?, ?> props, String configName){ if(props.containsKey(configName)) { String validValue = getString(configName) ; if (!StringUtils.isEmpty(validValue)) { return validValue; }else throw new ConfigException("You should have non-empty value for Configuration" + configName); } else throw new ConfigException("Missing required configuration " + configName); } public String getName() { return name; } public String getAwsRegionName() { return awsRegionName; } public String getEventTrackingId() { return eventTrackingId; } public String getDataSetArn() { return dataSetArn; } public String getDataType() { return dataType; } public int getMaxRetries() { return maxRetries; } /************** * This method is used for providing AWS credentials which will be used by personalize client * @return AWS credentials provider */ public AWSCredentialsProvider getCredentionalProvider() { try { AWSCredentialsProvider provider = ((Class<? extends AWSCredentialsProvider>) getClass(AMAZON_PERSONALIZE_CREDENTIALS_PROVIDER_CLASS)).newInstance(); if (provider instanceof Configurable) { Map<String, Object> configs = originalsWithPrefix(AMAZON_PERSONALIZE_CREDENTIALS_PROVIDER_CLASS_PREFIX); configs.remove(AMAZON_PERSONALIZE_CREDENTIALS_PROVIDER_CLASS.substring( AMAZON_PERSONALIZE_CREDENTIALS_PROVIDER_CLASS_PREFIX.length() )); configs.put(AWS_ACCESS_KEY, awsAccessKey()); configs.put(AWS_SECRET_KEY, awsSecretKey().value()); ((Configurable) provider).configure(configs); } else { final String accessKeyId = awsAccessKey(); final String secretKey = awsSecretKey().value(); if (StringUtils.isNotBlank(accessKeyId) && StringUtils.isNotBlank(secretKey)) { BasicAWSCredentials basicCredentials = new BasicAWSCredentials(accessKeyId, secretKey); provider = new AWSStaticCredentialsProvider(basicCredentials); } } return provider; } catch (Exception e) { throw new ConnectException("Invalid class for: " + AMAZON_PERSONALIZE_CREDENTIALS_PROVIDER_CLASS, e); } } }
4,214
0
Create_ds/personalize-kafka-connector/src/main/java/com/aws/config
Create_ds/personalize-kafka-connector/src/main/java/com/aws/config/validators/ArnValidator.java
package com.aws.config.validators; import com.amazonaws.arn.Arn; import org.apache.kafka.common.config.ConfigDef; import org.apache.kafka.common.config.ConfigException; import static com.aws.util.Constants.*; /********* * This is used for validation ARN for Items or Users Dataset */ public class ArnValidator implements ConfigDef.Validator { @Override public void ensureValid(String arnVar, Object value) { if (null != value && ((String) value).isEmpty()) { return; } try { String arnValue = (String) value; Arn arn = Arn.fromString(arnValue); if ((arn.getResourceAsString().endsWith(PERSONALIZE_USERS_DATASET_RESOURCE_NAME) || arn.getResourceAsString().endsWith(PERSONALIZE_ITEMS_DATASET_RESOURCE_NAME)) && arn.getResource().getResourceType().equals(PERSONALIZE_DATASET_RESOURCE) && arn.getService().equals(PERSONALIZE_SERVICE_NAME)) { return; } else { throw new ConfigException("Invalid Arn for User/Item dataset"); } } catch (Throwable e) { throw new ConfigException("Invalid Arn for User/Item dataset"); } } }
4,215
0
Create_ds/personalize-kafka-connector/src/main/java/com/aws/config
Create_ds/personalize-kafka-connector/src/main/java/com/aws/config/validators/PersonalizeDataTypeValidator.java
package com.aws.config.validators; import org.apache.kafka.common.config.ConfigDef; import org.apache.kafka.common.config.ConfigException; import static com.aws.util.Constants.VALID_DATA_TYPE; /************* * This class is used for validating Personalize Data Type configuration */ public class PersonalizeDataTypeValidator implements ConfigDef.Validator { @Override public void ensureValid(String eventType, Object value) { if (null != value && ((String) value).isEmpty()) { return; } if (!VALID_DATA_TYPE.contains(((String) value).toLowerCase())) { throw new ConfigException(String.format( "%s must be one out of %s", eventType, String.join(",", VALID_DATA_TYPE) )); } } }
4,216
0
Create_ds/personalize-kafka-connector/src/main/java/com/aws/config
Create_ds/personalize-kafka-connector/src/main/java/com/aws/config/validators/PersonalizeCredentialsProviderValidator.java
package com.aws.config.validators; import com.amazonaws.auth.AWSCredentialsProvider; import org.apache.kafka.common.config.ConfigDef; import org.apache.kafka.common.config.ConfigException; /********* * This is used for validation Credential Provider class */ public class PersonalizeCredentialsProviderValidator implements ConfigDef.Validator { @Override public void ensureValid(String name, Object provider) { if (provider != null && provider instanceof Class && AWSCredentialsProvider.class.isAssignableFrom((Class<?>) provider)) { return; } throw new ConfigException( name, provider, "Class must extend: " + AWSCredentialsProvider.class ); } }
4,217
0
Create_ds/personalize-kafka-connector/src/main/java/com/aws
Create_ds/personalize-kafka-connector/src/main/java/com/aws/auth/AssumeRoleCredentialsProvider.java
package com.aws.auth; import com.amazonaws.auth.*; import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder; import org.apache.commons.lang3.StringUtils; import org.apache.kafka.common.Configurable; import org.apache.kafka.common.config.AbstractConfig; import org.apache.kafka.common.config.ConfigDef; import java.util.Map; import static com.aws.util.Constants.AWS_ACCESS_KEY; import static com.aws.util.Constants.AWS_SECRET_KEY; /****************** * This class provide default implementation for if client using trusted account for providing authentication */ public class AssumeRoleCredentialsProvider implements AWSCredentialsProvider, Configurable { public static final String AMAZON_PERSONALIZE_STS_ROLE_EXTERNAL_ID_CONFIG = "amazon.personalize.sts.role.external.id"; public static final String AMAZON_PERSONALIZE_ROLE_ARN_CONFIG = "amazon.personalize.sts.role.arn"; public static final String AMAZON_PERSONALIZE_ROLE_SESSION_NAME_CONFIG = "amazon.personalize.sts.role.session.name"; private static final ConfigDef STS_CONFIG_DEF = new ConfigDef() .define( AMAZON_PERSONALIZE_STS_ROLE_EXTERNAL_ID_CONFIG, ConfigDef.Type.STRING, ConfigDef.Importance.MEDIUM, "Amazon Personalize external role ID used when retrieving session credentials under an assumed role." ).define( AMAZON_PERSONALIZE_ROLE_ARN_CONFIG, ConfigDef.Type.STRING, ConfigDef.Importance.HIGH, "Amazon Personalize Role ARN for creating AWS session." ).define( AMAZON_PERSONALIZE_ROLE_SESSION_NAME_CONFIG, ConfigDef.Type.STRING, ConfigDef.Importance.HIGH, "Amazon Personalize Role session name" ); private String roleArn; private String roleExternalId; private String roleSessionName; private BasicAWSCredentials basicCredentials; private STSAssumeRoleSessionCredentialsProvider stsAssumeRoleCredentialsProvider; @Override public void configure(Map<String, ?> configs) { AbstractConfig config = new AbstractConfig(STS_CONFIG_DEF, configs); roleArn = config.getString(AMAZON_PERSONALIZE_ROLE_ARN_CONFIG); roleExternalId = config.getString(AMAZON_PERSONALIZE_STS_ROLE_EXTERNAL_ID_CONFIG); roleSessionName = config.getString(AMAZON_PERSONALIZE_ROLE_SESSION_NAME_CONFIG); final String accessKeyId = (String) configs.get(AWS_ACCESS_KEY); final String secretKey = (String) configs.get(AWS_SECRET_KEY); if (StringUtils.isNotBlank(accessKeyId) && StringUtils.isNotBlank(secretKey)) { BasicAWSCredentials basicCredentials = new BasicAWSCredentials(accessKeyId, secretKey); stsAssumeRoleCredentialsProvider = new STSAssumeRoleSessionCredentialsProvider .Builder(roleArn, roleSessionName) .withStsClient(AWSSecurityTokenServiceClientBuilder .standard() .withCredentials(new AWSStaticCredentialsProvider(basicCredentials)).build() ) .withExternalId(roleExternalId) .build(); } else { basicCredentials = null; stsAssumeRoleCredentialsProvider = new STSAssumeRoleSessionCredentialsProvider.Builder(roleArn, roleSessionName) .withStsClient(AWSSecurityTokenServiceClientBuilder.defaultClient()) .withExternalId(roleExternalId).build(); } } @Override public AWSCredentials getCredentials() { return stsAssumeRoleCredentialsProvider.getCredentials(); } @Override public void refresh() { if(stsAssumeRoleCredentialsProvider != null) stsAssumeRoleCredentialsProvider.refresh(); } }
4,218
0
Create_ds/personalize-kafka-connector/src/main/java/com/aws
Create_ds/personalize-kafka-connector/src/main/java/com/aws/writer/DataWriter.java
package com.aws.writer; import com.amazonaws.services.personalizeevents.AmazonPersonalizeEvents; import com.amazonaws.services.personalizeevents.model.*; import com.aws.config.PersonalizeSinkConfig; import com.aws.converter.DataConverter; import com.aws.util.Constants; import org.apache.kafka.connect.sink.SinkRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; /************ * This class is used for writing Kafka Records into Personalize Event through PersonalizeEvent SDK */ public class DataWriter { private static final Logger log = LoggerFactory.getLogger(DataWriter.class); AmazonPersonalizeEvents client; String eventTrackingId; String dataSetArn; String dataType; public DataWriter(PersonalizeSinkConfig config, AmazonPersonalizeEvents client) { log.info("Initialing data writer for : " + config.getDataType()); int maxRetries = config.getMaxRetries(); this.client = client; dataType = config.getDataType(); eventTrackingId = config.getEventTrackingId(); dataSetArn = config.getDataSetArn(); } /********************** * This method is used for writing sink kafka record into personalize. * @param records of Sink records * @throws Exception */ public void write(final Collection<SinkRecord> records) throws Exception { log.debug("DataWriter started writing record with size :" + records.size()); try{ for (SinkRecord record : records) { log.debug("Processing record with value:"+ record.value()); if(Constants.PUT_EVENTS_REQUEST_TYPE.equals(dataType)){ Map<String, String> additionalValues = new HashMap<>(); Event eventInfo = DataConverter.convertSinkRecordToEventInfo(record, additionalValues); if(eventInfo != null) putEvents(eventInfo, additionalValues); }else if(Constants.PUT_ITEMS_REQUEST_TYPE.equals(dataType)){ Item itemInfo = DataConverter.convertSinkRecordToItemInfo(record); if(itemInfo != null) putItems(itemInfo); }else if(Constants.PUT_USERS_REQUEST_TYPE.equals(dataType)){ User userInfo = DataConverter.convertSinkRecordToUserInfo(record); if(userInfo != null) putUsers(userInfo); }else log.error("Invalid Operation" ); } }catch(Throwable e){ log.error("Exception occurred while writing data to personalize", e); throw e; } } /*************************** * This method to call put event APIs * @param eventInfo * @return */ private void putEvents(Event eventInfo, Map<String, String> additionalValues) { try { PutEventsRequest putEventsRequest = new PutEventsRequest(); putEventsRequest.setTrackingId(eventTrackingId); putEventsRequest.setUserId(additionalValues.get(Constants.FIELD_USER_ID)); putEventsRequest.setSessionId(additionalValues.get(Constants.FIELD_SESSION_ID)); putEventsRequest.setEventList(Collections.singletonList(eventInfo)); client.putEvents(putEventsRequest); } catch (AmazonPersonalizeEventsException e) { log.error("Error in Put events API", e); throw e; } } /*********** * This method to call put user APIs * @param userInfo */ private void putUsers(User userInfo) { try { PutUsersRequest putUsersRequest = new PutUsersRequest(); putUsersRequest.setUsers(Collections.singletonList(userInfo)); putUsersRequest.setDatasetArn(dataSetArn); client.putUsers(putUsersRequest); } catch (AmazonPersonalizeEventsException e) { log.error("Error in Put Users API", e); throw e; } } /******* * This method to call put item APIs * @param itemInfo */ private void putItems(Item itemInfo) { try { PutItemsRequest putItemsRequest = new PutItemsRequest(); putItemsRequest.setItems(Collections.singletonList(itemInfo)); putItemsRequest.setDatasetArn(dataSetArn); client.putItems(putItemsRequest); } catch (AmazonPersonalizeEventsException e) { log.error("Error in Put Items API", e); throw e; } } /******************* * This method is used to close AWS personalize client. */ public void closeQuietly() { client.shutdown(); } }
4,219
0
Create_ds/personalize-kafka-connector/src/main/java/com/aws
Create_ds/personalize-kafka-connector/src/main/java/com/aws/task/PersonlizeSinkTask.java
package com.aws.task; import com.amazonaws.ClientConfiguration; import com.amazonaws.retry.PredefinedRetryPolicies; import com.amazonaws.retry.RetryPolicy; import com.amazonaws.services.personalizeevents.AmazonPersonalizeEvents; import com.amazonaws.services.personalizeevents.AmazonPersonalizeEventsClient; import com.aws.util.Constants; import com.aws.util.Version; import com.aws.writer.DataWriter; import com.aws.config.PersonalizeSinkConfig; import org.apache.kafka.connect.sink.ErrantRecordReporter; import org.apache.kafka.connect.sink.SinkRecord; import org.apache.kafka.connect.sink.SinkTask; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.Collections; import java.util.Map; /**************** * This is main class which used for Sink Task functionality by overriding required methods. */ public class PersonlizeSinkTask extends SinkTask { private static final String USER_AGENT_PREFIX = "PersonalizeKafkaSinkConnector"; private static final Logger log = LoggerFactory.getLogger(PersonlizeSinkTask.class); ErrantRecordReporter reporter; PersonalizeSinkConfig config; DataWriter writer; int remainingRetries; @Override public String version() { return new Version().getVersion(); } @Override public void start(Map<String, String> props) { log.info("Starting Amazon Personalize Sink task"); config = new PersonalizeSinkConfig(props); initWriter(); remainingRetries = config.getMaxRetries(); try { reporter = context.errantRecordReporter(); } catch (NoSuchMethodError | NoClassDefFoundError e) { // Will occur in Connect runtimes earlier than 2.6 reporter = null; } } private void initWriter() { ClientConfiguration configuration = new ClientConfiguration() .withRetryPolicy(new RetryPolicy(PredefinedRetryPolicies.DEFAULT_RETRY_CONDITION, PredefinedRetryPolicies.DEFAULT_BACKOFF_STRATEGY,config.getMaxRetries(),true)) .withUserAgentPrefix(USER_AGENT_PREFIX) .withMaxErrorRetry(config.getMaxRetries()); AmazonPersonalizeEvents client = AmazonPersonalizeEventsClient.builder() .withCredentials(config.getCredentionalProvider()) .withRegion(null != config.getAwsRegionName() ? config.getAwsRegionName() : Constants.DEFAULT_AWS_REGION_NAME) .withClientConfiguration(configuration) .build(); writer = new DataWriter(config, client); } @Override public void put(Collection<SinkRecord> records) { if (records.isEmpty()) { return; } final SinkRecord first = records.iterator().next(); final int recordsCount = records.size(); try { writer.write(records); } catch (Exception ex) { if (reporter != null) { unrollAndRetry(records); } else { log.error("Error in writing data:", ex); } } } private void unrollAndRetry(Collection<SinkRecord> records) { int retryAttempts = remainingRetries; if (retryAttempts > 0) { writer.closeQuietly(); initWriter(); for (SinkRecord record : records) { try { writer.write(Collections.singletonList(record)); } catch (Exception ex) { reporter.report(record, ex); writer.closeQuietly(); } } retryAttempts--; } } @Override public void stop() { log.info("Stopping Amazon Personalize Sink task"); } }
4,220
0
Create_ds/personalize-kafka-connector/src/main/java/com/aws
Create_ds/personalize-kafka-connector/src/main/java/com/aws/connector/PersonalizeSinkConnector.java
package com.aws.connector; import com.aws.config.PersonalizeSinkConfig; import com.aws.task.PersonlizeSinkTask; import com.aws.util.Constants; import com.aws.util.Version; import org.apache.kafka.common.config.ConfigDef; import org.apache.kafka.connect.connector.Task; import org.apache.kafka.connect.sink.SinkConnector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /**************** * This is main class which used for Sink connector functionality by overriding required methods. */ public class PersonalizeSinkConnector extends SinkConnector { private static final Logger log = LoggerFactory.getLogger(PersonalizeSinkConnector.class); private Map<String, String> configProps; private PersonalizeSinkConfig config; @Override public void start(Map<String, String> props) { configProps = new HashMap<>(props); addRecordRateLimitConfiguration(configProps); config = new PersonalizeSinkConfig(props); log.info("Starting Personalize connector with name :", config.getName()); } private void addRecordRateLimitConfiguration(Map<String, String> configProps) { if (!configProps.containsKey(Constants.RECORD_RATE_LIMIT_PROPERTY_NAME)) { int maxTask = 1; if (configProps.containsKey(Constants.MAX_TASKS_PROPERTY_NAME)) { maxTask = Integer.parseInt(configProps.get(Constants.MAX_TASKS_PROPERTY_NAME)); } String dataType = configProps.get(Constants.AMAZON_PERSONALIZE_DATA_TYPE); if (null == dataType || dataType.equals(Constants.PUT_EVENTS_REQUEST_TYPE)) { configProps.put(Constants.RECORD_RATE_LIMIT_PROPERTY_NAME, String.valueOf(Constants.DEFAULT_VALUE_FOR_EVENT_RECORD_RATE / maxTask)); } else { configProps.put(Constants.RECORD_RATE_LIMIT_PROPERTY_NAME, String.valueOf(Constants.DEFAULT_VALUE_FOR_ITEM_AND_USER_RECORD_RATE / maxTask)); } } } @Override public Class<? extends Task> taskClass() { return PersonlizeSinkTask.class; } @Override public List<Map<String, String>> taskConfigs(int maxTasks) { log.info("Setting task configurations for {} workers.", maxTasks); final List<Map<String, String>> configs = new ArrayList<>(maxTasks); for (int i = 0; i < maxTasks; ++i) { configs.add(configProps); } return configs; } @Override public void stop() { log.info("Shutting Down Personalize Connector with name :" + config.getName()); } @Override public ConfigDef config() { return PersonalizeSinkConfig.CONFIG_DEF; } @Override public String version() { return new Version().getVersion(); } }
4,221
0
Create_ds/personalize-kafka-connector/src/main/java/com/aws
Create_ds/personalize-kafka-connector/src/main/java/com/aws/transform/CombineFieldsToJSONTransformation.java
package com.aws.transform; import org.apache.kafka.common.cache.Cache; import org.apache.kafka.common.cache.LRUCache; import org.apache.kafka.common.cache.SynchronizedCache; import org.apache.kafka.common.config.ConfigDef; import org.apache.kafka.common.config.ConfigException; import org.apache.kafka.connect.connector.ConnectRecord; import org.apache.kafka.connect.data.*; import org.apache.kafka.connect.transforms.Transformation; import org.apache.kafka.connect.transforms.util.SchemaUtil; import org.apache.kafka.connect.transforms.util.SimpleConfig; import org.jose4j.json.internal.json_simple.JSONObject; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.apache.kafka.connect.transforms.util.Requirements.requireMap; import static org.apache.kafka.connect.transforms.util.Requirements.requireStruct; /*********** * This is custom transformation used for constructing properties field value by including multiple fields in kafka records. * @param <R> */ public abstract class CombineFieldsToJSONTransformation <R extends ConnectRecord<R>> implements Transformation<R> { public static final String FIELDS_TO_INCLUDE = "fieldsToInclude"; public static final String TARGET_FIELD_NAME = "targetFieldName"; public static final String DEFAULT_FIELD_NAME = "properties"; public static final ConfigDef CONFIG_DEF = new ConfigDef() .define(FIELDS_TO_INCLUDE, ConfigDef.Type.LIST, Collections.emptyList(), ConfigDef.Importance.HIGH, "Fields to be included in transformation") .define(TARGET_FIELD_NAME, ConfigDef.Type.STRING, DEFAULT_FIELD_NAME, ConfigDef.Importance.MEDIUM, "Name of the transformed field"); private static final String PURPOSE = "Merge Properties Field"; private List<String> include; private String combinedFieldName; private Map<String, List<String>> mappedFieldMap; private Cache<Schema, Schema> schemaUpdateCache; @Override public void configure(Map<String, ?> configs){ final SimpleConfig config = new SimpleConfig(CONFIG_DEF, configs); include = config.getList(FIELDS_TO_INCLUDE); combinedFieldName = config.getString(TARGET_FIELD_NAME); if(null != include && include.isEmpty()) throw new ConfigException("Field List cant be empty"); mappedFieldMap = prepareMappedFieldMap(combinedFieldName, include); schemaUpdateCache = new SynchronizedCache<>(new LRUCache<>(16)); } private Map<String, List<String>> prepareMappedFieldMap(String combinedFieldName, List<String> include) { Map<String, List<String>> mappedFieldMap = new HashMap<>(); mappedFieldMap.put(combinedFieldName,include); return mappedFieldMap; } @Override public R apply(R record){ if (getValue(record) == null) { return record; } else if (getSchema(record) == null) { return processDataWithoutSchema(record); } else { return processDataWithSchema(record); } } private R processDataWithSchema(R record) { final Struct value = requireStruct(getValue(record), PURPOSE); Schema updatedSchema = schemaUpdateCache.get(value.schema()); if (updatedSchema == null) { updatedSchema = makeUpdatedSchema(value.schema()); schemaUpdateCache.put(value.schema(), updatedSchema); } final Struct updatedValue = new Struct(updatedSchema); for (Field field : updatedSchema.fields()) { if(field.name().equals(combinedFieldName)){ JSONObject jsonObject = new JSONObject(); for(String oldFieldName : mappedFieldMap.get(combinedFieldName)){ jsonObject.put(oldFieldName,value.get(oldFieldName)); } if(!jsonObject.isEmpty()) updatedValue.put(field.name(), jsonObject.toJSONString()); }else { final Object fieldValue = value.get(field.name()); updatedValue.put(field.name(), fieldValue); } } return createRecord(record, updatedSchema, updatedValue); } private R processDataWithoutSchema(R record) { final Map<String, Object> value = requireMap(getValue(record), PURPOSE); final Map<String, Object> updatedValue = new HashMap<>(value.size()); JSONObject jsonObject = new JSONObject(); for (Map.Entry<String, Object> e : value.entrySet()) { final String fieldName = e.getKey(); if(null != include && !include.isEmpty()){ if(include.contains(fieldName)){ jsonObject.put(fieldName, e.getValue()); }else{ updatedValue.put(fieldName,e.getValue()); } }else{ updatedValue.put(fieldName,e.getValue()); } } if(!jsonObject.isEmpty()) updatedValue.put(combinedFieldName, jsonObject.toJSONString()); return createRecord(record, null, updatedValue); } private Schema makeUpdatedSchema(Schema schema) { final SchemaBuilder builder = SchemaUtil.copySchemaBasics(schema, SchemaBuilder.struct()); boolean isCombinedFieldAdded = false; for (Field field : schema.fields()) { if (mappedFieldMap.get(combinedFieldName).contains(field.name())) { if(!isCombinedFieldAdded) { builder.field(combinedFieldName, new ConnectSchema(Schema.Type.STRING)); isCombinedFieldAdded= true; } }else { builder.field(field.name(), field.schema()); } } return builder.build(); } @Override public ConfigDef config() { return CONFIG_DEF; } @Override public void close() { schemaUpdateCache = null; } protected abstract Schema getSchema(R record); protected abstract Object getValue(R record); protected abstract R createRecord(R record, Schema updatedSchema, Object updatedValue); /************** * This class is used for Transformation of Key in Kafka record * @param <R> */ public static class Key<R extends ConnectRecord<R>> extends CombineFieldsToJSONTransformation<R> { @Override protected Schema getSchema(R record){ return record.keySchema(); } @Override protected Object getValue(R record) { return record.key(); } @Override protected R createRecord(R record, Schema updatedSchema, Object updatedValue) { return record.newRecord(record.topic(), record.kafkaPartition(), updatedSchema, updatedValue, record.valueSchema(), record.value(), record.timestamp()); } } /**************** * This class is used for Transformation of Value in Kafka record * @param <R> */ public static class Value<R extends ConnectRecord<R>> extends CombineFieldsToJSONTransformation<R> { @Override protected Schema getSchema(R record) { return record.valueSchema(); } @Override protected Object getValue(R record) { return record.value(); } @Override protected R createRecord(R record, Schema updatedSchema, Object updatedValue) { return record.newRecord(record.topic(), record.kafkaPartition(), record.keySchema(), record.key(), updatedSchema, updatedValue, record.timestamp()); } } }
4,222
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/encryption/NumberAttributeTestClass.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBIgnore; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Calendar; import java.util.Date; /** Simple domain class with numeric attributes */ @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public class NumberAttributeTestClass { private String key; private int intAttribute; private Integer integerAttribute; private double doubleAttribute; private Double doubleObjectAttribute; private float floatAttribute; private Float floatObjectAttribute; private BigDecimal bigDecimalAttribute; private BigInteger bigIntegerAttribute; private long longAttribute; private Long longObjectAttribute; private short shortAttribute; private Short shortObjectAttribute; private byte byteAttribute; private Byte byteObjectAttribute; private Date dateAttribute; private Calendar calendarAttribute; private Boolean booleanObjectAttribute; private boolean booleanAttribute; private String ignored = "notSent"; @DynamoDBAutoGeneratedKey @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } public int getIntAttribute() { return intAttribute; } public void setIntAttribute(int intAttribute) { this.intAttribute = intAttribute; } public Integer getIntegerAttribute() { return integerAttribute; } public void setIntegerAttribute(Integer integerAttribute) { this.integerAttribute = integerAttribute; } public double getDoubleAttribute() { return doubleAttribute; } public void setDoubleAttribute(double doubleAttribute) { this.doubleAttribute = doubleAttribute; } public Double getDoubleObjectAttribute() { return doubleObjectAttribute; } public void setDoubleObjectAttribute(Double doubleObjectAttribute) { this.doubleObjectAttribute = doubleObjectAttribute; } @DynamoDBAttribute public float getFloatAttribute() { return floatAttribute; } public void setFloatAttribute(float floatAttribute) { this.floatAttribute = floatAttribute; } public Float getFloatObjectAttribute() { return floatObjectAttribute; } public void setFloatObjectAttribute(Float floatObjectAttribute) { this.floatObjectAttribute = floatObjectAttribute; } public BigDecimal getBigDecimalAttribute() { return bigDecimalAttribute; } public void setBigDecimalAttribute(BigDecimal bigDecimalAttribute) { this.bigDecimalAttribute = bigDecimalAttribute; } public BigInteger getBigIntegerAttribute() { return bigIntegerAttribute; } public void setBigIntegerAttribute(BigInteger bigIntegerAttribute) { this.bigIntegerAttribute = bigIntegerAttribute; } public long getLongAttribute() { return longAttribute; } public void setLongAttribute(long longAttribute) { this.longAttribute = longAttribute; } public Long getLongObjectAttribute() { return longObjectAttribute; } public void setLongObjectAttribute(Long longObjectAttribute) { this.longObjectAttribute = longObjectAttribute; } public byte getByteAttribute() { return byteAttribute; } public void setByteAttribute(byte byteAttribute) { this.byteAttribute = byteAttribute; } public Byte getByteObjectAttribute() { return byteObjectAttribute; } public void setByteObjectAttribute(Byte byteObjectAttribute) { this.byteObjectAttribute = byteObjectAttribute; } public Date getDateAttribute() { return dateAttribute; } public void setDateAttribute(Date dateAttribute) { this.dateAttribute = dateAttribute; } public Calendar getCalendarAttribute() { return calendarAttribute; } public void setCalendarAttribute(Calendar calendarAttribute) { this.calendarAttribute = calendarAttribute; } public Boolean getBooleanObjectAttribute() { return booleanObjectAttribute; } public void setBooleanObjectAttribute(Boolean booleanObjectAttribute) { this.booleanObjectAttribute = booleanObjectAttribute; } public boolean isBooleanAttribute() { return booleanAttribute; } public void setBooleanAttribute(boolean booleanAttribute) { this.booleanAttribute = booleanAttribute; } @DynamoDBIgnore public String getIgnored() { return ignored; } public void setIgnored(String ignored) { this.ignored = ignored; } public short getShortAttribute() { return shortAttribute; } public void setShortAttribute(short shortAttribute) { this.shortAttribute = shortAttribute; } public Short getShortObjectAttribute() { return shortObjectAttribute; } public void setShortObjectAttribute(Short shortObjectAttribute) { this.shortObjectAttribute = shortObjectAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((bigDecimalAttribute == null) ? 0 : bigDecimalAttribute.hashCode()); result = prime * result + ((bigIntegerAttribute == null) ? 0 : bigIntegerAttribute.hashCode()); result = prime * result + (booleanAttribute ? 1231 : 1237); result = prime * result + ((booleanObjectAttribute == null) ? 0 : booleanObjectAttribute.hashCode()); result = prime * result + byteAttribute; result = prime * result + ((byteObjectAttribute == null) ? 0 : byteObjectAttribute.hashCode()); result = prime * result + ((calendarAttribute == null) ? 0 : calendarAttribute.hashCode()); result = prime * result + ((dateAttribute == null) ? 0 : dateAttribute.hashCode()); long temp; temp = Double.doubleToLongBits(doubleAttribute); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((doubleObjectAttribute == null) ? 0 : doubleObjectAttribute.hashCode()); result = prime * result + Float.floatToIntBits(floatAttribute); result = prime * result + ((floatObjectAttribute == null) ? 0 : floatObjectAttribute.hashCode()); result = prime * result + ((ignored == null) ? 0 : ignored.hashCode()); result = prime * result + intAttribute; result = prime * result + ((integerAttribute == null) ? 0 : integerAttribute.hashCode()); result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + (int) (longAttribute ^ (longAttribute >>> 32)); result = prime * result + ((longObjectAttribute == null) ? 0 : longObjectAttribute.hashCode()); result = prime * result + shortAttribute; result = prime * result + ((shortObjectAttribute == null) ? 0 : shortObjectAttribute.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NumberAttributeTestClass other = (NumberAttributeTestClass) obj; if (bigDecimalAttribute == null) { if (other.bigDecimalAttribute != null) return false; } else if (!bigDecimalAttribute.equals(other.bigDecimalAttribute)) return false; if (bigIntegerAttribute == null) { if (other.bigIntegerAttribute != null) return false; } else if (!bigIntegerAttribute.equals(other.bigIntegerAttribute)) return false; if (booleanAttribute != other.booleanAttribute) return false; if (booleanObjectAttribute == null) { if (other.booleanObjectAttribute != null) return false; } else if (!booleanObjectAttribute.equals(other.booleanObjectAttribute)) return false; if (byteAttribute != other.byteAttribute) return false; if (byteObjectAttribute == null) { if (other.byteObjectAttribute != null) return false; } else if (!byteObjectAttribute.equals(other.byteObjectAttribute)) return false; if (calendarAttribute == null) { if (other.calendarAttribute != null) return false; } else if (!calendarAttribute.equals(other.calendarAttribute)) return false; if (dateAttribute == null) { if (other.dateAttribute != null) return false; } else if (!dateAttribute.equals(other.dateAttribute)) return false; if (Double.doubleToLongBits(doubleAttribute) != Double.doubleToLongBits(other.doubleAttribute)) return false; if (doubleObjectAttribute == null) { if (other.doubleObjectAttribute != null) return false; } else if (!doubleObjectAttribute.equals(other.doubleObjectAttribute)) return false; if (Float.floatToIntBits(floatAttribute) != Float.floatToIntBits(other.floatAttribute)) return false; if (floatObjectAttribute == null) { if (other.floatObjectAttribute != null) return false; } else if (!floatObjectAttribute.equals(other.floatObjectAttribute)) return false; if (ignored == null) { if (other.ignored != null) return false; } else if (!ignored.equals(other.ignored)) return false; if (intAttribute != other.intAttribute) return false; if (integerAttribute == null) { if (other.integerAttribute != null) return false; } else if (!integerAttribute.equals(other.integerAttribute)) return false; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (longAttribute != other.longAttribute) return false; if (longObjectAttribute == null) { if (other.longObjectAttribute != null) return false; } else if (!longObjectAttribute.equals(other.longObjectAttribute)) return false; if (shortAttribute != other.shortAttribute) return false; if (shortObjectAttribute == null) { if (other.shortObjectAttribute != null) return false; } else if (!shortObjectAttribute.equals(other.shortObjectAttribute)) return false; return true; } }
4,223
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/encryption/BinaryAttributeByteBufferTestClass.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import java.nio.ByteBuffer; import java.util.Set; /** Test domain class with byteBuffer attribute, byteBuffer set and a string key */ @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public class BinaryAttributeByteBufferTestClass { private String key; private ByteBuffer binaryAttribute; private Set<ByteBuffer> binarySetAttribute; @DynamoDBHashKey(attributeName = "key") public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAttribute(attributeName = "binaryAttribute") public ByteBuffer getBinaryAttribute() { return binaryAttribute; } public void setBinaryAttribute(ByteBuffer binaryAttribute) { this.binaryAttribute = binaryAttribute; } @DynamoDBAttribute(attributeName = "binarySetAttribute") public Set<ByteBuffer> getBinarySetAttribute() { return binarySetAttribute; } public void setBinarySetAttribute(Set<ByteBuffer> binarySetAttribute) { this.binarySetAttribute = binarySetAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((binaryAttribute == null) ? 0 : binaryAttribute.hashCode()); result = prime * result + ((binarySetAttribute == null) ? 0 : binarySetAttribute.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BinaryAttributeByteBufferTestClass other = (BinaryAttributeByteBufferTestClass) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (binaryAttribute == null) { if (other.binaryAttribute != null) return false; } else if (!binaryAttribute.equals(other.binaryAttribute)) return false; if (binarySetAttribute == null) { if (other.binarySetAttribute != null) return false; } else if (!binarySetAttribute.equals(other.binarySetAttribute)) return false; return true; } }
4,224
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/encryption/RangeKeyTestClass.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBVersionAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotEncrypt; import java.math.BigDecimal; import java.util.Set; /** Comprehensive domain class */ @DynamoDBTable(tableName = "aws-java-sdk-range-test-crypto") public class RangeKeyTestClass { private long key; private double rangeKey; private Long version; private Set<Integer> integerSetAttribute; private Set<String> stringSetAttribute; private BigDecimal bigDecimalAttribute; private String stringAttribute; @DynamoDBHashKey public long getKey() { return key; } public void setKey(long key) { this.key = key; } @DynamoDBRangeKey public double getRangeKey() { return rangeKey; } public void setRangeKey(double rangeKey) { this.rangeKey = rangeKey; } @DynamoDBAttribute(attributeName = "integerSetAttribute") public Set<Integer> getIntegerAttribute() { return integerSetAttribute; } public void setIntegerAttribute(Set<Integer> integerAttribute) { this.integerSetAttribute = integerAttribute; } @DynamoDBAttribute public Set<String> getStringSetAttribute() { return stringSetAttribute; } public void setStringSetAttribute(Set<String> stringSetAttribute) { this.stringSetAttribute = stringSetAttribute; } @DoNotEncrypt @DynamoDBAttribute public BigDecimal getBigDecimalAttribute() { return bigDecimalAttribute; } public void setBigDecimalAttribute(BigDecimal bigDecimalAttribute) { this.bigDecimalAttribute = bigDecimalAttribute; } @DynamoDBAttribute public String getStringAttribute() { return stringAttribute; } public void setStringAttribute(String stringAttribute) { this.stringAttribute = stringAttribute; } @DoNotEncrypt @DynamoDBVersionAttribute public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((bigDecimalAttribute == null) ? 0 : bigDecimalAttribute.hashCode()); result = prime * result + ((integerSetAttribute == null) ? 0 : integerSetAttribute.hashCode()); result = prime * result + (int) (key ^ (key >>> 32)); long temp; temp = Double.doubleToLongBits(rangeKey); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((stringAttribute == null) ? 0 : stringAttribute.hashCode()); result = prime * result + ((stringSetAttribute == null) ? 0 : stringSetAttribute.hashCode()); result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RangeKeyTestClass other = (RangeKeyTestClass) obj; if (bigDecimalAttribute == null) { if (other.bigDecimalAttribute != null) return false; } else if (!bigDecimalAttribute.equals(other.bigDecimalAttribute)) return false; if (integerSetAttribute == null) { if (other.integerSetAttribute != null) return false; } else if (!integerSetAttribute.equals(other.integerSetAttribute)) return false; if (key != other.key) return false; if (Double.doubleToLongBits(rangeKey) != Double.doubleToLongBits(other.rangeKey)) return false; if (stringAttribute == null) { if (other.stringAttribute != null) return false; } else if (!stringAttribute.equals(other.stringAttribute)) return false; if (stringSetAttribute == null) { if (other.stringSetAttribute != null) return false; } else if (!stringSetAttribute.equals(other.stringSetAttribute)) return false; if (version == null) { if (other.version != null) return false; } else if (!version.equals(other.version)) return false; return true; } @Override public String toString() { return "RangeKeyTestClass [key=" + key + ", rangeKey=" + rangeKey + ", version=" + version + ", integerSetAttribute=" + integerSetAttribute + ", stringSetAttribute=" + stringSetAttribute + ", bigDecimalAttribute=" + bigDecimalAttribute + ", stringAttribute=" + stringAttribute + "]"; } }
4,225
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/encryption/NumberSetAttributeTestClass.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Calendar; import java.util.Date; import java.util.Set; /** Simple domain class with numeric attributes */ @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public class NumberSetAttributeTestClass { private String key; private Set<Integer> integerAttribute; private Set<Double> doubleObjectAttribute; private Set<Float> floatObjectAttribute; private Set<BigDecimal> bigDecimalAttribute; private Set<BigInteger> bigIntegerAttribute; private Set<Long> longObjectAttribute; private Set<Byte> byteObjectAttribute; private Set<Date> dateAttribute; private Set<Calendar> calendarAttribute; private Set<Boolean> booleanAttribute; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAttribute public Set<Integer> getIntegerAttribute() { return integerAttribute; } public void setIntegerAttribute(Set<Integer> integerAttribute) { this.integerAttribute = integerAttribute; } @DynamoDBAttribute public Set<Double> getDoubleObjectAttribute() { return doubleObjectAttribute; } public void setDoubleObjectAttribute(Set<Double> doubleObjectAttribute) { this.doubleObjectAttribute = doubleObjectAttribute; } @DynamoDBAttribute public Set<Float> getFloatObjectAttribute() { return floatObjectAttribute; } public void setFloatObjectAttribute(Set<Float> floatObjectAttribute) { this.floatObjectAttribute = floatObjectAttribute; } @DynamoDBAttribute public Set<BigDecimal> getBigDecimalAttribute() { return bigDecimalAttribute; } public void setBigDecimalAttribute(Set<BigDecimal> bigDecimalAttribute) { this.bigDecimalAttribute = bigDecimalAttribute; } @DynamoDBAttribute public Set<BigInteger> getBigIntegerAttribute() { return bigIntegerAttribute; } public void setBigIntegerAttribute(Set<BigInteger> bigIntegerAttribute) { this.bigIntegerAttribute = bigIntegerAttribute; } @DynamoDBAttribute public Set<Long> getLongObjectAttribute() { return longObjectAttribute; } public void setLongObjectAttribute(Set<Long> longObjectAttribute) { this.longObjectAttribute = longObjectAttribute; } @DynamoDBAttribute public Set<Byte> getByteObjectAttribute() { return byteObjectAttribute; } public void setByteObjectAttribute(Set<Byte> byteObjectAttribute) { this.byteObjectAttribute = byteObjectAttribute; } @DynamoDBAttribute public Set<Date> getDateAttribute() { return dateAttribute; } public void setDateAttribute(Set<Date> dateAttribute) { this.dateAttribute = dateAttribute; } @DynamoDBAttribute public Set<Calendar> getCalendarAttribute() { return calendarAttribute; } public void setCalendarAttribute(Set<Calendar> calendarAttribute) { this.calendarAttribute = calendarAttribute; } @DynamoDBAttribute public Set<Boolean> getBooleanAttribute() { return booleanAttribute; } public void setBooleanAttribute(Set<Boolean> booleanAttribute) { this.booleanAttribute = booleanAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((bigDecimalAttribute == null) ? 0 : bigDecimalAttribute.hashCode()); result = prime * result + ((bigIntegerAttribute == null) ? 0 : bigIntegerAttribute.hashCode()); result = prime * result + ((booleanAttribute == null) ? 0 : booleanAttribute.hashCode()); result = prime * result + ((byteObjectAttribute == null) ? 0 : byteObjectAttribute.hashCode()); result = prime * result + ((calendarAttribute == null) ? 0 : calendarAttribute.hashCode()); result = prime * result + ((dateAttribute == null) ? 0 : dateAttribute.hashCode()); result = prime * result + ((doubleObjectAttribute == null) ? 0 : doubleObjectAttribute.hashCode()); result = prime * result + ((floatObjectAttribute == null) ? 0 : floatObjectAttribute.hashCode()); result = prime * result + ((integerAttribute == null) ? 0 : integerAttribute.hashCode()); result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((longObjectAttribute == null) ? 0 : longObjectAttribute.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NumberSetAttributeTestClass other = (NumberSetAttributeTestClass) obj; if (bigDecimalAttribute == null) { if (other.bigDecimalAttribute != null) return false; } else if (!bigDecimalAttribute.equals(other.bigDecimalAttribute)) return false; if (bigIntegerAttribute == null) { if (other.bigIntegerAttribute != null) return false; } else if (!bigIntegerAttribute.equals(other.bigIntegerAttribute)) return false; if (booleanAttribute == null) { if (other.booleanAttribute != null) return false; } else if (!booleanAttribute.equals(other.booleanAttribute)) return false; if (byteObjectAttribute == null) { if (other.byteObjectAttribute != null) return false; } else if (!byteObjectAttribute.equals(other.byteObjectAttribute)) return false; if (calendarAttribute == null) { if (other.calendarAttribute != null) return false; } else if (!calendarAttribute.equals(other.calendarAttribute)) return false; if (dateAttribute == null) { if (other.dateAttribute != null) return false; } else if (!dateAttribute.equals(other.dateAttribute)) return false; if (doubleObjectAttribute == null) { if (other.doubleObjectAttribute != null) return false; } else if (!doubleObjectAttribute.equals(other.doubleObjectAttribute)) return false; if (floatObjectAttribute == null) { if (other.floatObjectAttribute != null) return false; } else if (!floatObjectAttribute.equals(other.floatObjectAttribute)) return false; if (integerAttribute == null) { if (other.integerAttribute != null) return false; } else if (!integerAttribute.equals(other.integerAttribute)) return false; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (longObjectAttribute == null) { if (other.longObjectAttribute != null) return false; } else if (!longObjectAttribute.equals(other.longObjectAttribute)) return false; return true; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "NumberSetAttributeTestClass [key=" + key; // + ", integerAttribute=" + integerAttribute // + ", doubleObjectAttribute=" + doubleObjectAttribute + ", // floatObjectAttribute=" + floatObjectAttribute // + ", bigDecimalAttribute=" + bigDecimalAttribute + ", bigIntegerAttribute=" + // bigIntegerAttribute // + ", longObjectAttribute=" + longObjectAttribute + ", byteObjectAttribute=" + // byteObjectAttribute // + ", dateAttribute=" + dateAttribute + ", calendarAttribute=" + // calendarAttribute // + ", booleanAttribute=" + booleanAttribute + "]"; } }
4,226
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/encryption/StringAttributeTestClass.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; /** Test domain class with a single string attribute and a string key */ @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public class StringAttributeTestClass { private String key; private String stringAttribute; private String renamedAttribute; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAttribute public String getStringAttribute() { return stringAttribute; } public void setStringAttribute(String stringAttribute) { this.stringAttribute = stringAttribute; } @DynamoDBAttribute(attributeName = "originalName") public String getRenamedAttribute() { return renamedAttribute; } public void setRenamedAttribute(String renamedAttribute) { this.renamedAttribute = renamedAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((renamedAttribute == null) ? 0 : renamedAttribute.hashCode()); result = prime * result + ((stringAttribute == null) ? 0 : stringAttribute.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; StringAttributeTestClass other = (StringAttributeTestClass) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (renamedAttribute == null) { if (other.renamedAttribute != null) return false; } else if (!renamedAttribute.equals(other.renamedAttribute)) return false; if (stringAttribute == null) { if (other.stringAttribute != null) return false; } else if (!stringAttribute.equals(other.stringAttribute)) return false; return true; } }
4,227
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/encryption/TestEncryptionMaterialsProvider.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.EncryptionMaterialsProvider; import com.amazonaws.util.StringMapBuilder; import java.security.Key; import java.util.Map; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class TestEncryptionMaterialsProvider implements EncryptionMaterialsProvider { private final EncryptionMaterials em = new EncryptionMaterials() { @Override public Map<String, String> getMaterialDescription() { return new StringMapBuilder("id", "test").build(); } @Override public SecretKey getEncryptionKey() { return new SecretKeySpec(new byte[32], "AES"); } @Override public Key getSigningKey() { return new SecretKeySpec(new byte[32], "HmacSHA256"); } }; private final DecryptionMaterials dm = new DecryptionMaterials() { @Override public Map<String, String> getMaterialDescription() { return new StringMapBuilder("id", "test").build(); } @Override public SecretKey getDecryptionKey() { return new SecretKeySpec(new byte[32], "AES"); } @Override public Key getVerificationKey() { return new SecretKeySpec(new byte[32], "HmacSHA256"); } }; @Override public DecryptionMaterials getDecryptionMaterials(EncryptionContext context) { return dm; } @Override public EncryptionMaterials getEncryptionMaterials(EncryptionContext context) { return em; } @Override public void refresh() {} }
4,228
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/encryption/TestDynamoDBMapperFactory.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.datamodeling.AttributeEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; public class TestDynamoDBMapperFactory { public static DynamoDBMapper createDynamoDBMapper(AmazonDynamoDB dynamo) { return new DynamoDBMapper( dynamo, DynamoDBMapperConfig.builder() .withSaveBehavior(DynamoDBMapperConfig.SaveBehavior.PUT) .build(), new AttributeEncryptor(new TestEncryptionMaterialsProvider())); } public static DynamoDBMapper createDynamoDBMapper( AmazonDynamoDB dynamo, DynamoDBMapperConfig config) { return new DynamoDBMapper( dynamo, config, new AttributeEncryptor(new TestEncryptionMaterialsProvider())); } }
4,229
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/encryption/MapperQueryExpressionCryptoTest.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBIndexHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBIndexRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.ComparisonOperator; import com.amazonaws.services.dynamodbv2.model.Condition; import com.amazonaws.services.dynamodbv2.model.QueryRequest; import com.amazonaws.util.ImmutableMapParameter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Unit test for the private method DynamoDBMapper#createQueryRequestFromExpression */ public class MapperQueryExpressionCryptoTest { private static final String TABLE_NAME = "table_name_crypto"; private static final Condition RANGE_KEY_CONDITION = new Condition() .withAttributeValueList(new AttributeValue("some value")) .withComparisonOperator(ComparisonOperator.EQ); private static DynamoDBMapper mapper; private static Method testedMethod; @BeforeClass public static void setUp() throws SecurityException, NoSuchMethodException { AmazonDynamoDB dynamo = new AmazonDynamoDBClient(); mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); testedMethod = DynamoDBMapper.class.getDeclaredMethod( "createQueryRequestFromExpression", Class.class, DynamoDBQueryExpression.class, DynamoDBMapperConfig.class); testedMethod.setAccessible(true); } @DynamoDBTable(tableName = TABLE_NAME) public final class HashOnlyClass { @DynamoDBHashKey @DynamoDBIndexHashKey(globalSecondaryIndexNames = "GSI-primary-hash") private String primaryHashKey; @DynamoDBIndexHashKey(globalSecondaryIndexNames = {"GSI-index-hash-1", "GSI-index-hash-2"}) private String indexHashKey; @DynamoDBIndexHashKey(globalSecondaryIndexNames = {"GSI-another-index-hash"}) private String anotherIndexHashKey; public HashOnlyClass(String primaryHashKey, String indexHashKey, String anotherIndexHashKey) { this.primaryHashKey = primaryHashKey; this.indexHashKey = indexHashKey; this.anotherIndexHashKey = anotherIndexHashKey; } public String getPrimaryHashKey() { return primaryHashKey; } public void setPrimaryHashKey(String primaryHashKey) { this.primaryHashKey = primaryHashKey; } public String getIndexHashKey() { return indexHashKey; } public void setIndexHashKey(String indexHashKey) { this.indexHashKey = indexHashKey; } public String getAnotherIndexHashKey() { return anotherIndexHashKey; } public void setAnotherIndexHashKey(String anotherIndexHashKey) { this.anotherIndexHashKey = anotherIndexHashKey; } } /** Tests different scenarios of hash-only query */ @Test public void testHashConditionOnly() { // Primary hash only QueryRequest queryRequest = testCreateQueryRequestFromExpression( HashOnlyClass.class, new DynamoDBQueryExpression<HashOnlyClass>() .withHashKeyValues(new HashOnlyClass("foo", null, null))); assertTrue(queryRequest.getKeyConditions().size() == 1); assertEquals("primaryHashKey", queryRequest.getKeyConditions().keySet().iterator().next()); assertEquals( new Condition() .withAttributeValueList(new AttributeValue("foo")) .withComparisonOperator(ComparisonOperator.EQ), queryRequest.getKeyConditions().get("primaryHashKey")); assertNull(queryRequest.getIndexName()); // Primary hash used for a GSI queryRequest = testCreateQueryRequestFromExpression( HashOnlyClass.class, new DynamoDBQueryExpression<HashOnlyClass>() .withHashKeyValues(new HashOnlyClass("foo", null, null)) .withIndexName("GSI-primary-hash")); assertTrue(queryRequest.getKeyConditions().size() == 1); assertEquals("primaryHashKey", queryRequest.getKeyConditions().keySet().iterator().next()); assertEquals( new Condition() .withAttributeValueList(new AttributeValue("foo")) .withComparisonOperator(ComparisonOperator.EQ), queryRequest.getKeyConditions().get("primaryHashKey")); assertEquals("GSI-primary-hash", queryRequest.getIndexName()); // Primary hash query takes higher priority then index hash query queryRequest = testCreateQueryRequestFromExpression( HashOnlyClass.class, new DynamoDBQueryExpression<HashOnlyClass>() .withHashKeyValues(new HashOnlyClass("foo", "bar", null))); assertTrue(queryRequest.getKeyConditions().size() == 1); assertEquals("primaryHashKey", queryRequest.getKeyConditions().keySet().iterator().next()); assertEquals( new Condition() .withAttributeValueList(new AttributeValue("foo")) .withComparisonOperator(ComparisonOperator.EQ), queryRequest.getKeyConditions().get("primaryHashKey")); assertNull(queryRequest.getIndexName()); // Ambiguous query on multiple index hash keys queryRequest = testCreateQueryRequestFromExpression( HashOnlyClass.class, new DynamoDBQueryExpression<HashOnlyClass>() .withHashKeyValues(new HashOnlyClass(null, "bar", "charlie")), "Ambiguous query expression: More than one index hash key EQ conditions"); // Ambiguous query when not specifying index name queryRequest = testCreateQueryRequestFromExpression( HashOnlyClass.class, new DynamoDBQueryExpression<HashOnlyClass>() .withHashKeyValues(new HashOnlyClass(null, "bar", null)), "Ambiguous query expression: More than one GSIs"); // Explicitly specify a GSI. queryRequest = testCreateQueryRequestFromExpression( HashOnlyClass.class, new DynamoDBQueryExpression<HashOnlyClass>() .withHashKeyValues(new HashOnlyClass("foo", "bar", null)) .withIndexName("GSI-index-hash-1")); assertTrue(queryRequest.getKeyConditions().size() == 1); assertEquals("indexHashKey", queryRequest.getKeyConditions().keySet().iterator().next()); assertEquals( new Condition() .withAttributeValueList(new AttributeValue("bar")) .withComparisonOperator(ComparisonOperator.EQ), queryRequest.getKeyConditions().get("indexHashKey")); assertEquals("GSI-index-hash-1", queryRequest.getIndexName()); // Non-existent GSI queryRequest = testCreateQueryRequestFromExpression( HashOnlyClass.class, new DynamoDBQueryExpression<HashOnlyClass>() .withHashKeyValues(new HashOnlyClass("foo", "bar", null)) .withIndexName("some fake gsi"), "No hash key condition is applicable to the specified index"); // No hash key condition specified queryRequest = testCreateQueryRequestFromExpression( HashOnlyClass.class, new DynamoDBQueryExpression<HashOnlyClass>() .withHashKeyValues(new HashOnlyClass(null, null, null)), "Illegal query expression: No hash key condition is found in the query"); } @DynamoDBTable(tableName = TABLE_NAME) public final class HashRangeClass { private String primaryHashKey; private String indexHashKey; private String primaryRangeKey; private String indexRangeKey; private String anotherIndexRangeKey; public HashRangeClass(String primaryHashKey, String indexHashKey) { this.primaryHashKey = primaryHashKey; this.indexHashKey = indexHashKey; } @DynamoDBHashKey @DynamoDBIndexHashKey( globalSecondaryIndexNames = { "GSI-primary-hash-index-range-1", "GSI-primary-hash-index-range-2" }) public String getPrimaryHashKey() { return primaryHashKey; } public void setPrimaryHashKey(String primaryHashKey) { this.primaryHashKey = primaryHashKey; } @DynamoDBIndexHashKey( globalSecondaryIndexNames = { "GSI-index-hash-primary-range", "GSI-index-hash-index-range-1", "GSI-index-hash-index-range-2" }) public String getIndexHashKey() { return indexHashKey; } public void setIndexHashKey(String indexHashKey) { this.indexHashKey = indexHashKey; } @DynamoDBRangeKey @DynamoDBIndexRangeKey( globalSecondaryIndexNames = {"GSI-index-hash-primary-range"}, localSecondaryIndexName = "LSI-primary-range") public String getPrimaryRangeKey() { return primaryRangeKey; } public void setPrimaryRangeKey(String primaryRangeKey) { this.primaryRangeKey = primaryRangeKey; } @DynamoDBIndexRangeKey( globalSecondaryIndexNames = { "GSI-primary-hash-index-range-1", "GSI-index-hash-index-range-1", "GSI-index-hash-index-range-2" }, localSecondaryIndexNames = {"LSI-index-range-1", "LSI-index-range-2"}) public String getIndexRangeKey() { return indexRangeKey; } public void setIndexRangeKey(String indexRangeKey) { this.indexRangeKey = indexRangeKey; } @DynamoDBIndexRangeKey( localSecondaryIndexName = "LSI-index-range-3", globalSecondaryIndexName = "GSI-primary-hash-index-range-2") public String getAnotherIndexRangeKey() { return anotherIndexRangeKey; } public void setAnotherIndexRangeKey(String anotherIndexRangeKey) { this.anotherIndexRangeKey = anotherIndexRangeKey; } } /** Tests hash + range query */ @Test public void testHashAndRangeCondition() { // Primary hash + primary range QueryRequest queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass("foo", null)) .withRangeKeyCondition("primaryRangeKey", RANGE_KEY_CONDITION)); assertTrue(queryRequest.getKeyConditions().size() == 2); assertTrue(queryRequest.getKeyConditions().containsKey("primaryHashKey")); assertEquals( new Condition() .withAttributeValueList(new AttributeValue("foo")) .withComparisonOperator(ComparisonOperator.EQ), queryRequest.getKeyConditions().get("primaryHashKey")); assertTrue(queryRequest.getKeyConditions().containsKey("primaryRangeKey")); assertEquals(RANGE_KEY_CONDITION, queryRequest.getKeyConditions().get("primaryRangeKey")); assertNull(queryRequest.getIndexName()); // Primary hash + primary range on a LSI queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass("foo", null)) .withRangeKeyCondition("primaryRangeKey", RANGE_KEY_CONDITION) .withIndexName("LSI-primary-range")); assertTrue(queryRequest.getKeyConditions().size() == 2); assertTrue(queryRequest.getKeyConditions().containsKey("primaryHashKey")); assertEquals( new Condition() .withAttributeValueList(new AttributeValue("foo")) .withComparisonOperator(ComparisonOperator.EQ), queryRequest.getKeyConditions().get("primaryHashKey")); assertTrue(queryRequest.getKeyConditions().containsKey("primaryRangeKey")); assertEquals(RANGE_KEY_CONDITION, queryRequest.getKeyConditions().get("primaryRangeKey")); assertEquals("LSI-primary-range", queryRequest.getIndexName()); // Primary hash + index range used by multiple LSI. But also a GSI hash + range queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass("foo", null)) .withRangeKeyCondition("indexRangeKey", RANGE_KEY_CONDITION)); assertTrue(queryRequest.getKeyConditions().size() == 2); assertTrue(queryRequest.getKeyConditions().containsKey("primaryHashKey")); assertEquals( new Condition() .withAttributeValueList(new AttributeValue("foo")) .withComparisonOperator(ComparisonOperator.EQ), queryRequest.getKeyConditions().get("primaryHashKey")); assertTrue(queryRequest.getKeyConditions().containsKey("indexRangeKey")); assertEquals(RANGE_KEY_CONDITION, queryRequest.getKeyConditions().get("indexRangeKey")); assertEquals("GSI-primary-hash-index-range-1", queryRequest.getIndexName()); // Primary hash + index range on a LSI queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass("foo", null)) .withRangeKeyCondition("indexRangeKey", RANGE_KEY_CONDITION) .withIndexName("LSI-index-range-1")); assertTrue(queryRequest.getKeyConditions().size() == 2); assertTrue(queryRequest.getKeyConditions().containsKey("primaryHashKey")); assertEquals( new Condition() .withAttributeValueList(new AttributeValue("foo")) .withComparisonOperator(ComparisonOperator.EQ), queryRequest.getKeyConditions().get("primaryHashKey")); assertTrue(queryRequest.getKeyConditions().containsKey("indexRangeKey")); assertEquals(RANGE_KEY_CONDITION, queryRequest.getKeyConditions().get("indexRangeKey")); assertEquals("LSI-index-range-1", queryRequest.getIndexName()); // Non-existent LSI queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass("foo", null)) .withRangeKeyCondition("indexRangeKey", RANGE_KEY_CONDITION) .withIndexName("some fake lsi"), "No range key condition is applicable to the specified index"); // Illegal query: Primary hash + primary range on a GSI queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass("foo", null)) .withRangeKeyCondition("indexRangeKey", RANGE_KEY_CONDITION) .withIndexName("GSI-index-hash-index-range-1"), "Illegal query expression: No hash key condition is applicable to the specified index"); // GSI hash + GSI range queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass(null, "foo")) .withRangeKeyCondition("primaryRangeKey", RANGE_KEY_CONDITION)); assertTrue(queryRequest.getKeyConditions().size() == 2); assertTrue(queryRequest.getKeyConditions().containsKey("indexHashKey")); assertEquals( new Condition() .withAttributeValueList(new AttributeValue("foo")) .withComparisonOperator(ComparisonOperator.EQ), queryRequest.getKeyConditions().get("indexHashKey")); assertTrue(queryRequest.getKeyConditions().containsKey("primaryRangeKey")); assertEquals(RANGE_KEY_CONDITION, queryRequest.getKeyConditions().get("primaryRangeKey")); assertEquals("GSI-index-hash-primary-range", queryRequest.getIndexName()); // Ambiguous query: GSI hash + index range used by multiple GSIs queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass(null, "foo")) .withRangeKeyCondition("indexRangeKey", RANGE_KEY_CONDITION), "Illegal query expression: Cannot infer the index name from the query expression."); // Explicitly specify the GSI name queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass(null, "foo")) .withRangeKeyCondition("indexRangeKey", RANGE_KEY_CONDITION) .withIndexName("GSI-index-hash-index-range-2")); assertTrue(queryRequest.getKeyConditions().size() == 2); assertTrue(queryRequest.getKeyConditions().containsKey("indexHashKey")); assertEquals( new Condition() .withAttributeValueList(new AttributeValue("foo")) .withComparisonOperator(ComparisonOperator.EQ), queryRequest.getKeyConditions().get("indexHashKey")); assertTrue(queryRequest.getKeyConditions().containsKey("indexRangeKey")); assertEquals(RANGE_KEY_CONDITION, queryRequest.getKeyConditions().get("indexRangeKey")); assertEquals("GSI-index-hash-index-range-2", queryRequest.getIndexName()); // Ambiguous query: (1) primary hash + LSI range OR (2) GSI hash + range queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass("foo", null)) .withRangeKeyCondition("anotherIndexRangeKey", RANGE_KEY_CONDITION), "Ambiguous query expression: Found multiple valid queries:"); // Multiple range key conditions specified queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass("foo", null)) .withRangeKeyConditions( ImmutableMapParameter.of( "primaryRangeKey", RANGE_KEY_CONDITION, "indexRangeKey", RANGE_KEY_CONDITION)), "Illegal query expression: Conditions on multiple range keys"); // Using an un-annotated range key queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass("foo", null)) .withRangeKeyCondition("indexHashKey", RANGE_KEY_CONDITION), "not annotated with either @DynamoDBRangeKey or @DynamoDBIndexRangeKey."); } @DynamoDBTable(tableName = TABLE_NAME) public final class LSIRangeKeyTestClass { private String primaryHashKey; private String primaryRangeKey; private String lsiRangeKey; public LSIRangeKeyTestClass(String primaryHashKey, String primaryRangeKey) { this.primaryHashKey = primaryHashKey; this.primaryRangeKey = primaryRangeKey; } @DynamoDBHashKey public String getPrimaryHashKey() { return primaryHashKey; } public void setPrimaryHashKey(String primaryHashKey) { this.primaryHashKey = primaryHashKey; } @DynamoDBRangeKey public String getPrimaryRangeKey() { return primaryRangeKey; } public void setPrimaryRangeKey(String primaryRangeKey) { this.primaryRangeKey = primaryRangeKey; } @DynamoDBIndexRangeKey(localSecondaryIndexName = "LSI") public String getLsiRangeKey() { return lsiRangeKey; } public void setLsiRangeKey(String lsiRangeKey) { this.lsiRangeKey = lsiRangeKey; } } @Test public void testHashOnlyQueryOnHashRangeTable() { // Primary hash only query on a Hash+Range table QueryRequest queryRequest = testCreateQueryRequestFromExpression( LSIRangeKeyTestClass.class, new DynamoDBQueryExpression<LSIRangeKeyTestClass>() .withHashKeyValues(new LSIRangeKeyTestClass("foo", null))); assertTrue(queryRequest.getKeyConditions().size() == 1); assertTrue(queryRequest.getKeyConditions().containsKey("primaryHashKey")); assertNull(queryRequest.getIndexName()); // Hash+Range query on a LSI queryRequest = testCreateQueryRequestFromExpression( LSIRangeKeyTestClass.class, new DynamoDBQueryExpression<LSIRangeKeyTestClass>() .withHashKeyValues(new LSIRangeKeyTestClass("foo", null)) .withRangeKeyCondition("lsiRangeKey", RANGE_KEY_CONDITION) .withIndexName("LSI")); assertTrue(queryRequest.getKeyConditions().size() == 2); assertTrue(queryRequest.getKeyConditions().containsKey("primaryHashKey")); assertTrue(queryRequest.getKeyConditions().containsKey("lsiRangeKey")); assertEquals("LSI", queryRequest.getIndexName()); // Hash-only query on a LSI queryRequest = testCreateQueryRequestFromExpression( LSIRangeKeyTestClass.class, new DynamoDBQueryExpression<LSIRangeKeyTestClass>() .withHashKeyValues(new LSIRangeKeyTestClass("foo", null)) .withIndexName("LSI")); assertTrue(queryRequest.getKeyConditions().size() == 1); assertTrue(queryRequest.getKeyConditions().containsKey("primaryHashKey")); assertEquals("LSI", queryRequest.getIndexName()); } private static <T> QueryRequest testCreateQueryRequestFromExpression( Class<T> clazz, DynamoDBQueryExpression<T> queryExpression) { return testCreateQueryRequestFromExpression(clazz, queryExpression, null); } private static <T> QueryRequest testCreateQueryRequestFromExpression( Class<T> clazz, DynamoDBQueryExpression<T> queryExpression, String expectedErrorMessage) { try { QueryRequest request = (QueryRequest) testedMethod.invoke(mapper, clazz, queryExpression, DynamoDBMapperConfig.DEFAULT); if (expectedErrorMessage != null) { fail("Exception containing messsage (" + expectedErrorMessage + ") is expected."); } return request; } catch (InvocationTargetException ite) { if (expectedErrorMessage != null) { assertTrue( "Exception message [" + ite.getCause().getMessage() + "] does not contain " + "the expected message [" + expectedErrorMessage + "].", ite.getCause().getMessage().contains(expectedErrorMessage)); } else { ite.getCause().printStackTrace(); fail("Internal error when calling createQueryRequestFromExpressio method"); } } catch (Exception e) { fail(e.getMessage()); } return null; } }
4,230
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/encryption/CrossSDKVerificationTestClass.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBVersionAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotEncrypt; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Calendar; import java.util.Date; import java.util.Set; /** Exhaustive exercise of DynamoDB domain mapping, exercising every supported data type. */ @DynamoDBTable(tableName = "aws-xsdk-crypto") public class CrossSDKVerificationTestClass { private String key; private String rangeKey; private Long version; private String lastUpdater; private Integer integerAttribute; private Long longAttribute; private Double doubleAttribute; private Float floatAttribute; private BigDecimal bigDecimalAttribute; private BigInteger bigIntegerAttribute; private Byte byteAttribute; private Date dateAttribute; private Calendar calendarAttribute; private Boolean booleanAttribute; private Set<String> stringSetAttribute; private Set<Integer> integerSetAttribute; private Set<Double> doubleSetAttribute; private Set<Float> floatSetAttribute; private Set<BigDecimal> bigDecimalSetAttribute; private Set<BigInteger> bigIntegerSetAttribute; private Set<Long> longSetAttribute; private Set<Byte> byteSetAttribute; private Set<Date> dateSetAttribute; private Set<Calendar> calendarSetAttribute; // these are kind of pointless, but here for completeness private Set<Boolean> booleanSetAttribute; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBRangeKey public String getRangeKey() { return rangeKey; } public void setRangeKey(String rangeKey) { this.rangeKey = rangeKey; } @DoNotEncrypt @DynamoDBVersionAttribute public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } public String getLastUpdater() { return lastUpdater; } public void setLastUpdater(String lastUpdater) { this.lastUpdater = lastUpdater; } public Integer getIntegerAttribute() { return integerAttribute; } public void setIntegerAttribute(Integer integerAttribute) { this.integerAttribute = integerAttribute; } public Long getLongAttribute() { return longAttribute; } public void setLongAttribute(Long longAttribute) { this.longAttribute = longAttribute; } public Double getDoubleAttribute() { return doubleAttribute; } public void setDoubleAttribute(Double doubleAttribute) { this.doubleAttribute = doubleAttribute; } public Float getFloatAttribute() { return floatAttribute; } public void setFloatAttribute(Float floatAttribute) { this.floatAttribute = floatAttribute; } public BigDecimal getBigDecimalAttribute() { return bigDecimalAttribute; } public void setBigDecimalAttribute(BigDecimal bigDecimalAttribute) { this.bigDecimalAttribute = bigDecimalAttribute; } public BigInteger getBigIntegerAttribute() { return bigIntegerAttribute; } public void setBigIntegerAttribute(BigInteger bigIntegerAttribute) { this.bigIntegerAttribute = bigIntegerAttribute; } public Byte getByteAttribute() { return byteAttribute; } public void setByteAttribute(Byte byteAttribute) { this.byteAttribute = byteAttribute; } public Date getDateAttribute() { return dateAttribute; } public void setDateAttribute(Date dateAttribute) { this.dateAttribute = dateAttribute; } public Calendar getCalendarAttribute() { return calendarAttribute; } public void setCalendarAttribute(Calendar calendarAttribute) { this.calendarAttribute = calendarAttribute; } public Boolean getBooleanAttribute() { return booleanAttribute; } public void setBooleanAttribute(Boolean booleanAttribute) { this.booleanAttribute = booleanAttribute; } public Set<Integer> getIntegerSetAttribute() { return integerSetAttribute; } public void setIntegerSetAttribute(Set<Integer> integerSetAttribute) { this.integerSetAttribute = integerSetAttribute; } public Set<Double> getDoubleSetAttribute() { return doubleSetAttribute; } public void setDoubleSetAttribute(Set<Double> doubleSetAttribute) { this.doubleSetAttribute = doubleSetAttribute; } public Set<Float> getFloatSetAttribute() { return floatSetAttribute; } public void setFloatSetAttribute(Set<Float> floatSetAttribute) { this.floatSetAttribute = floatSetAttribute; } public Set<BigDecimal> getBigDecimalSetAttribute() { return bigDecimalSetAttribute; } public void setBigDecimalSetAttribute(Set<BigDecimal> bigDecimalSetAttribute) { this.bigDecimalSetAttribute = bigDecimalSetAttribute; } public Set<BigInteger> getBigIntegerSetAttribute() { return bigIntegerSetAttribute; } public void setBigIntegerSetAttribute(Set<BigInteger> bigIntegerSetAttribute) { this.bigIntegerSetAttribute = bigIntegerSetAttribute; } public Set<Long> getLongSetAttribute() { return longSetAttribute; } public void setLongSetAttribute(Set<Long> longSetAttribute) { this.longSetAttribute = longSetAttribute; } public Set<Byte> getByteSetAttribute() { return byteSetAttribute; } public void setByteSetAttribute(Set<Byte> byteSetAttribute) { this.byteSetAttribute = byteSetAttribute; } public Set<Date> getDateSetAttribute() { return dateSetAttribute; } public void setDateSetAttribute(Set<Date> dateSetAttribute) { this.dateSetAttribute = dateSetAttribute; } public Set<Calendar> getCalendarSetAttribute() { return calendarSetAttribute; } public void setCalendarSetAttribute(Set<Calendar> calendarSetAttribute) { this.calendarSetAttribute = calendarSetAttribute; } public Set<Boolean> getBooleanSetAttribute() { return booleanSetAttribute; } public void setBooleanSetAttribute(Set<Boolean> booleanSetAttribute) { this.booleanSetAttribute = booleanSetAttribute; } public Set<String> getStringSetAttribute() { return stringSetAttribute; } public void setStringSetAttribute(Set<String> stringSetAttribute) { this.stringSetAttribute = stringSetAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((bigDecimalAttribute == null) ? 0 : bigDecimalAttribute.hashCode()); result = prime * result + ((bigDecimalSetAttribute == null) ? 0 : bigDecimalSetAttribute.hashCode()); result = prime * result + ((bigIntegerAttribute == null) ? 0 : bigIntegerAttribute.hashCode()); result = prime * result + ((bigIntegerSetAttribute == null) ? 0 : bigIntegerSetAttribute.hashCode()); result = prime * result + ((booleanAttribute == null) ? 0 : booleanAttribute.hashCode()); result = prime * result + ((booleanSetAttribute == null) ? 0 : booleanSetAttribute.hashCode()); result = prime * result + ((byteAttribute == null) ? 0 : byteAttribute.hashCode()); result = prime * result + ((byteSetAttribute == null) ? 0 : byteSetAttribute.hashCode()); result = prime * result + ((calendarAttribute == null) ? 0 : calendarAttribute.hashCode()); result = prime * result + ((calendarSetAttribute == null) ? 0 : calendarSetAttribute.hashCode()); result = prime * result + ((dateAttribute == null) ? 0 : dateAttribute.hashCode()); result = prime * result + ((dateSetAttribute == null) ? 0 : dateSetAttribute.hashCode()); result = prime * result + ((doubleAttribute == null) ? 0 : doubleAttribute.hashCode()); result = prime * result + ((doubleSetAttribute == null) ? 0 : doubleSetAttribute.hashCode()); result = prime * result + ((floatAttribute == null) ? 0 : floatAttribute.hashCode()); result = prime * result + ((floatSetAttribute == null) ? 0 : floatSetAttribute.hashCode()); result = prime * result + ((integerAttribute == null) ? 0 : integerAttribute.hashCode()); result = prime * result + ((integerSetAttribute == null) ? 0 : integerSetAttribute.hashCode()); result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((lastUpdater == null) ? 0 : lastUpdater.hashCode()); result = prime * result + ((longAttribute == null) ? 0 : longAttribute.hashCode()); result = prime * result + ((longSetAttribute == null) ? 0 : longSetAttribute.hashCode()); result = prime * result + ((rangeKey == null) ? 0 : rangeKey.hashCode()); result = prime * result + ((stringSetAttribute == null) ? 0 : stringSetAttribute.hashCode()); result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CrossSDKVerificationTestClass other = (CrossSDKVerificationTestClass) obj; if (bigDecimalAttribute == null) { if (other.bigDecimalAttribute != null) return false; } else if (!bigDecimalAttribute.equals(other.bigDecimalAttribute)) return false; if (bigDecimalSetAttribute == null) { if (other.bigDecimalSetAttribute != null) return false; } else if (!bigDecimalSetAttribute.equals(other.bigDecimalSetAttribute)) return false; if (bigIntegerAttribute == null) { if (other.bigIntegerAttribute != null) return false; } else if (!bigIntegerAttribute.equals(other.bigIntegerAttribute)) return false; if (bigIntegerSetAttribute == null) { if (other.bigIntegerSetAttribute != null) return false; } else if (!bigIntegerSetAttribute.equals(other.bigIntegerSetAttribute)) return false; if (booleanAttribute == null) { if (other.booleanAttribute != null) return false; } else if (!booleanAttribute.equals(other.booleanAttribute)) return false; if (booleanSetAttribute == null) { if (other.booleanSetAttribute != null) return false; } else if (!booleanSetAttribute.equals(other.booleanSetAttribute)) return false; if (byteAttribute == null) { if (other.byteAttribute != null) return false; } else if (!byteAttribute.equals(other.byteAttribute)) return false; if (byteSetAttribute == null) { if (other.byteSetAttribute != null) return false; } else if (!byteSetAttribute.equals(other.byteSetAttribute)) return false; if (calendarAttribute == null) { if (other.calendarAttribute != null) return false; } else if (!calendarAttribute.equals(other.calendarAttribute)) return false; if (calendarSetAttribute == null) { if (other.calendarSetAttribute != null) return false; } else if (!calendarSetAttribute.equals(other.calendarSetAttribute)) return false; if (dateAttribute == null) { if (other.dateAttribute != null) return false; } else if (!dateAttribute.equals(other.dateAttribute)) return false; if (dateSetAttribute == null) { if (other.dateSetAttribute != null) return false; } else if (!dateSetAttribute.equals(other.dateSetAttribute)) return false; if (doubleAttribute == null) { if (other.doubleAttribute != null) return false; } else if (!doubleAttribute.equals(other.doubleAttribute)) return false; if (doubleSetAttribute == null) { if (other.doubleSetAttribute != null) return false; } else if (!doubleSetAttribute.equals(other.doubleSetAttribute)) return false; if (floatAttribute == null) { if (other.floatAttribute != null) return false; } else if (!floatAttribute.equals(other.floatAttribute)) return false; if (floatSetAttribute == null) { if (other.floatSetAttribute != null) return false; } else if (!floatSetAttribute.equals(other.floatSetAttribute)) return false; if (integerAttribute == null) { if (other.integerAttribute != null) return false; } else if (!integerAttribute.equals(other.integerAttribute)) return false; if (integerSetAttribute == null) { if (other.integerSetAttribute != null) return false; } else if (!integerSetAttribute.equals(other.integerSetAttribute)) return false; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (lastUpdater == null) { if (other.lastUpdater != null) return false; } else if (!lastUpdater.equals(other.lastUpdater)) return false; if (longAttribute == null) { if (other.longAttribute != null) return false; } else if (!longAttribute.equals(other.longAttribute)) return false; if (longSetAttribute == null) { if (other.longSetAttribute != null) return false; } else if (!longSetAttribute.equals(other.longSetAttribute)) return false; if (rangeKey == null) { if (other.rangeKey != null) return false; } else if (!rangeKey.equals(other.rangeKey)) return false; if (stringSetAttribute == null) { if (other.stringSetAttribute != null) return false; } else if (!stringSetAttribute.equals(other.stringSetAttribute)) return false; if (version == null) { if (other.version != null) return false; } else if (!version.equals(other.version)) return false; return true; } }
4,231
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/encryption/StringSetAttributeTestClass.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import java.util.Set; /** Test domain class with a string set attribute and a string key */ @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public class StringSetAttributeTestClass { private String key; private Set<String> stringSetAttribute; private Set<String> StringSetAttributeRenamed; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAttribute public Set<String> getStringSetAttribute() { return stringSetAttribute; } public void setStringSetAttribute(Set<String> stringSetAttribute) { this.stringSetAttribute = stringSetAttribute; } @DynamoDBAttribute(attributeName = "originalName") public Set<String> getStringSetAttributeRenamed() { return StringSetAttributeRenamed; } public void setStringSetAttributeRenamed(Set<String> stringSetAttributeRenamed) { StringSetAttributeRenamed = stringSetAttributeRenamed; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((StringSetAttributeRenamed == null) ? 0 : StringSetAttributeRenamed.hashCode()); result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((stringSetAttribute == null) ? 0 : stringSetAttribute.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; StringSetAttributeTestClass other = (StringSetAttributeTestClass) obj; if (StringSetAttributeRenamed == null) { if (other.StringSetAttributeRenamed != null) return false; } else if (!StringSetAttributeRenamed.equals(other.StringSetAttributeRenamed)) return false; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (stringSetAttribute == null) { if (other.stringSetAttribute != null) return false; } else if (!stringSetAttribute.equals(other.stringSetAttribute)) return false; return true; } }
4,232
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/encryption/NoSuchTableTestClass.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; @DynamoDBTable(tableName = "tableNotExist") public class NoSuchTableTestClass { private String key; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } }
4,233
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/encryption/BinaryAttributeByteArrayTestClass.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import java.util.Set; /** Test domain class with byte[] attribute, byte[] set and a string key */ @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public class BinaryAttributeByteArrayTestClass { private String key; private byte[] binaryAttribute; private Set<byte[]> binarySetAttribute; @DynamoDBHashKey(attributeName = "key") public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAttribute(attributeName = "binaryAttribute") public byte[] getBinaryAttribute() { return binaryAttribute; } public void setBinaryAttribute(byte[] binaryAttribute) { this.binaryAttribute = binaryAttribute; } @DynamoDBAttribute(attributeName = "binarySetAttribute") public Set<byte[]> getBinarySetAttribute() { return binarySetAttribute; } public void setBinarySetAttribute(Set<byte[]> binarySetAttribute) { this.binarySetAttribute = binarySetAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((binaryAttribute == null) ? 0 : binaryAttribute.hashCode()); result = prime * result + ((binarySetAttribute == null) ? 0 : binarySetAttribute.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BinaryAttributeByteArrayTestClass other = (BinaryAttributeByteArrayTestClass) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (binaryAttribute == null) { if (other.binaryAttribute != null) return false; } else if (!binaryAttribute.equals(other.binaryAttribute)) return false; if (binarySetAttribute == null) { if (other.binarySetAttribute != null) return false; } else if (!binarySetAttribute.equals(other.binarySetAttribute)) return false; return true; } }
4,234
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/encryption/IndexRangeKeyTestClass.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBIndexRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBVersionAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotEncrypt; /** Comprehensive domain class */ @DynamoDBTable(tableName = "aws-java-sdk-index-range-test-crypto") public class IndexRangeKeyTestClass { private long key; private double rangeKey; private Double indexFooRangeKey; private Double indexBarRangeKey; private Double multipleIndexRangeKey; private Long version; private String fooAttribute; private String barAttribute; @DynamoDBHashKey public long getKey() { return key; } public void setKey(long key) { this.key = key; } @DynamoDBRangeKey public double getRangeKey() { return rangeKey; } public void setRangeKey(double rangeKey) { this.rangeKey = rangeKey; } @DoNotEncrypt @DynamoDBIndexRangeKey(localSecondaryIndexName = "index_foo", attributeName = "indexFooRangeKey") public Double getIndexFooRangeKeyWithFakeName() { return indexFooRangeKey; } public void setIndexFooRangeKeyWithFakeName(Double indexFooRangeKey) { this.indexFooRangeKey = indexFooRangeKey; } @DoNotEncrypt @DynamoDBIndexRangeKey(localSecondaryIndexName = "index_bar") public Double getIndexBarRangeKey() { return indexBarRangeKey; } public void setIndexBarRangeKey(Double indexBarRangeKey) { this.indexBarRangeKey = indexBarRangeKey; } @DoNotEncrypt @DynamoDBIndexRangeKey(localSecondaryIndexNames = {"index_foo_copy", "index_bar_copy"}) public Double getMultipleIndexRangeKey() { return multipleIndexRangeKey; } public void setMultipleIndexRangeKey(Double multipleIndexRangeKey) { this.multipleIndexRangeKey = multipleIndexRangeKey; } @DynamoDBAttribute public String getFooAttribute() { return fooAttribute; } public void setFooAttribute(String fooAttribute) { this.fooAttribute = fooAttribute; } @DynamoDBAttribute public String getBarAttribute() { return barAttribute; } public void setBarAttribute(String barAttribute) { this.barAttribute = barAttribute; } @DoNotEncrypt @DynamoDBVersionAttribute public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((fooAttribute == null) ? 0 : fooAttribute.hashCode()); result = prime * result + ((barAttribute == null) ? 0 : barAttribute.hashCode()); result = prime * result + (int) (key ^ (key >>> 32)); long temp; temp = Double.doubleToLongBits(rangeKey); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(indexFooRangeKey); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(indexBarRangeKey); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; IndexRangeKeyTestClass other = (IndexRangeKeyTestClass) obj; if (fooAttribute == null) { if (other.fooAttribute != null) return false; } else if (!fooAttribute.equals(other.fooAttribute)) return false; if (barAttribute == null) { if (other.barAttribute != null) return false; } else if (!barAttribute.equals(other.barAttribute)) return false; if (key != other.key) return false; if (Double.doubleToLongBits(rangeKey) != Double.doubleToLongBits(other.rangeKey)) return false; if (Double.doubleToLongBits(indexFooRangeKey) != Double.doubleToLongBits(other.indexFooRangeKey)) return false; if (Double.doubleToLongBits(indexBarRangeKey) != Double.doubleToLongBits(other.indexBarRangeKey)) return false; if (version == null) { if (other.version != null) return false; } else if (!version.equals(other.version)) return false; return true; } @Override public String toString() { return "IndexRangeKeyTestClass [key=" + key + ", rangeKey=" + rangeKey + ", version=" + version + ", indexFooRangeKey=" + indexFooRangeKey + ", indexBarRangeKey=" + indexBarRangeKey + ", fooAttribute=" + fooAttribute + ", barAttribute=" + barAttribute + "]"; } }
4,235
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/MapperSaveConfigITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionFlags; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestEncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import java.security.GeneralSecurityException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; /** * Tests the behavior of save method of DynamoDBMapper under different SaveBehavior configurations. */ public class MapperSaveConfigITCase extends MapperSaveConfigCryptoIntegrationTestBase { @AfterClass public static void teatDown() throws Exception { try { // dynamo.deleteTable(new DeleteTableRequest(tableName)); } catch (Exception e) { } } /********************************************* ** UPDATE (default) ** *********************************************/ /** * Tests that a key-only object could be saved with UPDATE configuration, even when the key has * already existed in the table. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testDefaultWithOnlyKeyAttributesSpecifiedRecordInTable() throws Exception { /* First put a new item (with non-key attribute)*/ TestItem testItem = putRandomUniqueItem("foo", null); /* Put an key-only object with the same key */ testItem.setNonKeyAttribute(null); dynamoMapper.save(testItem, defaultConfig); /* The non-key attribute should be nulled out. */ TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertNull(returnedObject.getNonKeyAttribute()); } /** * Tests an edge case that we have fixed according a forum bug report. If the object is only * specified with key attributes, and such key is not present in the table, we should add this * object by a key-only put request even if it is using UPDATE configuration. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testDefaultWithOnlyKeyAttributesSpecifiedRecordNotInTable() throws Exception { TestItem testItem = new TestItem(); testItem.setHashKey(UUID.randomUUID().toString()); testItem.setRangeKey(System.currentTimeMillis()); dynamoMapper.save(testItem, defaultConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertNull(returnedObject.getNonKeyAttribute()); } /** Update an existing item in the table. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testDefaultWithKeyAndNonKeyAttributesSpecifiedRecordInTable() throws Exception { /* First put a new item (without non-key attribute)*/ TestItem testItem = putRandomUniqueItem(null, null); String hashKeyValue = testItem.getHashKey(); Long rangeKeyValue = testItem.getRangeKey(); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(hashKeyValue, returnedObject.getHashKey()); assertEquals(rangeKeyValue, returnedObject.getRangeKey()); assertNull(returnedObject.getNonKeyAttribute()); /* Put an updated object with the same key and an additional non-key attribute. */ testItem.setHashKey(hashKeyValue); testItem.setRangeKey(rangeKeyValue); testItem.setNonKeyAttribute("update"); dynamoMapper.save(testItem, defaultConfig); returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals(testItem.getNonKeyAttribute(), returnedObject.getNonKeyAttribute()); } /** Use UPDATE to put a new item in the table. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testDefaultWithKeyAndNonKeyAttributesSpecifiedRecordNotInTable() throws Exception { TestItem testItem = new TestItem(); testItem.setHashKey(UUID.randomUUID().toString()); testItem.setRangeKey(System.currentTimeMillis()); testItem.setNonKeyAttribute("new item"); dynamoMapper.save(testItem, defaultConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals(testItem.getNonKeyAttribute(), returnedObject.getNonKeyAttribute()); } /********************************************* ** UPDATE_SKIP_NULL_ATTRIBUTES ** *********************************************/ /** * When using UPDATE_SKIP_NULL_ATTRIBUTES, key-only update on existing item should not affect the * item at all, since all the null-valued non-key attributes are ignored. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testUpdateSkipNullWithOnlyKeyAttributesSpecifiedRecordInTable() throws Exception { /* First put a new item (with non-key attribute)*/ TestItem testItem = putRandomUniqueItem("foo", null); /* Put an key-only object with the same key */ testItem.setNonKeyAttribute(null); dynamoMapper.save(testItem, updateSkipNullConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); /* The non-key attribute should not be removed */ assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals("foo", returnedObject.getNonKeyAttribute()); } /** The behavior should be the same as UPDATE. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testUpdateSkipNullWithOnlyKeyAttributesSpecifiedRecordNotInTable() throws Exception { TestItem testItem = new TestItem(); testItem.setHashKey(UUID.randomUUID().toString()); testItem.setRangeKey(System.currentTimeMillis()); dynamoMapper.save(testItem, updateSkipNullConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertNull(returnedObject.getNonKeyAttribute()); } /** Use UPDATE_SKIP_NULL_ATTRIBUTES to update an existing item in the table. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testUpdateSkipNullWithKeyAndNonKeyAttributesSpecifiedRecordInTable() throws Exception { /* First put a new item (without non-key attribute)*/ TestItem testItem = putRandomUniqueItem(null, null); String hashKeyValue = testItem.getHashKey(); Long rangeKeyValue = testItem.getRangeKey(); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(hashKeyValue, returnedObject.getHashKey()); assertEquals(rangeKeyValue, returnedObject.getRangeKey()); assertNull(returnedObject.getNonKeyAttribute()); /* Put an updated object with the same key and an additional non-key attribute. */ String nonKeyAttributeValue = "update"; testItem.setHashKey(hashKeyValue); testItem.setRangeKey(rangeKeyValue); testItem.setNonKeyAttribute(nonKeyAttributeValue); dynamoMapper.save(testItem, updateSkipNullConfig); returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals(testItem.getNonKeyAttribute(), returnedObject.getNonKeyAttribute()); /* At last, save the object again, but with non-key attribute set as null. * This should not change the existing item. */ testItem.setNonKeyAttribute(null); dynamoMapper.save(testItem, updateSkipNullConfig); returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals(nonKeyAttributeValue, returnedObject.getNonKeyAttribute()); } /** Use UPDATE_SKIP_NULL_ATTRIBUTES to put a new item in the table. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testUpdateSkipNullWithKeyAndNonKeyAttributesSpecifiedRecordNotInTable() throws Exception { TestItem testItem = new TestItem(); testItem.setHashKey(UUID.randomUUID().toString()); testItem.setRangeKey(System.currentTimeMillis()); testItem.setNonKeyAttribute("new item"); dynamoMapper.save(testItem, updateSkipNullConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals(testItem.getNonKeyAttribute(), returnedObject.getNonKeyAttribute()); } /********************************************* ** APPEND_SET ** *********************************************/ /** The behavior should be the same as UPDATE_SKIP_NULL_ATTRIBUTES. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testAppendSetWithOnlyKeyAttributesSpecifiedRecordInTable() throws Exception { /* First put a new item (with non-key attributes)*/ Set<String> randomSet = generateRandomStringSet(3); TestItem testItem = putRandomUniqueItem("foo", randomSet); /* Put an key-only object with the same key */ testItem.setNonKeyAttribute(null); testItem.setStringSetAttribute(null); dynamoMapper.save(testItem, appendSetConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); /* The non-key attribute should not be removed */ assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals("foo", returnedObject.getNonKeyAttribute()); assertTrue(assertSetEquals(randomSet, returnedObject.getStringSetAttribute())); } /** The behavior should be the same as UPDATE and UPDATE_SKIP_NULL_ATTRIBUTES. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testAppendSetWithOnlyKeyAttributesSpecifiedRecordNotInTable() throws Exception { TestItem testItem = new TestItem(); testItem.setHashKey(UUID.randomUUID().toString()); testItem.setRangeKey(System.currentTimeMillis()); dynamoMapper.save(testItem, appendSetConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertNull(returnedObject.getNonKeyAttribute()); assertNull(returnedObject.getStringSetAttribute()); } /** Use APPEND_SET to update an existing item in the table. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testAppendSetWithKeyAndNonKeyAttributesSpecifiedRecordInTable() throws Exception { /* First put a new item (without non-key attribute)*/ TestItem testItem = putRandomUniqueItem(null, null); String hashKeyValue = testItem.getHashKey(); Long rangeKeyValue = testItem.getRangeKey(); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(hashKeyValue, returnedObject.getHashKey()); assertEquals(rangeKeyValue, returnedObject.getRangeKey()); assertNull(returnedObject.getNonKeyAttribute()); assertNull(returnedObject.getStringSetAttribute()); /* Put an updated object with the same key and an additional non-key attribute. */ String nonKeyAttributeValue = "update"; Set<String> stringSetAttributeValue = generateRandomStringSet(3); testItem.setHashKey(hashKeyValue); testItem.setRangeKey(rangeKeyValue); testItem.setNonKeyAttribute(nonKeyAttributeValue); testItem.setStringSetAttribute(stringSetAttributeValue); dynamoMapper.save(testItem, appendSetConfig); returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals(testItem.getNonKeyAttribute(), returnedObject.getNonKeyAttribute()); assertTrue( assertSetEquals(testItem.getStringSetAttribute(), returnedObject.getStringSetAttribute())); /* Override nonKeyAttribute and append stringSetAttribute */ testItem.setNonKeyAttribute("blabla"); Set<String> appendSetAttribute = generateRandomStringSet(3); testItem.setStringSetAttribute(appendSetAttribute); dynamoMapper.save(testItem, appendSetConfig); returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals("blabla", returnedObject.getNonKeyAttribute()); // expected set after the append stringSetAttributeValue.addAll(appendSetAttribute); assertTrue(assertSetEquals(stringSetAttributeValue, returnedObject.getStringSetAttribute())); /* Append on an existing scalar attribute would result in an exception */ TestAppendToScalarItem testAppendToScalarItem = new TestAppendToScalarItem(); testAppendToScalarItem.setHashKey(testItem.getHashKey()); testAppendToScalarItem.setRangeKey(testItem.getRangeKey()); // this fake set attribute actually points to a scalar attribute testAppendToScalarItem.setFakeStringSetAttribute(generateRandomStringSet(1)); try { dynamoMapper.save(testAppendToScalarItem, appendSetConfig); fail("Should have thrown a 'Type mismatch' service exception."); } catch (AmazonServiceException ase) { assertEquals("ValidationException", ase.getErrorCode()); } } /** Use APPEND_SET to put a new item in the table. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testAppendSetWithKeyAndNonKeyAttributesSpecifiedRecordNotInTable() throws Exception { TestItem testItem = new TestItem(); testItem.setHashKey(UUID.randomUUID().toString()); testItem.setRangeKey(System.currentTimeMillis()); testItem.setNonKeyAttribute("new item"); testItem.setStringSetAttribute(generateRandomStringSet(3)); dynamoMapper.save(testItem, appendSetConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals(testItem.getNonKeyAttribute(), returnedObject.getNonKeyAttribute()); assertEquals(testItem.getStringSetAttribute(), returnedObject.getStringSetAttribute()); } /********************************************* ** CLOBBER ** *********************************************/ /** Use CLOBBER to override the existing item by saving a key-only object. */ @Test public void testClobberWithOnlyKeyAttributesSpecifiedRecordInTable() throws Exception { /* Put the item with non-key attribute */ TestItem testItem = putRandomUniqueItem("foo", null); /* Override the item by saving a key-only object. */ testItem.setNonKeyAttribute(null); dynamoMapper.save(testItem, clobberConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertNull(returnedObject.getNonKeyAttribute()); } /** Use CLOBBER to put a new item with only key attributes. */ @Test public void testClobberWithOnlyKeyAttributesSpecifiedRecordNotInTable() throws Exception { TestItem testItem = new TestItem(); testItem.setHashKey(UUID.randomUUID().toString()); testItem.setRangeKey(System.currentTimeMillis()); dynamoMapper.save(testItem, clobberConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertNull(returnedObject.getNonKeyAttribute()); } /** Use CLOBBER to override the existing item. */ @Test public void testClobberWithKeyAndNonKeyAttributesSpecifiedRecordInTable() throws Exception { /* Put the item with non-key attribute */ TestItem testItem = putRandomUniqueItem("foo", null); /* Override the item. */ testItem.setNonKeyAttribute("not foo"); dynamoMapper.save(testItem, clobberConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals(testItem.getNonKeyAttribute(), returnedObject.getNonKeyAttribute()); } /** Use CLOBBER to put a new item. */ @Test public void testClobberWithKeyAndNonKeyAttributesSpecifiedRecordNotInTable() throws Exception { TestItem testItem = new TestItem(); testItem.setHashKey(UUID.randomUUID().toString()); testItem.setRangeKey(System.currentTimeMillis()); testItem.setNonKeyAttribute("new item"); dynamoMapper.save(testItem, clobberConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals(testItem.getNonKeyAttribute(), returnedObject.getNonKeyAttribute()); } private static TestItem putRandomUniqueItem( String nonKeyAttributeValue, Set<String> stringSetAttributeValue) throws GeneralSecurityException { String hashKeyValue = UUID.randomUUID().toString(); Long rangeKeyValue = System.currentTimeMillis(); Map<String, AttributeValue> item = new HashMap<String, AttributeValue>(); item.put(hashKeyName, new AttributeValue().withS(hashKeyValue)); item.put(rangeKeyName, new AttributeValue().withN(rangeKeyValue.toString())); if (null != nonKeyAttributeValue) { item.put(nonKeyAttributeName, new AttributeValue().withS(nonKeyAttributeValue)); } if (null != stringSetAttributeValue) { item.put(stringSetAttributeName, new AttributeValue().withSS(stringSetAttributeValue)); } DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(new TestEncryptionMaterialsProvider()); EncryptionContext context = new EncryptionContext.Builder() .withHashKeyName(hashKeyName) .withRangeKeyName(rangeKeyName) .withTableName(tableName) .build(); Map<String, Set<EncryptionFlags>> flags = encryptor.allEncryptionFlagsExcept(item, hashKeyName, rangeKeyName); // completely exclude the nonKeyAttributeName; otherwise some of the // updateSkipNullConfig test will never work flags.remove(nonKeyAttributeName); flags.remove(stringSetAttributeName); item = encryptor.encryptRecord(item, flags, context); // item = encryptor.encryptAllFieldsExcept(item, context, hashKeyName, rangeKeyName); dynamo.putItem(new PutItemRequest().withTableName(tableName).withItem(item)); /* Returns the item as a modeled object. */ TestItem testItem = new TestItem(); testItem.setHashKey(hashKeyValue); testItem.setRangeKey(rangeKeyValue); testItem.setNonKeyAttribute(nonKeyAttributeValue); testItem.setStringSetAttribute(stringSetAttributeValue); return testItem; } private static Set<String> generateRandomStringSet(int size) { Set<String> result = new HashSet<String>(); for (int i = 0; i < size; i++) { result.add(UUID.randomUUID().toString()); } return result; } private static boolean assertSetEquals(Set<?> expected, Set<?> actual) { if (expected == null || actual == null) { return (expected == null && actual == null); } if (expected.size() != actual.size()) { return false; } for (Object item : expected) { if (!actual.contains(item)) { return false; } } return true; } }
4,236
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/PlaintextItemITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotTouch; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import java.util.HashMap; import java.util.Map; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class PlaintextItemITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static final String STRING_ATTRIBUTE = "stringAttribute"; private static Map<String, AttributeValue> plaintextItem = new HashMap<>(); // Test data static { plaintextItem.put(KEY_NAME, new AttributeValue().withS("" + startKey++)); plaintextItem.put(STRING_ATTRIBUTE, new AttributeValue().withS("" + startKey++)); } @BeforeClass public static void setUp() throws Exception { DynamoDBMapperCryptoIntegrationTestBase.setUp(); // Insert the data dynamo.putItem(new PutItemRequest(TABLE_NAME, plaintextItem)); } @Test public void testLoadWithPlaintextItem() { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); UntouchedTable load = util.load(UntouchedTable.class, plaintextItem.get(KEY_NAME).getS()); assertEquals(load.getKey(), plaintextItem.get(KEY_NAME).getS()); assertEquals(load.getStringAttribute(), plaintextItem.get(STRING_ATTRIBUTE).getS()); } @Test public void testLoadWithPlaintextItemWithModelHavingNewEncryptedAttribute() { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); UntouchedWithNewEncryptedAttributeTable load = util.load( UntouchedWithNewEncryptedAttributeTable.class, plaintextItem.get(KEY_NAME).getS()); assertEquals(load.getKey(), plaintextItem.get(KEY_NAME).getS()); assertEquals(load.getStringAttribute(), plaintextItem.get(STRING_ATTRIBUTE).getS()); assertNull(load.getNewAttribute()); } @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public static class UntouchedTable { private String key; private String stringAttribute; @DynamoDBHashKey @DoNotTouch public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAttribute @DoNotTouch public String getStringAttribute() { return stringAttribute; } public void setStringAttribute(String stringAttribute) { this.stringAttribute = stringAttribute; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UntouchedTable that = (UntouchedTable) o; return key.equals(that.key) && stringAttribute.equals(that.stringAttribute); } } public static final class UntouchedWithNewEncryptedAttributeTable extends UntouchedTable { private String newAttribute; public String getNewAttribute() { return newAttribute; } public void setNewAttribute(String newAttribute) { this.newAttribute = newAttribute; } } }
4,237
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/InheritanceITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import java.util.ArrayList; import java.util.List; import org.testng.annotations.Test; /** Tests inheritance behavior in DynamoDB mapper. */ public class InheritanceITCase extends DynamoDBMapperCryptoIntegrationTestBase { @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public static class BaseClass { protected String key; protected String normalStringAttribute; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAttribute public String getNormalStringAttribute() { return normalStringAttribute; } public void setNormalStringAttribute(String normalStringAttribute) { this.normalStringAttribute = normalStringAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((normalStringAttribute == null) ? 0 : normalStringAttribute.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BaseClass other = (BaseClass) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (normalStringAttribute == null) { if (other.normalStringAttribute != null) return false; } else if (!normalStringAttribute.equals(other.normalStringAttribute)) return false; return true; } } public static class SubClass extends BaseClass { private String subField; public String getSubField() { return subField; } public void setSubField(String subField) { this.subField = subField; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((subField == null) ? 0 : subField.hashCode()); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; SubClass other = (SubClass) obj; if (subField == null) { if (other.subField != null) return false; } else if (!subField.equals(other.subField)) return false; return true; } } public static class SubSubClass extends SubClass { private String subSubField; public String getSubSubField() { return subSubField; } public void setSubSubField(String subSubField) { this.subSubField = subSubField; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((subSubField == null) ? 0 : subSubField.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; SubSubClass other = (SubSubClass) obj; if (subSubField == null) { if (other.subSubField != null) return false; } else if (!subSubField.equals(other.subSubField)) return false; return true; } } @Test public void testSubClass() throws Exception { List<Object> objs = new ArrayList<Object>(); for (int i = 0; i < 5; i++) { SubClass obj = getUniqueObject(new SubClass()); obj.setSubField("" + startKey++); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (Object obj : objs) { util.save(obj); assertEquals(util.load(SubClass.class, ((SubClass) obj).getKey()), obj); } } @Test public void testSubSubClass() throws Exception { List<SubSubClass> objs = new ArrayList<SubSubClass>(); for (int i = 0; i < 5; i++) { SubSubClass obj = getUniqueObject(new SubSubClass()); obj.setSubField("" + startKey++); obj.setSubSubField("" + startKey++); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (SubSubClass obj : objs) { util.save(obj); assertEquals(util.load(SubSubClass.class, obj.getKey()), obj); } } @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public static interface Interface { @DynamoDBHashKey public String getKey(); public void setKey(String key); @DynamoDBAttribute public String getAttribute(); public void setAttribute(String attribute); } public static class Implementation implements Interface { private String key; private String attribute; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getAttribute() { return attribute; } public void setAttribute(String attribute) { this.attribute = attribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((attribute == null) ? 0 : attribute.hashCode()); result = prime * result + ((key == null) ? 0 : key.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Implementation other = (Implementation) obj; if (attribute == null) { if (other.attribute != null) return false; } else if (!attribute.equals(other.attribute)) return false; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; return true; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testImplementation() throws Exception { List<Implementation> objs = new ArrayList<Implementation>(); for (int i = 0; i < 5; i++) { Implementation obj = new Implementation(); obj.setKey("" + startKey++); obj.setAttribute("" + startKey++); objs.add(obj); } // Saving new objects with a null version field should populate it DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (Interface obj : objs) { util.save(obj); assertEquals(util.load(Implementation.class, obj.getKey()), obj); } } private <T extends BaseClass> T getUniqueObject(T obj) { obj.setKey("" + startKey++); obj.setNormalStringAttribute("" + startKey++); return obj; } }
4,238
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/QueryITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.ConsistentReads; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression; import com.amazonaws.services.dynamodbv2.mapper.encryption.RangeKeyTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.ComparisonOperator; import com.amazonaws.services.dynamodbv2.model.Condition; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Random; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Integration tests for the query operation on DynamoDBMapper. */ public class QueryITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static final boolean DEBUG = true; private static final long HASH_KEY = System.currentTimeMillis(); private static RangeKeyTestClass hashKeyObject; private static final int TEST_ITEM_NUMBER = 500; private static DynamoDBMapper mapper; @BeforeClass public static void setUp() throws Exception { setUpTableWithRangeAttribute(); DynamoDBMapperConfig mapperConfig = new DynamoDBMapperConfig(ConsistentReads.CONSISTENT); mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo, mapperConfig); putTestData(mapper, TEST_ITEM_NUMBER); hashKeyObject = new RangeKeyTestClass(); hashKeyObject.setKey(HASH_KEY); } @Test public void testQueryWithPrimaryRangeKey() throws Exception { DynamoDBQueryExpression<RangeKeyTestClass> queryExpression = new DynamoDBQueryExpression<RangeKeyTestClass>() .withHashKeyValues(hashKeyObject) .withRangeKeyCondition( "rangeKey", new Condition() .withComparisonOperator(ComparisonOperator.GT) .withAttributeValueList(new AttributeValue().withN("1.0"))) .withLimit(11); List<RangeKeyTestClass> list = mapper.query(RangeKeyTestClass.class, queryExpression); int count = 0; Iterator<RangeKeyTestClass> iterator = list.iterator(); while (iterator.hasNext()) { count++; RangeKeyTestClass next = iterator.next(); assertTrue(next.getRangeKey() > 1.00); } int numMatchingObjects = TEST_ITEM_NUMBER - 2; if (DEBUG) System.err.println("count=" + count + ", numMatchingObjects=" + numMatchingObjects); assertTrue(count == numMatchingObjects); assertTrue(numMatchingObjects == list.size()); assertNotNull(list.get(list.size() / 2)); assertTrue(list.contains(list.get(list.size() / 2))); assertTrue(numMatchingObjects == list.toArray().length); Thread.sleep(250); int totalCount = mapper.count(RangeKeyTestClass.class, queryExpression); assertTrue(numMatchingObjects == totalCount); /** Tests query with only hash key */ queryExpression = new DynamoDBQueryExpression<RangeKeyTestClass>().withHashKeyValues(hashKeyObject); list = mapper.query(RangeKeyTestClass.class, queryExpression); assertTrue(TEST_ITEM_NUMBER == list.size()); } /** Tests making queries using query filter on non-key attributes. */ @Test public void testQueryFilter() { // A random filter condition to be applied to the query. Random random = new Random(); int randomFilterValue = random.nextInt(TEST_ITEM_NUMBER); Condition filterCondition = new Condition() .withComparisonOperator(ComparisonOperator.LT) .withAttributeValueList( new AttributeValue().withN(Integer.toString(randomFilterValue))); /* * (1) Apply the filter on the range key, in form of key condition */ DynamoDBQueryExpression<RangeKeyTestClass> queryWithRangeKeyCondition = new DynamoDBQueryExpression<RangeKeyTestClass>() .withHashKeyValues(hashKeyObject) .withRangeKeyCondition("rangeKey", filterCondition); List<RangeKeyTestClass> rangeKeyConditionResult = mapper.query(RangeKeyTestClass.class, queryWithRangeKeyCondition); /* * (2) Apply the filter on the bigDecimalAttribute, in form of query * filter */ DynamoDBQueryExpression<RangeKeyTestClass> queryWithQueryFilterCondition = new DynamoDBQueryExpression<RangeKeyTestClass>() .withHashKeyValues(hashKeyObject) .withQueryFilter(Collections.singletonMap("bigDecimalAttribute", filterCondition)); List<RangeKeyTestClass> queryFilterResult = mapper.query(RangeKeyTestClass.class, queryWithQueryFilterCondition); if (DEBUG) { System.err.println( "rangeKeyConditionResult.size()=" + rangeKeyConditionResult.size() + ", queryFilterResult.size()=" + queryFilterResult.size()); } assertTrue(rangeKeyConditionResult.size() == queryFilterResult.size()); for (int i = 0; i < rangeKeyConditionResult.size(); i++) { assertEquals(rangeKeyConditionResult.get(i), queryFilterResult.get(i)); } } /** * Tests that exception should be raised when user provides an index name when making query with * the primary range key. */ @Test public void testUnnecessaryIndexNameException() { try { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); long hashKey = System.currentTimeMillis(); RangeKeyTestClass keyObject = new RangeKeyTestClass(); keyObject.setKey(hashKey); DynamoDBQueryExpression<RangeKeyTestClass> queryExpression = new DynamoDBQueryExpression<RangeKeyTestClass>().withHashKeyValues(keyObject); queryExpression .withRangeKeyCondition( "rangeKey", new Condition() .withComparisonOperator(ComparisonOperator.GT.toString()) .withAttributeValueList(new AttributeValue().withN("1.0"))) .withLimit(11) .withIndexName("some_index"); mapper.query(RangeKeyTestClass.class, queryExpression); fail("User should not provide index name when making query with the primary range key"); } catch (IllegalArgumentException expected) { System.out.println(expected.getMessage()); } catch (Exception e) { fail("Should trigger AmazonClientException."); } } /** * Use BatchSave to put some test data into the tested table. Each item is hash-keyed by the same * value, and range-keyed by numbers starting from 0. */ private static void putTestData(DynamoDBMapper mapper, int itemNumber) { List<RangeKeyTestClass> objs = new ArrayList<RangeKeyTestClass>(); for (int i = 0; i < itemNumber; i++) { RangeKeyTestClass obj = new RangeKeyTestClass(); obj.setKey(HASH_KEY); obj.setRangeKey(i); obj.setBigDecimalAttribute(new BigDecimal(i)); objs.add(obj); } mapper.batchSave(objs); } }
4,239
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/DynamoDBMapperCryptoIntegrationTestBase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import com.amazonaws.services.dynamodbv2.mapper.encryption.BinaryAttributeByteBufferTestClass; import java.nio.ByteBuffer; import java.util.HashSet; import java.util.Set; public class DynamoDBMapperCryptoIntegrationTestBase extends DynamoDBCryptoIntegrationTestBase { public static void setUpMapperTestBase() { DynamoDBCryptoIntegrationTestBase.setUpTestBase(); } /* * Utility methods */ protected static BinaryAttributeByteBufferTestClass getUniqueByteBufferObject(int contentLength) { BinaryAttributeByteBufferTestClass obj = new BinaryAttributeByteBufferTestClass(); obj.setKey(String.valueOf(startKey++)); obj.setBinaryAttribute(ByteBuffer.wrap(generateByteArray(contentLength))); Set<ByteBuffer> byteBufferSet = new HashSet<ByteBuffer>(); byteBufferSet.add(ByteBuffer.wrap(generateByteArray(contentLength))); obj.setBinarySetAttribute(byteBufferSet); return obj; } }
4,240
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/SimpleStringAttributesITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.ConsistentReads; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.SaveBehavior; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.mapper.encryption.StringAttributeTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestEncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Tests simple string attributes */ public class SimpleStringAttributesITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static final String ORIGINAL_NAME_ATTRIBUTE = "originalName"; private static final String STRING_ATTRIBUTE = "stringAttribute"; private static final List<Map<String, AttributeValue>> attrs = new LinkedList<Map<String, AttributeValue>>(); // Test data static { for (int i = 0; i < 5; i++) { Map<String, AttributeValue> attr = new HashMap<String, AttributeValue>(); attr.put(KEY_NAME, new AttributeValue().withS("" + startKey++)); attr.put(STRING_ATTRIBUTE, new AttributeValue().withS("" + startKey++)); attr.put(ORIGINAL_NAME_ATTRIBUTE, new AttributeValue().withS("" + startKey++)); attrs.add(attr); } } ; @BeforeClass public static void setUp() throws Exception { DynamoDBMapperCryptoIntegrationTestBase.setUp(); DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(new TestEncryptionMaterialsProvider()); EncryptionContext context = new EncryptionContext.Builder().withHashKeyName(KEY_NAME).withTableName(TABLE_NAME).build(); // Insert the data for (Map<String, AttributeValue> attr : attrs) { attr = encryptor.encryptAllFieldsExcept(attr, context, KEY_NAME); dynamo.putItem(new PutItemRequest(TABLE_NAME, attr)); } } @Test public void testLoad() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (Map<String, AttributeValue> attr : attrs) { StringAttributeTestClass x = util.load(StringAttributeTestClass.class, attr.get(KEY_NAME).getS()); assertEquals(x.getKey(), attr.get(KEY_NAME).getS()); assertEquals(x.getStringAttribute(), attr.get(STRING_ATTRIBUTE).getS()); assertEquals(x.getRenamedAttribute(), attr.get(ORIGINAL_NAME_ATTRIBUTE).getS()); } } @Test public void testSave() { List<StringAttributeTestClass> objs = new ArrayList<StringAttributeTestClass>(); for (int i = 0; i < 5; i++) { StringAttributeTestClass obj = getUniqueObject(); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (StringAttributeTestClass obj : objs) { util.save(obj); } for (StringAttributeTestClass obj : objs) { StringAttributeTestClass loaded = util.load(StringAttributeTestClass.class, obj.getKey()); assertEquals(obj, loaded); } } /** Tests saving an incomplete object into DynamoDB */ @Test public void testIncompleteObject() { StringAttributeTestClass obj = getUniqueObject(); obj.setStringAttribute(null); DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.save(obj); assertEquals(obj, util.load(StringAttributeTestClass.class, obj.getKey())); // test removing an attribute assertNotNull(obj.getRenamedAttribute()); obj.setRenamedAttribute(null); util.save(obj); assertEquals(obj, util.load(StringAttributeTestClass.class, obj.getKey())); } @Test public void testUpdate() { List<StringAttributeTestClass> objs = new ArrayList<StringAttributeTestClass>(); for (int i = 0; i < 5; i++) { StringAttributeTestClass obj = getUniqueObject(); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (StringAttributeTestClass obj : objs) { util.save(obj); } for (StringAttributeTestClass obj : objs) { StringAttributeTestClass replacement = getUniqueObject(); replacement.setKey(obj.getKey()); util.save(replacement); assertEquals(replacement, util.load(StringAttributeTestClass.class, obj.getKey())); } } @Test public void testSaveOnlyKey() { KeyOnly obj = new KeyOnly(); obj.setKey("" + startKey++); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.save(obj); KeyOnly loaded = mapper.load( KeyOnly.class, obj.getKey(), new DynamoDBMapperConfig(ConsistentReads.CONSISTENT)); assertEquals(obj, loaded); // saving again shouldn't be an error mapper.save(obj); } @Test public void testSaveOnlyKeyClobber() { KeyOnly obj = new KeyOnly(); obj.setKey("" + startKey++); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.save(obj, new DynamoDBMapperConfig(SaveBehavior.CLOBBER)); KeyOnly loaded = mapper.load( KeyOnly.class, obj.getKey(), new DynamoDBMapperConfig(ConsistentReads.CONSISTENT)); assertEquals(obj, loaded); // saving again shouldn't be an error mapper.save(obj, new DynamoDBMapperConfig(SaveBehavior.CLOBBER)); } @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public static final class KeyOnly { private String key; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; KeyOnly other = (KeyOnly) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; return true; } } private StringAttributeTestClass getUniqueObject() { StringAttributeTestClass obj = new StringAttributeTestClass(); obj.setKey(String.valueOf(startKey++)); obj.setRenamedAttribute(String.valueOf(startKey++)); obj.setStringAttribute(String.valueOf(startKey++)); return obj; } }
4,241
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/DynamoDBTestBase.java
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.fail; import static org.testng.AssertJUnit.assertTrue; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded; import java.math.BigDecimal; import java.util.Collection; import java.util.HashSet; import java.util.Set; public class DynamoDBTestBase { protected static AmazonDynamoDB dynamo; public static void setUpTestBase() { dynamo = DynamoDBEmbedded.create(); } public static AmazonDynamoDB getClient() { if (dynamo == null) { setUpTestBase(); } return dynamo; } protected static <T extends Object> Set<T> toSet(T... array) { Set<T> set = new HashSet<T>(); for (T t : array) { set.add(t); } return set; } protected static <T extends Object> void assertSetsEqual( Collection<T> expected, Collection<T> given) { Set<T> givenCopy = new HashSet<T>(); givenCopy.addAll(given); for (T e : expected) { if (!givenCopy.remove(e)) { fail("Expected element not found: " + e); } } assertTrue("Unexpected elements found: " + givenCopy, givenCopy.isEmpty()); } protected static void assertNumericSetsEquals( Set<? extends Number> expected, Collection<String> given) { Set<BigDecimal> givenCopy = new HashSet<BigDecimal>(); for (String s : given) { BigDecimal bd = new BigDecimal(s); givenCopy.add(bd.setScale(0)); } Set<BigDecimal> expectedCopy = new HashSet<BigDecimal>(); for (Number n : expected) { BigDecimal bd = new BigDecimal(n.toString()); expectedCopy.add(bd.setScale(0)); } assertSetsEqual(expectedCopy, givenCopy); } protected static <T extends Object> Set<T> toSet(Collection<T> collection) { Set<T> set = new HashSet<T>(); for (T t : collection) { set.add(t); } return set; } protected static byte[] generateByteArray(int length) { byte[] bytes = new byte[length]; for (int i = 0; i < length; i++) { bytes[i] = (byte) (i % Byte.MAX_VALUE); } return bytes; } }
4,242
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/IndexRangeKeyAttributesITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.mapper.encryption.IndexRangeKeyTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestEncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.ComparisonOperator; import com.amazonaws.services.dynamodbv2.model.Condition; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.UUID; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Tests that index range keys are properly handled as common attribute when items are loaded, * saved/updated by using primary key. Also tests using index range keys for queries. */ public class IndexRangeKeyAttributesITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static DynamoDBMapper mapper; private static final String RANGE_KEY = "rangeKey"; private static final String INDEX_FOO_RANGE_KEY = "indexFooRangeKey"; private static final String INDEX_BAR_RANGE_KEY = "indexBarRangeKey"; private static final String MULTIPLE_INDEX_RANGE_KEY = "multipleIndexRangeKey"; private static final String FOO_ATTRIBUTE = "fooAttribute"; private static final String BAR_ATTRIBUTE = "barAttribute"; private static final String VERSION_ATTRIBUTE = "version"; // We don't start with the current system millis like other tests because // it's out of the range of some data types private static int start = 1; private static final List<Map<String, AttributeValue>> attrs = new LinkedList<Map<String, AttributeValue>>(); private static final List<Long> hashKeyValues = new LinkedList<Long>(); private static final int totalHash = 5; private static final int rangePerHash = 64; private static final int indexFooRangeStep = 2; private static final int indexBarRangeStep = 4; private static final int multipleIndexRangeStep = 8; // Test data static { for (int i = 0; i < totalHash; i++) { long hashKeyValue = startKey++; hashKeyValues.add(hashKeyValue); for (int j = 0; j < rangePerHash; j++) { Map<String, AttributeValue> attr = new HashMap<String, AttributeValue>(); attr.put(KEY_NAME, new AttributeValue().withN("" + hashKeyValue)); attr.put(RANGE_KEY, new AttributeValue().withN("" + j)); if (j % indexFooRangeStep == 0) attr.put(INDEX_FOO_RANGE_KEY, new AttributeValue().withN("" + j)); if (j % indexBarRangeStep == 0) attr.put(INDEX_BAR_RANGE_KEY, new AttributeValue().withN("" + j)); if (j % multipleIndexRangeStep == 0) attr.put(MULTIPLE_INDEX_RANGE_KEY, new AttributeValue().withN("" + j)); attr.put(FOO_ATTRIBUTE, new AttributeValue().withS(UUID.randomUUID().toString())); attr.put(BAR_ATTRIBUTE, new AttributeValue().withS(UUID.randomUUID().toString())); attr.put(VERSION_ATTRIBUTE, new AttributeValue().withN("1")); attrs.add(attr); } } } ; @BeforeClass public static void setUp() throws Exception { boolean recreateTable = false; setUpTableWithIndexRangeAttribute(recreateTable); DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(new TestEncryptionMaterialsProvider()); EncryptionContext context = new EncryptionContext.Builder() .withHashKeyName(KEY_NAME) .withRangeKeyName(RANGE_KEY) .withTableName(TABLE_WITH_INDEX_RANGE_ATTRIBUTE) .build(); // Insert the data for (Map<String, AttributeValue> attr : attrs) { attr = encryptor.encryptAllFieldsExcept( attr, context, KEY_NAME, RANGE_KEY, INDEX_FOO_RANGE_KEY, INDEX_BAR_RANGE_KEY, MULTIPLE_INDEX_RANGE_KEY, VERSION_ATTRIBUTE); dynamo.putItem(new PutItemRequest(TABLE_WITH_INDEX_RANGE_ATTRIBUTE, attr)); } mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); } /** * Tests that attribute annotated with @DynamoDBIndexRangeKey is properly set in the loaded * object. */ @Test public void testLoad() throws Exception { for (Map<String, AttributeValue> attr : attrs) { IndexRangeKeyTestClass x = mapper.load( newIndexRangeKey( Long.parseLong(attr.get(KEY_NAME).getN()), Double.parseDouble(attr.get(RANGE_KEY).getN()))); // Convert all numbers to the most inclusive type for easy // comparison assertEquals(new BigDecimal(x.getKey()), new BigDecimal(attr.get(KEY_NAME).getN())); assertEquals(new BigDecimal(x.getRangeKey()), new BigDecimal(attr.get(RANGE_KEY).getN())); if (null == attr.get(INDEX_FOO_RANGE_KEY)) assertNull(x.getIndexFooRangeKeyWithFakeName()); else assertEquals( new BigDecimal(x.getIndexFooRangeKeyWithFakeName()), new BigDecimal(attr.get(INDEX_FOO_RANGE_KEY).getN())); if (null == attr.get(INDEX_BAR_RANGE_KEY)) assertNull(x.getIndexBarRangeKey()); else assertEquals( new BigDecimal(x.getIndexBarRangeKey()), new BigDecimal(attr.get(INDEX_BAR_RANGE_KEY).getN())); assertEquals( new BigDecimal(x.getVersion()), new BigDecimal(attr.get(VERSION_ATTRIBUTE).getN())); assertEquals(x.getFooAttribute(), attr.get(FOO_ATTRIBUTE).getS()); assertEquals(x.getBarAttribute(), attr.get(BAR_ATTRIBUTE).getS()); } } private IndexRangeKeyTestClass newIndexRangeKey(long hashKey, double rangeKey) { IndexRangeKeyTestClass obj = new IndexRangeKeyTestClass(); obj.setKey(hashKey); obj.setRangeKey(rangeKey); return obj; } /** Tests that attribute annotated with @DynamoDBIndexRangeKey is properly saved. */ @Test public void testSave() throws Exception { List<IndexRangeKeyTestClass> objs = new ArrayList<IndexRangeKeyTestClass>(); for (int i = 0; i < 5; i++) { IndexRangeKeyTestClass obj = getUniqueObject(); objs.add(obj); } for (IndexRangeKeyTestClass obj : objs) { mapper.save(obj); } for (IndexRangeKeyTestClass obj : objs) { IndexRangeKeyTestClass loaded = mapper.load(IndexRangeKeyTestClass.class, obj.getKey(), obj.getRangeKey()); assertEquals(obj, loaded); } } /** Tests that version attribute is still working as expected. */ @Test public void testUpdate() throws Exception { List<IndexRangeKeyTestClass> objs = new ArrayList<IndexRangeKeyTestClass>(); for (int i = 0; i < 5; i++) { IndexRangeKeyTestClass obj = getUniqueObject(); objs.add(obj); } for (IndexRangeKeyTestClass obj : objs) { mapper.save(obj); } for (IndexRangeKeyTestClass obj : objs) { IndexRangeKeyTestClass replacement = getUniqueObject(); replacement.setKey(obj.getKey()); replacement.setRangeKey(obj.getRangeKey()); replacement.setVersion(obj.getVersion()); mapper.save(replacement); IndexRangeKeyTestClass loadedObject = mapper.load(IndexRangeKeyTestClass.class, obj.getKey(), obj.getRangeKey()); assertEquals(replacement, loadedObject); // If we try to update the old version, we should get an error replacement.setVersion(replacement.getVersion() - 1); try { mapper.save(replacement); fail("Should have thrown an exception"); } catch (Exception expected) { } } } /** Tests making queries on local secondary index */ @Test public void testQueryWithIndexRangekey() { int indexFooRangePerHash = rangePerHash / indexFooRangeStep; int indexBarRangePerHash = rangePerHash / indexBarRangeStep; for (long hashKeyValue : hashKeyValues) { IndexRangeKeyTestClass hashKeyItem = new IndexRangeKeyTestClass(); hashKeyItem.setKey(hashKeyValue); /** Query items by primary range key */ List<IndexRangeKeyTestClass> result = mapper.query( IndexRangeKeyTestClass.class, new DynamoDBQueryExpression<IndexRangeKeyTestClass>() .withHashKeyValues(hashKeyItem) .withRangeKeyCondition( RANGE_KEY, new Condition() .withAttributeValueList(new AttributeValue().withN("0")) .withComparisonOperator(ComparisonOperator.GE.toString()))); assertTrue(rangePerHash == result.size()); // check that all attributes are retrieved for (IndexRangeKeyTestClass itemInFooIndex : result) { assertNotNull(itemInFooIndex.getFooAttribute()); assertNotNull(itemInFooIndex.getBarAttribute()); } /** Query items on index_foo */ result = mapper.query( IndexRangeKeyTestClass.class, new DynamoDBQueryExpression<IndexRangeKeyTestClass>() .withHashKeyValues(hashKeyItem) .withRangeKeyCondition( INDEX_FOO_RANGE_KEY, new Condition() .withAttributeValueList(new AttributeValue().withN("0")) .withComparisonOperator(ComparisonOperator.GE.toString()))); assertTrue(indexFooRangePerHash == result.size()); // check that only the projected attributes are retrieved for (IndexRangeKeyTestClass itemInFooIndex : result) { assertNotNull(itemInFooIndex.getFooAttribute()); assertNotNull(itemInFooIndex.getBarAttribute()); } /** Query items on index_bar */ result = mapper.query( IndexRangeKeyTestClass.class, new DynamoDBQueryExpression<IndexRangeKeyTestClass>() .withHashKeyValues(hashKeyItem) .withRangeKeyCondition( INDEX_BAR_RANGE_KEY, new Condition() .withAttributeValueList(new AttributeValue().withN("0")) .withComparisonOperator(ComparisonOperator.GE.toString()))); assertTrue(indexBarRangePerHash == result.size()); // check that only the projected attributes are retrieved for (IndexRangeKeyTestClass itemInBarIndex : result) { assertNotNull(itemInBarIndex.getFooAttribute()); assertNotNull(itemInBarIndex.getBarAttribute()); } } } /** Tests the exception when user specifies an invalid range key name in the query. */ @Test public void testInvalidRangeKeyNameException() { IndexRangeKeyTestClass hashKeyItem = new IndexRangeKeyTestClass(); hashKeyItem.setKey(0); try { mapper.query( IndexRangeKeyTestClass.class, new DynamoDBQueryExpression<IndexRangeKeyTestClass>() .withHashKeyValues(hashKeyItem) .withRangeKeyCondition( "some_range_key", new Condition() .withAttributeValueList(new AttributeValue().withN("0")) .withComparisonOperator(ComparisonOperator.GE.toString()))); fail("some_range_key is not a valid range key name."); } catch (DynamoDBMappingException e) { System.out.println(e.getMessage()); } catch (Exception e) { fail("Should trigger an DynamoDBMappingException."); } } /** Tests the exception when user specifies an invalid index name in the query. */ @Test public void testInvalidIndexNameException() { IndexRangeKeyTestClass hashKeyItem = new IndexRangeKeyTestClass(); hashKeyItem.setKey(0); try { mapper.query( IndexRangeKeyTestClass.class, new DynamoDBQueryExpression<IndexRangeKeyTestClass>() .withHashKeyValues(hashKeyItem) .withRangeKeyCondition( INDEX_BAR_RANGE_KEY, new Condition() .withAttributeValueList(new AttributeValue().withN("0")) .withComparisonOperator(ComparisonOperator.GE.toString())) .withIndexName("some_index")); fail("some_index is not a valid index name."); } catch (IllegalArgumentException iae) { System.out.println(iae.getMessage()); } catch (Exception e) { fail("Should trigger an IllegalArgumentException."); } } /** Tests making queries by using range key that is shared by multiple indexes. */ @Test public void testQueryWithRangeKeyForMultipleIndexes() { int multipleIndexRangePerHash = rangePerHash / multipleIndexRangeStep; for (long hashKeyValue : hashKeyValues) { IndexRangeKeyTestClass hashKeyItem = new IndexRangeKeyTestClass(); hashKeyItem.setKey(hashKeyValue); /** Query items by a range key that is shared by multiple indexes */ List<IndexRangeKeyTestClass> result = mapper.query( IndexRangeKeyTestClass.class, new DynamoDBQueryExpression<IndexRangeKeyTestClass>() .withHashKeyValues(hashKeyItem) .withRangeKeyCondition( MULTIPLE_INDEX_RANGE_KEY, new Condition() .withAttributeValueList(new AttributeValue().withN("0")) .withComparisonOperator(ComparisonOperator.GE.toString())) .withIndexName("index_foo_copy")); assertTrue(multipleIndexRangePerHash == result.size()); // check that only the projected attributes are retrieved for (IndexRangeKeyTestClass itemInFooIndex : result) { assertNotNull(itemInFooIndex.getFooAttribute()); assertNotNull(itemInFooIndex.getBarAttribute()); } result = mapper.query( IndexRangeKeyTestClass.class, new DynamoDBQueryExpression<IndexRangeKeyTestClass>() .withHashKeyValues(hashKeyItem) .withRangeKeyCondition( MULTIPLE_INDEX_RANGE_KEY, new Condition() .withAttributeValueList(new AttributeValue().withN("0")) .withComparisonOperator(ComparisonOperator.GE.toString())) .withIndexName("index_bar_copy")); assertTrue(multipleIndexRangePerHash == result.size()); // check that only the projected attributes are retrieved for (IndexRangeKeyTestClass itemInFooIndex : result) { assertNotNull(itemInFooIndex.getFooAttribute()); assertNotNull(itemInFooIndex.getBarAttribute()); } /** Exception when user doesn't specify which index to use */ try { mapper.query( IndexRangeKeyTestClass.class, new DynamoDBQueryExpression<IndexRangeKeyTestClass>() .withHashKeyValues(hashKeyItem) .withRangeKeyCondition( MULTIPLE_INDEX_RANGE_KEY, new Condition() .withAttributeValueList(new AttributeValue().withN("0")) .withComparisonOperator(ComparisonOperator.GE.toString()))); fail("No index name is specified when query with a range key shared by multiple indexes"); } catch (IllegalArgumentException iae) { System.out.println(iae.getMessage()); } catch (Exception e) { fail("Should trigger an IllegalArgumentException."); } /** Exception when user uses an invalid index name */ try { mapper.query( IndexRangeKeyTestClass.class, new DynamoDBQueryExpression<IndexRangeKeyTestClass>() .withHashKeyValues(hashKeyItem) .withRangeKeyCondition( MULTIPLE_INDEX_RANGE_KEY, new Condition() .withAttributeValueList(new AttributeValue().withN("0")) .withComparisonOperator(ComparisonOperator.GE.toString())) .withIndexName("index_foo")); fail( "index_foo is not annotated as part of the localSecondaryIndexNames in " + "the @DynamoDBIndexRangeKey annotation of multipleIndexRangeKey"); } catch (IllegalArgumentException iae) { System.out.println(iae.getMessage()); } catch (Exception e) { fail("Should trigger an IllegalArgumentException."); } } } private IndexRangeKeyTestClass getUniqueObject() { IndexRangeKeyTestClass obj = new IndexRangeKeyTestClass(); obj.setKey(startKey++); obj.setRangeKey((double) start++); obj.setIndexFooRangeKeyWithFakeName((double) start++); obj.setIndexBarRangeKey((double) start++); obj.setFooAttribute("" + startKey++); obj.setBarAttribute("" + startKey++); return obj; } }
4,243
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/MapperLoadingStrategyConfigITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.ConsistentReads; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.PaginationLoadingStrategy; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBScanExpression; import com.amazonaws.services.dynamodbv2.datamodeling.PaginatedList; import com.amazonaws.services.dynamodbv2.mapper.encryption.RangeKeyTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.ComparisonOperator; import com.amazonaws.services.dynamodbv2.model.Condition; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Integration tests for PaginationLoadingStrategy configuration */ public class MapperLoadingStrategyConfigITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static long hashKey = System.currentTimeMillis(); private static int PAGE_SIZE = 5; private static int PARALLEL_SEGMENT = 3; private static int OBJECTS_NUM = 50; private static int RESULTS_NUM = OBJECTS_NUM - 2; // condition: rangeKey > 1.0 @BeforeClass public static void setUp() throws Exception { setUpTableWithRangeAttribute(); createTestData(); } @Test public void testLazyLoading() { // Get all the paginated lists using the tested loading strategy PaginatedList<RangeKeyTestClass> queryList = getTestPaginatedQueryList(PaginationLoadingStrategy.LAZY_LOADING); PaginatedList<RangeKeyTestClass> scanList = getTestPaginatedScanList(PaginationLoadingStrategy.LAZY_LOADING); PaginatedList<RangeKeyTestClass> parallelScanList = getTestPaginatedParallelScanList(PaginationLoadingStrategy.LAZY_LOADING); // check that only at most one page of results are loaded up to this point assertTrue(getLoadedResultsNumber(queryList) <= PAGE_SIZE); assertTrue(getLoadedResultsNumber(scanList) <= PAGE_SIZE); assertTrue(getLoadedResultsNumber(parallelScanList) <= PAGE_SIZE * PARALLEL_SEGMENT); testAllPaginatedListOperations(queryList); testAllPaginatedListOperations(scanList); testAllPaginatedListOperations(parallelScanList); // Re-construct the paginated lists and test the iterator behavior queryList = getTestPaginatedQueryList(PaginationLoadingStrategy.LAZY_LOADING); scanList = getTestPaginatedScanList(PaginationLoadingStrategy.LAZY_LOADING); parallelScanList = getTestPaginatedParallelScanList(PaginationLoadingStrategy.LAZY_LOADING); testPaginatedListIterator(queryList); testPaginatedListIterator(scanList); testPaginatedListIterator(parallelScanList); } @Test public void testEagerLoading() { // Get all the paginated lists using the tested loading strategy PaginatedList<RangeKeyTestClass> queryList = getTestPaginatedQueryList(PaginationLoadingStrategy.EAGER_LOADING); PaginatedList<RangeKeyTestClass> scanList = getTestPaginatedScanList(PaginationLoadingStrategy.EAGER_LOADING); PaginatedList<RangeKeyTestClass> parallelScanList = getTestPaginatedParallelScanList(PaginationLoadingStrategy.EAGER_LOADING); // check that all results have been loaded assertTrue(RESULTS_NUM == getLoadedResultsNumber(queryList)); assertTrue(RESULTS_NUM == getLoadedResultsNumber(scanList)); assertTrue(RESULTS_NUM == getLoadedResultsNumber(parallelScanList)); testAllPaginatedListOperations(queryList); testAllPaginatedListOperations(scanList); testAllPaginatedListOperations(parallelScanList); // Re-construct the paginated lists and test the iterator behavior queryList = getTestPaginatedQueryList(PaginationLoadingStrategy.LAZY_LOADING); scanList = getTestPaginatedScanList(PaginationLoadingStrategy.LAZY_LOADING); parallelScanList = getTestPaginatedParallelScanList(PaginationLoadingStrategy.LAZY_LOADING); testPaginatedListIterator(queryList); testPaginatedListIterator(scanList); testPaginatedListIterator(parallelScanList); } @Test public void testIterationOnly() { // Get all the paginated lists using the tested loading strategy PaginatedList<RangeKeyTestClass> queryList = getTestPaginatedQueryList(PaginationLoadingStrategy.ITERATION_ONLY); PaginatedList<RangeKeyTestClass> scanList = getTestPaginatedScanList(PaginationLoadingStrategy.ITERATION_ONLY); PaginatedList<RangeKeyTestClass> parallelScanList = getTestPaginatedParallelScanList(PaginationLoadingStrategy.ITERATION_ONLY); // check that only at most one page of results are loaded up to this point assertTrue(getLoadedResultsNumber(queryList) <= PAGE_SIZE); assertTrue(getLoadedResultsNumber(scanList) <= PAGE_SIZE); assertTrue(getLoadedResultsNumber(parallelScanList) <= PAGE_SIZE * PARALLEL_SEGMENT); testIterationOnlyPaginatedListOperations(queryList); testIterationOnlyPaginatedListOperations(scanList); testIterationOnlyPaginatedListOperations(parallelScanList); } private static void createTestData() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); List<RangeKeyTestClass> objs = new ArrayList<RangeKeyTestClass>(); for (int i = 0; i < OBJECTS_NUM; i++) { RangeKeyTestClass obj = new RangeKeyTestClass(); obj.setKey(hashKey); obj.setRangeKey(i); objs.add(obj); } mapper.batchSave(objs); } private static PaginatedList<RangeKeyTestClass> getTestPaginatedQueryList( PaginationLoadingStrategy paginationLoadingStrategy) { DynamoDBMapperConfig mapperConfig = new DynamoDBMapperConfig(ConsistentReads.CONSISTENT); DynamoDBMapper mapper = new DynamoDBMapper(dynamo, mapperConfig); // Construct the query expression for the tested hash-key value and any range-key value greater // that 1.0 RangeKeyTestClass keyObject = new RangeKeyTestClass(); keyObject.setKey(hashKey); DynamoDBQueryExpression<RangeKeyTestClass> queryExpression = new DynamoDBQueryExpression<RangeKeyTestClass>().withHashKeyValues(keyObject); queryExpression .withRangeKeyCondition( "rangeKey", new Condition() .withComparisonOperator(ComparisonOperator.GT.toString()) .withAttributeValueList(new AttributeValue().withN("1.0"))) .withLimit(PAGE_SIZE); return mapper.query( RangeKeyTestClass.class, queryExpression, new DynamoDBMapperConfig(paginationLoadingStrategy)); } private static PaginatedList<RangeKeyTestClass> getTestPaginatedScanList( PaginationLoadingStrategy paginationLoadingStrategy) { DynamoDBMapperConfig mapperConfig = new DynamoDBMapperConfig(ConsistentReads.CONSISTENT); DynamoDBMapper mapper = new DynamoDBMapper(dynamo, mapperConfig); // Construct the scan expression with the exact same conditions DynamoDBScanExpression scanExpression = new DynamoDBScanExpression(); scanExpression.addFilterCondition( "key", new Condition() .withComparisonOperator(ComparisonOperator.EQ) .withAttributeValueList(new AttributeValue().withN(Long.toString(hashKey)))); scanExpression.addFilterCondition( "rangeKey", new Condition() .withComparisonOperator(ComparisonOperator.GT) .withAttributeValueList(new AttributeValue().withN("1.0"))); scanExpression.setLimit(PAGE_SIZE); return mapper.scan( RangeKeyTestClass.class, scanExpression, new DynamoDBMapperConfig(paginationLoadingStrategy)); } private static PaginatedList<RangeKeyTestClass> getTestPaginatedParallelScanList( PaginationLoadingStrategy paginationLoadingStrategy) { DynamoDBMapperConfig mapperConfig = new DynamoDBMapperConfig(ConsistentReads.CONSISTENT); DynamoDBMapper mapper = new DynamoDBMapper(dynamo, mapperConfig); // Construct the scan expression with the exact same conditions DynamoDBScanExpression scanExpression = new DynamoDBScanExpression(); scanExpression.addFilterCondition( "key", new Condition() .withComparisonOperator(ComparisonOperator.EQ) .withAttributeValueList(new AttributeValue().withN(Long.toString(hashKey)))); scanExpression.addFilterCondition( "rangeKey", new Condition() .withComparisonOperator(ComparisonOperator.GT) .withAttributeValueList(new AttributeValue().withN("1.0"))); scanExpression.setLimit(PAGE_SIZE); return mapper.parallelScan( RangeKeyTestClass.class, scanExpression, PARALLEL_SEGMENT, new DynamoDBMapperConfig(paginationLoadingStrategy)); } private static void testAllPaginatedListOperations(PaginatedList<RangeKeyTestClass> list) { // (1) isEmpty() assertFalse(list.isEmpty()); // (2) get(int n) assertNotNull(list.get(RESULTS_NUM / 2)); // (3) contains(Object org0) RangeKeyTestClass obj = new RangeKeyTestClass(); obj.setKey(hashKey); obj.setRangeKey(0); assertFalse(list.contains(obj)); obj.setRangeKey(2); assertTrue(list.contains(obj)); // (4) subList(int org0, int arg1) List<RangeKeyTestClass> subList = list.subList(0, RESULTS_NUM); assertTrue(RESULTS_NUM == subList.size()); try { list.subList(0, RESULTS_NUM + 1); fail("IndexOutOfBoundsException is IndexOutOfBoundsException but not thrown"); } catch (IndexOutOfBoundsException e) { } // (5) indexOf(Object org0) assertTrue(list.indexOf(obj) < RESULTS_NUM); // (6) loadAllResults() list.loadAllResults(); // (7) size() assertTrue(RESULTS_NUM == list.size()); } private static void testPaginatedListIterator(PaginatedList<RangeKeyTestClass> list) { for (RangeKeyTestClass item : list) { assertTrue(hashKey == item.getKey()); assertTrue(item.getRangeKey() < OBJECTS_NUM); } // make sure the list could be iterated again for (RangeKeyTestClass item : list) { assertTrue(hashKey == item.getKey()); assertTrue(item.getRangeKey() < OBJECTS_NUM); } } private static void testIterationOnlyPaginatedListOperations( PaginatedList<RangeKeyTestClass> list) { // Unsupported operations // (1) isEmpty() try { list.isEmpty(); fail("UnsupportedOperationException expected but is not thrown"); } catch (UnsupportedOperationException e) { } // (2) get(int n) try { list.get(RESULTS_NUM / 2); fail("UnsupportedOperationException expected but is not thrown"); } catch (UnsupportedOperationException e) { } // (3) contains(Object org0) try { list.contains(new RangeKeyTestClass()); fail("UnsupportedOperationException expected but is not thrown"); } catch (UnsupportedOperationException e) { } // (4) subList(int org0, int arg1) try { list.subList(0, RESULTS_NUM); fail("UnsupportedOperationException expected but is not thrown"); } catch (UnsupportedOperationException e) { } // (5) indexOf(Object org0) try { list.indexOf(new RangeKeyTestClass()); fail("UnsupportedOperationException expected but is not thrown"); } catch (UnsupportedOperationException e) { } // (6) loadAllResults() try { list.loadAllResults(); fail("UnsupportedOperationException expected but is not thrown"); } catch (UnsupportedOperationException e) { } // (7) size() try { list.size(); fail("UnsupportedOperationException expected but is not thrown"); } catch (UnsupportedOperationException e) { } ; // Could be iterated once for (RangeKeyTestClass item : list) { assertTrue(hashKey == item.getKey()); assertTrue(item.getRangeKey() < OBJECTS_NUM); // At most one page of results in memeory assertTrue(getLoadedResultsNumber(list) <= PAGE_SIZE); } // not twice try { for (@SuppressWarnings("unused") RangeKeyTestClass item : list) { fail("UnsupportedOperationException expected but is not thrown"); } } catch (UnsupportedOperationException e) { } } /** Use reflection to get the size of the private allResults field * */ @SuppressWarnings("unchecked") private static int getLoadedResultsNumber(PaginatedList<RangeKeyTestClass> list) { Field privateAllResults = null; try { privateAllResults = list.getClass().getSuperclass().getDeclaredField("allResults"); } catch (SecurityException e) { fail(e.getMessage()); } catch (NoSuchFieldException e) { fail(e.getMessage()); } privateAllResults.setAccessible(true); List<RangeKeyTestClass> allResults = null; try { allResults = (List<RangeKeyTestClass>) privateAllResults.get(list); } catch (IllegalArgumentException e) { fail(e.getMessage()); } catch (IllegalAccessException e) { fail(e.getMessage()); } return allResults.size(); } }
4,244
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/RangeKeyAttributesITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.fail; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.mapper.encryption.RangeKeyTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestEncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Tests range and hash key combination */ public class RangeKeyAttributesITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static final String RANGE_KEY = "rangeKey"; private static final String INTEGER_ATTRIBUTE = "integerSetAttribute"; private static final String BIG_DECIMAL_ATTRIBUTE = "bigDecimalAttribute"; private static final String STRING_SET_ATTRIBUTE = "stringSetAttribute"; private static final String STRING_ATTRIBUTE = "stringAttribute"; private static final String VERSION_ATTRIBUTE = "version"; // We don't start with the current system millis like other tests because // it's out of the range of some data types private static int start = 1; private static final List<Map<String, AttributeValue>> attrs = new LinkedList<Map<String, AttributeValue>>(); // Test data static { for (int i = 0; i < 5; i++) { Map<String, AttributeValue> attr = new HashMap<String, AttributeValue>(); attr.put(KEY_NAME, new AttributeValue().withN("" + startKey++)); attr.put(RANGE_KEY, new AttributeValue().withN("" + start++)); attr.put( INTEGER_ATTRIBUTE, new AttributeValue().withNS("" + start++, "" + start++, "" + start++)); attr.put(BIG_DECIMAL_ATTRIBUTE, new AttributeValue().withN("" + start++)); attr.put(STRING_ATTRIBUTE, new AttributeValue().withS("" + start++)); attr.put( STRING_SET_ATTRIBUTE, new AttributeValue().withSS("" + start++, "" + start++, "" + start++)); attr.put(VERSION_ATTRIBUTE, new AttributeValue().withN("1")); attrs.add(attr); } } ; @BeforeClass public static void setUp() throws Exception { setUpTableWithRangeAttribute(); DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(new TestEncryptionMaterialsProvider()); EncryptionContext context = new EncryptionContext.Builder() .withHashKeyName(KEY_NAME) .withRangeKeyName(RANGE_KEY) .withTableName(TABLE_WITH_RANGE_ATTRIBUTE) .build(); // Insert the data for (Map<String, AttributeValue> attr : attrs) { attr = encryptor.encryptAllFieldsExcept( attr, context, KEY_NAME, RANGE_KEY, VERSION_ATTRIBUTE, BIG_DECIMAL_ATTRIBUTE); dynamo.putItem(new PutItemRequest(TABLE_WITH_RANGE_ATTRIBUTE, attr)); } } @Test public void testLoad() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (Map<String, AttributeValue> attr : attrs) { RangeKeyTestClass x = util.load( newRangeKey( Long.parseLong(attr.get(KEY_NAME).getN()), Double.parseDouble(attr.get(RANGE_KEY).getN()))); // Convert all numbers to the most inclusive type for easy // comparison assertEquals(new BigDecimal(x.getKey()), new BigDecimal(attr.get(KEY_NAME).getN())); assertEquals(new BigDecimal(x.getRangeKey()), new BigDecimal(attr.get(RANGE_KEY).getN())); assertEquals( new BigDecimal(x.getVersion()), new BigDecimal(attr.get(VERSION_ATTRIBUTE).getN())); assertEquals( x.getBigDecimalAttribute(), new BigDecimal(attr.get(BIG_DECIMAL_ATTRIBUTE).getN())); assertNumericSetsEquals(x.getIntegerAttribute(), attr.get(INTEGER_ATTRIBUTE).getNS()); assertEquals(x.getStringAttribute(), attr.get(STRING_ATTRIBUTE).getS()); assertSetsEqual(x.getStringSetAttribute(), toSet(attr.get(STRING_SET_ATTRIBUTE).getSS())); } } private RangeKeyTestClass newRangeKey(long hashKey, double rangeKey) { RangeKeyTestClass obj = new RangeKeyTestClass(); obj.setKey(hashKey); obj.setRangeKey(rangeKey); return obj; } @Test public void testSave() throws Exception { List<RangeKeyTestClass> objs = new ArrayList<RangeKeyTestClass>(); for (int i = 0; i < 5; i++) { RangeKeyTestClass obj = getUniqueObject(); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (RangeKeyTestClass obj : objs) { util.save(obj); } for (RangeKeyTestClass obj : objs) { RangeKeyTestClass loaded = util.load(RangeKeyTestClass.class, obj.getKey(), obj.getRangeKey()); assertEquals(obj, loaded); } } @Test public void testUpdate() throws Exception { List<RangeKeyTestClass> objs = new ArrayList<RangeKeyTestClass>(); for (int i = 0; i < 5; i++) { RangeKeyTestClass obj = getUniqueObject(); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (RangeKeyTestClass obj : objs) { util.save(obj); } for (RangeKeyTestClass obj : objs) { RangeKeyTestClass replacement = getUniqueObject(); replacement.setKey(obj.getKey()); replacement.setRangeKey(obj.getRangeKey()); replacement.setVersion(obj.getVersion()); util.save(replacement); RangeKeyTestClass loadedObject = util.load(RangeKeyTestClass.class, obj.getKey(), obj.getRangeKey()); assertEquals(replacement, loadedObject); // If we try to update the old version, we should get an error replacement.setVersion(replacement.getVersion() - 1); try { util.save(replacement); fail("Should have thrown an exception"); } catch (Exception expected) { } } } private RangeKeyTestClass getUniqueObject() { RangeKeyTestClass obj = new RangeKeyTestClass(); obj.setKey(startKey++); obj.setIntegerAttribute(toSet(start++, start++, start++)); obj.setBigDecimalAttribute(new BigDecimal(startKey++)); obj.setRangeKey(start++); obj.setStringAttribute("" + startKey++); obj.setStringSetAttribute(toSet("" + startKey++, "" + startKey++, "" + startKey++)); return obj; } }
4,245
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/HashKeyOnlyTableWithGSIITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBIndexHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBIndexRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.PaginatedQueryList; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotEncrypt; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.ComparisonOperator; import com.amazonaws.services.dynamodbv2.model.Condition; import com.amazonaws.services.dynamodbv2.model.CreateTableRequest; import com.amazonaws.services.dynamodbv2.model.GlobalSecondaryIndex; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.Projection; import com.amazonaws.services.dynamodbv2.model.ProjectionType; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType; import com.amazonaws.services.dynamodbv2.util.TableUtils; import java.util.ArrayList; import java.util.List; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Integration test for GSI support with a table that has no primary range key (only a primary hash * key). */ public class HashKeyOnlyTableWithGSIITCase extends DynamoDBMapperCryptoIntegrationTestBase { public static final String HASH_KEY_ONLY_TABLE_NAME = "no-primary-range-key-gsi-test-crypto"; @BeforeClass public static void setUp() throws Exception { DynamoDBTestBase.setUpTestBase(); List<KeySchemaElement> keySchema = new ArrayList<KeySchemaElement>(); keySchema.add(new KeySchemaElement("id", KeyType.HASH)); CreateTableRequest req = new CreateTableRequest(HASH_KEY_ONLY_TABLE_NAME, keySchema) .withProvisionedThroughput(new ProvisionedThroughput(10L, 10L)) .withAttributeDefinitions( new AttributeDefinition("id", ScalarAttributeType.S), new AttributeDefinition("status", ScalarAttributeType.S), new AttributeDefinition("ts", ScalarAttributeType.S)) .withGlobalSecondaryIndexes( new GlobalSecondaryIndex() .withProvisionedThroughput(new ProvisionedThroughput(10L, 10L)) .withIndexName("statusAndCreation") .withKeySchema( new KeySchemaElement("status", KeyType.HASH), new KeySchemaElement("ts", KeyType.RANGE)) .withProjection(new Projection().withProjectionType(ProjectionType.ALL))); TableUtils.createTableIfNotExists(dynamo, req); TableUtils.waitUntilActive(dynamo, HASH_KEY_ONLY_TABLE_NAME); } @AfterClass public static void tearDown() throws Exception { dynamo.deleteTable(HASH_KEY_ONLY_TABLE_NAME); } @DynamoDBTable(tableName = HASH_KEY_ONLY_TABLE_NAME) public static class User { private String id; private String status; private String ts; @DynamoDBHashKey public String getId() { return id; } public void setId(String id) { this.id = id; } @DoNotEncrypt @DynamoDBIndexHashKey(globalSecondaryIndexName = "statusAndCreation") public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @DoNotEncrypt @DynamoDBIndexRangeKey(globalSecondaryIndexName = "statusAndCreation") public String getTs() { return ts; } public void setTs(String ts) { this.ts = ts; } } /** Tests that we can query using the hash/range GSI on our hash-key only table. */ @Test public void testGSIQuery() throws Exception { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); String status = "foo-status"; User user = new User(); user.setId("123"); user.setStatus(status); user.setTs("321"); mapper.save(user); DynamoDBQueryExpression<User> expr = new DynamoDBQueryExpression<User>() .withIndexName("statusAndCreation") .withLimit(100) .withConsistentRead(false) .withHashKeyValues(user) .withRangeKeyCondition( "ts", new Condition() .withComparisonOperator(ComparisonOperator.GT) .withAttributeValueList(new AttributeValue("100"))); PaginatedQueryList<User> query = mapper.query(User.class, expr); int size = query.size(); if (DEBUG) System.err.println("size=" + size); assertTrue(1 == size); assertEquals(status, query.get(0).getStatus()); } private static final boolean DEBUG = false; }
4,246
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/SimpleNumericAttributesITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.mapper.encryption.NumberAttributeTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestEncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.GetItemRequest; import com.amazonaws.services.dynamodbv2.model.GetItemResult; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Tests numeric attributes */ public class SimpleNumericAttributesITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static final String INT_ATTRIBUTE = "intAttribute"; private static final String INTEGER_ATTRIBUTE = "integerAttribute"; private static final String FLOAT_ATTRIBUTE = "floatAttribute"; private static final String FLOAT_OBJECT_ATTRIBUTE = "floatObjectAttribute"; private static final String DOUBLE_ATTRIBUTE = "doubleAttribute"; private static final String DOUBLE_OBJECT_ATTRIBUTE = "doubleObjectAttribute"; private static final String BIG_INTEGER_ATTRIBUTE = "bigIntegerAttribute"; private static final String BIG_DECIMAL_ATTRIBUTE = "bigDecimalAttribute"; private static final String LONG_ATTRIBUTE = "longAttribute"; private static final String LONG_OBJECT_ATTRIBUTE = "longObjectAttribute"; private static final String BYTE_ATTRIBUTE = "byteAttribute"; private static final String BYTE_OBJECT_ATTRIBUTE = "byteObjectAttribute"; private static final String BOOLEAN_ATTRIBUTE = "booleanAttribute"; private static final String BOOLEAN_OBJECT_ATTRIBUTE = "booleanObjectAttribute"; private static final String SHORT_ATTRIBUTE = "shortAttribute"; private static final String SHORT_OBJECT_ATTRIBUTE = "shortObjectAttribute"; // We don't start with the current system millis like other tests because // it's out of the range of some data types private static int start = 1; private static int byteStart = -127; private static final List<Map<String, AttributeValue>> attrs = new LinkedList<Map<String, AttributeValue>>(); // Test data static { for (int i = 0; i < 5; i++) { Map<String, AttributeValue> attr = new HashMap<String, AttributeValue>(); attr.put(KEY_NAME, new AttributeValue().withS("" + start++)); attr.put(INT_ATTRIBUTE, new AttributeValue().withN("" + start++)); attr.put(INTEGER_ATTRIBUTE, new AttributeValue().withN("" + start++)); attr.put(FLOAT_ATTRIBUTE, new AttributeValue().withN("" + start++)); attr.put(FLOAT_OBJECT_ATTRIBUTE, new AttributeValue().withN("" + start++)); attr.put(DOUBLE_ATTRIBUTE, new AttributeValue().withN("" + start++)); attr.put(DOUBLE_OBJECT_ATTRIBUTE, new AttributeValue().withN("" + start++)); attr.put(BIG_INTEGER_ATTRIBUTE, new AttributeValue().withN("" + start++)); attr.put(BIG_DECIMAL_ATTRIBUTE, new AttributeValue().withN("" + start++)); attr.put(LONG_ATTRIBUTE, new AttributeValue().withN("" + start++)); attr.put(LONG_OBJECT_ATTRIBUTE, new AttributeValue().withN("" + start++)); attr.put(BYTE_ATTRIBUTE, new AttributeValue().withN("" + byteStart++)); attr.put(BYTE_OBJECT_ATTRIBUTE, new AttributeValue().withN("" + byteStart++)); attr.put(BOOLEAN_ATTRIBUTE, new AttributeValue().withN(start++ % 2 == 0 ? "1" : "0")); attr.put(BOOLEAN_OBJECT_ATTRIBUTE, new AttributeValue().withN(start++ % 2 == 0 ? "1" : "0")); attr.put(SHORT_ATTRIBUTE, new AttributeValue().withN("" + byteStart++)); attr.put(SHORT_OBJECT_ATTRIBUTE, new AttributeValue().withN("" + byteStart++)); attrs.add(attr); } } ; @BeforeClass public static void setUp() throws Exception { DynamoDBMapperCryptoIntegrationTestBase.setUp(); DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(new TestEncryptionMaterialsProvider()); EncryptionContext context = new EncryptionContext.Builder().withHashKeyName(KEY_NAME).withTableName(TABLE_NAME).build(); // Insert the data for (Map<String, AttributeValue> attr : attrs) { attr = encryptor.encryptAllFieldsExcept(attr, context, KEY_NAME); dynamo.putItem(new PutItemRequest(TABLE_NAME, attr)); } } private NumberAttributeTestClass getKeyObject(String key) { NumberAttributeTestClass obj = new NumberAttributeTestClass(); obj.setKey(key); return obj; } @Test public void testLoad() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (Map<String, AttributeValue> attr : attrs) { NumberAttributeTestClass x = util.load(getKeyObject(attr.get(KEY_NAME).getS())); assertEquals(x.getKey(), attr.get(KEY_NAME).getS()); // Convert all numbers to the most inclusive type for easy comparison assertEquals( x.getBigDecimalAttribute(), new BigDecimal(attr.get(BIG_DECIMAL_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getBigIntegerAttribute()), new BigDecimal(attr.get(BIG_INTEGER_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getFloatAttribute()), new BigDecimal(attr.get(FLOAT_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getFloatObjectAttribute()), new BigDecimal(attr.get(FLOAT_OBJECT_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getDoubleAttribute()), new BigDecimal(attr.get(DOUBLE_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getDoubleObjectAttribute()), new BigDecimal(attr.get(DOUBLE_OBJECT_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getIntAttribute()), new BigDecimal(attr.get(INT_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getIntegerAttribute()), new BigDecimal(attr.get(INTEGER_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getLongAttribute()), new BigDecimal(attr.get(LONG_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getLongObjectAttribute()), new BigDecimal(attr.get(LONG_OBJECT_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getByteAttribute()), new BigDecimal(attr.get(BYTE_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getByteObjectAttribute()), new BigDecimal(attr.get(BYTE_OBJECT_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getShortAttribute()), new BigDecimal(attr.get(SHORT_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getShortObjectAttribute()), new BigDecimal(attr.get(SHORT_OBJECT_ATTRIBUTE).getN())); assertEquals(x.isBooleanAttribute(), attr.get(BOOLEAN_ATTRIBUTE).getN().equals("1")); assertEquals( (Object) x.getBooleanObjectAttribute(), (Object) attr.get(BOOLEAN_OBJECT_ATTRIBUTE).getN().equals("1")); } // Test loading an object that doesn't exist assertNull(util.load(getKeyObject("does not exist"))); } @Test public void testSave() throws Exception { List<NumberAttributeTestClass> objs = new ArrayList<NumberAttributeTestClass>(); for (int i = 0; i < 5; i++) { NumberAttributeTestClass obj = getUniqueObject(); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (NumberAttributeTestClass obj : objs) { util.save(obj); } for (NumberAttributeTestClass obj : objs) { NumberAttributeTestClass loaded = util.load(obj); loaded.setIgnored(obj.getIgnored()); assertEquals(obj, loaded); } } @Test public void testUpdate() throws Exception { List<NumberAttributeTestClass> objs = new ArrayList<NumberAttributeTestClass>(); for (int i = 0; i < 5; i++) { NumberAttributeTestClass obj = getUniqueObject(); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (NumberAttributeTestClass obj : objs) { util.save(obj); } for (NumberAttributeTestClass obj : objs) { NumberAttributeTestClass replacement = getUniqueObject(); replacement.setKey(obj.getKey()); util.save(replacement); NumberAttributeTestClass loadedObject = util.load(obj); assertFalse(replacement.getIgnored().equals(loadedObject.getIgnored())); loadedObject.setIgnored(replacement.getIgnored()); assertEquals(replacement, loadedObject); } } /** Tests automatically setting a hash key upon saving. */ @Test public void testSetHashKey() throws Exception { List<NumberAttributeTestClass> objs = new ArrayList<NumberAttributeTestClass>(); for (int i = 0; i < 5; i++) { NumberAttributeTestClass obj = getUniqueObject(); obj.setKey(null); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (NumberAttributeTestClass obj : objs) { assertNull(obj.getKey()); util.save(obj); assertNotNull(obj.getKey()); NumberAttributeTestClass loadedObject = util.load(obj); assertFalse(obj.getIgnored().equals(loadedObject.getIgnored())); loadedObject.setIgnored(obj.getIgnored()); assertEquals(obj, loadedObject); } } @Test public void testDelete() throws Exception { NumberAttributeTestClass obj = getUniqueObject(); DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.save(obj); NumberAttributeTestClass loaded = util.load(NumberAttributeTestClass.class, obj.getKey()); loaded.setIgnored(obj.getIgnored()); assertEquals(obj, loaded); util.delete(obj); assertNull(util.load(NumberAttributeTestClass.class, obj.getKey())); } @Test public void performanceTest() throws Exception { NumberAttributeTestClass obj = getUniqueObject(); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.save(obj); HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>(); key.put(KEY_NAME, new AttributeValue().withS(obj.getKey())); GetItemResult item = dynamo.getItem(new GetItemRequest().withTableName("aws-java-sdk-util-crypto").withKey(key)); long start = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { mapper.marshallIntoObject(NumberAttributeTestClass.class, item.getItem()); } long end = System.currentTimeMillis(); System.err.println("time: " + (end - start)); } private NumberAttributeTestClass getUniqueObject() { NumberAttributeTestClass obj = new NumberAttributeTestClass(); obj.setKey(String.valueOf(startKey++)); obj.setBigDecimalAttribute(new BigDecimal(startKey++)); obj.setBigIntegerAttribute(new BigInteger("" + startKey++)); obj.setByteAttribute((byte) byteStart++); obj.setByteObjectAttribute(new Byte("" + byteStart++)); obj.setDoubleAttribute(new Double("" + start++)); obj.setDoubleObjectAttribute(new Double("" + start++)); obj.setFloatAttribute(new Float("" + start++)); obj.setFloatObjectAttribute(new Float("" + start++)); obj.setIntAttribute(new Integer("" + start++)); obj.setIntegerAttribute(new Integer("" + start++)); obj.setLongAttribute(new Long("" + start++)); obj.setLongObjectAttribute(new Long("" + start++)); obj.setShortAttribute(new Short("" + start++)); obj.setShortObjectAttribute(new Short("" + start++)); obj.setDateAttribute(new Date(startKey++)); obj.setBooleanAttribute(start++ % 2 == 0); obj.setBooleanObjectAttribute(start++ % 2 == 0); obj.setIgnored("" + start++); Calendar cal = GregorianCalendar.getInstance(); cal.setTime(new Date(startKey++)); obj.setCalendarAttribute(cal); return obj; } }
4,247
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/NumericSetAttributesITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.mapper.encryption.NumberSetAttributeTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestEncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Tests string set attributes */ public class NumericSetAttributesITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static final String INTEGER_ATTRIBUTE = "integerAttribute"; private static final String FLOAT_OBJECT_ATTRIBUTE = "floatObjectAttribute"; private static final String DOUBLE_OBJECT_ATTRIBUTE = "doubleObjectAttribute"; private static final String BIG_INTEGER_ATTRIBUTE = "bigIntegerAttribute"; private static final String BIG_DECIMAL_ATTRIBUTE = "bigDecimalAttribute"; private static final String LONG_OBJECT_ATTRIBUTE = "longObjectAttribute"; private static final String BYTE_OBJECT_ATTRIBUTE = "byteObjectAttribute"; private static final String BOOLEAN_ATTRIBUTE = "booleanAttribute"; // We don't start with the current system millis like other tests because // it's out of the range of some data types private static int start = 1; private static int byteStart = 1; private static final List<Map<String, AttributeValue>> attrs = new LinkedList<Map<String, AttributeValue>>(); // Test data static { for (int i = 0; i < 5; i++) { Map<String, AttributeValue> attr = new HashMap<String, AttributeValue>(); attr.put(KEY_NAME, new AttributeValue().withS("" + start++)); attr.put( INTEGER_ATTRIBUTE, new AttributeValue().withNS("" + start++, "" + start++, "" + start++)); attr.put( FLOAT_OBJECT_ATTRIBUTE, new AttributeValue().withNS("" + start++, "" + start++, "" + start++)); attr.put( DOUBLE_OBJECT_ATTRIBUTE, new AttributeValue().withNS("" + start++, "" + start++, "" + start++)); attr.put( BIG_INTEGER_ATTRIBUTE, new AttributeValue().withNS("" + start++, "" + start++, "" + start++)); attr.put( BIG_DECIMAL_ATTRIBUTE, new AttributeValue().withNS("" + start++, "" + start++, "" + start++)); attr.put( LONG_OBJECT_ATTRIBUTE, new AttributeValue().withNS("" + start++, "" + start++, "" + start++)); attr.put( BYTE_OBJECT_ATTRIBUTE, new AttributeValue().withNS("" + byteStart++, "" + byteStart++, "" + byteStart++)); attr.put(BOOLEAN_ATTRIBUTE, new AttributeValue().withNS("0", "1")); attrs.add(attr); } } ; @BeforeClass public static void setUp() throws Exception { DynamoDBMapperCryptoIntegrationTestBase.setUp(); DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(new TestEncryptionMaterialsProvider()); EncryptionContext context = new EncryptionContext.Builder().withHashKeyName(KEY_NAME).withTableName(TABLE_NAME).build(); // Insert the data for (Map<String, AttributeValue> attr : attrs) { attr = encryptor.encryptAllFieldsExcept(attr, context, KEY_NAME); dynamo.putItem(new PutItemRequest(TABLE_NAME, attr)); } } @Test public void testLoad() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (Map<String, AttributeValue> attr : attrs) { NumberSetAttributeTestClass x = util.load(NumberSetAttributeTestClass.class, attr.get(KEY_NAME).getS()); assertEquals(x.getKey(), attr.get(KEY_NAME).getS()); // Convert all numbers to the most inclusive type for easy comparison assertNumericSetsEquals(x.getBigDecimalAttribute(), attr.get(BIG_DECIMAL_ATTRIBUTE).getNS()); assertNumericSetsEquals(x.getBigIntegerAttribute(), attr.get(BIG_INTEGER_ATTRIBUTE).getNS()); assertNumericSetsEquals( x.getFloatObjectAttribute(), attr.get(FLOAT_OBJECT_ATTRIBUTE).getNS()); assertNumericSetsEquals( x.getDoubleObjectAttribute(), attr.get(DOUBLE_OBJECT_ATTRIBUTE).getNS()); assertNumericSetsEquals(x.getIntegerAttribute(), attr.get(INTEGER_ATTRIBUTE).getNS()); assertNumericSetsEquals(x.getLongObjectAttribute(), attr.get(LONG_OBJECT_ATTRIBUTE).getNS()); assertNumericSetsEquals(x.getByteObjectAttribute(), attr.get(BYTE_OBJECT_ATTRIBUTE).getNS()); assertSetsEqual(toSet("0", "1"), attr.get(BOOLEAN_ATTRIBUTE).getNS()); } } @Test public void testSave() throws Exception { List<NumberSetAttributeTestClass> objs = new ArrayList<NumberSetAttributeTestClass>(); for (int i = 0; i < 5; i++) { NumberSetAttributeTestClass obj = getUniqueObject(); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (NumberSetAttributeTestClass obj : objs) { util.save(obj); } for (NumberSetAttributeTestClass obj : objs) { NumberSetAttributeTestClass loaded = util.load(NumberSetAttributeTestClass.class, obj.getKey()); assertEquals(obj, loaded); } } @Test public void testUpdate() throws Exception { List<NumberSetAttributeTestClass> objs = new ArrayList<NumberSetAttributeTestClass>(); for (int i = 0; i < 5; i++) { NumberSetAttributeTestClass obj = getUniqueObject(); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (NumberSetAttributeTestClass obj : objs) { util.save(obj); } for (NumberSetAttributeTestClass obj : objs) { NumberSetAttributeTestClass replacement = getUniqueObject(); replacement.setKey(obj.getKey()); util.save(replacement); assertEquals(replacement, util.load(NumberSetAttributeTestClass.class, obj.getKey())); } } private NumberSetAttributeTestClass getUniqueObject() { NumberSetAttributeTestClass obj = new NumberSetAttributeTestClass(); obj.setKey(String.valueOf(startKey++)); obj.setBigDecimalAttribute( toSet(new BigDecimal(startKey++), new BigDecimal(startKey++), new BigDecimal(startKey++))); obj.setBigIntegerAttribute( toSet( new BigInteger("" + startKey++), new BigInteger("" + startKey++), new BigInteger("" + startKey++))); obj.setByteObjectAttribute( toSet(new Byte("" + byteStart++), new Byte("" + byteStart++), new Byte("" + byteStart++))); obj.setDoubleObjectAttribute( toSet(new Double("" + start++), new Double("" + start++), new Double("" + start++))); obj.setFloatObjectAttribute( toSet(new Float("" + start++), new Float("" + start++), new Float("" + start++))); obj.setIntegerAttribute( toSet(new Integer("" + start++), new Integer("" + start++), new Integer("" + start++))); obj.setLongObjectAttribute( toSet(new Long("" + start++), new Long("" + start++), new Long("" + start++))); obj.setBooleanAttribute(toSet(true, false)); obj.setDateAttribute(toSet(new Date(startKey++), new Date(startKey++), new Date(startKey++))); Set<Calendar> cals = new HashSet<Calendar>(); for (Date d : obj.getDateAttribute()) { Calendar cal = GregorianCalendar.getInstance(); cal.setTime(d); cals.add(cal); } obj.setCalendarAttribute(toSet(cals)); return obj; } }
4,248
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/BinaryAttributesITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.mapper.encryption.BinaryAttributeByteArrayTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.BinaryAttributeByteBufferTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestEncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Tests simple string attributes */ public class BinaryAttributesITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static final String BINARY_ATTRIBUTE = "binaryAttribute"; private static final String BINARY_SET_ATTRIBUTE = "binarySetAttribute"; private static final List<Map<String, AttributeValue>> attrs = new LinkedList<Map<String, AttributeValue>>(); private static final int contentLength = 512; // Test data static { Map<String, AttributeValue> attr = new HashMap<String, AttributeValue>(); attr.put(KEY_NAME, new AttributeValue().withS("" + startKey++)); attr.put( BINARY_ATTRIBUTE, new AttributeValue().withB(ByteBuffer.wrap(generateByteArray(contentLength)))); attr.put( BINARY_SET_ATTRIBUTE, new AttributeValue() .withBS( ByteBuffer.wrap(generateByteArray(contentLength)), ByteBuffer.wrap(generateByteArray(contentLength + 1)))); attrs.add(attr); } ; @BeforeClass public static void setUp() throws Exception { DynamoDBMapperCryptoIntegrationTestBase.setUp(); DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(new TestEncryptionMaterialsProvider()); EncryptionContext context = new EncryptionContext.Builder().withHashKeyName(KEY_NAME).withTableName(TABLE_NAME).build(); // Insert the data for (Map<String, AttributeValue> attr : attrs) { attr = encryptor.encryptAllFieldsExcept(attr, context, KEY_NAME); dynamo.putItem(new PutItemRequest(TABLE_NAME, attr)); } } @Test public void testLoad() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (Map<String, AttributeValue> attr : attrs) { // test BinaryAttributeClass BinaryAttributeByteBufferTestClass x = util.load(BinaryAttributeByteBufferTestClass.class, attr.get(KEY_NAME).getS()); assertEquals(x.getKey(), attr.get(KEY_NAME).getS()); assertEquals(x.getBinaryAttribute(), ByteBuffer.wrap(generateByteArray(contentLength))); assertTrue( x.getBinarySetAttribute().contains(ByteBuffer.wrap(generateByteArray(contentLength)))); assertTrue( x.getBinarySetAttribute() .contains(ByteBuffer.wrap(generateByteArray(contentLength + 1)))); // test BinaryAttributeByteArrayTestClass BinaryAttributeByteArrayTestClass y = util.load(BinaryAttributeByteArrayTestClass.class, attr.get(KEY_NAME).getS()); assertEquals(y.getKey(), attr.get(KEY_NAME).getS()); assertTrue(Arrays.equals(y.getBinaryAttribute(), (generateByteArray(contentLength)))); assertTrue(2 == y.getBinarySetAttribute().size()); assertTrue(setContainsBytes(y.getBinarySetAttribute(), generateByteArray(contentLength))); assertTrue(setContainsBytes(y.getBinarySetAttribute(), generateByteArray(contentLength + 1))); } } @Test public void testSave() { // test BinaryAttributeClass List<BinaryAttributeByteBufferTestClass> byteBufferObjs = new ArrayList<BinaryAttributeByteBufferTestClass>(); for (int i = 0; i < 5; i++) { BinaryAttributeByteBufferTestClass obj = getUniqueByteBufferObject(contentLength); byteBufferObjs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (BinaryAttributeByteBufferTestClass obj : byteBufferObjs) { util.save(obj); } for (BinaryAttributeByteBufferTestClass obj : byteBufferObjs) { BinaryAttributeByteBufferTestClass loaded = util.load(BinaryAttributeByteBufferTestClass.class, obj.getKey()); assertEquals(loaded.getKey(), obj.getKey()); assertEquals(loaded.getBinaryAttribute(), ByteBuffer.wrap(generateByteArray(contentLength))); assertTrue( loaded .getBinarySetAttribute() .contains(ByteBuffer.wrap(generateByteArray(contentLength)))); } // test BinaryAttributeByteArrayTestClass List<BinaryAttributeByteArrayTestClass> bytesObjs = new ArrayList<BinaryAttributeByteArrayTestClass>(); for (int i = 0; i < 5; i++) { BinaryAttributeByteArrayTestClass obj = getUniqueBytesObject(contentLength); bytesObjs.add(obj); } for (BinaryAttributeByteArrayTestClass obj : bytesObjs) { util.save(obj); } for (BinaryAttributeByteArrayTestClass obj : bytesObjs) { BinaryAttributeByteArrayTestClass loaded = util.load(BinaryAttributeByteArrayTestClass.class, obj.getKey()); assertEquals(loaded.getKey(), obj.getKey()); assertTrue(Arrays.equals(loaded.getBinaryAttribute(), (generateByteArray(contentLength)))); assertTrue(1 == loaded.getBinarySetAttribute().size()); assertTrue( setContainsBytes(loaded.getBinarySetAttribute(), generateByteArray(contentLength))); } } /** Tests saving an incomplete object into DynamoDB */ @Test public void testIncompleteObject() { // test BinaryAttributeClass BinaryAttributeByteBufferTestClass byteBufferObj = getUniqueByteBufferObject(contentLength); byteBufferObj.setBinarySetAttribute(null); DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.save(byteBufferObj); BinaryAttributeByteBufferTestClass loadedX = util.load(BinaryAttributeByteBufferTestClass.class, byteBufferObj.getKey()); assertEquals(loadedX.getKey(), byteBufferObj.getKey()); assertEquals(loadedX.getBinaryAttribute(), ByteBuffer.wrap(generateByteArray(contentLength))); assertEquals(loadedX.getBinarySetAttribute(), null); // test removing an attribute assertNotNull(byteBufferObj.getBinaryAttribute()); byteBufferObj.setBinaryAttribute(null); util.save(byteBufferObj); loadedX = util.load(BinaryAttributeByteBufferTestClass.class, byteBufferObj.getKey()); assertEquals(loadedX.getKey(), byteBufferObj.getKey()); assertEquals(loadedX.getBinaryAttribute(), null); assertEquals(loadedX.getBinarySetAttribute(), null); // test BinaryAttributeByteArrayTestClass BinaryAttributeByteArrayTestClass bytesObj = getUniqueBytesObject(contentLength); bytesObj.setBinarySetAttribute(null); util.save(bytesObj); BinaryAttributeByteArrayTestClass loadedY = util.load(BinaryAttributeByteArrayTestClass.class, bytesObj.getKey()); assertEquals(loadedY.getKey(), bytesObj.getKey()); assertTrue(Arrays.equals(loadedY.getBinaryAttribute(), generateByteArray(contentLength))); assertEquals(loadedY.getBinarySetAttribute(), null); // test removing an attribute assertNotNull(bytesObj.getBinaryAttribute()); bytesObj.setBinaryAttribute(null); util.save(bytesObj); loadedY = util.load(BinaryAttributeByteArrayTestClass.class, bytesObj.getKey()); assertEquals(loadedY.getKey(), bytesObj.getKey()); assertEquals(loadedY.getBinaryAttribute(), null); assertEquals(loadedY.getBinarySetAttribute(), null); } @Test public void testUpdate() { // test BinaryAttributeClass List<BinaryAttributeByteBufferTestClass> byteBufferObjs = new ArrayList<BinaryAttributeByteBufferTestClass>(); for (int i = 0; i < 5; i++) { BinaryAttributeByteBufferTestClass obj = getUniqueByteBufferObject(contentLength); byteBufferObjs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (BinaryAttributeByteBufferTestClass obj : byteBufferObjs) { util.save(obj); } for (BinaryAttributeByteBufferTestClass obj : byteBufferObjs) { BinaryAttributeByteBufferTestClass replacement = getUniqueByteBufferObject(contentLength - 1); replacement.setKey(obj.getKey()); util.save(replacement); BinaryAttributeByteBufferTestClass loaded = util.load(BinaryAttributeByteBufferTestClass.class, obj.getKey()); assertEquals(loaded.getKey(), obj.getKey()); assertEquals( loaded.getBinaryAttribute(), ByteBuffer.wrap(generateByteArray(contentLength - 1))); assertTrue( loaded .getBinarySetAttribute() .contains(ByteBuffer.wrap(generateByteArray(contentLength - 1)))); } // test BinaryAttributeByteArrayTestClass List<BinaryAttributeByteArrayTestClass> bytesObj = new ArrayList<BinaryAttributeByteArrayTestClass>(); for (int i = 0; i < 5; i++) { BinaryAttributeByteArrayTestClass obj = getUniqueBytesObject(contentLength); bytesObj.add(obj); } for (BinaryAttributeByteArrayTestClass obj : bytesObj) { util.save(obj); } for (BinaryAttributeByteArrayTestClass obj : bytesObj) { BinaryAttributeByteArrayTestClass replacement = getUniqueBytesObject(contentLength - 1); replacement.setKey(obj.getKey()); util.save(replacement); BinaryAttributeByteArrayTestClass loaded = util.load(BinaryAttributeByteArrayTestClass.class, obj.getKey()); assertEquals(loaded.getKey(), obj.getKey()); assertTrue( Arrays.equals(loaded.getBinaryAttribute(), (generateByteArray(contentLength - 1)))); assertTrue(1 == loaded.getBinarySetAttribute().size()); assertTrue( setContainsBytes(loaded.getBinarySetAttribute(), generateByteArray(contentLength - 1))); } } @Test public void testDelete() throws Exception { // test BinaryAttributeClass BinaryAttributeByteBufferTestClass byteBufferObj = getUniqueByteBufferObject(contentLength); DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.save(byteBufferObj); util.delete(byteBufferObj); assertNull(util.load(BinaryAttributeByteBufferTestClass.class, byteBufferObj.getKey())); // test BinaryAttributeByteArrayTestClass BinaryAttributeByteArrayTestClass bytesObj = getUniqueBytesObject(contentLength); util.save(bytesObj); util.delete(bytesObj); assertNull(util.load(BinaryAttributeByteArrayTestClass.class, bytesObj.getKey())); } private BinaryAttributeByteArrayTestClass getUniqueBytesObject(int contentLength) { BinaryAttributeByteArrayTestClass obj = new BinaryAttributeByteArrayTestClass(); obj.setKey(String.valueOf(startKey++)); obj.setBinaryAttribute(generateByteArray(contentLength)); Set<byte[]> byteArray = new HashSet<byte[]>(); byteArray.add(generateByteArray(contentLength)); obj.setBinarySetAttribute(byteArray); return obj; } private boolean setContainsBytes(Set<byte[]> set, byte[] bytes) { Iterator<byte[]> iter = set.iterator(); while (iter.hasNext()) { if (Arrays.equals(iter.next(), bytes)) return true; } return false; } }
4,249
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/ScanITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBScanExpression; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.PaginatedParallelScanList; import com.amazonaws.services.dynamodbv2.datamodeling.ScanResultPage; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.ComparisonOperator; import com.amazonaws.services.dynamodbv2.model.Condition; import com.amazonaws.services.dynamodbv2.model.ConditionalOperator; import com.amazonaws.services.dynamodbv2.model.CreateTableRequest; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType; import com.amazonaws.services.dynamodbv2.util.TableUtils; import com.amazonaws.util.ImmutableMapParameter; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.UUID; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Integration tests for the scan operation on DynamoDBMapper. */ public class ScanITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static final String TABLE_NAME = "aws-java-sdk-util-scan-crypto"; /** * We set a small limit in order to test the behavior of PaginatedList when it could not load all * the scan result in one batch. */ private static final int SCAN_LIMIT = 10; private static final int PARALLEL_SCAN_SEGMENTS = 5; private static void createTestData() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (int i = 0; i < 500; i++) { util.save(new SimpleClass(Integer.toString(i), Integer.toString(i))); } } @BeforeClass public static void setUpTestData() throws Exception { String keyName = "id"; CreateTableRequest createTableRequest = new CreateTableRequest() .withTableName(TABLE_NAME) .withKeySchema( new KeySchemaElement().withAttributeName(keyName).withKeyType(KeyType.HASH)) .withAttributeDefinitions( new AttributeDefinition() .withAttributeName(keyName) .withAttributeType(ScalarAttributeType.S)); createTableRequest.setProvisionedThroughput( new ProvisionedThroughput().withReadCapacityUnits(10L).withWriteCapacityUnits(5L)); TableUtils.createTableIfNotExists(dynamo, createTableRequest); TableUtils.waitUntilActive(dynamo, TABLE_NAME); createTestData(); } @Test public void testScan() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); DynamoDBScanExpression scanExpression = new DynamoDBScanExpression().withLimit(SCAN_LIMIT); scanExpression.addFilterCondition( "value", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL.toString())); scanExpression.addFilterCondition( "extraData", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL.toString())); List<SimpleClass> list = util.scan(SimpleClass.class, scanExpression); int count = 0; Iterator<SimpleClass> iterator = list.iterator(); while (iterator.hasNext()) { count++; SimpleClass next = iterator.next(); assertNotNull(next.getExtraData()); assertNotNull(next.getValue()); } int totalCount = util.count(SimpleClass.class, scanExpression); assertNotNull(list.get(totalCount / 2)); assertTrue(totalCount == count); assertTrue(totalCount == list.size()); assertTrue(list.contains(list.get(list.size() / 2))); assertTrue(count == list.toArray().length); } /** Tests scanning the table with AND/OR logic operator. */ @Test public void testScanWithConditionalOperator() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); DynamoDBScanExpression scanExpression = new DynamoDBScanExpression() .withLimit(SCAN_LIMIT) .withScanFilter( ImmutableMapParameter.of( "value", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL), "non-existent-field", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL))) .withConditionalOperator(ConditionalOperator.AND); List<SimpleClass> andConditionResult = mapper.scan(SimpleClass.class, scanExpression); assertTrue(andConditionResult.isEmpty()); List<SimpleClass> orConditionResult = mapper.scan( SimpleClass.class, scanExpression.withConditionalOperator(ConditionalOperator.OR)); assertFalse(orConditionResult.isEmpty()); } @Test public void testParallelScan() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); DynamoDBScanExpression scanExpression = new DynamoDBScanExpression().withLimit(SCAN_LIMIT); scanExpression.addFilterCondition( "value", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL.toString())); scanExpression.addFilterCondition( "extraData", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL.toString())); PaginatedParallelScanList<SimpleClass> parallelScanList = util.parallelScan(SimpleClass.class, scanExpression, PARALLEL_SCAN_SEGMENTS); int count = 0; Iterator<SimpleClass> iterator = parallelScanList.iterator(); HashMap<String, Boolean> allDataAppearance = new HashMap<String, Boolean>(); for (int i = 0; i < 500; i++) { allDataAppearance.put("" + i, false); } while (iterator.hasNext()) { count++; SimpleClass next = iterator.next(); assertNotNull(next.getExtraData()); assertNotNull(next.getValue()); allDataAppearance.put(next.getId(), true); } assertFalse(allDataAppearance.values().contains(false)); int totalCount = util.count(SimpleClass.class, scanExpression); assertNotNull(parallelScanList.get(totalCount / 2)); assertTrue(totalCount == count); assertTrue(totalCount == parallelScanList.size()); assertTrue(parallelScanList.contains(parallelScanList.get(parallelScanList.size() / 2))); assertTrue(count == parallelScanList.toArray().length); } @Test public void testParallelScanExceptionHandling() { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); int INVALID_LIMIT = 0; DynamoDBScanExpression scanExpression = new DynamoDBScanExpression().withLimit(INVALID_LIMIT); try { // Using 2 segments to reduce the chance of a RejectedExecutionException occurring when too // many threads are spun up // An alternative would be to maintain a higher segment count, but re-test when a // RejectedExecutionException occurs PaginatedParallelScanList<SimpleClass> parallelScanList = util.parallelScan(SimpleClass.class, scanExpression, 2); fail("Test succeeded when it should have failed"); } catch (AmazonServiceException ase) { assertNotNull(ase.getErrorCode()); assertNotNull(ase.getErrorType()); assertNotNull(ase.getMessage()); } catch (Exception e) { fail("Should have seen the AmazonServiceException"); } } @Test public void testScanPage() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); DynamoDBScanExpression scanExpression = new DynamoDBScanExpression(); scanExpression.addFilterCondition( "value", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL.toString())); scanExpression.addFilterCondition( "extraData", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL.toString())); int limit = 3; scanExpression.setLimit(limit); ScanResultPage<SimpleClass> result = util.scanPage(SimpleClass.class, scanExpression); int count = 0; Iterator<SimpleClass> iterator = result.getResults().iterator(); Set<SimpleClass> seen = new HashSet<ScanITCase.SimpleClass>(); while (iterator.hasNext()) { count++; SimpleClass next = iterator.next(); assertNotNull(next.getExtraData()); assertNotNull(next.getValue()); assertTrue(seen.add(next)); } assertTrue(limit == count); assertTrue(count == result.getResults().toArray().length); scanExpression.setExclusiveStartKey(result.getLastEvaluatedKey()); result = util.scanPage(SimpleClass.class, scanExpression); iterator = result.getResults().iterator(); count = 0; while (iterator.hasNext()) { count++; SimpleClass next = iterator.next(); assertNotNull(next.getExtraData()); assertNotNull(next.getValue()); assertTrue(seen.add(next)); } assertTrue(limit == count); assertTrue(count == result.getResults().toArray().length); } @DynamoDBTable(tableName = "aws-java-sdk-util-scan-crypto") public static final class SimpleClass { private String id; private String value; private String extraData; public SimpleClass() {} public SimpleClass(String id, String value) { this.id = id; this.value = value; this.extraData = UUID.randomUUID().toString(); } @DynamoDBHashKey public String getId() { return id; } public void setId(String id) { this.id = id; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getExtraData() { return extraData; } public void setExtraData(String extraData) { this.extraData = extraData; } } }
4,250
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/ExceptionHandlingITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBVersionAttribute; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.annotations.Test; /** Tests of exception handling */ public class ExceptionHandlingITCase extends DynamoDBMapperCryptoIntegrationTestBase { public static class NoTableAnnotation { private String key; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testNoTableAnnotation() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.save(new NoTableAnnotation()); } @Test(expectedExceptions = DynamoDBMappingException.class) public void testNoTableAnnotationLoad() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.load(NoTableAnnotation.class, "abc"); } @DynamoDBTable(tableName = TABLE_NAME) public static class NoDefaultConstructor { private String key; private String attribute; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getAttribute() { return attribute; } public void setAttribute(String attribute) { this.attribute = attribute; } public NoDefaultConstructor(String key, String attribute) { super(); this.key = key; this.attribute = attribute; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testNoDefaultConstructor() { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); NoDefaultConstructor obj = new NoDefaultConstructor("" + startKey++, "abc"); util.save(obj); util.load(NoDefaultConstructor.class, obj.getKey()); } @DynamoDBTable(tableName = TABLE_NAME) public static class NoKeyGetterDefined { @SuppressWarnings("unused") private String key; } @Test(expectedExceptions = DynamoDBMappingException.class) public void testNoHashKeyGetter() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.save(new NoKeyGetterDefined()); } @Test(expectedExceptions = DynamoDBMappingException.class) public void testNoHashKeyGetterLoad() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.load(NoKeyGetterDefined.class, "abc"); } @DynamoDBTable(tableName = TABLE_NAME) public static class PrivateKeyGetter { private String key; @SuppressWarnings("unused") @DynamoDBHashKey public String getKey() { return key; } @SuppressWarnings("unused") private void setKey(String key) { this.key = key; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testPrivateKeyGetter() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.save(new PrivateKeyGetter()); } @Test(expectedExceptions = DynamoDBMappingException.class) public void testPrivateKeyGetterLoad() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.load(PrivateKeyGetter.class, "abc"); } @DynamoDBTable(tableName = TABLE_NAME) public static class PrivateKeySetter { private String key; @DynamoDBHashKey @DynamoDBAutoGeneratedKey public String getKey() { return key; } @SuppressWarnings("unused") private void setKey(String key) { this.key = key; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testPrivateKeySetter() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.save(new PrivateKeySetter()); } /* * To trigger this error, we need for a service object to be present, so * we'll insert one manually. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testPrivateKeySetterLoad() throws Exception { Map<String, AttributeValue> attr = new HashMap<String, AttributeValue>(); attr.put(KEY_NAME, new AttributeValue().withS("abc")); dynamo.putItem(new PutItemRequest().withTableName(TABLE_NAME).withItem(attr)); DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.load(PrivateKeySetter.class, "abc"); } @DynamoDBTable(tableName = TABLE_NAME) public static class PrivateSetter { private String key; private String StringProperty; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getStringProperty() { return StringProperty; } private void setStringProperty(String stringProperty) { StringProperty = stringProperty; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testPrivateSetterLoad() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); PrivateSetter object = new PrivateSetter(); object.setStringProperty("value"); util.save(object); util.load(PrivateSetter.class, object.getKey()); } @DynamoDBTable(tableName = TABLE_NAME) public static class OverloadedSetter { private String key; private String attribute; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getAttribute() { return attribute; } public void setAttribute(String attribute, String unused) { this.attribute = attribute; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testOverloadedSetter() { OverloadedSetter obj = new OverloadedSetter(); obj.setKey("" + startKey++); obj.setAttribute("abc", "123"); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.save(obj); mapper.load(OverloadedSetter.class, obj.getKey()); } @DynamoDBTable(tableName = TABLE_NAME) public static class WrongTypeForSetter { private String key; private String attribute; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getAttribute() { return attribute; } public void setAttribute(Integer attribute) { this.attribute = String.valueOf(attribute); } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testWrongTypeForSetter() { WrongTypeForSetter obj = new WrongTypeForSetter(); obj.setKey("" + startKey++); obj.setAttribute(123); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.save(obj); mapper.load(WrongTypeForSetter.class, obj.getKey()); } @DynamoDBTable(tableName = TABLE_NAME) public static class NumericFields { private String key; private Integer integerProperty; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } public Integer getIntegerProperty() { return integerProperty; } public void setIntegerProperty(Integer integerProperty) { this.integerProperty = integerProperty; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testWrongDataType() { Map<String, AttributeValue> attr = new HashMap<String, AttributeValue>(); attr.put("integerProperty", new AttributeValue().withS("abc")); attr.put(KEY_NAME, new AttributeValue().withS("" + startKey++)); dynamo.putItem(new PutItemRequest().withTableName(TABLE_NAME).withItem(attr)); DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.load(NumericFields.class, attr.get(KEY_NAME).getS()); } @Test(expectedExceptions = DynamoDBMappingException.class) public void testWrongDataType2() { Map<String, AttributeValue> attr = new HashMap<String, AttributeValue>(); attr.put("integerProperty", new AttributeValue().withNS("1", "2", "3")); attr.put(KEY_NAME, new AttributeValue().withS("" + startKey++)); dynamo.putItem(new PutItemRequest().withTableName(TABLE_NAME).withItem(attr)); DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.load(NumericFields.class, attr.get(KEY_NAME).getS()); } @DynamoDBTable(tableName = TABLE_NAME) public static class ComplexType { public String key; public ComplexType type; public ComplexType(String key, ComplexType type) { super(); this.key = key; this.type = type; } @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } public ComplexType getType() { return type; } public void setType(ComplexType type) { this.type = type; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testComplexTypeFailure() { ComplexType complexType = new ComplexType("" + startKey++, new ComplexType("" + startKey++, null)); DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.save(complexType); } @DynamoDBTable(tableName = TABLE_NAME) public static class ComplexHashKeyType { private ComplexType key; private String attribute; @DynamoDBHashKey public ComplexType getKey() { return key; } public void setKey(ComplexType key) { this.key = key; } public String getAttribute() { return attribute; } public void setAttribute(String attribute) { this.attribute = attribute; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testUnsupportedHashKeyType() { ComplexType complexType = new ComplexType("" + startKey++, new ComplexType("" + startKey++, null)); ComplexHashKeyType obj = new ComplexHashKeyType(); obj.setKey(complexType); obj.setAttribute("abc"); DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.save(obj); } @DynamoDBTable(tableName = TABLE_NAME) public static class NonSetCollectionType { private String key; private List<String> badlyMapped; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } public List<String> getBadlyMapped() { return badlyMapped; } public void setBadlyMapped(List<String> badlyMapped) { this.badlyMapped = badlyMapped; } } @Test public void testNonSetCollection() { NonSetCollectionType obj = new NonSetCollectionType(); obj.setKey("" + startKey++); obj.setBadlyMapped(new ArrayList<String>()); obj.getBadlyMapped().add("abc"); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.save(obj); } @DynamoDBTable(tableName = TABLE_NAME) public static class FractionalVersionAttribute { private String key; private Double version; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBVersionAttribute public Double getVersion() { return version; } public void setVersion(Double version) { this.version = version; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testFractionalVersionAttribute() { FractionalVersionAttribute obj = new FractionalVersionAttribute(); obj.setKey("" + startKey++); obj.setVersion(0d); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.save(obj); } @DynamoDBTable(tableName = TABLE_NAME) public static class AutoGeneratedIntegerKey { private Integer key; private String value; @DynamoDBHashKey @DynamoDBAutoGeneratedKey public Integer getKey() { return key; } public void setKey(Integer key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testAutoGeneratedIntegerHashKey() { AutoGeneratedIntegerKey obj = new AutoGeneratedIntegerKey(); obj.setValue("fdgfdsgf"); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.save(obj); } @DynamoDBTable(tableName = TABLE_NAME) public static class AutoGeneratedIntegerRangeKey { private String key; private Integer rangekey; private String value; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAutoGeneratedKey @DynamoDBRangeKey public Integer getRangekey() { return rangekey; } public void setRangekey(Integer rangekey) { this.rangekey = rangekey; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testAutoGeneratedIntegerRangeKey() { AutoGeneratedIntegerRangeKey obj = new AutoGeneratedIntegerRangeKey(); obj.setKey("Bldadsfa"); obj.setValue("fdgfdsgf"); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.save(obj); } }
4,251
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/KeyOnlyPutITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; public class KeyOnlyPutITCase extends DynamoDBCryptoIntegrationTestBase { @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public static class HashAndAttribute { protected String key; protected String normalStringAttribute; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAttribute public String getNormalStringAttribute() { return normalStringAttribute; } public void setNormalStringAttribute(String normalStringAttribute) { this.normalStringAttribute = normalStringAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((normalStringAttribute == null) ? 0 : normalStringAttribute.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; HashAndAttribute other = (HashAndAttribute) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (normalStringAttribute == null) { if (other.normalStringAttribute != null) return false; } else if (!normalStringAttribute.equals(other.normalStringAttribute)) return false; return true; } } private <T extends HashAndAttribute> T getUniqueObject(T obj) { obj.setKey("" + startKey++); return obj; } }
4,252
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/MapperSaveConfigCryptoIntegrationTestBase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.SaveBehavior; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotTouch; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.CreateTableRequest; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType; import com.amazonaws.services.dynamodbv2.model.TableDescription; import com.amazonaws.services.dynamodbv2.util.TableUtils; import java.util.Set; import org.testng.annotations.BeforeClass; public class MapperSaveConfigCryptoIntegrationTestBase extends DynamoDBCryptoIntegrationTestBase { protected static DynamoDBMapper dynamoMapper; protected static final DynamoDBMapperConfig defaultConfig = new DynamoDBMapperConfig(SaveBehavior.UPDATE); protected static final DynamoDBMapperConfig updateSkipNullConfig = new DynamoDBMapperConfig(SaveBehavior.UPDATE_SKIP_NULL_ATTRIBUTES); protected static final DynamoDBMapperConfig appendSetConfig = new DynamoDBMapperConfig(SaveBehavior.APPEND_SET); protected static final DynamoDBMapperConfig clobberConfig = new DynamoDBMapperConfig(SaveBehavior.CLOBBER); protected static final String tableName = "aws-java-sdk-dynamodb-mapper-save-config-test-crypto"; protected static final String hashKeyName = "hashKey"; protected static final String rangeKeyName = "rangeKey"; protected static final String nonKeyAttributeName = "nonKeyAttribute"; protected static final String stringSetAttributeName = "stringSetAttribute"; /** Read capacity for the test table being created in Amazon DynamoDB. */ protected static final Long READ_CAPACITY = 10L; /** Write capacity for the test table being created in Amazon DynamoDB. */ protected static final Long WRITE_CAPACITY = 5L; /** Provisioned Throughput for the test table created in Amazon DynamoDB */ protected static final ProvisionedThroughput DEFAULT_PROVISIONED_THROUGHPUT = new ProvisionedThroughput() .withReadCapacityUnits(READ_CAPACITY) .withWriteCapacityUnits(WRITE_CAPACITY); @BeforeClass public static void setUp() throws Exception { System.setProperty("sqlite4java.library.path", "target/test-lib"); DynamoDBCryptoIntegrationTestBase.setUp(); dynamoMapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); CreateTableRequest createTableRequest = new CreateTableRequest() .withTableName(tableName) .withKeySchema( new KeySchemaElement().withAttributeName(hashKeyName).withKeyType(KeyType.HASH)) .withKeySchema( new KeySchemaElement().withAttributeName(rangeKeyName).withKeyType(KeyType.RANGE)) .withAttributeDefinitions( new AttributeDefinition() .withAttributeName(hashKeyName) .withAttributeType(ScalarAttributeType.S)) .withAttributeDefinitions( new AttributeDefinition() .withAttributeName(rangeKeyName) .withAttributeType(ScalarAttributeType.N)); createTableRequest.setProvisionedThroughput(DEFAULT_PROVISIONED_THROUGHPUT); if (TableUtils.createTableIfNotExists(dynamo, createTableRequest)) { TableUtils.waitUntilActive(dynamo, tableName); } } @DynamoDBTable(tableName = tableName) public static class TestItem { private String hashKey; private Long rangeKey; private String nonKeyAttribute; private Set<String> stringSetAttribute; @DynamoDBHashKey(attributeName = hashKeyName) public String getHashKey() { return hashKey; } public void setHashKey(String hashKey) { this.hashKey = hashKey; } @DynamoDBRangeKey(attributeName = rangeKeyName) public Long getRangeKey() { return rangeKey; } public void setRangeKey(Long rangeKey) { this.rangeKey = rangeKey; } @DoNotTouch @DynamoDBAttribute(attributeName = nonKeyAttributeName) public String getNonKeyAttribute() { return nonKeyAttribute; } public void setNonKeyAttribute(String nonKeyAttribute) { this.nonKeyAttribute = nonKeyAttribute; } @DoNotTouch @DynamoDBAttribute(attributeName = stringSetAttributeName) public Set<String> getStringSetAttribute() { return stringSetAttribute; } public void setStringSetAttribute(Set<String> stringSetAttribute) { this.stringSetAttribute = stringSetAttribute; } } @DynamoDBTable(tableName = tableName) public static class TestAppendToScalarItem { private String hashKey; private Long rangeKey; private Set<String> fakeStringSetAttribute; @DynamoDBHashKey(attributeName = hashKeyName) public String getHashKey() { return hashKey; } public void setHashKey(String hashKey) { this.hashKey = hashKey; } @DynamoDBRangeKey(attributeName = rangeKeyName) public Long getRangeKey() { return rangeKey; } public void setRangeKey(Long rangeKey) { this.rangeKey = rangeKey; } @DynamoDBAttribute(attributeName = nonKeyAttributeName) public Set<String> getFakeStringSetAttribute() { return fakeStringSetAttribute; } public void setFakeStringSetAttribute(Set<String> stringSetAttribute) { this.fakeStringSetAttribute = stringSetAttribute; } } /** Helper method to create a table in Amazon DynamoDB */ protected static void createTestTable(ProvisionedThroughput provisionedThroughput) { CreateTableRequest createTableRequest = new CreateTableRequest() .withTableName(tableName) .withKeySchema( new KeySchemaElement().withAttributeName(hashKeyName).withKeyType(KeyType.HASH)) .withKeySchema( new KeySchemaElement().withAttributeName(rangeKeyName).withKeyType(KeyType.RANGE)) .withAttributeDefinitions( new AttributeDefinition() .withAttributeName(hashKeyName) .withAttributeType(ScalarAttributeType.S)) .withAttributeDefinitions( new AttributeDefinition() .withAttributeName(rangeKeyName) .withAttributeType(ScalarAttributeType.N)); createTableRequest.setProvisionedThroughput(provisionedThroughput); TableDescription createdTableDescription = dynamo.createTable(createTableRequest).getTableDescription(); System.out.println("Created Table: " + createdTableDescription); assertEquals(tableName, createdTableDescription.getTableName()); assertNotNull(createdTableDescription.getTableStatus()); assertEquals(hashKeyName, createdTableDescription.getKeySchema().get(0).getAttributeName()); assertEquals( KeyType.HASH.toString(), createdTableDescription.getKeySchema().get(0).getKeyType()); assertEquals(rangeKeyName, createdTableDescription.getKeySchema().get(1).getAttributeName()); assertEquals( KeyType.RANGE.toString(), createdTableDescription.getKeySchema().get(1).getKeyType()); } }
4,253
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/DynamoDBCryptoIntegrationTestBase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.model.AmazonDynamoDBException; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.CreateTableRequest; import com.amazonaws.services.dynamodbv2.model.DeleteTableRequest; import com.amazonaws.services.dynamodbv2.model.DescribeTableRequest; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.LocalSecondaryIndex; import com.amazonaws.services.dynamodbv2.model.Projection; import com.amazonaws.services.dynamodbv2.model.ProjectionType; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType; import com.amazonaws.services.dynamodbv2.model.TableDescription; import com.amazonaws.services.dynamodbv2.util.TableUtils; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import org.testng.annotations.BeforeClass; public class DynamoDBCryptoIntegrationTestBase extends DynamoDBTestBase { protected static final boolean DEBUG = false; protected static final String KEY_NAME = "key"; protected static final String TABLE_NAME = "aws-java-sdk-util-crypto"; protected static long startKey = System.currentTimeMillis(); protected static final String TABLE_WITH_RANGE_ATTRIBUTE = "aws-java-sdk-range-test-crypto"; protected static final String TABLE_WITH_INDEX_RANGE_ATTRIBUTE = "aws-java-sdk-index-range-test-crypto"; protected static Logger log = Logger.getLogger("DynamoDBCryptoITCaseBase"); @BeforeClass public static void setUp() throws Exception { // Create a table DynamoDBTestBase.setUpTestBase(); String keyName = KEY_NAME; CreateTableRequest createTableRequest = new CreateTableRequest() .withTableName(TABLE_NAME) .withKeySchema( new KeySchemaElement().withAttributeName(keyName).withKeyType(KeyType.HASH)) .withAttributeDefinitions( new AttributeDefinition() .withAttributeName(keyName) .withAttributeType(ScalarAttributeType.S)); createTableRequest.setProvisionedThroughput( new ProvisionedThroughput().withReadCapacityUnits(10L).withWriteCapacityUnits(5L)); if (TableUtils.createTableIfNotExists(dynamo, createTableRequest)) { TableUtils.waitUntilActive(dynamo, TABLE_NAME); } } /** Utility method to delete tables used in the integration test */ public static void deleteCryptoIntegrationTestTables() { List<String> integrationTestTables = new ArrayList<>(); integrationTestTables.add(TABLE_NAME); integrationTestTables.add(TABLE_WITH_INDEX_RANGE_ATTRIBUTE); integrationTestTables.add(TABLE_WITH_RANGE_ATTRIBUTE); for (String name : integrationTestTables) { dynamo.deleteTable(new DeleteTableRequest().withTableName(name)); } } protected static void setUpTableWithRangeAttribute() throws Exception { setUp(); String keyName = DynamoDBCryptoIntegrationTestBase.KEY_NAME; String rangeKeyAttributeName = "rangeKey"; CreateTableRequest createTableRequest = new CreateTableRequest() .withTableName(TABLE_WITH_RANGE_ATTRIBUTE) .withKeySchema( new KeySchemaElement().withAttributeName(keyName).withKeyType(KeyType.HASH), new KeySchemaElement() .withAttributeName(rangeKeyAttributeName) .withKeyType(KeyType.RANGE)) .withAttributeDefinitions( new AttributeDefinition() .withAttributeName(keyName) .withAttributeType(ScalarAttributeType.N), new AttributeDefinition() .withAttributeName(rangeKeyAttributeName) .withAttributeType(ScalarAttributeType.N)); createTableRequest.setProvisionedThroughput( new ProvisionedThroughput().withReadCapacityUnits(10L).withWriteCapacityUnits(5L)); if (TableUtils.createTableIfNotExists(dynamo, createTableRequest)) { TableUtils.waitUntilActive(dynamo, TABLE_WITH_RANGE_ATTRIBUTE); } } protected static void setUpTableWithIndexRangeAttribute(boolean recreateTable) throws Exception { setUp(); if (recreateTable) { dynamo.deleteTable(new DeleteTableRequest().withTableName(TABLE_WITH_INDEX_RANGE_ATTRIBUTE)); waitForTableToBecomeDeleted(TABLE_WITH_INDEX_RANGE_ATTRIBUTE); } String keyName = DynamoDBCryptoIntegrationTestBase.KEY_NAME; String rangeKeyAttributeName = "rangeKey"; String indexFooRangeKeyAttributeName = "indexFooRangeKey"; String indexBarRangeKeyAttributeName = "indexBarRangeKey"; String multipleIndexRangeKeyAttributeName = "multipleIndexRangeKey"; String indexFooName = "index_foo"; String indexBarName = "index_bar"; String indexFooCopyName = "index_foo_copy"; String indexBarCopyName = "index_bar_copy"; CreateTableRequest createTableRequest = new CreateTableRequest() .withTableName(TABLE_WITH_INDEX_RANGE_ATTRIBUTE) .withKeySchema( new KeySchemaElement().withAttributeName(keyName).withKeyType(KeyType.HASH), new KeySchemaElement() .withAttributeName(rangeKeyAttributeName) .withKeyType(KeyType.RANGE)) .withLocalSecondaryIndexes( new LocalSecondaryIndex() .withIndexName(indexFooName) .withKeySchema( new KeySchemaElement().withAttributeName(keyName).withKeyType(KeyType.HASH), new KeySchemaElement() .withAttributeName(indexFooRangeKeyAttributeName) .withKeyType(KeyType.RANGE)) .withProjection(new Projection().withProjectionType(ProjectionType.ALL)), new LocalSecondaryIndex() .withIndexName(indexBarName) .withKeySchema( new KeySchemaElement().withAttributeName(keyName).withKeyType(KeyType.HASH), new KeySchemaElement() .withAttributeName(indexBarRangeKeyAttributeName) .withKeyType(KeyType.RANGE)) .withProjection(new Projection().withProjectionType(ProjectionType.ALL)), new LocalSecondaryIndex() .withIndexName(indexFooCopyName) .withKeySchema( new KeySchemaElement().withAttributeName(keyName).withKeyType(KeyType.HASH), new KeySchemaElement() .withAttributeName(multipleIndexRangeKeyAttributeName) .withKeyType(KeyType.RANGE)) .withProjection(new Projection().withProjectionType(ProjectionType.ALL)), new LocalSecondaryIndex() .withIndexName(indexBarCopyName) .withKeySchema( new KeySchemaElement().withAttributeName(keyName).withKeyType(KeyType.HASH), new KeySchemaElement() .withAttributeName(multipleIndexRangeKeyAttributeName) .withKeyType(KeyType.RANGE)) .withProjection(new Projection().withProjectionType(ProjectionType.ALL))) .withAttributeDefinitions( new AttributeDefinition() .withAttributeName(keyName) .withAttributeType(ScalarAttributeType.N), new AttributeDefinition() .withAttributeName(rangeKeyAttributeName) .withAttributeType(ScalarAttributeType.N), new AttributeDefinition() .withAttributeName(indexFooRangeKeyAttributeName) .withAttributeType(ScalarAttributeType.N), new AttributeDefinition() .withAttributeName(indexBarRangeKeyAttributeName) .withAttributeType(ScalarAttributeType.N), new AttributeDefinition() .withAttributeName(multipleIndexRangeKeyAttributeName) .withAttributeType(ScalarAttributeType.N)); createTableRequest.setProvisionedThroughput( new ProvisionedThroughput().withReadCapacityUnits(10L).withWriteCapacityUnits(5L)); if (TableUtils.createTableIfNotExists(dynamo, createTableRequest)) { TableUtils.waitUntilActive(dynamo, TABLE_WITH_INDEX_RANGE_ATTRIBUTE); } } protected static void waitForTableToBecomeDeleted(String tableName) { waitForTableToBecomeDeleted(dynamo, tableName); } public static void waitForTableToBecomeDeleted(AmazonDynamoDB dynamo, String tableName) { log.info(() -> "Waiting for " + tableName + " to become Deleted..."); long startTime = System.currentTimeMillis(); long endTime = startTime + (60_000); while (System.currentTimeMillis() < endTime) { try { Thread.sleep(5_000); } catch (Exception e) { // Ignored or expected. } try { DescribeTableRequest request = new DescribeTableRequest(tableName); TableDescription table = dynamo.describeTable(request).getTable(); log.info(() -> " - current state: " + table.getTableStatus()); if (table.getTableStatus() == "DELETING") { continue; } } catch (AmazonDynamoDBException exception) { if (exception.getErrorCode().equalsIgnoreCase("ResourceNotFoundException")) { log.info(() -> "successfully deleted"); return; } } } throw new RuntimeException("Table " + tableName + " never went deleted"); } public static void main(String[] args) throws Exception { setUp(); deleteCryptoIntegrationTestTables(); } }
4,254
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/AutoGeneratedKeysITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.fail; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBSaveExpression; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; import com.amazonaws.services.dynamodbv2.model.ConditionalOperator; import com.amazonaws.services.dynamodbv2.model.CreateTableRequest; import com.amazonaws.services.dynamodbv2.model.ExpectedAttributeValue; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType; import com.amazonaws.services.dynamodbv2.util.TableUtils; import com.amazonaws.util.ImmutableMapParameter; import java.util.Collections; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Tests using auto-generated keys for range keys, hash keys, or both. */ public class AutoGeneratedKeysITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static final String TABLE_NAME = "aws-java-sdk-string-range-crypto"; @BeforeClass public static void setUp() throws Exception { DynamoDBMapperCryptoIntegrationTestBase.setUp(); // Create a table String keyName = DynamoDBMapperCryptoIntegrationTestBase.KEY_NAME; String rangeKeyAttributeName = "rangeKey"; CreateTableRequest createTableRequest = new CreateTableRequest() .withTableName(TABLE_NAME) .withKeySchema( new KeySchemaElement().withAttributeName(keyName).withKeyType(KeyType.HASH), new KeySchemaElement() .withAttributeName(rangeKeyAttributeName) .withKeyType(KeyType.RANGE)) .withAttributeDefinitions( new AttributeDefinition() .withAttributeName(keyName) .withAttributeType(ScalarAttributeType.S), new AttributeDefinition() .withAttributeName(rangeKeyAttributeName) .withAttributeType(ScalarAttributeType.S)); createTableRequest.setProvisionedThroughput( new ProvisionedThroughput().withReadCapacityUnits(10L).withWriteCapacityUnits(5L)); if (TableUtils.createTableIfNotExists(dynamo, createTableRequest)) { TableUtils.waitUntilActive(dynamo, TABLE_NAME); } } @DynamoDBTable(tableName = "aws-java-sdk-string-range-crypto") public static class HashKeyRangeKeyBothAutoGenerated { private String key; private String rangeKey; private String otherAttribute; @DynamoDBAutoGeneratedKey @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAutoGeneratedKey @DynamoDBRangeKey public String getRangeKey() { return rangeKey; } public void setRangeKey(String rangeKey) { this.rangeKey = rangeKey; } public String getOtherAttribute() { return otherAttribute; } public void setOtherAttribute(String otherAttribute) { this.otherAttribute = otherAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((otherAttribute == null) ? 0 : otherAttribute.hashCode()); result = prime * result + ((rangeKey == null) ? 0 : rangeKey.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; HashKeyRangeKeyBothAutoGenerated other = (HashKeyRangeKeyBothAutoGenerated) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (otherAttribute == null) { if (other.otherAttribute != null) return false; } else if (!otherAttribute.equals(other.otherAttribute)) return false; if (rangeKey == null) { if (other.rangeKey != null) return false; } else if (!rangeKey.equals(other.rangeKey)) return false; return true; } } @Test public void testHashKeyRangeKeyBothAutogenerated() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); HashKeyRangeKeyBothAutoGenerated obj = new HashKeyRangeKeyBothAutoGenerated(); obj.setOtherAttribute("blah"); assertNull(obj.getKey()); assertNull(obj.getRangeKey()); mapper.save(obj); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); HashKeyRangeKeyBothAutoGenerated other = mapper.load(HashKeyRangeKeyBothAutoGenerated.class, obj.getKey(), obj.getRangeKey()); assertEquals(other, obj); } @Test public void testHashKeyRangeKeyBothAutogeneratedBatchWrite() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); HashKeyRangeKeyBothAutoGenerated obj = new HashKeyRangeKeyBothAutoGenerated(); obj.setOtherAttribute("blah"); HashKeyRangeKeyBothAutoGenerated obj2 = new HashKeyRangeKeyBothAutoGenerated(); obj2.setOtherAttribute("blah"); assertNull(obj.getKey()); assertNull(obj.getRangeKey()); assertNull(obj2.getKey()); assertNull(obj2.getRangeKey()); mapper.batchSave(obj, obj2); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); assertNotNull(obj2.getKey()); assertNotNull(obj2.getRangeKey()); assertEquals( mapper.load(HashKeyRangeKeyBothAutoGenerated.class, obj.getKey(), obj.getRangeKey()), obj); assertEquals( mapper.load(HashKeyRangeKeyBothAutoGenerated.class, obj2.getKey(), obj2.getRangeKey()), obj2); } /** Tests providing additional expected conditions when saving item with auto-generated keys. */ @Test public void testAutogeneratedKeyWithUserProvidedExpectedConditions() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); HashKeyRangeKeyBothAutoGenerated obj = new HashKeyRangeKeyBothAutoGenerated(); obj.setOtherAttribute("blah"); assertNull(obj.getKey()); assertNull(obj.getRangeKey()); // Add additional expected conditions via DynamoDBSaveExpression. // Expected conditions joined by AND are compatible with the conditions // for auto-generated keys. DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression(); saveExpression .withExpected(Collections.singletonMap("otherAttribute", new ExpectedAttributeValue(false))) .withConditionalOperator(ConditionalOperator.AND); // The save should succeed since the user provided conditions are joined by AND. mapper.save(obj, saveExpression); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); HashKeyRangeKeyBothAutoGenerated other = mapper.load(HashKeyRangeKeyBothAutoGenerated.class, obj.getKey(), obj.getRangeKey()); assertEquals(other, obj); // Change the conditional operator to OR. // IllegalArgumentException is expected since the additional expected // conditions cannot be joined with the conditions for auto-generated // keys. saveExpression.setConditionalOperator(ConditionalOperator.OR); try { mapper.save(new HashKeyRangeKeyBothAutoGenerated(), saveExpression); } catch (IllegalArgumentException expected) { } // User-provided OR conditions should work if they completely override the generated conditions. saveExpression .withExpected( ImmutableMapParameter.of( "otherAttribute", new ExpectedAttributeValue(false), "key", new ExpectedAttributeValue(false), "rangeKey", new ExpectedAttributeValue(false))) .withConditionalOperator(ConditionalOperator.OR); mapper.save(new HashKeyRangeKeyBothAutoGenerated(), saveExpression); saveExpression .withExpected( ImmutableMapParameter.of( "otherAttribute", new ExpectedAttributeValue(new AttributeValue("non-existent-value")), "key", new ExpectedAttributeValue(new AttributeValue("non-existent-value")), "rangeKey", new ExpectedAttributeValue(new AttributeValue("non-existent-value")))) .withConditionalOperator(ConditionalOperator.OR); try { mapper.save(new HashKeyRangeKeyBothAutoGenerated(), saveExpression); } catch (ConditionalCheckFailedException expected) { } } @DynamoDBTable(tableName = "aws-java-sdk-string-range-crypto") public static class HashKeyAutoGenerated { private String key; private String rangeKey; private String otherAttribute; @DynamoDBAutoGeneratedKey @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBRangeKey public String getRangeKey() { return rangeKey; } public void setRangeKey(String rangeKey) { this.rangeKey = rangeKey; } public String getOtherAttribute() { return otherAttribute; } public void setOtherAttribute(String otherAttribute) { this.otherAttribute = otherAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((otherAttribute == null) ? 0 : otherAttribute.hashCode()); result = prime * result + ((rangeKey == null) ? 0 : rangeKey.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; HashKeyAutoGenerated other = (HashKeyAutoGenerated) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (otherAttribute == null) { if (other.otherAttribute != null) return false; } else if (!otherAttribute.equals(other.otherAttribute)) return false; if (rangeKey == null) { if (other.rangeKey != null) return false; } else if (!rangeKey.equals(other.rangeKey)) return false; return true; } } @Test public void testHashKeyAutogenerated() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); HashKeyAutoGenerated obj = new HashKeyAutoGenerated(); obj.setOtherAttribute("blah"); obj.setRangeKey("" + System.currentTimeMillis()); assertNull(obj.getKey()); assertNotNull(obj.getRangeKey()); mapper.save(obj); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); HashKeyAutoGenerated other = mapper.load(HashKeyAutoGenerated.class, obj.getKey(), obj.getRangeKey()); assertEquals(other, obj); } @DynamoDBTable(tableName = "aws-java-sdk-string-range-crypto") public static class RangeKeyAutoGenerated { private String key; private String rangeKey; private String otherAttribute; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAutoGeneratedKey @DynamoDBRangeKey public String getRangeKey() { return rangeKey; } public void setRangeKey(String rangeKey) { this.rangeKey = rangeKey; } public String getOtherAttribute() { return otherAttribute; } public void setOtherAttribute(String otherAttribute) { this.otherAttribute = otherAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((otherAttribute == null) ? 0 : otherAttribute.hashCode()); result = prime * result + ((rangeKey == null) ? 0 : rangeKey.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RangeKeyAutoGenerated other = (RangeKeyAutoGenerated) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (otherAttribute == null) { if (other.otherAttribute != null) return false; } else if (!otherAttribute.equals(other.otherAttribute)) return false; if (rangeKey == null) { if (other.rangeKey != null) return false; } else if (!rangeKey.equals(other.rangeKey)) return false; return true; } } @Test public void testRangeKeyAutogenerated() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); RangeKeyAutoGenerated obj = new RangeKeyAutoGenerated(); obj.setOtherAttribute("blah"); obj.setKey("" + System.currentTimeMillis()); assertNotNull(obj.getKey()); assertNull(obj.getRangeKey()); mapper.save(obj); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); RangeKeyAutoGenerated other = mapper.load(RangeKeyAutoGenerated.class, obj.getKey(), obj.getRangeKey()); assertEquals(other, obj); } @DynamoDBTable(tableName = "aws-java-sdk-string-range-crypto") public static class NothingAutoGenerated { private String key; private String rangeKey; private String otherAttribute; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBRangeKey public String getRangeKey() { return rangeKey; } public void setRangeKey(String rangeKey) { this.rangeKey = rangeKey; } public String getOtherAttribute() { return otherAttribute; } public void setOtherAttribute(String otherAttribute) { this.otherAttribute = otherAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((otherAttribute == null) ? 0 : otherAttribute.hashCode()); result = prime * result + ((rangeKey == null) ? 0 : rangeKey.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NothingAutoGenerated other = (NothingAutoGenerated) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (otherAttribute == null) { if (other.otherAttribute != null) return false; } else if (!otherAttribute.equals(other.otherAttribute)) return false; if (rangeKey == null) { if (other.rangeKey != null) return false; } else if (!rangeKey.equals(other.rangeKey)) return false; return true; } } @Test public void testNothingAutogenerated() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); NothingAutoGenerated obj = new NothingAutoGenerated(); obj.setOtherAttribute("blah"); obj.setKey("" + System.currentTimeMillis()); obj.setRangeKey("" + System.currentTimeMillis()); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); mapper.save(obj); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); NothingAutoGenerated other = mapper.load(NothingAutoGenerated.class, obj.getKey(), obj.getRangeKey()); assertEquals(other, obj); } @Test public void testNothingAutogeneratedErrors() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); NothingAutoGenerated obj = new NothingAutoGenerated(); try { mapper.save(obj); fail("Expected a mapping exception"); } catch (DynamoDBMappingException expected) { } obj.setKey("" + System.currentTimeMillis()); try { mapper.save(obj); fail("Expected a mapping exception"); } catch (DynamoDBMappingException expected) { } obj.setRangeKey("" + System.currentTimeMillis()); obj.setKey(null); try { mapper.save(obj); fail("Expected a mapping exception"); } catch (DynamoDBMappingException expected) { } obj.setRangeKey(""); obj.setKey("" + System.currentTimeMillis()); try { mapper.save(obj); fail("Expected a mapping exception"); } catch (DynamoDBMappingException expected) { } obj.setRangeKey("" + System.currentTimeMillis()); mapper.save(obj); } @DynamoDBTable(tableName = "aws-java-sdk-string-range-crypto") public static class HashKeyRangeKeyBothAutoGeneratedKeyOnly { private String key; private String rangeKey; @DynamoDBAutoGeneratedKey @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAutoGeneratedKey @DynamoDBRangeKey public String getRangeKey() { return rangeKey; } public void setRangeKey(String rangeKey) { this.rangeKey = rangeKey; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((rangeKey == null) ? 0 : rangeKey.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; HashKeyRangeKeyBothAutoGeneratedKeyOnly other = (HashKeyRangeKeyBothAutoGeneratedKeyOnly) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (rangeKey == null) { if (other.rangeKey != null) return false; } else if (!rangeKey.equals(other.rangeKey)) return false; return true; } } @Test public void testHashKeyRangeKeyBothAutogeneratedKeyOnly() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); HashKeyRangeKeyBothAutoGeneratedKeyOnly obj = new HashKeyRangeKeyBothAutoGeneratedKeyOnly(); assertNull(obj.getKey()); assertNull(obj.getRangeKey()); mapper.save(obj); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); HashKeyRangeKeyBothAutoGeneratedKeyOnly other = mapper.load(HashKeyRangeKeyBothAutoGeneratedKeyOnly.class, obj.getKey(), obj.getRangeKey()); assertEquals(other, obj); } @DynamoDBTable(tableName = "aws-java-sdk-string-range-crypto") public static class HashKeyAutoGeneratedKeyOnly { private String key; private String rangeKey; @DynamoDBAutoGeneratedKey @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBRangeKey public String getRangeKey() { return rangeKey; } public void setRangeKey(String rangeKey) { this.rangeKey = rangeKey; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((rangeKey == null) ? 0 : rangeKey.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; HashKeyAutoGeneratedKeyOnly other = (HashKeyAutoGeneratedKeyOnly) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (rangeKey == null) { if (other.rangeKey != null) return false; } else if (!rangeKey.equals(other.rangeKey)) return false; return true; } } @Test public void testHashKeyAutogeneratedKeyOnly() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); HashKeyAutoGeneratedKeyOnly obj = new HashKeyAutoGeneratedKeyOnly(); obj.setRangeKey("" + System.currentTimeMillis()); assertNull(obj.getKey()); assertNotNull(obj.getRangeKey()); mapper.save(obj); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); HashKeyAutoGeneratedKeyOnly other = mapper.load(HashKeyAutoGeneratedKeyOnly.class, obj.getKey(), obj.getRangeKey()); assertEquals(other, obj); } @DynamoDBTable(tableName = "aws-java-sdk-string-range-crypto") public static class RangeKeyAutoGeneratedKeyOnly { private String key; private String rangeKey; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAutoGeneratedKey @DynamoDBRangeKey public String getRangeKey() { return rangeKey; } public void setRangeKey(String rangeKey) { this.rangeKey = rangeKey; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((rangeKey == null) ? 0 : rangeKey.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RangeKeyAutoGeneratedKeyOnly other = (RangeKeyAutoGeneratedKeyOnly) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (rangeKey == null) { if (other.rangeKey != null) return false; } else if (!rangeKey.equals(other.rangeKey)) return false; return true; } } @Test public void testRangeKeyAutogeneratedKeyOnly() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); RangeKeyAutoGeneratedKeyOnly obj = new RangeKeyAutoGeneratedKeyOnly(); obj.setKey("" + System.currentTimeMillis()); assertNotNull(obj.getKey()); assertNull(obj.getRangeKey()); mapper.save(obj); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); RangeKeyAutoGeneratedKeyOnly other = mapper.load(RangeKeyAutoGeneratedKeyOnly.class, obj.getKey(), obj.getRangeKey()); assertEquals(other, obj); } @DynamoDBTable(tableName = "aws-java-sdk-string-range-crypto") public static class NothingAutoGeneratedKeyOnly { private String key; private String rangeKey; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBRangeKey public String getRangeKey() { return rangeKey; } public void setRangeKey(String rangeKey) { this.rangeKey = rangeKey; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((rangeKey == null) ? 0 : rangeKey.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NothingAutoGeneratedKeyOnly other = (NothingAutoGeneratedKeyOnly) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (rangeKey == null) { if (other.rangeKey != null) return false; } else if (!rangeKey.equals(other.rangeKey)) return false; return true; } } @Test public void testNothingAutogeneratedKeyOnly() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); NothingAutoGeneratedKeyOnly obj = new NothingAutoGeneratedKeyOnly(); obj.setKey("" + System.currentTimeMillis()); obj.setRangeKey("" + System.currentTimeMillis()); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); mapper.save(obj); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); NothingAutoGeneratedKeyOnly other = mapper.load(NothingAutoGeneratedKeyOnly.class, obj.getKey(), obj.getRangeKey()); assertEquals(other, obj); } @Test public void testNothingAutogeneratedKeyOnlyErrors() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); NothingAutoGeneratedKeyOnly obj = new NothingAutoGeneratedKeyOnly(); try { mapper.save(obj); fail("Expected a mapping exception"); } catch (DynamoDBMappingException expected) { } obj.setKey("" + System.currentTimeMillis()); try { mapper.save(obj); fail("Expected a mapping exception"); } catch (DynamoDBMappingException expected) { } obj.setRangeKey("" + System.currentTimeMillis()); obj.setKey(null); try { mapper.save(obj); fail("Expected a mapping exception"); } catch (DynamoDBMappingException expected) { } obj.setRangeKey(""); obj.setKey("" + System.currentTimeMillis()); try { mapper.save(obj); fail("Expected a mapping exception"); } catch (DynamoDBMappingException expected) { } obj.setRangeKey("" + System.currentTimeMillis()); mapper.save(obj); } }
4,255
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/ConfigurationITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.fail; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.SaveBehavior; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.TableNameOverride; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.mapper.encryption.NumberAttributeTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.UUID; import org.testng.annotations.Test; /** Tests of the configuration object */ public class ConfigurationITCase extends DynamoDBMapperCryptoIntegrationTestBase { // We don't start with the current system millis like other tests because // it's out of the range of some data types private static int start = 1; private static int byteStart = -127; @Test public void testClobber() throws Exception { DynamoDBMapper util = new DynamoDBMapper(dynamo, new DynamoDBMapperConfig(SaveBehavior.CLOBBER)); NumberAttributeTestClassExtended obj = getUniqueObject(); util.save(obj); assertEquals(obj, util.load(obj.getClass(), obj.getKey())); NumberAttributeTestClass copy = copy(obj); util.save(copy); assertEquals(copy, util.load(copy.getClass(), obj.getKey())); // We should have lost the extra field because of the clobber behavior assertNull(util.load(NumberAttributeTestClassExtended.class, obj.getKey()).getExtraField()); // Now test overriding the clobber behavior on a per-save basis obj = getUniqueObject(); util.save(obj); assertEquals(obj, util.load(obj.getClass(), obj.getKey())); copy = copy(obj); util.save(copy, new DynamoDBMapperConfig(SaveBehavior.UPDATE)); assertEquals(copy, util.load(copy.getClass(), obj.getKey())); // We shouldn't have lost any extra info assertNotNull(util.load(NumberAttributeTestClassExtended.class, obj.getKey()).getExtraField()); } @Test public void testTableOverride() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); TableOverrideTestClass obj = new TableOverrideTestClass(); obj.setOtherField(UUID.randomUUID().toString()); try { util.save(obj); fail("Expected an exception"); } catch (Exception e) { } util.save(obj, new DynamoDBMapperConfig(new TableNameOverride("aws-java-sdk-util-crypto"))); try { util.load(TableOverrideTestClass.class, obj.getKey()); fail("Expected an exception"); } catch (Exception e) { } Object loaded = util.load( TableOverrideTestClass.class, obj.getKey(), new DynamoDBMapperConfig(TableNameOverride.withTableNamePrefix("aws-"))); assertEquals(loaded, obj); try { util.delete(obj); fail("Expected an exception"); } catch (Exception e) { } util.delete(obj, new DynamoDBMapperConfig(TableNameOverride.withTableNamePrefix("aws-"))); } private NumberAttributeTestClassExtended getUniqueObject() { NumberAttributeTestClassExtended obj = new NumberAttributeTestClassExtended(); obj.setKey(String.valueOf(startKey++)); obj.setBigDecimalAttribute(new BigDecimal(startKey++)); obj.setBigIntegerAttribute(new BigInteger("" + startKey++)); obj.setByteAttribute((byte) byteStart++); obj.setByteObjectAttribute(new Byte("" + byteStart++)); obj.setDoubleAttribute(new Double("" + start++)); obj.setDoubleObjectAttribute(new Double("" + start++)); obj.setFloatAttribute(new Float("" + start++)); obj.setFloatObjectAttribute(new Float("" + start++)); obj.setIntAttribute(new Integer("" + start++)); obj.setIntegerAttribute(new Integer("" + start++)); obj.setLongAttribute(new Long("" + start++)); obj.setLongObjectAttribute(new Long("" + start++)); obj.setDateAttribute(new Date(startKey++)); obj.setBooleanAttribute(start++ % 2 == 0); obj.setBooleanObjectAttribute(start++ % 2 == 0); obj.setExtraField("" + startKey++); Calendar cal = GregorianCalendar.getInstance(); cal.setTime(new Date(startKey++)); obj.setCalendarAttribute(cal); return obj; } private NumberAttributeTestClass copy(NumberAttributeTestClassExtended obj) { NumberAttributeTestClass copy = new NumberAttributeTestClass(); copy.setKey(obj.getKey()); copy.setBigDecimalAttribute(obj.getBigDecimalAttribute()); copy.setBigIntegerAttribute(obj.getBigIntegerAttribute()); copy.setByteAttribute(obj.getByteAttribute()); copy.setByteObjectAttribute(obj.getByteObjectAttribute()); copy.setDoubleAttribute(obj.getDoubleAttribute()); copy.setDoubleObjectAttribute(obj.getDoubleObjectAttribute()); copy.setFloatAttribute(obj.getFloatAttribute()); copy.setFloatObjectAttribute(obj.getFloatObjectAttribute()); copy.setIntAttribute(obj.getIntAttribute()); copy.setIntegerAttribute(obj.getIntegerAttribute()); copy.setLongAttribute(obj.getLongAttribute()); copy.setLongObjectAttribute(obj.getLongObjectAttribute()); copy.setDateAttribute(obj.getDateAttribute()); copy.setBooleanAttribute(obj.isBooleanAttribute()); copy.setBooleanObjectAttribute(obj.getBooleanObjectAttribute()); return copy; } @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public static final class NumberAttributeTestClassExtended extends NumberAttributeTestClass { private String extraField; public String getExtraField() { return extraField; } public void setExtraField(String extraField) { this.extraField = extraField; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((extraField == null) ? 0 : extraField.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; NumberAttributeTestClassExtended other = (NumberAttributeTestClassExtended) obj; if (extraField == null) { if (other.extraField != null) return false; } else if (!extraField.equals(other.extraField)) return false; return true; } } @DynamoDBTable(tableName = "java-sdk-util-crypto") // doesn't exist public static final class TableOverrideTestClass { private String key; private String otherField; @DynamoDBAutoGeneratedKey @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getOtherField() { return otherField; } public void setOtherField(String otherField) { this.otherField = otherField; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((otherField == null) ? 0 : otherField.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TableOverrideTestClass other = (TableOverrideTestClass) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (otherField == null) { if (other.otherField != null) return false; } else if (!otherField.equals(other.otherField)) return false; return true; } } }
4,256
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/VersionAttributeUpdateITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.fail; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBDeleteExpression; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.SaveBehavior; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBSaveExpression; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBVersionAttribute; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; import com.amazonaws.services.dynamodbv2.model.ConditionalOperator; import com.amazonaws.services.dynamodbv2.model.ExpectedAttributeValue; import com.amazonaws.util.ImmutableMapParameter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.annotations.Test; /** Tests updating version fields correctly */ public class VersionAttributeUpdateITCase extends DynamoDBMapperCryptoIntegrationTestBase { @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public static class VersionFieldBaseClass { protected String key; protected String normalStringAttribute; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAttribute public String getNormalStringAttribute() { return normalStringAttribute; } public void setNormalStringAttribute(String normalStringAttribute) { this.normalStringAttribute = normalStringAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((normalStringAttribute == null) ? 0 : normalStringAttribute.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; VersionFieldBaseClass other = (VersionFieldBaseClass) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (normalStringAttribute == null) { if (other.normalStringAttribute != null) return false; } else if (!normalStringAttribute.equals(other.normalStringAttribute)) return false; return true; } } public static class StringVersionField extends VersionFieldBaseClass { private String version; @DynamoDBVersionAttribute public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; StringVersionField other = (StringVersionField) obj; if (version == null) { if (other.version != null) return false; } else if (!version.equals(other.version)) return false; return true; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testStringVersion() throws Exception { List<StringVersionField> objs = new ArrayList<StringVersionField>(); for (int i = 0; i < 5; i++) { StringVersionField obj = getUniqueObject(new StringVersionField()); objs.add(obj); } // Saving new objects with a null version field should populate it DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (StringVersionField obj : objs) { assertNull(obj.getVersion()); util.save(obj); assertNotNull(obj.getVersion()); assertEquals(obj, util.load(StringVersionField.class, obj.getKey())); } } public static class BigIntegerVersionField extends VersionFieldBaseClass { private BigInteger version; @DynamoDBVersionAttribute public BigInteger getVersion() { return version; } public void setVersion(BigInteger version) { this.version = version; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; BigIntegerVersionField other = (BigIntegerVersionField) obj; if (version == null) { if (other.version != null) return false; } else if (!version.equals(other.version)) return false; return true; } @Override public String toString() { return "BigIntegerVersionField [version=" + version + ", key=" + key + ", normalStringAttribute=" + normalStringAttribute + "]"; } } @Test public void testBigIntegerVersion() { List<BigIntegerVersionField> objs = new ArrayList<BigIntegerVersionField>(); for (int i = 0; i < 5; i++) { BigIntegerVersionField obj = getUniqueObject(new BigIntegerVersionField()); objs.add(obj); } // Saving new objects with a null version field should populate it DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (BigIntegerVersionField obj : objs) { assertNull(obj.getVersion()); util.save(obj); assertNotNull(obj.getVersion()); assertEquals(obj, util.load(BigIntegerVersionField.class, obj.getKey())); } for (BigIntegerVersionField obj : objs) { BigIntegerVersionField replacement = getUniqueObject(new BigIntegerVersionField()); replacement.setKey(obj.getKey()); replacement.setVersion(obj.getVersion()); util.save(replacement); // The version field should have changed in memory assertFalse(obj.getVersion().equals(replacement.getVersion())); BigIntegerVersionField loadedObject = util.load(BigIntegerVersionField.class, obj.getKey()); assertEquals(replacement, loadedObject); // Trying to update the object again should trigger a concurrency // exception try { util.save(obj); fail("Should have thrown an exception"); } catch (Exception expected) { } // Now try again overlaying the correct version number by using a saveExpression // this should not throw the conditional check failed exception try { DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression(); Map<String, ExpectedAttributeValue> expected = new HashMap<String, ExpectedAttributeValue>(); ExpectedAttributeValue expectedVersion = new ExpectedAttributeValue() .withValue( new AttributeValue() .withN(obj.getVersion().add(BigInteger.valueOf(1)).toString())); expected.put("version", expectedVersion); saveExpression.setExpected(expected); util.save(obj, saveExpression); } catch (Exception expected) { fail("This should succeed, version was updated."); } } } public static final class IntegerVersionField extends VersionFieldBaseClass { private Integer notCalledVersion; // Making sure that we can substitute attribute names as necessary @DynamoDBVersionAttribute(attributeName = "version") public Integer getNotCalledVersion() { return notCalledVersion; } public void setNotCalledVersion(Integer notCalledVersion) { this.notCalledVersion = notCalledVersion; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((notCalledVersion == null) ? 0 : notCalledVersion.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; IntegerVersionField other = (IntegerVersionField) obj; if (notCalledVersion == null) { if (other.notCalledVersion != null) return false; } else if (!notCalledVersion.equals(other.notCalledVersion)) return false; return true; } } @Test public void testIntegerVersion() { List<IntegerVersionField> objs = new ArrayList<IntegerVersionField>(); for (int i = 0; i < 5; i++) { IntegerVersionField obj = getUniqueObject(new IntegerVersionField()); objs.add(obj); } // Saving new objects with a null version field should populate it DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (IntegerVersionField obj : objs) { assertNull(obj.getNotCalledVersion()); util.save(obj); assertNotNull(obj.getNotCalledVersion()); assertEquals(obj, util.load(IntegerVersionField.class, obj.getKey())); } for (IntegerVersionField obj : objs) { IntegerVersionField replacement = getUniqueObject(new IntegerVersionField()); replacement.setKey(obj.getKey()); replacement.setNotCalledVersion(obj.getNotCalledVersion()); util.save(replacement); // The version field should have changed in memory assertFalse(obj.getNotCalledVersion().equals(replacement.getNotCalledVersion())); IntegerVersionField loadedObject = util.load(IntegerVersionField.class, obj.getKey()); assertEquals(replacement, loadedObject); // Trying to update the object again should trigger a concurrency // exception try { util.save(obj); fail("Should have thrown an exception"); } catch (Exception expected) { } // Trying to delete the object should also fail try { util.delete(obj); fail("Should have thrown an exception"); } catch (Exception expected) { } // But specifying CLOBBER will allow deletion util.save(obj, new DynamoDBMapperConfig(SaveBehavior.CLOBBER)); // Trying to delete with the wrong version should fail try { // version is now 2 in db, set object version to 3. obj.setNotCalledVersion(3); util.delete(obj); fail("Should have thrown an exception"); } catch (Exception expected) { } // Now try deleting again overlaying the correct version number by using a deleteExpression // this should not throw the conditional check failed exception try { DynamoDBDeleteExpression deleteExpression = new DynamoDBDeleteExpression(); Map<String, ExpectedAttributeValue> expected = new HashMap<String, ExpectedAttributeValue>(); ExpectedAttributeValue expectedVersion = new ExpectedAttributeValue() .withValue(new AttributeValue().withN("2")); // version is still 2 in db expected.put("version", expectedVersion); deleteExpression.setExpected(expected); util.delete(obj, deleteExpression); } catch (Exception expected) { fail("This should succeed, version was updated."); } } } /** * Tests providing additional expected conditions when saving and deleting item with versioned * fields. */ @Test public void testVersionedAttributeWithUserProvidedExpectedConditions() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); IntegerVersionField versionedObject = getUniqueObject(new IntegerVersionField()); assertNull(versionedObject.getNotCalledVersion()); // Add additional expected conditions via DynamoDBSaveExpression. // Expected conditions joined by AND are compatible with the conditions // for auto-generated keys. DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression() .withExpected( Collections.singletonMap("otherAttribute", new ExpectedAttributeValue(false))) .withConditionalOperator(ConditionalOperator.AND); // The save should succeed since the user provided conditions are joined by AND. mapper.save(versionedObject, saveExpression); // The version field should be populated assertNotNull(versionedObject.getNotCalledVersion()); IntegerVersionField other = mapper.load(IntegerVersionField.class, versionedObject.getKey()); assertEquals(other, versionedObject); // delete should also work DynamoDBDeleteExpression deleteExpression = new DynamoDBDeleteExpression() .withExpected( Collections.singletonMap("otherAttribute", new ExpectedAttributeValue(false))) .withConditionalOperator(ConditionalOperator.AND); mapper.delete(versionedObject, deleteExpression); // Change the conditional operator to OR. // IllegalArgumentException is expected since the additional expected // conditions cannot be joined with the conditions for auto-generated // keys. saveExpression.setConditionalOperator(ConditionalOperator.OR); deleteExpression.setConditionalOperator(ConditionalOperator.OR); try { mapper.save(getUniqueObject(new IntegerVersionField()), saveExpression); } catch (IllegalArgumentException expected) { } try { mapper.delete(getUniqueObject(new IntegerVersionField()), deleteExpression); } catch (IllegalArgumentException expected) { } // User-provided OR conditions should work if they completely override // the generated conditions for the version field. Map<String, ExpectedAttributeValue> goodConditions = ImmutableMapParameter.of( "otherAttribute", new ExpectedAttributeValue(false), "version", new ExpectedAttributeValue(false)); Map<String, ExpectedAttributeValue> badConditions = ImmutableMapParameter.of( "otherAttribute", new ExpectedAttributeValue(new AttributeValue("non-existent-value")), "version", new ExpectedAttributeValue(new AttributeValue().withN("-1"))); IntegerVersionField newObj = getUniqueObject(new IntegerVersionField()); saveExpression.setExpected(badConditions); try { mapper.save(newObj, saveExpression); } catch (ConditionalCheckFailedException expected) { } saveExpression.setExpected(goodConditions); mapper.save(newObj, saveExpression); deleteExpression.setExpected(badConditions); try { mapper.delete(newObj, deleteExpression); } catch (ConditionalCheckFailedException expected) { } deleteExpression.setExpected(goodConditions); mapper.delete(newObj, deleteExpression); } public static final class ByteVersionField extends VersionFieldBaseClass { private Byte version; @DynamoDBVersionAttribute public Byte getVersion() { return version; } public void setVersion(Byte version) { this.version = version; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; ByteVersionField other = (ByteVersionField) obj; if (version == null) { if (other.version != null) return false; } else if (!version.equals(other.version)) return false; return true; } } @Test public void testByteVersion() { List<ByteVersionField> objs = new ArrayList<ByteVersionField>(); for (int i = 0; i < 5; i++) { ByteVersionField obj = getUniqueObject(new ByteVersionField()); objs.add(obj); } // Saving new objects with a null version field should populate it DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (ByteVersionField obj : objs) { assertNull(obj.getVersion()); util.save(obj); assertNotNull(obj.getVersion()); assertEquals(obj, util.load(ByteVersionField.class, obj.getKey())); } for (ByteVersionField obj : objs) { ByteVersionField replacement = getUniqueObject(new ByteVersionField()); replacement.setKey(obj.getKey()); replacement.setVersion(obj.getVersion()); util.save(replacement); // The version field should have changed in memory assertFalse(obj.getVersion().equals(replacement.getVersion())); ByteVersionField loadedObject = util.load(ByteVersionField.class, obj.getKey()); assertEquals(replacement, loadedObject); // Trying to update the object again should trigger a concurrency // exception try { util.save(obj); fail("Should have thrown an exception"); } catch (Exception expected) { } } } public static final class LongVersionField extends VersionFieldBaseClass { private Long version; @DynamoDBVersionAttribute public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; LongVersionField other = (LongVersionField) obj; if (version == null) { if (other.version != null) return false; } else if (!version.equals(other.version)) return false; return true; } } @Test public void testLongVersion() { List<LongVersionField> objs = new ArrayList<LongVersionField>(); for (int i = 0; i < 5; i++) { LongVersionField obj = getUniqueObject(new LongVersionField()); objs.add(obj); } // Saving new objects with a null version field should populate it DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (LongVersionField obj : objs) { assertNull(obj.getVersion()); util.save(obj); assertNotNull(obj.getVersion()); assertEquals(obj, util.load(LongVersionField.class, obj.getKey())); } for (LongVersionField obj : objs) { LongVersionField replacement = getUniqueObject(new LongVersionField()); replacement.setKey(obj.getKey()); replacement.setVersion(obj.getVersion()); util.save(replacement); // The version field should have changed in memory assertFalse(obj.getVersion().equals(replacement.getVersion())); LongVersionField loadedObject = util.load(LongVersionField.class, obj.getKey()); assertEquals(replacement, loadedObject); // Trying to update the object again should trigger a concurrency // exception try { util.save(obj); fail("Should have thrown an exception"); } catch (Exception expected) { } } } private <T extends VersionFieldBaseClass> T getUniqueObject(T obj) { obj.setKey("" + startKey++); obj.setNormalStringAttribute("" + startKey++); return obj; } }
4,257
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/StringSetAttributesITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionFlags; import com.amazonaws.services.dynamodbv2.mapper.encryption.StringSetAttributeTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestEncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Tests string set attributes */ public class StringSetAttributesITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static final String ORIGINAL_NAME_ATTRIBUTE = "originalName"; private static final String STRING_SET_ATTRIBUTE = "stringSetAttribute"; private static final String EXTRA_ATTRIBUTE = "extra"; private static final List<Map<String, AttributeValue>> attrs = new LinkedList<Map<String, AttributeValue>>(); // Test data static { for (int i = 0; i < 5; i++) { Map<String, AttributeValue> attr = new HashMap<String, AttributeValue>(); attr.put(KEY_NAME, new AttributeValue().withS("" + startKey++)); attr.put( STRING_SET_ATTRIBUTE, new AttributeValue().withSS("" + ++startKey, "" + ++startKey, "" + ++startKey)); attr.put( ORIGINAL_NAME_ATTRIBUTE, new AttributeValue().withSS("" + ++startKey, "" + ++startKey, "" + ++startKey)); attr.put( EXTRA_ATTRIBUTE, new AttributeValue().withSS("" + ++startKey, "" + ++startKey, "" + ++startKey)); attrs.add(attr); } } ; @BeforeClass public static void setUp() throws Exception { DynamoDBMapperCryptoIntegrationTestBase.setUp(); DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(new TestEncryptionMaterialsProvider()); EncryptionContext context = new EncryptionContext.Builder().withHashKeyName(KEY_NAME).withTableName(TABLE_NAME).build(); // Insert the data for (Map<String, AttributeValue> attr : attrs) { Map<String, Set<EncryptionFlags>> flags = encryptor.allEncryptionFlagsExcept(attr, KEY_NAME); flags.remove(EXTRA_ATTRIBUTE); // exclude "extra" entirely since // it's not defined in the // StringSetAttributeTestClass pojo attr = encryptor.encryptRecord(attr, flags, context); dynamo.putItem(new PutItemRequest(TABLE_NAME, attr)); } } @Test public void testLoad() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (Map<String, AttributeValue> attr : attrs) { StringSetAttributeTestClass x = util.load(StringSetAttributeTestClass.class, attr.get(KEY_NAME).getS()); assertEquals(x.getKey(), attr.get(KEY_NAME).getS()); assertSetsEqual(x.getStringSetAttribute(), toSet(attr.get(STRING_SET_ATTRIBUTE).getSS())); assertSetsEqual( x.getStringSetAttributeRenamed(), toSet(attr.get(ORIGINAL_NAME_ATTRIBUTE).getSS())); } } /** Tests saving only some attributes of an object. */ @Test public void testIncompleteObject() { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); StringSetAttributeTestClass obj = getUniqueObject(); obj.setStringSetAttribute(null); util.save(obj); assertEquals(obj, util.load(StringSetAttributeTestClass.class, obj.getKey())); obj.setStringSetAttributeRenamed(null); util.save(obj); assertEquals(obj, util.load(StringSetAttributeTestClass.class, obj.getKey())); } @Test public void testSave() throws Exception { List<StringSetAttributeTestClass> objs = new ArrayList<StringSetAttributeTestClass>(); for (int i = 0; i < 5; i++) { StringSetAttributeTestClass obj = getUniqueObject(); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (StringSetAttributeTestClass obj : objs) { util.save(obj); } for (StringSetAttributeTestClass obj : objs) { StringSetAttributeTestClass loaded = util.load(StringSetAttributeTestClass.class, obj.getKey()); assertEquals(obj, loaded); } } @Test public void testUpdate() throws Exception { List<StringSetAttributeTestClass> objs = new ArrayList<StringSetAttributeTestClass>(); for (int i = 0; i < 5; i++) { StringSetAttributeTestClass obj = getUniqueObject(); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (StringSetAttributeTestClass obj : objs) { util.save(obj); } for (StringSetAttributeTestClass obj : objs) { StringSetAttributeTestClass replacement = getUniqueObject(); replacement.setKey(obj.getKey()); util.save(replacement); assertEquals(replacement, util.load(StringSetAttributeTestClass.class, obj.getKey())); } } private StringSetAttributeTestClass getUniqueObject() { StringSetAttributeTestClass obj = new StringSetAttributeTestClass(); obj.setKey(String.valueOf(startKey++)); obj.setStringSetAttribute( toSet(String.valueOf(startKey++), String.valueOf(startKey++), String.valueOf(startKey++))); obj.setStringSetAttributeRenamed( toSet(String.valueOf(startKey++), String.valueOf(startKey++), String.valueOf(startKey++))); return obj; } }
4,258
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/ComplexTypeITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMarshalling; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.JsonMarshaller; import com.amazonaws.services.dynamodbv2.mapper.encryption.NumberAttributeTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.MappingJsonFactory; import java.io.StringReader; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import org.testng.annotations.Test; /** Tests of the configuration object */ public class ComplexTypeITCase extends DynamoDBMapperCryptoIntegrationTestBase { // We don't start with the current system millis like other tests because // it's out of the range of some data types private static int start = 1; private static int byteStart = -127; @Test public void testComplexTypes() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); ComplexClass obj = getUniqueObject(); util.save(obj); ComplexClass loaded = util.load(ComplexClass.class, obj.getKey()); assertEquals(obj, loaded); } private ComplexClass getUniqueObject() { ComplexClass obj = new ComplexClass(); obj.setKey(String.valueOf(startKey++)); obj.setBigDecimalAttribute(new BigDecimal(startKey++)); obj.setBigIntegerAttribute(new BigInteger("" + startKey++)); obj.setByteAttribute((byte) byteStart++); obj.setByteObjectAttribute(new Byte("" + byteStart++)); obj.setDoubleAttribute(new Double("" + start++)); obj.setDoubleObjectAttribute(new Double("" + start++)); obj.setFloatAttribute(new Float("" + start++)); obj.setFloatObjectAttribute(new Float("" + start++)); obj.setIntAttribute(new Integer("" + start++)); obj.setIntegerAttribute(new Integer("" + start++)); obj.setLongAttribute(new Long("" + start++)); obj.setLongObjectAttribute(new Long("" + start++)); obj.setDateAttribute(new Date(startKey++)); obj.setBooleanAttribute(start++ % 2 == 0); obj.setBooleanObjectAttribute(start++ % 2 == 0); obj.setExtraField("" + startKey++); Calendar cal = GregorianCalendar.getInstance(); cal.setTime(new Date(startKey++)); obj.setCalendarAttribute(cal); obj.setComplexNestedType( new ComplexNestedType( "" + start++, start++, new ComplexNestedType("" + start++, start++, null))); List<ComplexNestedType> complexTypes = new ArrayList<ComplexTypeITCase.ComplexNestedType>(); complexTypes.add( new ComplexNestedType( "" + start++, start++, new ComplexNestedType("" + start++, start++, null))); complexTypes.add( new ComplexNestedType( "" + start++, start++, new ComplexNestedType("" + start++, start++, null))); complexTypes.add( new ComplexNestedType( "" + start++, start++, new ComplexNestedType("" + start++, start++, null))); obj.setComplexNestedTypeList(complexTypes); return obj; } /* * Type with a complex nested field for working with marshallers */ public static final class ComplexNestedTypeMarshaller extends JsonMarshaller<ComplexNestedType> {} public static final class ComplexNestedListTypeMarshaller extends JsonMarshaller<List<ComplexNestedType>> { /* (non-Javadoc) * @see com.amazonaws.services.dynamodbv2.datamodeling.JsonMarshaller#unmarshall(java.lang.Class, java.lang.String) */ @Override public List<ComplexNestedType> unmarshall(Class<List<ComplexNestedType>> clazz, String obj) { try { JsonFactory jsonFactory = new MappingJsonFactory(); JsonParser jsonParser = jsonFactory.createJsonParser(new StringReader(obj)); return jsonParser.readValueAs(new TypeReference<List<ComplexNestedType>>() {}); } catch (Exception e) { throw new RuntimeException(e); } } } @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public static final class ComplexClass extends NumberAttributeTestClass { private String extraField; private ComplexNestedType complexNestedType; private List<ComplexNestedType> complexNestedTypeList; @DynamoDBMarshalling(marshallerClass = ComplexNestedTypeMarshaller.class) public ComplexNestedType getComplexNestedType() { return complexNestedType; } public void setComplexNestedType(ComplexNestedType complexNestedType) { this.complexNestedType = complexNestedType; } @DynamoDBMarshalling(marshallerClass = ComplexNestedListTypeMarshaller.class) public List<ComplexNestedType> getComplexNestedTypeList() { return complexNestedTypeList; } public void setComplexNestedTypeList(List<ComplexNestedType> complexNestedTypeList) { this.complexNestedTypeList = complexNestedTypeList; } public String getExtraField() { return extraField; } public void setExtraField(String extraField) { this.extraField = extraField; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((complexNestedType == null) ? 0 : complexNestedType.hashCode()); result = prime * result + ((complexNestedTypeList == null) ? 0 : complexNestedTypeList.hashCode()); result = prime * result + ((extraField == null) ? 0 : extraField.hashCode()); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; ComplexClass other = (ComplexClass) obj; if (complexNestedType == null) { if (other.complexNestedType != null) return false; } else if (!complexNestedType.equals(other.complexNestedType)) return false; if (complexNestedTypeList == null) { if (other.complexNestedTypeList != null) return false; } else if (!complexNestedTypeList.equals(other.complexNestedTypeList)) return false; if (extraField == null) { if (other.extraField != null) return false; } else if (!extraField.equals(other.extraField)) return false; return true; } } public static final class ComplexNestedType { private String stringValue; private Integer intValue; private ComplexNestedType nestedType; public ComplexNestedType() {} public ComplexNestedType(String stringValue, Integer intValue, ComplexNestedType nestedType) { super(); this.stringValue = stringValue; this.intValue = intValue; this.nestedType = nestedType; } public String getStringValue() { return stringValue; } public void setStringValue(String stringValue) { this.stringValue = stringValue; } public Integer getIntValue() { return intValue; } public void setIntValue(Integer intValue) { this.intValue = intValue; } public ComplexNestedType getNestedType() { return nestedType; } public void setNestedType(ComplexNestedType nestedType) { this.nestedType = nestedType; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((intValue == null) ? 0 : intValue.hashCode()); result = prime * result + ((nestedType == null) ? 0 : nestedType.hashCode()); result = prime * result + ((stringValue == null) ? 0 : stringValue.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ComplexNestedType other = (ComplexNestedType) obj; if (intValue == null) { if (other.intValue != null) return false; } else if (!intValue.equals(other.intValue)) return false; if (nestedType == null) { if (other.nestedType != null) return false; } else if (!nestedType.equals(other.nestedType)) return false; if (stringValue == null) { if (other.stringValue != null) return false; } else if (!stringValue.equals(other.stringValue)) return false; return true; } } @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public static final class ComplexKey { private ComplexNestedType key; private String otherAttribute; @DynamoDBHashKey @DynamoDBMarshalling(marshallerClass = ComplexNestedTypeMarshaller.class) public ComplexNestedType getKey() { return key; } public void setKey(ComplexNestedType key) { this.key = key; } public String getOtherAttribute() { return otherAttribute; } public void setOtherAttribute(String otherAttribute) { this.otherAttribute = otherAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((otherAttribute == null) ? 0 : otherAttribute.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ComplexKey other = (ComplexKey) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (otherAttribute == null) { if (other.otherAttribute != null) return false; } else if (!otherAttribute.equals(other.otherAttribute)) return false; return true; } } /** Tests using a complex type for a (string) key */ @Test public void testComplexKey() throws Exception { ComplexKey obj = new ComplexKey(); ComplexNestedType key = new ComplexNestedType(); key.setIntValue(start++); key.setStringValue("" + start++); obj.setKey(key); obj.setOtherAttribute("" + start++); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.save(obj); ComplexKey loaded = mapper.load(ComplexKey.class, obj.getKey()); assertEquals(obj, loaded); } }
4,259
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/mapper/integration/BatchWriteITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.FailedBatch; import com.amazonaws.services.dynamodbv2.mapper.encryption.BinaryAttributeByteBufferTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.NoSuchTableTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.NumberSetAttributeTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.RangeKeyTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Tests batch write calls */ public class BatchWriteITCase extends DynamoDBMapperCryptoIntegrationTestBase { // We don't start with the current system millis like other tests because // it's out of the range of some data types private static int start = 1; private static int byteStart = 1; private static int startKeyDebug = 1; @BeforeClass public static void setUp() throws Exception { setUpTableWithRangeAttribute(); } @Test public void testBatchSave() throws Exception { List<NumberSetAttributeTestClass> objs = new ArrayList<NumberSetAttributeTestClass>(); for (int i = 0; i < 40; i++) { NumberSetAttributeTestClass obj = getUniqueNumericObject(); objs.add(obj); } DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); List<FailedBatch> failedBatches = mapper.batchSave(objs); assertTrue(0 == failedBatches.size()); for (NumberSetAttributeTestClass obj : objs) { NumberSetAttributeTestClass loaded = mapper.load(NumberSetAttributeTestClass.class, obj.getKey()); assertEquals(obj, loaded); } } @Test public void testBatchSaveAsArray() throws Exception { List<NumberSetAttributeTestClass> objs = new ArrayList<NumberSetAttributeTestClass>(); for (int i = 0; i < 40; i++) { NumberSetAttributeTestClass obj = getUniqueNumericObject(); objs.add(obj); } DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); NumberSetAttributeTestClass[] objsArray = objs.toArray(new NumberSetAttributeTestClass[objs.size()]); mapper.batchSave((Object[]) objsArray); for (NumberSetAttributeTestClass obj : objs) { NumberSetAttributeTestClass loaded = mapper.load(NumberSetAttributeTestClass.class, obj.getKey()); assertEquals(obj, loaded); } } @Test public void testBatchSaveAsListFromArray() throws Exception { List<NumberSetAttributeTestClass> objs = new ArrayList<NumberSetAttributeTestClass>(); for (int i = 0; i < 40; i++) { NumberSetAttributeTestClass obj = getUniqueNumericObject(); objs.add(obj); } DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); NumberSetAttributeTestClass[] objsArray = objs.toArray(new NumberSetAttributeTestClass[objs.size()]); mapper.batchSave(Arrays.asList(objsArray)); for (NumberSetAttributeTestClass obj : objs) { NumberSetAttributeTestClass loaded = mapper.load(NumberSetAttributeTestClass.class, obj.getKey()); assertEquals(obj, loaded); } } @Test public void testBatchDelete() throws Exception { List<NumberSetAttributeTestClass> objs = new ArrayList<NumberSetAttributeTestClass>(); for (int i = 0; i < 40; i++) { NumberSetAttributeTestClass obj = getUniqueNumericObject(); objs.add(obj); } DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.batchSave(objs); for (NumberSetAttributeTestClass obj : objs) { NumberSetAttributeTestClass loaded = mapper.load(NumberSetAttributeTestClass.class, obj.getKey()); assertEquals(obj, loaded); } // Delete the odd ones int i = 0; List<NumberSetAttributeTestClass> toDelete = new LinkedList<NumberSetAttributeTestClass>(); for (NumberSetAttributeTestClass obj : objs) { if (i++ % 2 == 0) toDelete.add(obj); } mapper.batchDelete(toDelete); i = 0; for (NumberSetAttributeTestClass obj : objs) { NumberSetAttributeTestClass loaded = mapper.load(NumberSetAttributeTestClass.class, obj.getKey()); if (i++ % 2 == 0) { assertNull(loaded); } else { assertEquals(obj, loaded); } } } @Test public void testBatchSaveAndDelete() throws Exception { List<NumberSetAttributeTestClass> objs = new ArrayList<NumberSetAttributeTestClass>(); for (int i = 0; i < 40; i++) { NumberSetAttributeTestClass obj = getUniqueNumericObject(); objs.add(obj); } DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.batchSave(objs); for (NumberSetAttributeTestClass obj : objs) { NumberSetAttributeTestClass loaded = mapper.load(NumberSetAttributeTestClass.class, obj.getKey()); assertEquals(obj, loaded); } // Delete the odd ones int i = 0; List<NumberSetAttributeTestClass> toDelete = new LinkedList<NumberSetAttributeTestClass>(); for (NumberSetAttributeTestClass obj : objs) { if (i++ % 2 == 0) toDelete.add(obj); } // And add a bunch of new ones List<NumberSetAttributeTestClass> toSave = new LinkedList<NumberSetAttributeTestClass>(); for (i = 0; i < 50; i++) { NumberSetAttributeTestClass obj = getUniqueNumericObject(); toSave.add(obj); } mapper.batchWrite(toSave, toDelete); i = 0; for (NumberSetAttributeTestClass obj : objs) { NumberSetAttributeTestClass loaded = mapper.load(NumberSetAttributeTestClass.class, obj.getKey()); if (i++ % 2 == 0) { assertNull(loaded); } else { assertEquals(obj, loaded); } } for (NumberSetAttributeTestClass obj : toSave) { NumberSetAttributeTestClass loaded = mapper.load(NumberSetAttributeTestClass.class, obj.getKey()); assertEquals(obj, loaded); } } @Test public void testMultipleTables() throws Exception { List<Object> objs = new ArrayList<Object>(); int numItems = 10; for (int i = 0; i < numItems; i++) { NumberSetAttributeTestClass obj = getUniqueNumericObject(); objs.add(obj); } for (int i = 0; i < numItems; i++) { RangeKeyTestClass obj = getUniqueRangeKeyObject(); objs.add(obj); } Collections.shuffle(objs); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); List<FailedBatch> failedBatches = mapper.batchSave(objs); assertTrue(failedBatches.size() == 0); for (Object obj : objs) { Object loaded = null; if (obj instanceof NumberSetAttributeTestClass) { loaded = mapper.load( NumberSetAttributeTestClass.class, ((NumberSetAttributeTestClass) obj).getKey()); } else if (obj instanceof RangeKeyTestClass) { loaded = mapper.load( RangeKeyTestClass.class, ((RangeKeyTestClass) obj).getKey(), ((RangeKeyTestClass) obj).getRangeKey()); } else { fail(); } assertEquals(obj, loaded); } // Delete the odd ones int i = 0; List<Object> toDelete = new LinkedList<Object>(); for (Object obj : objs) { if (i++ % 2 == 0) toDelete.add(obj); } // And add a bunch of new ones List<Object> toSave = new LinkedList<Object>(); for (i = 0; i < numItems; i++) { if (i % 2 == 0) toSave.add(getUniqueNumericObject()); else toSave.add(getUniqueRangeKeyObject()); } failedBatches = mapper.batchWrite(toSave, toDelete); assertTrue(0 == failedBatches.size()); i = 0; for (Object obj : objs) { Object loaded = null; if (obj instanceof NumberSetAttributeTestClass) { loaded = mapper.load( NumberSetAttributeTestClass.class, ((NumberSetAttributeTestClass) obj).getKey()); } else if (obj instanceof RangeKeyTestClass) { loaded = mapper.load( RangeKeyTestClass.class, ((RangeKeyTestClass) obj).getKey(), ((RangeKeyTestClass) obj).getRangeKey()); } else { fail(); } if (i++ % 2 == 0) { assertNull(loaded); } else { assertEquals(obj, loaded); } } for (Object obj : toSave) { Object loaded = null; if (obj instanceof NumberSetAttributeTestClass) { loaded = mapper.load( NumberSetAttributeTestClass.class, ((NumberSetAttributeTestClass) obj).getKey()); } else if (obj instanceof RangeKeyTestClass) { loaded = mapper.load( RangeKeyTestClass.class, ((RangeKeyTestClass) obj).getKey(), ((RangeKeyTestClass) obj).getRangeKey()); } else { fail(); } assertEquals(obj, loaded); } } /** Test whether it finish processing all the items even if the first batch is failed. */ @Test public void testErrorHandling() { List<Object> objs = new ArrayList<Object>(); int numItems = 25; for (int i = 0; i < numItems; i++) { NoSuchTableTestClass obj = getuniqueBadObject(); objs.add(obj); } for (int i = 0; i < numItems; i++) { RangeKeyTestClass obj = getUniqueRangeKeyObject(); objs.add(obj); } DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); // The failed batch List<FailedBatch> failedBatches = mapper.batchSave(objs); assertTrue(1 == failedBatches.size()); assertTrue(numItems == failedBatches.get(0).getUnprocessedItems().get("tableNotExist").size()); // The second batch succeeds, get them back for (Object obj : objs.subList(25, 50)) { RangeKeyTestClass loaded = mapper.load( RangeKeyTestClass.class, ((RangeKeyTestClass) obj).getKey(), ((RangeKeyTestClass) obj).getRangeKey()); assertEquals(obj, loaded); } } /** Test whether we can split large batch request into small pieces. */ @Test public void testLargeRequestEntity() { // The total batch size is beyond 1M, test whether our client can split // the batch correctly List<BinaryAttributeByteBufferTestClass> objs = new ArrayList<BinaryAttributeByteBufferTestClass>(); int numItems = 25; final int CONTENT_LENGTH = 1024 * 25; for (int i = 0; i < numItems; i++) { BinaryAttributeByteBufferTestClass obj = getUniqueByteBufferObject(CONTENT_LENGTH); objs.add(obj); } DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); List<FailedBatch> failedBatches = mapper.batchSave(objs); assertEquals(failedBatches.size(), 0); // Get these objects back for (BinaryAttributeByteBufferTestClass obj : objs) { BinaryAttributeByteBufferTestClass loaded = mapper.load(BinaryAttributeByteBufferTestClass.class, obj.getKey()); assertEquals(obj, loaded); } // There are three super large item together with some small ones, test // whether we can successfully // save these small items. objs.clear(); numItems = 10; List<BinaryAttributeByteBufferTestClass> largeObjs = new ArrayList<BinaryAttributeByteBufferTestClass>(); // Put three super large item(beyond 64k) largeObjs.add(getUniqueByteBufferObject(CONTENT_LENGTH * 30)); largeObjs.add(getUniqueByteBufferObject(CONTENT_LENGTH * 30)); largeObjs.add(getUniqueByteBufferObject(CONTENT_LENGTH * 30)); for (int i = 0; i < numItems - 3; i++) { BinaryAttributeByteBufferTestClass obj = getUniqueByteBufferObject(CONTENT_LENGTH / 25); objs.add(obj); } objs.addAll(largeObjs); failedBatches = mapper.batchSave(objs); final int size = failedBatches.size(); if (DEBUG) System.err.println("failedBatches.size()=" + size); assertThat(size, equalTo(1)); objs.removeAll(largeObjs); mapper.batchSave(objs); // Get these small objects back for (BinaryAttributeByteBufferTestClass obj : objs) { BinaryAttributeByteBufferTestClass loaded = mapper.load(BinaryAttributeByteBufferTestClass.class, obj.getKey()); assertEquals(obj, loaded); } // The whole batch is super large objects, none of them will be // processed largeObjs.clear(); for (int i = 0; i < 5; i++) { BinaryAttributeByteBufferTestClass obj = getUniqueByteBufferObject(CONTENT_LENGTH * 30); largeObjs.add(obj); } if (DEBUG) System.err.println("failedBatches.size()=" + size); assertThat(failedBatches.size(), equalTo(1)); } private NoSuchTableTestClass getuniqueBadObject() { NoSuchTableTestClass obj = new NoSuchTableTestClass(); obj.setKey(String.valueOf(startKeyDebug++)); return obj; } private NumberSetAttributeTestClass getUniqueNumericObject() { NumberSetAttributeTestClass obj = new NumberSetAttributeTestClass(); obj.setKey(String.valueOf(startKeyDebug++)); obj.setBigDecimalAttribute( toSet(new BigDecimal(startKey++), new BigDecimal(startKey++), new BigDecimal(startKey++))); obj.setBigIntegerAttribute( toSet( new BigInteger("" + startKey++), new BigInteger("" + startKey++), new BigInteger("" + startKey++))); obj.setByteObjectAttribute( toSet(new Byte(nextByte()), new Byte(nextByte()), new Byte(nextByte()))); obj.setDoubleObjectAttribute( toSet(new Double("" + start++), new Double("" + start++), new Double("" + start++))); obj.setFloatObjectAttribute( toSet(new Float("" + start++), new Float("" + start++), new Float("" + start++))); obj.setIntegerAttribute( toSet(new Integer("" + start++), new Integer("" + start++), new Integer("" + start++))); obj.setLongObjectAttribute( toSet(new Long("" + start++), new Long("" + start++), new Long("" + start++))); obj.setBooleanAttribute(toSet(true, false)); obj.setDateAttribute(toSet(new Date(startKey++), new Date(startKey++), new Date(startKey++))); Set<Calendar> cals = new HashSet<Calendar>(); for (Date d : obj.getDateAttribute()) { Calendar cal = GregorianCalendar.getInstance(); cal.setTime(d); cals.add(cal); } obj.setCalendarAttribute(toSet(cals)); return obj; } private RangeKeyTestClass getUniqueRangeKeyObject() { RangeKeyTestClass obj = new RangeKeyTestClass(); obj.setKey(startKey++); obj.setIntegerAttribute(toSet(start++, start++, start++)); obj.setBigDecimalAttribute(new BigDecimal(startKey++)); obj.setRangeKey(start++); obj.setStringAttribute("" + startKey++); obj.setStringSetAttribute(toSet("" + startKey++, "" + startKey++, "" + startKey++)); return obj; } private String nextByte() { return "" + byteStart++ % Byte.MAX_VALUE; } }
4,260
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/AttributeValueMatcher.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import java.math.BigDecimal; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; public class AttributeValueMatcher extends BaseMatcher<AttributeValue> { private final AttributeValue expected; private final boolean invert; public static AttributeValueMatcher invert(AttributeValue expected) { return new AttributeValueMatcher(expected, true); } public static AttributeValueMatcher match(AttributeValue expected) { return new AttributeValueMatcher(expected, false); } public AttributeValueMatcher(AttributeValue expected, boolean invert) { this.expected = expected; this.invert = invert; } @Override public boolean matches(Object item) { AttributeValue other = (AttributeValue) item; return invert ^ attrEquals(expected, other); } @Override public void describeTo(Description description) {} public static boolean attrEquals(AttributeValue e, AttributeValue a) { if (!isEqual(e.getB(), a.getB()) || !isNumberEqual(e.getN(), a.getN()) || !isEqual(e.getS(), a.getS()) || !isEqual(e.getBS(), a.getBS()) || !isNumberEqual(e.getNS(), a.getNS()) || !isEqual(e.getSS(), a.getSS())) { return false; } return true; } private static boolean isNumberEqual(String o1, String o2) { if (o1 == null ^ o2 == null) { return false; } if (o1 == o2) return true; BigDecimal d1 = new BigDecimal(o1); BigDecimal d2 = new BigDecimal(o2); return d1.equals(d2); } private static boolean isEqual(Object o1, Object o2) { if (o1 == null ^ o2 == null) { return false; } if (o1 == o2) return true; return o1.equals(o2); } private static boolean isNumberEqual(Collection<String> c1, Collection<String> c2) { if (c1 == null ^ c2 == null) { return false; } if (c1 != null) { Set<BigDecimal> s1 = new HashSet<BigDecimal>(); Set<BigDecimal> s2 = new HashSet<BigDecimal>(); for (String s : c1) { s1.add(new BigDecimal(s)); } for (String s : c2) { s2.add(new BigDecimal(s)); } if (!s1.equals(s2)) { return false; } } return true; } private static <T> boolean isEqual(Collection<T> c1, Collection<T> c2) { if (c1 == null ^ c2 == null) { return false; } if (c1 != null) { Set<T> s1 = new HashSet<T>(c1); Set<T> s2 = new HashSet<T>(c2); if (!s1.equals(s2)) { return false; } } return true; } }
4,261
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/FakeKMS.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.regions.Region; import com.amazonaws.services.kms.AbstractAWSKMS; import com.amazonaws.services.kms.model.CreateKeyRequest; import com.amazonaws.services.kms.model.CreateKeyResult; import com.amazonaws.services.kms.model.DecryptRequest; import com.amazonaws.services.kms.model.DecryptResult; import com.amazonaws.services.kms.model.EncryptRequest; import com.amazonaws.services.kms.model.EncryptResult; import com.amazonaws.services.kms.model.GenerateDataKeyRequest; import com.amazonaws.services.kms.model.GenerateDataKeyResult; import com.amazonaws.services.kms.model.GenerateDataKeyWithoutPlaintextRequest; import com.amazonaws.services.kms.model.GenerateDataKeyWithoutPlaintextResult; import com.amazonaws.services.kms.model.InvalidCiphertextException; import com.amazonaws.services.kms.model.KeyMetadata; import com.amazonaws.services.kms.model.KeyUsageType; import java.nio.ByteBuffer; import java.security.SecureRandom; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class FakeKMS extends AbstractAWSKMS { private static final SecureRandom rnd = new SecureRandom(); private static final String ACCOUNT_ID = "01234567890"; private final Map<DecryptMapKey, DecryptResult> results_ = new HashMap<>(); @Override public CreateKeyResult createKey() throws AmazonServiceException, AmazonClientException { return createKey(new CreateKeyRequest()); } @Override public CreateKeyResult createKey(CreateKeyRequest req) throws AmazonServiceException, AmazonClientException { String keyId = UUID.randomUUID().toString(); String arn = "arn:aws:testing:kms:" + ACCOUNT_ID + ":key/" + keyId; CreateKeyResult result = new CreateKeyResult(); result.setKeyMetadata( new KeyMetadata() .withAWSAccountId(ACCOUNT_ID) .withCreationDate(new Date()) .withDescription(req.getDescription()) .withEnabled(true) .withKeyId(keyId) .withKeyUsage(KeyUsageType.ENCRYPT_DECRYPT) .withArn(arn)); return result; } @Override public DecryptResult decrypt(DecryptRequest req) throws AmazonServiceException, AmazonClientException { DecryptResult result = results_.get(new DecryptMapKey(req)); if (result != null) { return result; } else { throw new InvalidCiphertextException("Invalid Ciphertext"); } } @Override public EncryptResult encrypt(EncryptRequest req) throws AmazonServiceException, AmazonClientException { final byte[] cipherText = new byte[512]; rnd.nextBytes(cipherText); DecryptResult dec = new DecryptResult(); dec.withKeyId(req.getKeyId()).withPlaintext(req.getPlaintext().asReadOnlyBuffer()); ByteBuffer ctBuff = ByteBuffer.wrap(cipherText); results_.put(new DecryptMapKey(ctBuff, req.getEncryptionContext()), dec); return new EncryptResult().withCiphertextBlob(ctBuff).withKeyId(req.getKeyId()); } @Override public GenerateDataKeyResult generateDataKey(GenerateDataKeyRequest req) throws AmazonServiceException, AmazonClientException { byte[] pt; if (req.getKeySpec() != null) { if (req.getKeySpec().contains("256")) { pt = new byte[32]; } else if (req.getKeySpec().contains("128")) { pt = new byte[16]; } else { throw new UnsupportedOperationException(); } } else { pt = new byte[req.getNumberOfBytes()]; } rnd.nextBytes(pt); ByteBuffer ptBuff = ByteBuffer.wrap(pt); EncryptResult encryptResult = encrypt( new EncryptRequest() .withKeyId(req.getKeyId()) .withPlaintext(ptBuff) .withEncryptionContext(req.getEncryptionContext())); return new GenerateDataKeyResult() .withKeyId(req.getKeyId()) .withCiphertextBlob(encryptResult.getCiphertextBlob()) .withPlaintext(ptBuff); } @Override public GenerateDataKeyWithoutPlaintextResult generateDataKeyWithoutPlaintext( GenerateDataKeyWithoutPlaintextRequest req) throws AmazonServiceException, AmazonClientException { GenerateDataKeyResult generateDataKey = generateDataKey( new GenerateDataKeyRequest() .withEncryptionContext(req.getEncryptionContext()) .withNumberOfBytes(req.getNumberOfBytes())); return new GenerateDataKeyWithoutPlaintextResult() .withCiphertextBlob(generateDataKey.getCiphertextBlob()) .withKeyId(req.getKeyId()); } @Override public void setEndpoint(String arg0) throws IllegalArgumentException { // Do nothing } @Override public void setRegion(Region arg0) throws IllegalArgumentException { // Do nothing } @Override public void shutdown() { // Do nothing } public void dump() { System.out.println(results_); } public Map<String, String> getSingleEc() { if (results_.size() != 1) { throw new IllegalStateException("Unexpected number of ciphertexts"); } for (final DecryptMapKey k : results_.keySet()) { return k.ec; } throw new IllegalStateException("Unexpected number of ciphertexts"); } private static class DecryptMapKey { private final ByteBuffer cipherText; private final Map<String, String> ec; public DecryptMapKey(DecryptRequest req) { cipherText = req.getCiphertextBlob().asReadOnlyBuffer(); if (req.getEncryptionContext() != null) { ec = Collections.unmodifiableMap(new HashMap<String, String>(req.getEncryptionContext())); } else { ec = Collections.emptyMap(); } } public DecryptMapKey(ByteBuffer ctBuff, Map<String, String> ec) { cipherText = ctBuff.asReadOnlyBuffer(); if (ec != null) { this.ec = Collections.unmodifiableMap(new HashMap<String, String>(ec)); } else { this.ec = Collections.emptyMap(); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((cipherText == null) ? 0 : cipherText.hashCode()); result = prime * result + ((ec == null) ? 0 : ec.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DecryptMapKey other = (DecryptMapKey) obj; if (cipherText == null) { if (other.cipherText != null) return false; } else if (!cipherText.equals(other.cipherText)) return false; if (ec == null) { if (other.ec != null) return false; } else if (!ec.equals(other.ec)) return false; return true; } @Override public String toString() { return "DecryptMapKey [cipherText=" + cipherText + ", ec=" + ec + "]"; } } }
4,262
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/FakeParameters.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing; import com.amazonaws.services.dynamodbv2.datamodeling.AttributeTransformer; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Collections; import java.util.Map; public class FakeParameters<T> { public static <T> AttributeTransformer.Parameters<T> getInstance( Class<T> clazz, Map<String, AttributeValue> attribs, DynamoDBMapperConfig config, String tableName, String hashKeyName, String rangeKeyName) { return getInstance(clazz, attribs, config, tableName, hashKeyName, rangeKeyName, false); } public static <T> AttributeTransformer.Parameters<T> getInstance( Class<T> clazz, Map<String, AttributeValue> attribs, DynamoDBMapperConfig config, String tableName, String hashKeyName, String rangeKeyName, boolean isPartialUpdate) { // We use this relatively insane proxy setup so that modifications to the Parameters // interface doesn't break our tests (unless it actually impacts our code). FakeParameters<T> fakeParams = new FakeParameters<T>( clazz, attribs, config, tableName, hashKeyName, rangeKeyName, isPartialUpdate); @SuppressWarnings("unchecked") AttributeTransformer.Parameters<T> proxyObject = (AttributeTransformer.Parameters<T>) Proxy.newProxyInstance( AttributeTransformer.class.getClassLoader(), new Class[] {AttributeTransformer.Parameters.class}, new ParametersInvocationHandler<T>(fakeParams)); return proxyObject; } private static class ParametersInvocationHandler<T> implements InvocationHandler { private final FakeParameters<T> params; public ParametersInvocationHandler(FakeParameters<T> params) { this.params = params; } @Override public Object invoke(Object obj, Method method, Object[] args) throws Throwable { if (args != null && args.length > 0) { throw new UnsupportedOperationException(); } Method innerMethod = params.getClass().getMethod(method.getName()); return innerMethod.invoke(params); } } private final Map<String, AttributeValue> attrs; private final Class<T> clazz; private final DynamoDBMapperConfig config; private final String tableName; private final String hashKeyName; private final String rangeKeyName; private final boolean isPartialUpdate; private FakeParameters( Class<T> clazz, Map<String, AttributeValue> attribs, DynamoDBMapperConfig config, String tableName, String hashKeyName, String rangeKeyName, boolean isPartialUpdate) { super(); this.clazz = clazz; this.attrs = Collections.unmodifiableMap(attribs); this.config = config; this.tableName = tableName; this.hashKeyName = hashKeyName; this.rangeKeyName = rangeKeyName; this.isPartialUpdate = isPartialUpdate; } public Map<String, AttributeValue> getAttributeValues() { return attrs; } public Class<T> getModelClass() { return clazz; } public DynamoDBMapperConfig getMapperConfig() { return config; } public String getTableName() { return tableName; } public String getHashKeyName() { return hashKeyName; } public String getRangeKeyName() { return rangeKeyName; } public boolean isPartialUpdate() { return isPartialUpdate; } }
4,263
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/AttributeValueDeserializer.java
package com.amazonaws.services.dynamodbv2.testing; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Iterator; import java.util.Map; import java.util.Set; public class AttributeValueDeserializer extends JsonDeserializer<AttributeValue> { @Override public AttributeValue deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); JsonNode attribute = jp.getCodec().readTree(jp); for (Iterator<Map.Entry<String, JsonNode>> iter = attribute.fields(); iter.hasNext(); ) { Map.Entry<String, JsonNode> rawAttribute = iter.next(); // If there is more than one entry in this map, there is an error with our test data if (iter.hasNext()) { throw new IllegalStateException("Attribute value JSON has more than one value mapped."); } String typeString = rawAttribute.getKey(); JsonNode value = rawAttribute.getValue(); switch (typeString) { case "S": return new AttributeValue().withS(value.asText()); case "B": ByteBuffer b = ByteBuffer.wrap(java.util.Base64.getDecoder().decode(value.asText())); return new AttributeValue().withB(b); case "N": return new AttributeValue().withN(value.asText()); case "SS": final Set<String> stringSet = objectMapper.readValue( objectMapper.treeAsTokens(value), new TypeReference<Set<String>>() {}); return new AttributeValue().withSS(stringSet); case "NS": final Set<String> numSet = objectMapper.readValue( objectMapper.treeAsTokens(value), new TypeReference<Set<String>>() {}); return new AttributeValue().withNS(numSet); default: throw new IllegalStateException( "DDB JSON type " + typeString + " not implemented for test attribute value deserialization."); } } return null; } }
4,264
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/AttributeValueSerializer.java
package com.amazonaws.services.dynamodbv2.testing; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.util.Base64; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import java.io.IOException; import java.nio.ByteBuffer; public class AttributeValueSerializer extends JsonSerializer<AttributeValue> { @Override public void serialize(AttributeValue value, JsonGenerator jgen, SerializerProvider provider) throws IOException { if (value != null) { jgen.writeStartObject(); if (value.getS() != null) { jgen.writeStringField("S", value.getS()); } else if (value.getB() != null) { ByteBuffer valueBytes = value.getB(); byte[] arr = new byte[valueBytes.remaining()]; valueBytes.get(arr); jgen.writeStringField("B", Base64.encodeAsString(arr)); } else if (value.getN() != null) { jgen.writeStringField("N", value.getN()); } else if (value.getSS() != null) { jgen.writeFieldName("SS"); jgen.writeStartArray(); for (String s : value.getSS()) { jgen.writeString(s); } jgen.writeEndArray(); } else if (value.getNS() != null) { jgen.writeFieldName("NS"); jgen.writeStartArray(); for (String num : value.getNS()) { jgen.writeString(num); } jgen.writeEndArray(); } else { throw new IllegalStateException( "AttributeValue has no value or type not implemented for serialization."); } jgen.writeEndObject(); } } }
4,265
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/TestDelegatedKey.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DelegatedKey; import java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.Mac; import javax.crypto.NoSuchPaddingException; import javax.crypto.ShortBufferException; import javax.crypto.spec.IvParameterSpec; public class TestDelegatedKey implements DelegatedKey { private static final long serialVersionUID = 1L; private final Key realKey; public TestDelegatedKey(Key key) { this.realKey = key; } @Override public String getAlgorithm() { return "DELEGATED:" + realKey.getAlgorithm(); } @Override public byte[] getEncoded() { return realKey.getEncoded(); } @Override public String getFormat() { return realKey.getFormat(); } @Override public byte[] encrypt(byte[] plainText, byte[] additionalAssociatedData, String algorithm) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException { Cipher cipher = Cipher.getInstance(extractAlgorithm(algorithm)); cipher.init(Cipher.ENCRYPT_MODE, realKey); byte[] iv = cipher.getIV(); byte[] result = new byte[cipher.getOutputSize(plainText.length) + iv.length + 1]; result[0] = (byte) iv.length; System.arraycopy(iv, 0, result, 1, iv.length); try { cipher.doFinal(plainText, 0, plainText.length, result, iv.length + 1); } catch (ShortBufferException e) { throw new RuntimeException(e); } return result; } @Override public byte[] decrypt(byte[] cipherText, byte[] additionalAssociatedData, String algorithm) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { final byte ivLength = cipherText[0]; IvParameterSpec iv = new IvParameterSpec(cipherText, 1, ivLength); Cipher cipher = Cipher.getInstance(extractAlgorithm(algorithm)); cipher.init(Cipher.DECRYPT_MODE, realKey, iv); return cipher.doFinal(cipherText, ivLength + 1, cipherText.length - ivLength - 1); } @Override public byte[] wrap(Key key, byte[] additionalAssociatedData, String algorithm) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException { Cipher cipher = Cipher.getInstance(extractAlgorithm(algorithm)); cipher.init(Cipher.WRAP_MODE, realKey); return cipher.wrap(key); } @Override public Key unwrap( byte[] wrappedKey, String wrappedKeyAlgorithm, int wrappedKeyType, byte[] additionalAssociatedData, String algorithm) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { Cipher cipher = Cipher.getInstance(extractAlgorithm(algorithm)); cipher.init(Cipher.UNWRAP_MODE, realKey); return cipher.unwrap(wrappedKey, wrappedKeyAlgorithm, wrappedKeyType); } @Override public byte[] sign(byte[] dataToSign, String algorithm) throws NoSuchAlgorithmException, InvalidKeyException { Mac mac = Mac.getInstance(extractAlgorithm(algorithm)); mac.init(realKey); return mac.doFinal(dataToSign); } @Override public boolean verify(byte[] dataToSign, byte[] signature, String algorithm) { try { byte[] expected = sign(dataToSign, extractAlgorithm(algorithm)); return MessageDigest.isEqual(expected, signature); } catch (GeneralSecurityException ex) { return false; } } private String extractAlgorithm(String alg) { if (alg.startsWith(getAlgorithm())) { return alg.substring(10); } else { return alg; } } }
4,266
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/ScenarioManifest.java
package com.amazonaws.services.dynamodbv2.testing; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) public class ScenarioManifest { public static final String MOST_RECENT_PROVIDER_NAME = "most_recent"; public static final String WRAPPED_PROVIDER_NAME = "wrapped"; public static final String STATIC_PROVIDER_NAME = "static"; public static final String AWS_KMS_PROVIDER_NAME = "awskms"; public static final String SYMMETRIC_KEY_TYPE = "symmetric"; public List<Scenario> scenarios; @JsonProperty("keys") public String keyDataPath; @JsonIgnoreProperties(ignoreUnknown = true) public static class Scenario { @JsonProperty("ciphertext") public String ciphertextPath; @JsonProperty("provider") public String providerName; public String version; @JsonProperty("material_name") public String materialName; public Metastore metastore; public Keys keys; } @JsonIgnoreProperties(ignoreUnknown = true) public static class Metastore { @JsonProperty("ciphertext") public String path; @JsonProperty("table_name") public String tableName; @JsonProperty("provider") public String providerName; public Keys keys; } @JsonIgnoreProperties(ignoreUnknown = true) public static class Keys { @JsonProperty("encrypt") public String encryptName; @JsonProperty("sign") public String signName; @JsonProperty("decrypt") public String decryptName; @JsonProperty("verify") public String verifyName; } public static class KeyData { public String material; public String algorithm; public String encoding; @JsonProperty("type") public String keyType; public String keyId; } }
4,267
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/DdbRecordMatcher.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import java.util.Map; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; public class DdbRecordMatcher extends BaseMatcher<Map<String, AttributeValue>> { private final Map<String, AttributeValue> expected; private final boolean invert; public static DdbRecordMatcher invert(Map<String, AttributeValue> expected) { return new DdbRecordMatcher(expected, true); } public static DdbRecordMatcher match(Map<String, AttributeValue> expected) { return new DdbRecordMatcher(expected, false); } public DdbRecordMatcher(Map<String, AttributeValue> expected, boolean invert) { this.expected = expected; this.invert = invert; } @Override public boolean matches(Object item) { @SuppressWarnings("unchecked") Map<String, AttributeValue> actual = (Map<String, AttributeValue>) item; if (!expected.keySet().equals(actual.keySet())) { return invert; } for (String key : expected.keySet()) { AttributeValue e = expected.get(key); AttributeValue a = actual.get(key); if (!AttributeValueMatcher.attrEquals(a, e)) { return invert; } } return !invert; } @Override public void describeTo(Description description) {} }
4,268
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/AttrMatcher.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; public class AttrMatcher extends BaseMatcher<Map<String, AttributeValue>> { private final Map<String, AttributeValue> expected; private final boolean invert; public static AttrMatcher invert(Map<String, AttributeValue> expected) { return new AttrMatcher(expected, true); } public static AttrMatcher match(Map<String, AttributeValue> expected) { return new AttrMatcher(expected, false); } public AttrMatcher(Map<String, AttributeValue> expected, boolean invert) { this.expected = expected; this.invert = invert; } @Override public boolean matches(Object item) { @SuppressWarnings("unchecked") Map<String, AttributeValue> actual = (Map<String, AttributeValue>) item; if (!expected.keySet().equals(actual.keySet())) { return invert; } for (String key : expected.keySet()) { AttributeValue e = expected.get(key); AttributeValue a = actual.get(key); if (!attrEquals(a, e)) { return invert; } } return !invert; } public static boolean attrEquals(AttributeValue e, AttributeValue a) { if (!isEqual(e.getB(), a.getB()) || !isEqual(e.getBOOL(), a.getBOOL()) || !isSetEqual(e.getBS(), a.getBS()) || !isEqual(e.getN(), a.getN()) || !isSetEqual(e.getNS(), a.getNS()) || !isEqual(e.getNULL(), a.getNULL()) || !isEqual(e.getS(), a.getS()) || !isSetEqual(e.getSS(), a.getSS())) { return false; } // Recursive types need special handling if (e.getM() == null ^ a.getM() == null) { return false; } else if (e.getM() != null) { if (!e.getM().keySet().equals(a.getM().keySet())) { return false; } for (final String key : e.getM().keySet()) { if (!attrEquals(e.getM().get(key), a.getM().get(key))) { return false; } } } if (e.getL() == null ^ a.getL() == null) { return false; } else if (e.getL() != null) { if (e.getL().size() != a.getL().size()) { return false; } for (int x = 0; x < e.getL().size(); x++) { if (!attrEquals(e.getL().get(x), a.getL().get(x))) { return false; } } } return true; } @Override public void describeTo(Description description) {} private static boolean isEqual(Object o1, Object o2) { if (o1 == null ^ o2 == null) { return false; } if (o1 == o2) return true; return o1.equals(o2); } private static <T> boolean isSetEqual(Collection<T> c1, Collection<T> c2) { if (c1 == null ^ c2 == null) { return false; } if (c1 != null) { Set<T> s1 = new HashSet<T>(c1); Set<T> s2 = new HashSet<T>(c2); if (!s1.equals(s2)) { return false; } } return true; } }
4,269
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/types/UntouchedWithUnknownAttributeAnnotationWithNewAttribute.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotTouch; @DoNotTouch public class UntouchedWithUnknownAttributeAnnotationWithNewAttribute extends UntouchedWithUnknownAttributeAnnotation { private String newAttribute; public String getNewAttribute() { return newAttribute; } public void setNewAttribute(String newAttribute) { this.newAttribute = newAttribute; } }
4,270
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/types/KeysOnly.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; @DynamoDBTable(tableName = "TableName") public class KeysOnly { private int hashKey; private int rangeKey; public KeysOnly() {} public KeysOnly(int hashKey, int rangeKey) { this.hashKey = hashKey; this.rangeKey = rangeKey; } @DynamoDBRangeKey public int getRangeKey() { return rangeKey; } public void setRangeKey(int rangeKey) { this.rangeKey = rangeKey; } @DynamoDBHashKey public int getHashKey() { return hashKey; } public void setHashKey(int hashKey) { this.hashKey = hashKey; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + hashKey; result = prime * result + rangeKey; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; KeysOnly other = (KeysOnly) obj; if (hashKey != other.hashKey) return false; if (rangeKey != other.rangeKey) return false; return true; } }
4,271
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/types/DoNotTouchField.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotTouch; @DynamoDBTable(tableName = "TableName") public class DoNotTouchField extends Mixed { @DoNotTouch int value; public int getValue() { return value; } public void setValue(int value) { this.value = value; } @Override public int hashCode() { return 31 * super.hashCode() + value; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DoNotTouchField other = (DoNotTouchField) obj; if (value != other.value) return false; return true; } }
4,272
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/types/TableOverride.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.TableAadOverride; @TableAadOverride(tableName = "Override") public class TableOverride extends BaseClass {}
4,273
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/types/SignOnlyWithUnknownAttributeAnnotation.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotEncrypt; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.HandleUnknownAttributes; @DoNotEncrypt @HandleUnknownAttributes public class SignOnlyWithUnknownAttributeAnnotation extends BaseClass {}
4,274
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/types/UntouchedWithNewAttribute.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotTouch; @DoNotTouch public class UntouchedWithNewAttribute extends Untouched { private String newAttribute; public String getNewAttribute() { return newAttribute; } public void setNewAttribute(String newAttribute) { this.newAttribute = newAttribute; } }
4,275
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/types/BaseClass.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBVersionAttribute; import java.util.Arrays; import java.util.Set; @DynamoDBTable(tableName = "TableName") public class BaseClass { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(byteArrayValue); result = prime * result + hashKey; result = prime * result + ((intSet == null) ? 0 : intSet.hashCode()); result = prime * result + intValue; result = prime * result + rangeKey; result = prime * result + ((stringSet == null) ? 0 : stringSet.hashCode()); result = prime * result + ((stringValue == null) ? 0 : stringValue.hashCode()); result = prime * result + Double.valueOf(doubleValue).hashCode(); result = prime * result + ((doubleSet == null) ? 0 : doubleSet.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BaseClass other = (BaseClass) obj; if (!Arrays.equals(byteArrayValue, other.byteArrayValue)) return false; if (hashKey != other.hashKey) return false; if (intSet == null) { if (other.intSet != null) return false; } else if (!intSet.equals(other.intSet)) return false; if (intValue != other.intValue) return false; if (rangeKey != other.rangeKey) return false; if (stringSet == null) { if (other.stringSet != null) return false; } else if (!stringSet.equals(other.stringSet)) return false; if (stringValue == null) { if (other.stringValue != null) return false; } else if (!stringValue.equals(other.stringValue)) return false; if (doubleSet == null) { if (other.doubleSet != null) return false; } else if (!doubleSet.equals(other.doubleSet)) return false; return true; } private int hashKey; private int rangeKey; private String stringValue; private int intValue; private byte[] byteArrayValue; private Set<String> stringSet; private Set<Integer> intSet; private Integer version; private double doubleValue; private Set<Double> doubleSet; @DynamoDBHashKey public int getHashKey() { return hashKey; } public void setHashKey(int hashKey) { this.hashKey = hashKey; } @DynamoDBRangeKey public int getRangeKey() { return rangeKey; } public void setRangeKey(int rangeKey) { this.rangeKey = rangeKey; } public String getStringValue() { return stringValue; } public void setStringValue(String stringValue) { this.stringValue = stringValue; } public int getIntValue() { return intValue; } public void setIntValue(int intValue) { this.intValue = intValue; } public byte[] getByteArrayValue() { return byteArrayValue; } public void setByteArrayValue(byte[] byteArrayValue) { this.byteArrayValue = byteArrayValue; } public Set<String> getStringSet() { return stringSet; } public void setStringSet(Set<String> stringSet) { this.stringSet = stringSet; } public Set<Integer> getIntSet() { return intSet; } public void setIntSet(Set<Integer> intSet) { this.intSet = intSet; } public Set<Double> getDoubleSet() { return doubleSet; } public void setDoubleSet(Set<Double> doubleSet) { this.doubleSet = doubleSet; } public double getDoubleValue() { return doubleValue; } public void setDoubleValue(double doubleValue) { this.doubleValue = doubleValue; } @DynamoDBVersionAttribute public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } @Override public String toString() { return "BaseClass [hashKey=" + hashKey + ", rangeKey=" + rangeKey + ", stringValue=" + stringValue + ", intValue=" + intValue + ", byteArrayValue=" + Arrays.toString(byteArrayValue) + ", stringSet=" + stringSet + ", intSet=" + intSet + ", doubleSet=" + doubleSet + ", version=" + version + "]"; } }
4,276
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/types/BaseClassWithNewAttribute.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; public class BaseClassWithNewAttribute extends BaseClassWithUnknownAttributeAnnotation { private String newAttribute; public String getNewAttribute() { return newAttribute; } public void setNewAttribute(String newAttribute) { this.newAttribute = newAttribute; } }
4,277
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/types/HashKeyOnly.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; @DynamoDBTable(tableName = "HashKeyOnly") public class HashKeyOnly { private String hashKey; public HashKeyOnly() {} public HashKeyOnly(String hashKey) { this.hashKey = hashKey; } @DynamoDBHashKey public String getHashKey() { return hashKey; } public void setHashKey(String hashKey) { this.hashKey = hashKey; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((hashKey == null) ? 0 : hashKey.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; HashKeyOnly other = (HashKeyOnly) obj; if (hashKey == null) { if (other.hashKey != null) return false; } else if (!hashKey.equals(other.hashKey)) return false; return true; } }
4,278
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/types/Mixed.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotEncrypt; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotTouch; import java.util.Set; public class Mixed extends BaseClass { @Override @DoNotEncrypt public String getStringValue() { return super.getStringValue(); } @Override @DoNotEncrypt public double getDoubleValue() { return super.getDoubleValue(); } @Override @DoNotEncrypt public Set<Double> getDoubleSet() { return super.getDoubleSet(); } @Override @DoNotTouch public int getIntValue() { return super.getIntValue(); } }
4,279
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/types/SignOnly.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotEncrypt; @DoNotEncrypt public class SignOnly extends BaseClass {}
4,280
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/types/SignOnlyWithUnknownAttributeAnnotationWithNewAttribute.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotEncrypt; @DoNotEncrypt public class SignOnlyWithUnknownAttributeAnnotationWithNewAttribute extends SignOnlyWithUnknownAttributeAnnotation { private String newAttribute; public String getNewAttribute() { return newAttribute; } public void setNewAttribute(String newAttribute) { this.newAttribute = newAttribute; } }
4,281
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/types/BaseClassWithUnknownAttributeAnnotation.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.HandleUnknownAttributes; @HandleUnknownAttributes public class BaseClassWithUnknownAttributeAnnotation extends BaseClass {}
4,282
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/types/DoNotEncryptField.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotEncrypt; @DynamoDBTable(tableName = "TableName") public class DoNotEncryptField extends Mixed { @DoNotEncrypt int value; public int getValue() { return value; } public void setValue(int value) { this.value = value; } @Override public int hashCode() { return 31 * super.hashCode() + value; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DoNotEncryptField other = (DoNotEncryptField) obj; if (value != other.value) return false; return true; } }
4,283
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/types/Untouched.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotTouch; @DoNotTouch public class Untouched extends BaseClass {}
4,284
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/testing/types/UntouchedWithUnknownAttributeAnnotation.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotTouch; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.HandleUnknownAttributes; @DoNotTouch @HandleUnknownAttributes public class UntouchedWithUnknownAttributeAnnotation extends BaseClass {}
4,285
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/TransformerHolisticIT.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.services.dynamodbv2.datamodeling; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.SaveBehavior; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.AsymmetricStaticProvider; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.CachingMostRecentProvider; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.DirectKmsMaterialProvider; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.EncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.SymmetricStaticProvider; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.WrappedMaterialsProvider; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.store.MetaStore; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.store.ProviderStore; import com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded; import com.amazonaws.services.dynamodbv2.model.AttributeAction; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.AttributeValueUpdate; import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; import com.amazonaws.services.dynamodbv2.model.CreateTableRequest; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType; import com.amazonaws.services.dynamodbv2.model.ScanRequest; import com.amazonaws.services.dynamodbv2.model.ScanResult; import com.amazonaws.services.dynamodbv2.model.UpdateItemRequest; import com.amazonaws.services.dynamodbv2.testing.AttributeValueDeserializer; import com.amazonaws.services.dynamodbv2.testing.AttributeValueSerializer; import com.amazonaws.services.dynamodbv2.testing.ScenarioManifest; import com.amazonaws.services.dynamodbv2.testing.ScenarioManifest.KeyData; import com.amazonaws.services.dynamodbv2.testing.ScenarioManifest.Keys; import com.amazonaws.services.dynamodbv2.testing.ScenarioManifest.Scenario; import com.amazonaws.services.dynamodbv2.testing.types.BaseClass; import com.amazonaws.services.dynamodbv2.testing.types.HashKeyOnly; import com.amazonaws.services.dynamodbv2.testing.types.KeysOnly; import com.amazonaws.services.dynamodbv2.testing.types.Mixed; import com.amazonaws.services.dynamodbv2.testing.types.SignOnly; import com.amazonaws.services.dynamodbv2.testing.types.Untouched; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.AWSKMSClientBuilder; import com.amazonaws.util.Base64; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.module.SimpleModule; import java.io.File; import java.io.IOException; import java.net.URL; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.junit.Before; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class TransformerHolisticIT { private static final SecretKey aesKey = new SecretKeySpec(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, "AES"); private static final SecretKey hmacKey = new SecretKeySpec(new byte[] {0, 1, 2, 3, 4, 5, 6, 7}, "HmacSHA256"); private static final String rsaEncPub = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtiNSLSvT9cExXOcD0dGZ" + "9DFEMHw8895gAZcCdSppDrxbD7XgZiQYTlgt058i5fS+l11guAUJtKt5sZ2u8Fx0" + "K9pxMdlczGtvQJdx/LQETEnLnfzAijvHisJ8h6dQOVczM7t01KIkS24QZElyO+kY" + "qMWLytUV4RSHnrnIuUtPHCe6LieDWT2+1UBguxgtFt1xdXlquACLVv/Em3wp40Xc" + "bIwzhqLitb98rTY/wqSiGTz1uvvBX46n+f2j3geZKCEDGkWcXYw3dH4lRtDWTbqw" + "eRcaNDT/MJswQlBk/Up9KCyN7gjX67gttiCO6jMoTNDejGeJhG4Dd2o0vmn8WJlr" + "5wIDAQAB"; private static final String rsaEncPriv = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC2I1ItK9P1wTFc" + "5wPR0Zn0MUQwfDzz3mABlwJ1KmkOvFsPteBmJBhOWC3TnyLl9L6XXWC4BQm0q3mx" + "na7wXHQr2nEx2VzMa29Al3H8tARMScud/MCKO8eKwnyHp1A5VzMzu3TUoiRLbhBk" + "SXI76RioxYvK1RXhFIeeuci5S08cJ7ouJ4NZPb7VQGC7GC0W3XF1eWq4AItW/8Sb" + "fCnjRdxsjDOGouK1v3ytNj/CpKIZPPW6+8Ffjqf5/aPeB5koIQMaRZxdjDd0fiVG" + "0NZNurB5Fxo0NP8wmzBCUGT9Sn0oLI3uCNfruC22II7qMyhM0N6MZ4mEbgN3ajS+" + "afxYmWvnAgMBAAECggEBAIIU293zDWDZZ73oJ+w0fHXQsdjHAmlRitPX3CN99KZX" + "k9m2ldudL9bUV3Zqk2wUzgIg6LDEuFfWmAVojsaP4VBopKtriEFfAYfqIbjPgLpT" + "gh8FoyWW6D6MBJCFyGALjUAHQ7uRScathvt5ESMEqV3wKJTmdsfX97w/B8J+rLN3" + "3fT3ZJUck5duZ8XKD+UtX1Y3UE1hTWo3Ae2MFND964XyUqy+HaYXjH0x6dhZzqyJ" + "/OJ/MPGeMJgxp+nUbMWerwxrLQceNFVgnQgHj8e8k4fd04rkowkkPua912gNtmz7" + "DuIEvcMnY64z585cn+cnXUPJwtu3JbAmn/AyLsV9FLECgYEA798Ut/r+vORB16JD" + "KFu38pQCgIbdCPkXeI0DC6u1cW8JFhgRqi+AqSrEy5SzY3IY7NVMSRsBI9Y026Bl" + "R9OQwTrOzLRAw26NPSDvbTkeYXlY9+hX7IovHjGkho/OxyTJ7bKRDYLoNCz56BC1" + "khIWvECpcf/fZU0nqOFVFqF3H/UCgYEAwmJ4rjl5fksTNtNRL6ivkqkHIPKXzk5w" + "C+L90HKNicic9bqyX8K4JRkGKSNYN3mkjrguAzUlEld390qNBw5Lu7PwATv0e2i+" + "6hdwJsjTKNpj7Nh4Mieq6d7lWe1L8FLyHEhxgIeQ4BgqrVtPPOH8IBGpuzVZdWwI" + "dgOvEvAi/usCgYBdfk3NB/+SEEW5jn0uldE0s4vmHKq6fJwxWIT/X4XxGJ4qBmec" + "NbeoOAtMbkEdWbNtXBXHyMbA+RTRJctUG5ooNou0Le2wPr6+PMAVilXVGD8dIWpj" + "v9htpFvENvkZlbU++IKhCY0ICR++3ARpUrOZ3Hou/NRN36y9nlZT48tSoQKBgES2" + "Bi6fxmBsLUiN/f64xAc1lH2DA0I728N343xRYdK4hTMfYXoUHH+QjurvwXkqmI6S" + "cEFWAdqv7IoPYjaCSSb6ffYRuWP+LK4WxuAO0QV53SSViDdCalntHmlhRhyXVVnG" + "CckDIqT0JfHNev7savDzDWpNe2fUXlFJEBPDqrstAoGBAOpd5+QBHF/tP5oPILH4" + "aD/zmqMH7VtB+b/fOPwtIM+B/WnU7hHLO5t2lJYu18Be3amPkfoQIB7bpkM3Cer2" + "G7Jw+TcHrY+EtIziDB5vwau1fl4VcbA9SfWpBojJ5Ifo9ELVxGiK95WxeQNSmLUy" + "7AJzhK1Gwey8a/v+xfqiu9sE"; private static final PrivateKey rsaPriv; private static final PublicKey rsaPub; private static final KeyPair rsaPair; private static final EncryptionMaterialsProvider symProv; private static final EncryptionMaterialsProvider asymProv; private static final EncryptionMaterialsProvider symWrappedProv; private static final String HASH_KEY = "hashKey"; private static final String RANGE_KEY = "rangeKey"; private static final String RSA = "RSA"; private AmazonDynamoDB client; private static AWSKMS kmsClient = AWSKMSClientBuilder.standard().build(); private static Map<String, KeyData> keyDataMap = new HashMap<>(); // AttributeEncryptor *must* be used with SaveBehavior.CLOBBER to avoid the risk of data // corruption. private static final DynamoDBMapperConfig CLOBBER_CONFIG = DynamoDBMapperConfig.builder().withSaveBehavior(SaveBehavior.CLOBBER).build(); private static final BaseClass ENCRYPTED_TEST_VALUE = new BaseClass(); private static final Mixed MIXED_TEST_VALUE = new Mixed(); private static final SignOnly SIGNED_TEST_VALUE = new SignOnly(); private static final Untouched UNTOUCHED_TEST_VALUE = new Untouched(); private static final BaseClass ENCRYPTED_TEST_VALUE_2 = new BaseClass(); private static final Mixed MIXED_TEST_VALUE_2 = new Mixed(); private static final SignOnly SIGNED_TEST_VALUE_2 = new SignOnly(); private static final Untouched UNTOUCHED_TEST_VALUE_2 = new Untouched(); private static final String TEST_VECTOR_MANIFEST_DIR = "/vectors/encrypted_item/"; private static final String SCENARIO_MANIFEST_PATH = TEST_VECTOR_MANIFEST_DIR + "scenarios.json"; private static final String JAVA_DIR = "java"; static { try { KeyFactory rsaFact = KeyFactory.getInstance("RSA"); rsaPub = rsaFact.generatePublic(new X509EncodedKeySpec(Base64.decode(rsaEncPub))); rsaPriv = rsaFact.generatePrivate(new PKCS8EncodedKeySpec(Base64.decode(rsaEncPriv))); rsaPair = new KeyPair(rsaPub, rsaPriv); } catch (GeneralSecurityException ex) { throw new RuntimeException(ex); } symProv = new SymmetricStaticProvider(aesKey, hmacKey); asymProv = new AsymmetricStaticProvider(rsaPair, rsaPair); symWrappedProv = new WrappedMaterialsProvider(aesKey, aesKey, hmacKey); ENCRYPTED_TEST_VALUE.setHashKey(5); ENCRYPTED_TEST_VALUE.setRangeKey(7); ENCRYPTED_TEST_VALUE.setVersion(0); ENCRYPTED_TEST_VALUE.setIntValue(123); ENCRYPTED_TEST_VALUE.setStringValue("Hello world!"); ENCRYPTED_TEST_VALUE.setByteArrayValue(new byte[] {0, 1, 2, 3, 4, 5}); ENCRYPTED_TEST_VALUE.setStringSet( new HashSet<String>(Arrays.asList("Goodbye", "Cruel", "World", "?"))); ENCRYPTED_TEST_VALUE.setIntSet(new HashSet<Integer>(Arrays.asList(1, 200, 10, 15, 0))); MIXED_TEST_VALUE.setHashKey(6); MIXED_TEST_VALUE.setRangeKey(8); MIXED_TEST_VALUE.setVersion(0); MIXED_TEST_VALUE.setIntValue(123); MIXED_TEST_VALUE.setStringValue("Hello world!"); MIXED_TEST_VALUE.setByteArrayValue(new byte[] {0, 1, 2, 3, 4, 5}); MIXED_TEST_VALUE.setStringSet( new HashSet<String>(Arrays.asList("Goodbye", "Cruel", "World", "?"))); MIXED_TEST_VALUE.setIntSet(new HashSet<Integer>(Arrays.asList(1, 200, 10, 15, 0))); SIGNED_TEST_VALUE.setHashKey(8); SIGNED_TEST_VALUE.setRangeKey(10); SIGNED_TEST_VALUE.setVersion(0); SIGNED_TEST_VALUE.setIntValue(123); SIGNED_TEST_VALUE.setStringValue("Hello world!"); SIGNED_TEST_VALUE.setByteArrayValue(new byte[] {0, 1, 2, 3, 4, 5}); SIGNED_TEST_VALUE.setStringSet( new HashSet<String>(Arrays.asList("Goodbye", "Cruel", "World", "?"))); SIGNED_TEST_VALUE.setIntSet(new HashSet<Integer>(Arrays.asList(1, 200, 10, 15, 0))); UNTOUCHED_TEST_VALUE.setHashKey(7); UNTOUCHED_TEST_VALUE.setRangeKey(9); UNTOUCHED_TEST_VALUE.setVersion(0); UNTOUCHED_TEST_VALUE.setIntValue(123); UNTOUCHED_TEST_VALUE.setStringValue("Hello world!"); UNTOUCHED_TEST_VALUE.setByteArrayValue(new byte[] {0, 1, 2, 3, 4, 5}); UNTOUCHED_TEST_VALUE.setStringSet( new HashSet<String>(Arrays.asList("Goodbye", "Cruel", "World", "?"))); UNTOUCHED_TEST_VALUE.setIntSet(new HashSet<Integer>(Arrays.asList(1, 200, 10, 15, 0))); // Now storing doubles ENCRYPTED_TEST_VALUE_2.setHashKey(5); ENCRYPTED_TEST_VALUE_2.setRangeKey(7); ENCRYPTED_TEST_VALUE_2.setVersion(0); ENCRYPTED_TEST_VALUE_2.setIntValue(123); ENCRYPTED_TEST_VALUE_2.setStringValue("Hello world!"); ENCRYPTED_TEST_VALUE_2.setByteArrayValue(new byte[] {0, 1, 2, 3, 4, 5}); ENCRYPTED_TEST_VALUE_2.setStringSet( new HashSet<String>(Arrays.asList("Goodbye", "Cruel", "World", "?"))); ENCRYPTED_TEST_VALUE_2.setIntSet(new HashSet<Integer>(Arrays.asList(1, 200, 10, 15, 0))); ENCRYPTED_TEST_VALUE_2.setDoubleValue(15); ENCRYPTED_TEST_VALUE_2.setDoubleSet( new HashSet<Double>(Arrays.asList(15.0D, 7.6D, -3D, -34.2D, 0.0D))); MIXED_TEST_VALUE_2.setHashKey(6); MIXED_TEST_VALUE_2.setRangeKey(8); MIXED_TEST_VALUE_2.setVersion(0); MIXED_TEST_VALUE_2.setIntValue(123); MIXED_TEST_VALUE_2.setStringValue("Hello world!"); MIXED_TEST_VALUE_2.setByteArrayValue(new byte[] {0, 1, 2, 3, 4, 5}); MIXED_TEST_VALUE_2.setStringSet( new HashSet<String>(Arrays.asList("Goodbye", "Cruel", "World", "?"))); MIXED_TEST_VALUE_2.setIntSet(new HashSet<Integer>(Arrays.asList(1, 200, 10, 15, 0))); MIXED_TEST_VALUE_2.setDoubleValue(15); MIXED_TEST_VALUE_2.setDoubleSet( new HashSet<Double>(Arrays.asList(15.0D, 7.6D, -3D, -34.2D, 0.0D))); SIGNED_TEST_VALUE_2.setHashKey(8); SIGNED_TEST_VALUE_2.setRangeKey(10); SIGNED_TEST_VALUE_2.setVersion(0); SIGNED_TEST_VALUE_2.setIntValue(123); SIGNED_TEST_VALUE_2.setStringValue("Hello world!"); SIGNED_TEST_VALUE_2.setByteArrayValue(new byte[] {0, 1, 2, 3, 4, 5}); SIGNED_TEST_VALUE_2.setStringSet( new HashSet<String>(Arrays.asList("Goodbye", "Cruel", "World", "?"))); SIGNED_TEST_VALUE_2.setIntSet(new HashSet<Integer>(Arrays.asList(1, 200, 10, 15, 0))); SIGNED_TEST_VALUE_2.setDoubleValue(15); SIGNED_TEST_VALUE_2.setDoubleSet( new HashSet<Double>(Arrays.asList(15.0D, 7.6D, -3D, -34.2D, 0.0D))); UNTOUCHED_TEST_VALUE_2.setHashKey(7); UNTOUCHED_TEST_VALUE_2.setRangeKey(9); UNTOUCHED_TEST_VALUE_2.setVersion(0); UNTOUCHED_TEST_VALUE_2.setIntValue(123); UNTOUCHED_TEST_VALUE_2.setStringValue("Hello world!"); UNTOUCHED_TEST_VALUE_2.setByteArrayValue(new byte[] {0, 1, 2, 3, 4, 5}); UNTOUCHED_TEST_VALUE_2.setStringSet( new HashSet<String>(Arrays.asList("Goodbye", "Cruel", "World", "?"))); UNTOUCHED_TEST_VALUE_2.setIntSet(new HashSet<Integer>(Arrays.asList(1, 200, 10, 15, 0))); UNTOUCHED_TEST_VALUE_2.setDoubleValue(15); UNTOUCHED_TEST_VALUE_2.setDoubleSet( new HashSet<Double>(Arrays.asList(15.0D, 7.6D, -3D, -34.2D, 0.0D))); } @DataProvider(name = "getEncryptTestVectors") public static Object[][] getEncryptTestVectors() throws IOException { ScenarioManifest scenarioManifest = getManifestFromFile(SCENARIO_MANIFEST_PATH, new TypeReference<ScenarioManifest>() {}); loadKeyData(scenarioManifest.keyDataPath); // Only use Java generated test vectors to dedupe the scenarios for encrypt, // we only care that we are able to generate data using the different provider configurations List<Object[]> dedupedScenarios = scenarioManifest.scenarios.stream() .filter(s -> s.ciphertextPath.contains(JAVA_DIR)) .map(s -> new Object[] {s}) .collect(Collectors.toList()); return dedupedScenarios.toArray(new Object[dedupedScenarios.size()][]); } @DataProvider(name = "getDecryptTestVectors") public static Object[][] getDecryptTestVectors() throws IOException { ScenarioManifest scenarioManifest = getManifestFromFile(SCENARIO_MANIFEST_PATH, new TypeReference<ScenarioManifest>() {}); loadKeyData(scenarioManifest.keyDataPath); List<Object[]> scenarios = scenarioManifest.scenarios.stream().map(s -> new Object[] {s}).collect(Collectors.toList()); return scenarios.toArray(new Object[scenarios.size()][]); } // Set up for non-parameterized tests @Before public void setUp() { System.setProperty("sqlite4java.library.path", "target/test-lib"); client = DynamoDBEmbedded.create(); // load data into ciphertext tables createCiphertextTables(client); } @Test(dataProvider = "getDecryptTestVectors") public void decryptTestVector(Scenario scenario) throws IOException { System.setProperty("sqlite4java.library.path", "target/test-lib"); client = DynamoDBEmbedded.create(); // load data into ciphertext tables createCiphertextTables(client); // load data from vector file putDataFromFile(client, scenario.ciphertextPath); // create and load metastore table if necessary ProviderStore metastore = null; if (scenario.metastore != null) { MetaStore.createTable( client, scenario.metastore.tableName, new ProvisionedThroughput(100L, 100L)); putDataFromFile(client, scenario.metastore.path); EncryptionMaterialsProvider metaProvider = createProvider( scenario.metastore.providerName, scenario.materialName, scenario.metastore.keys, null); metastore = new MetaStore( client, scenario.metastore.tableName, DynamoDBEncryptor.getInstance(metaProvider)); } // Create the mapper with the provider under test EncryptionMaterialsProvider provider = createProvider(scenario.providerName, scenario.materialName, scenario.keys, metastore); DynamoDBMapper mapper = new DynamoDBMapper( client, new DynamoDBMapperConfig(SaveBehavior.CLOBBER), new AttributeEncryptor(provider)); // Verify successful decryption switch (scenario.version) { case "v0": assertVersionCompatibility(mapper); break; case "v1": assertVersionCompatibility_2(mapper); break; default: throw new IllegalStateException( "Version " + scenario.version + " not yet implemented in test vector runner"); } } @Test(dataProvider = "getEncryptTestVectors") public void encryptWithTestVector(Scenario scenario) throws IOException { System.setProperty("sqlite4java.library.path", "target/test-lib"); client = DynamoDBEmbedded.create(); // load data into ciphertext tables createCiphertextTables(client); // create and load metastore table if necessary ProviderStore metastore = null; if (scenario.metastore != null) { MetaStore.createTable( client, scenario.metastore.tableName, new ProvisionedThroughput(100L, 100L)); putDataFromFile(client, scenario.metastore.path); EncryptionMaterialsProvider metaProvider = createProvider( scenario.metastore.providerName, scenario.materialName, scenario.metastore.keys, null); metastore = new MetaStore( client, scenario.metastore.tableName, DynamoDBEncryptor.getInstance(metaProvider)); } // Encrypt data with the provider under test, only ensure that no exception is thrown EncryptionMaterialsProvider provider = createProvider(scenario.providerName, scenario.materialName, scenario.keys, metastore); generateStandardData(provider); } @Test public void simpleSaveLoad() { DynamoDBMapper mapper = new DynamoDBMapper(client, CLOBBER_CONFIG, new AttributeEncryptor(symProv)); Mixed obj = new Mixed(); obj.setHashKey(0); obj.setRangeKey(15); obj.setIntSet(new HashSet<Integer>()); obj.getIntSet().add(3); obj.getIntSet().add(5); obj.getIntSet().add(7); obj.setDoubleValue(15); obj.setStringValue("Blargh!"); obj.setDoubleSet(new HashSet<Double>(Arrays.asList(15.0D, 7.6D, -3D, -34.2D, 0.0D))); mapper.save(obj); Mixed result = mapper.load(Mixed.class, 0, 15); assertEquals(obj, result); result.setStringValue("Foo"); mapper.save(result); Mixed result2 = mapper.load(Mixed.class, 0, 15); assertEquals(result, result2); mapper.delete(result); assertNull(mapper.load(Mixed.class, 0, 15)); } /** * This test ensures that optimistic locking can be successfully done through the {@link * DynamoDBMapper} when combined with the {@link AttributeEncryptor}. Specifically it checks that * {@link SaveBehavior#PUT} properly enforces versioning and will result in a {@link * ConditionalCheckFailedException} when optimistic locking should prevent a write. Finally, it * checks that {@link SaveBehavior#CLOBBER} properly ignores optimistic locking and overwrites the * old value. */ @Test public void optimisticLockingTest() { DynamoDBMapper mapper = new DynamoDBMapper( client, DynamoDBMapperConfig.builder().withSaveBehavior(SaveBehavior.PUT).build(), new AttributeEncryptor(symProv)); DynamoDBMapper clobberMapper = new DynamoDBMapper(client, CLOBBER_CONFIG, new AttributeEncryptor(symProv)); /* * Lineage of objects * expected -> v1 -> v2 -> v3 * | * -> v2_2 -> clobbered * Splitting the lineage after v1 is what should * cause the ConditionalCheckFailedException. */ final int hashKey = 0; final int rangeKey = 15; final Mixed expected = new Mixed(); expected.setHashKey(hashKey); expected.setRangeKey(rangeKey); expected.setIntSet(new HashSet<Integer>()); expected.getIntSet().add(3); expected.getIntSet().add(5); expected.getIntSet().add(7); expected.setDoubleValue(15); expected.setStringValue("Blargh!"); expected.setDoubleSet(new HashSet<Double>(Arrays.asList(15.0D, 7.6D, -3D, -34.2D, 0.0D))); mapper.save(expected); Mixed v1 = mapper.load(Mixed.class, hashKey, rangeKey); assertEquals(expected, v1); v1.setStringValue("New value"); mapper.save(v1); Mixed v2 = mapper.load(Mixed.class, hashKey, rangeKey); assertEquals(v1, v2); Mixed v2_2 = mapper.load(Mixed.class, hashKey, rangeKey); v2.getIntSet().add(-37); mapper.save(v2); Mixed v3 = mapper.load(Mixed.class, hashKey, rangeKey); assertEquals(v2, v3); assertTrue(v3.getIntSet().contains(-37)); // This should fail due to optimistic locking v2_2.getIntSet().add(38); try { mapper.save(v2_2); fail("Expected ConditionalCheckFailedException"); } catch (ConditionalCheckFailedException ex) { // Expected exception } // Force the update with clobber clobberMapper.save(v2_2); Mixed clobbered = mapper.load(Mixed.class, hashKey, rangeKey); assertEquals(v2_2, clobbered); assertTrue(clobbered.getIntSet().contains(38)); assertFalse(clobbered.getIntSet().contains(-37)); } @Test public void leadingAndTrailingZeros() { DynamoDBMapper mapper = new DynamoDBMapper(client, CLOBBER_CONFIG, new AttributeEncryptor(symProv)); Mixed obj = new Mixed(); obj.setHashKey(0); obj.setRangeKey(15); obj.setIntSet(new HashSet<Integer>()); obj.getIntSet().add(3); obj.getIntSet().add(5); obj.getIntSet().add(7); obj.setStringValue("Blargh!"); obj.setDoubleValue(15); obj.setDoubleSet(new HashSet<Double>(Arrays.asList(15.0D, 7.6D, -3D, -34.2D, 0.0D))); mapper.save(obj); // TODO: Update the mock to handle this appropriately. // DynamoDb discards leading and trailing zeros from numbers Map<String, AttributeValue> key = new HashMap<String, AttributeValue>(); key.put(HASH_KEY, new AttributeValue().withN("0")); key.put(RANGE_KEY, new AttributeValue().withN("15")); Map<String, AttributeValueUpdate> attributeUpdates = new HashMap<String, AttributeValueUpdate>(); attributeUpdates.put( "doubleValue", new AttributeValueUpdate(new AttributeValue().withN("15"), AttributeAction.PUT)); UpdateItemRequest update = new UpdateItemRequest("TableName", key, attributeUpdates); client.updateItem(update); Mixed result = mapper.load(Mixed.class, 0, 15); assertEquals(obj, result); result.setStringValue("Foo"); mapper.save(result); Mixed result2 = mapper.load(Mixed.class, 0, 15); assertEquals(result, result2); mapper.delete(result); assertNull(mapper.load(Mixed.class, 0, 15)); } @Test public void simpleSaveLoadAsym() { DynamoDBMapper mapper = new DynamoDBMapper(client, CLOBBER_CONFIG, new AttributeEncryptor(asymProv)); BaseClass obj = new BaseClass(); obj.setHashKey(0); obj.setRangeKey(15); obj.setIntSet(new HashSet<Integer>()); obj.getIntSet().add(3); obj.getIntSet().add(5); obj.getIntSet().add(7); obj.setDoubleValue(15); obj.setStringValue("Blargh!"); obj.setDoubleSet(new HashSet<Double>(Arrays.asList(15.0D, 7.6D, -3D, -34.2D, 0.0D))); mapper.save(obj); BaseClass result = mapper.load(BaseClass.class, 0, 15); assertEquals(obj, result); result.setStringValue("Foo"); mapper.save(result); BaseClass result2 = mapper.load(BaseClass.class, 0, 15); assertEquals(result, result2); mapper.delete(result); assertNull(mapper.load(BaseClass.class, 0, 15)); } @Test public void simpleSaveLoadHashOnly() { DynamoDBMapper mapper = new DynamoDBMapper(client, CLOBBER_CONFIG, new AttributeEncryptor(symProv)); HashKeyOnly obj = new HashKeyOnly(""); obj.setHashKey("Foo"); mapper.save(obj); HashKeyOnly result = mapper.load(HashKeyOnly.class, "Foo"); assertEquals(obj, result); mapper.delete(obj); assertNull(mapper.load(BaseClass.class, 0, 15)); } @Test public void simpleSaveLoadKeysOnly() { DynamoDBMapper mapper = new DynamoDBMapper(client, CLOBBER_CONFIG, new AttributeEncryptor(asymProv)); KeysOnly obj = new KeysOnly(); obj.setHashKey(0); obj.setRangeKey(15); mapper.save(obj); KeysOnly result = mapper.load(KeysOnly.class, 0, 15); assertEquals(obj, result); mapper.delete(obj); assertNull(mapper.load(BaseClass.class, 0, 15)); } public void generateStandardData(EncryptionMaterialsProvider prov) { DynamoDBMapper mapper = new DynamoDBMapper( client, new DynamoDBMapperConfig(SaveBehavior.CLOBBER), new AttributeEncryptor(prov)); mapper.save(new HashKeyOnly("Foo")); mapper.save(new HashKeyOnly("Bar")); mapper.save(new HashKeyOnly("Baz")); mapper.save(new KeysOnly(0, 1)); mapper.save(new KeysOnly(0, 2)); mapper.save(new KeysOnly(0, 3)); mapper.save(new KeysOnly(1, 1)); mapper.save(new KeysOnly(1, 2)); mapper.save(new KeysOnly(1, 3)); mapper.save(new KeysOnly(5, 1)); mapper.save(new KeysOnly(6, 2)); mapper.save(new KeysOnly(7, 3)); mapper.save(ENCRYPTED_TEST_VALUE_2); mapper.save(MIXED_TEST_VALUE_2); mapper.save(SIGNED_TEST_VALUE_2); mapper.save(UNTOUCHED_TEST_VALUE_2); // Uncomment the function below to print the generated data // in our test vector format. // printTablesAsTestVectors(); } private void assertVersionCompatibility(DynamoDBMapper mapper) { assertEquals( UNTOUCHED_TEST_VALUE, mapper.load( UNTOUCHED_TEST_VALUE.getClass(), UNTOUCHED_TEST_VALUE.getHashKey(), UNTOUCHED_TEST_VALUE.getRangeKey())); assertEquals( SIGNED_TEST_VALUE, mapper.load( SIGNED_TEST_VALUE.getClass(), SIGNED_TEST_VALUE.getHashKey(), SIGNED_TEST_VALUE.getRangeKey())); assertEquals( MIXED_TEST_VALUE, mapper.load( MIXED_TEST_VALUE.getClass(), MIXED_TEST_VALUE.getHashKey(), MIXED_TEST_VALUE.getRangeKey())); assertEquals( ENCRYPTED_TEST_VALUE, mapper.load( ENCRYPTED_TEST_VALUE.getClass(), ENCRYPTED_TEST_VALUE.getHashKey(), ENCRYPTED_TEST_VALUE.getRangeKey())); assertEquals("Foo", mapper.load(HashKeyOnly.class, "Foo").getHashKey()); assertEquals("Bar", mapper.load(HashKeyOnly.class, "Bar").getHashKey()); assertEquals("Baz", mapper.load(HashKeyOnly.class, "Baz").getHashKey()); for (int x = 1; x <= 3; ++x) { KeysOnly obj = mapper.load(KeysOnly.class, 0, x); assertEquals(0, obj.getHashKey()); assertEquals(x, obj.getRangeKey()); obj = mapper.load(KeysOnly.class, 1, x); assertEquals(1, obj.getHashKey()); assertEquals(x, obj.getRangeKey()); obj = mapper.load(KeysOnly.class, 4 + x, x); assertEquals(4 + x, obj.getHashKey()); assertEquals(x, obj.getRangeKey()); } } private void assertVersionCompatibility_2(DynamoDBMapper mapper) { assertEquals( UNTOUCHED_TEST_VALUE_2, mapper.load( UNTOUCHED_TEST_VALUE_2.getClass(), UNTOUCHED_TEST_VALUE_2.getHashKey(), UNTOUCHED_TEST_VALUE_2.getRangeKey())); assertEquals( SIGNED_TEST_VALUE_2, mapper.load( SIGNED_TEST_VALUE_2.getClass(), SIGNED_TEST_VALUE_2.getHashKey(), SIGNED_TEST_VALUE_2.getRangeKey())); assertEquals( MIXED_TEST_VALUE_2, mapper.load( MIXED_TEST_VALUE_2.getClass(), MIXED_TEST_VALUE_2.getHashKey(), MIXED_TEST_VALUE_2.getRangeKey())); assertEquals( ENCRYPTED_TEST_VALUE_2, mapper.load( ENCRYPTED_TEST_VALUE_2.getClass(), ENCRYPTED_TEST_VALUE_2.getHashKey(), ENCRYPTED_TEST_VALUE_2.getRangeKey())); assertEquals("Foo", mapper.load(HashKeyOnly.class, "Foo").getHashKey()); assertEquals("Bar", mapper.load(HashKeyOnly.class, "Bar").getHashKey()); assertEquals("Baz", mapper.load(HashKeyOnly.class, "Baz").getHashKey()); for (int x = 1; x <= 3; ++x) { KeysOnly obj = mapper.load(KeysOnly.class, 0, x); assertEquals(0, obj.getHashKey()); assertEquals(x, obj.getRangeKey()); obj = mapper.load(KeysOnly.class, 1, x); assertEquals(1, obj.getHashKey()); assertEquals(x, obj.getRangeKey()); obj = mapper.load(KeysOnly.class, 4 + x, x); assertEquals(4 + x, obj.getHashKey()); assertEquals(x, obj.getRangeKey()); } } // Prints all current tables in the expected test vector format. // You may need to edit the output to grab the tables you care about, or // separate the tables into separate files for test vectors (metastores e.g.). private void printTablesAsTestVectors() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addSerializer(AttributeValue.class, new AttributeValueSerializer()); mapper.registerModule(module); Map<String, List<Map<String, AttributeValue>>> testVector = new HashMap<>(); for (String table : client.listTables().getTableNames()) { ScanResult scanResult; Map<String, AttributeValue> lastKey = null; do { scanResult = client.scan(new ScanRequest().withTableName(table).withExclusiveStartKey(lastKey)); lastKey = scanResult.getLastEvaluatedKey(); testVector.put(table, scanResult.getItems()); } while (lastKey != null); } String jsonResult = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(testVector); System.out.println(jsonResult); } private EncryptionMaterialsProvider createProvider( String providerName, String materialName, Keys keys, ProviderStore metastore) { switch (providerName) { case ScenarioManifest.MOST_RECENT_PROVIDER_NAME: return new CachingMostRecentProvider(metastore, materialName, 1000); case ScenarioManifest.STATIC_PROVIDER_NAME: KeyData decryptKeyData = keyDataMap.get(keys.decryptName); KeyData verifyKeyData = keyDataMap.get(keys.verifyName); SecretKey decryptKey = new SecretKeySpec(Base64.decode(decryptKeyData.material), decryptKeyData.algorithm); SecretKey verifyKey = new SecretKeySpec(Base64.decode(verifyKeyData.material), verifyKeyData.algorithm); return new SymmetricStaticProvider(decryptKey, verifyKey); case ScenarioManifest.WRAPPED_PROVIDER_NAME: decryptKeyData = keyDataMap.get(keys.decryptName); verifyKeyData = keyDataMap.get(keys.verifyName); // This can be either the asymmetric provider, where we should test using it's explicit // constructor, // or a wrapped symmetric where we use the wrapped materials constructor. if (decryptKeyData.keyType.equals(ScenarioManifest.SYMMETRIC_KEY_TYPE)) { decryptKey = new SecretKeySpec(Base64.decode(decryptKeyData.material), decryptKeyData.algorithm); verifyKey = new SecretKeySpec(Base64.decode(verifyKeyData.material), verifyKeyData.algorithm); return new WrappedMaterialsProvider(decryptKey, decryptKey, verifyKey); } else { KeyData encryptKeyData = keyDataMap.get(keys.encryptName); KeyData signKeyData = keyDataMap.get(keys.signName); try { // Hardcoded to use RSA for asymmetric keys. If we include vectors with a different // asymmetric scheme this will need to be updated. KeyFactory rsaFact = KeyFactory.getInstance(RSA); PublicKey encryptMaterial = rsaFact.generatePublic( new X509EncodedKeySpec(Base64.decode(encryptKeyData.material))); PrivateKey decryptMaterial = rsaFact.generatePrivate( new PKCS8EncodedKeySpec(Base64.decode(decryptKeyData.material))); KeyPair decryptPair = new KeyPair(encryptMaterial, decryptMaterial); PublicKey verifyMaterial = rsaFact.generatePublic( new X509EncodedKeySpec(Base64.decode(verifyKeyData.material))); PrivateKey signingMaterial = rsaFact.generatePrivate( new PKCS8EncodedKeySpec(Base64.decode(signKeyData.material))); KeyPair sigPair = new KeyPair(verifyMaterial, signingMaterial); return new AsymmetricStaticProvider(decryptPair, sigPair); } catch (GeneralSecurityException ex) { throw new RuntimeException(ex); } } case ScenarioManifest.AWS_KMS_PROVIDER_NAME: return new DirectKmsMaterialProvider(kmsClient, keyDataMap.get(keys.decryptName).keyId); default: throw new IllegalStateException( "Provider " + providerName + " not yet implemented in test vector runner"); } } // Create empty tables for the ciphertext. // The underlying structure to these tables is hardcoded, // and we run all test vectors assuming the ciphertext matches the key schema for these tables. private void createCiphertextTables(AmazonDynamoDB client) { ArrayList<AttributeDefinition> attrDef = new ArrayList<AttributeDefinition>(); attrDef.add( new AttributeDefinition() .withAttributeName(HASH_KEY) .withAttributeType(ScalarAttributeType.N)); attrDef.add( new AttributeDefinition() .withAttributeName(RANGE_KEY) .withAttributeType(ScalarAttributeType.N)); ArrayList<KeySchemaElement> keySchema = new ArrayList<KeySchemaElement>(); keySchema.add(new KeySchemaElement().withAttributeName(HASH_KEY).withKeyType(KeyType.HASH)); keySchema.add(new KeySchemaElement().withAttributeName(RANGE_KEY).withKeyType(KeyType.RANGE)); client.createTable( new CreateTableRequest() .withTableName("TableName") .withAttributeDefinitions(attrDef) .withKeySchema(keySchema) .withProvisionedThroughput(new ProvisionedThroughput(100L, 100L))); attrDef = new ArrayList<AttributeDefinition>(); attrDef.add( new AttributeDefinition() .withAttributeName(HASH_KEY) .withAttributeType(ScalarAttributeType.S)); keySchema = new ArrayList<KeySchemaElement>(); keySchema.add(new KeySchemaElement().withAttributeName(HASH_KEY).withKeyType(KeyType.HASH)); client.createTable( new CreateTableRequest() .withTableName("HashKeyOnly") .withAttributeDefinitions(attrDef) .withKeySchema(keySchema) .withProvisionedThroughput(new ProvisionedThroughput(100L, 100L))); attrDef = new ArrayList<AttributeDefinition>(); attrDef.add( new AttributeDefinition() .withAttributeName(HASH_KEY) .withAttributeType(ScalarAttributeType.B)); attrDef.add( new AttributeDefinition() .withAttributeName(RANGE_KEY) .withAttributeType(ScalarAttributeType.N)); keySchema = new ArrayList<KeySchemaElement>(); keySchema.add(new KeySchemaElement().withAttributeName(HASH_KEY).withKeyType(KeyType.HASH)); keySchema.add(new KeySchemaElement().withAttributeName(RANGE_KEY).withKeyType(KeyType.RANGE)); client.createTable( new CreateTableRequest() .withTableName("DeterministicTable") .withAttributeDefinitions(attrDef) .withKeySchema(keySchema) .withProvisionedThroughput(new ProvisionedThroughput(100L, 100L))); } // Given a file in the test vector ciphertext format, put those entries into their tables. // This assumes the expected tables have already been created. private void putDataFromFile(AmazonDynamoDB client, String filename) throws IOException { Map<String, List<Map<String, AttributeValue>>> manifest = getCiphertextManifestFromFile(filename); for (String tableName : manifest.keySet()) { for (Map<String, AttributeValue> attributes : manifest.get(tableName)) { client.putItem(new PutItemRequest(tableName, attributes)); } } } private Map<String, List<Map<String, AttributeValue>>> getCiphertextManifestFromFile( String filename) throws IOException { return getManifestFromFile( TEST_VECTOR_MANIFEST_DIR + stripFilePath(filename), new TypeReference<Map<String, List<Map<String, DeserializedAttributeValue>>>>() {}); } private static <T> T getManifestFromFile(String filename, TypeReference typeRef) throws IOException { final URL url = TransformerHolisticIT.class.getResource(filename); if (url == null) { throw new IllegalStateException("Missing file " + filename + " in src/test/resources."); } final File manifestFile = new File(url.getPath()); final ObjectMapper manifestMapper = new ObjectMapper(); return (T) manifestMapper.readValue(manifestFile, typeRef); } private static void loadKeyData(String filename) throws IOException { keyDataMap = getManifestFromFile( TEST_VECTOR_MANIFEST_DIR + stripFilePath(filename), new TypeReference<Map<String, KeyData>>() {}); } private static String stripFilePath(String path) { return path.replaceFirst("file://", ""); } @JsonDeserialize(using = AttributeValueDeserializer.class) public static class DeserializedAttributeValue extends AttributeValue {} }
4,286
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/AttributeEncryptorTest.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.datamodeling; import static org.hamcrest.MatcherAssert.assertThat; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import com.amazonaws.services.dynamodbv2.datamodeling.AttributeTransformer.Parameters; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.EncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.SymmetricStaticProvider; import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.testing.AttrMatcher; import com.amazonaws.services.dynamodbv2.testing.FakeParameters; import com.amazonaws.services.dynamodbv2.testing.types.BaseClass; import com.amazonaws.services.dynamodbv2.testing.types.BaseClassWithNewAttribute; import com.amazonaws.services.dynamodbv2.testing.types.BaseClassWithUnknownAttributeAnnotation; import com.amazonaws.services.dynamodbv2.testing.types.DoNotEncryptField; import com.amazonaws.services.dynamodbv2.testing.types.DoNotTouchField; import com.amazonaws.services.dynamodbv2.testing.types.Mixed; import com.amazonaws.services.dynamodbv2.testing.types.SignOnly; import com.amazonaws.services.dynamodbv2.testing.types.SignOnlyWithUnknownAttributeAnnotation; import com.amazonaws.services.dynamodbv2.testing.types.SignOnlyWithUnknownAttributeAnnotationWithNewAttribute; import com.amazonaws.services.dynamodbv2.testing.types.TableOverride; import com.amazonaws.services.dynamodbv2.testing.types.Untouched; import com.amazonaws.services.dynamodbv2.testing.types.UntouchedWithNewAttribute; import com.amazonaws.services.dynamodbv2.testing.types.UntouchedWithUnknownAttributeAnnotation; import com.amazonaws.services.dynamodbv2.testing.types.UntouchedWithUnknownAttributeAnnotationWithNewAttribute; import java.nio.ByteBuffer; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class AttributeEncryptorTest { private static final String RANGE_KEY = "rangeKey"; private static final String HASH_KEY = "hashKey"; private static final String TABLE_NAME = "TableName"; private static SecretKey encryptionKey; private static SecretKey macKey; private EncryptionMaterialsProvider prov; private AttributeEncryptor encryptor; private Map<String, AttributeValue> attribs; @BeforeClass public static void setUpClass() throws Exception { KeyGenerator aesGen = KeyGenerator.getInstance("AES"); aesGen.init(128, Utils.getRng()); encryptionKey = aesGen.generateKey(); KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256"); macGen.init(256, Utils.getRng()); macKey = macGen.generateKey(); } @BeforeMethod public void setUp() throws Exception { prov = new SymmetricStaticProvider(encryptionKey, macKey, Collections.<String, String>emptyMap()); encryptor = new AttributeEncryptor(prov); attribs = new HashMap<String, AttributeValue>(); attribs.put("intValue", new AttributeValue().withN("123")); attribs.put("stringValue", new AttributeValue().withS("Hello world!")); attribs.put( "byteArrayValue", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5}))); attribs.put("stringSet", new AttributeValue().withSS("Goodbye", "Cruel", "World", "?")); attribs.put("intSet", new AttributeValue().withNS("1", "200", "10", "15", "0")); attribs.put(HASH_KEY, new AttributeValue().withN("5")); attribs.put(RANGE_KEY, new AttributeValue().withN("7")); attribs.put("version", new AttributeValue().withN("0")); } @Test public void testUnaffected() { Parameters<Untouched> params = FakeParameters.getInstance(Untouched.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertEquals(attribs, encryptedAttributes); } @Test public void fullEncryption() { Parameters<BaseClass> params = FakeParameters.getInstance(BaseClass.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); params = FakeParameters.getInstance( BaseClass.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params); assertThat(decryptedAttributes, AttrMatcher.match(attribs)); // Make sure keys and version are not encrypted assertAttrEquals(attribs.get(HASH_KEY), encryptedAttributes.get(HASH_KEY)); assertAttrEquals(attribs.get(RANGE_KEY), encryptedAttributes.get(RANGE_KEY)); assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version")); // Make sure String has been encrypted (we'll assume the others are correct as well) assertTrue(encryptedAttributes.containsKey("stringValue")); assertNull(encryptedAttributes.get("stringValue").getS()); assertNotNull(encryptedAttributes.get("stringValue").getB()); } @Test(expectedExceptions = DynamoDBMappingException.class) public void rejectsPartialUpdate() { Parameters<BaseClass> params = FakeParameters.getInstance( BaseClass.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY, true); encryptor.transform(params); } @Test(expectedExceptions = DynamoDBMappingException.class) public void fullEncryptionBadSignature() { Parameters<BaseClass> params = FakeParameters.getInstance(BaseClass.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); encryptedAttributes.get(HASH_KEY).setN("666"); params = FakeParameters.getInstance( BaseClass.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); encryptor.untransform(params); } @Test(expectedExceptions = DynamoDBMappingException.class) public void badVersionNumber() { Parameters<BaseClass> params = FakeParameters.getInstance(BaseClass.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); ByteBuffer materialDescription = encryptedAttributes.get(encryptor.getEncryptor().getMaterialDescriptionFieldName()).getB(); byte[] rawArray = materialDescription.array(); assertEquals(0, rawArray[0]); // This will need to be kept in sync with the current version. rawArray[0] = 100; encryptedAttributes.put( encryptor.getEncryptor().getMaterialDescriptionFieldName(), new AttributeValue().withB(ByteBuffer.wrap(rawArray))); params = FakeParameters.getInstance( BaseClass.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); encryptor.untransform(params); } @Test public void signedOnly() { Parameters<SignOnly> params = FakeParameters.getInstance(SignOnly.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); params = FakeParameters.getInstance( SignOnly.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params); assertThat(decryptedAttributes, AttrMatcher.match(attribs)); // Make sure keys and version are not encrypted assertAttrEquals(attribs.get(HASH_KEY), encryptedAttributes.get(HASH_KEY)); assertAttrEquals(attribs.get(RANGE_KEY), encryptedAttributes.get(RANGE_KEY)); assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version")); // Make sure String has not been encrypted (we'll assume the others are correct as well) assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue")); } @Test public void signedOnlyNullCryptoKey() { prov = new SymmetricStaticProvider(null, macKey, Collections.<String, String>emptyMap()); encryptor = new AttributeEncryptor(prov); Parameters<SignOnly> params = FakeParameters.getInstance(SignOnly.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); params = FakeParameters.getInstance( SignOnly.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params); assertThat(decryptedAttributes, AttrMatcher.match(attribs)); // Make sure keys and version are not encrypted assertAttrEquals(attribs.get(HASH_KEY), encryptedAttributes.get(HASH_KEY)); assertAttrEquals(attribs.get(RANGE_KEY), encryptedAttributes.get(RANGE_KEY)); assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version")); // Make sure String has not been encrypted (we'll assume the others are correct as well) assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue")); } @Test(expectedExceptions = DynamoDBMappingException.class) public void signedOnlyBadSignature() { Parameters<SignOnly> params = FakeParameters.getInstance(SignOnly.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); encryptedAttributes.get(HASH_KEY).setN("666"); params = FakeParameters.getInstance( SignOnly.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); encryptor.untransform(params); } @Test(expectedExceptions = DynamoDBMappingException.class) public void signedOnlyNoSignature() { Parameters<SignOnly> params = FakeParameters.getInstance(SignOnly.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); encryptedAttributes.remove(encryptor.getEncryptor().getSignatureFieldName()); encryptor.untransform(params); } @Test public void RsaSignedOnly() throws NoSuchAlgorithmException { KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA"); rsaGen.initialize(2048, Utils.getRng()); KeyPair sigPair = rsaGen.generateKeyPair(); encryptor = new AttributeEncryptor( new SymmetricStaticProvider( encryptionKey, sigPair, Collections.<String, String>emptyMap())); Parameters<SignOnly> params = FakeParameters.getInstance(SignOnly.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); params = FakeParameters.getInstance( SignOnly.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params); assertThat(decryptedAttributes, AttrMatcher.match(attribs)); // Make sure keys and version are not encrypted assertAttrEquals(attribs.get(HASH_KEY), encryptedAttributes.get(HASH_KEY)); assertAttrEquals(attribs.get(RANGE_KEY), encryptedAttributes.get(RANGE_KEY)); assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version")); // Make sure String has not been encrypted (we'll assume the others are correct as well) assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue")); } @Test(expectedExceptions = DynamoDBMappingException.class) public void RsaSignedOnlyBadSignature() throws NoSuchAlgorithmException { KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA"); rsaGen.initialize(2048, Utils.getRng()); KeyPair sigPair = rsaGen.generateKeyPair(); encryptor = new AttributeEncryptor( new SymmetricStaticProvider( encryptionKey, sigPair, Collections.<String, String>emptyMap())); Parameters<SignOnly> params = FakeParameters.getInstance(SignOnly.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); encryptedAttributes.get(HASH_KEY).setN("666"); params = FakeParameters.getInstance( SignOnly.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); encryptor.untransform(params); } @Test public void mixed() { Parameters<Mixed> params = FakeParameters.getInstance(Mixed.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); params = FakeParameters.getInstance( Mixed.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params); assertThat(decryptedAttributes, AttrMatcher.match(attribs)); // Make sure keys and version are not encrypted assertAttrEquals(attribs.get(HASH_KEY), encryptedAttributes.get(HASH_KEY)); assertAttrEquals(attribs.get(RANGE_KEY), encryptedAttributes.get(RANGE_KEY)); assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version")); // Make sure StringSet has been encrypted (we'll assume the others are correct as well) assertTrue(encryptedAttributes.containsKey("stringSet")); assertNull(encryptedAttributes.get("stringSet").getSS()); assertNotNull(encryptedAttributes.get("stringSet").getB()); // Test those not encrypted assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue")); assertAttrEquals(attribs.get("intValue"), encryptedAttributes.get("intValue")); // intValue is not signed, make sure we can modify it and still decrypt encryptedAttributes.get("intValue").setN("666"); params = FakeParameters.getInstance( Mixed.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); decryptedAttributes = encryptor.untransform(params); assertThat(decryptedAttributes, AttrMatcher.match(attribs)); } @Test(expectedExceptions = DynamoDBMappingException.class) public void mixedBadSignature() { Parameters<Mixed> params = FakeParameters.getInstance(Mixed.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); encryptedAttributes.get("stringValue").setS("666"); params = FakeParameters.getInstance( Mixed.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); encryptor.untransform(params); } @Test(expectedExceptions = DynamoDBMappingException.class) public void tableNameRespected() { Parameters<BaseClass> params = FakeParameters.getInstance( BaseClass.class, attribs, null, "firstTable", HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); params = FakeParameters.getInstance( BaseClass.class, encryptedAttributes, null, "secondTable", HASH_KEY, RANGE_KEY); encryptor.untransform(params); } @Test public void tableNameOverridden() { Parameters<TableOverride> params = FakeParameters.getInstance( TableOverride.class, attribs, null, "firstTable", HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); params = FakeParameters.getInstance( TableOverride.class, encryptedAttributes, null, "secondTable", HASH_KEY, RANGE_KEY); encryptor.untransform(params); Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params); assertThat(decryptedAttributes, AttrMatcher.match(attribs)); } @Test(expectedExceptions = DynamoDBMappingException.class) public void testUnknownAttributeFails() { Map<String, AttributeValue> attributes = new HashMap<>(attribs); attributes.put("newAttribute", new AttributeValue().withS("foobar")); Parameters<? extends BaseClass> params = FakeParameters.getInstance( BaseClassWithNewAttribute.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attributes)); params = FakeParameters.getInstance( BaseClass.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); encryptor.untransform(params); } @Test public void testUntouchedWithUnknownAttribute() { Map<String, AttributeValue> attributes = new HashMap<>(attribs); attributes.put("newAttribute", new AttributeValue().withS("foobar")); Parameters<? extends Untouched> params = FakeParameters.getInstance( UntouchedWithNewAttribute.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.match(attributes)); params = FakeParameters.getInstance( Untouched.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params); assertThat(decryptedAttributes, AttrMatcher.match(attributes)); } @Test public void testUntouchedWithUnknownAttributeAnnotation() { Map<String, AttributeValue> attributes = new HashMap<>(attribs); attributes.put("newAttribute", new AttributeValue().withS("foobar")); Parameters<? extends UntouchedWithUnknownAttributeAnnotation> params = FakeParameters.getInstance( UntouchedWithUnknownAttributeAnnotationWithNewAttribute.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.match(attributes)); params = FakeParameters.getInstance( UntouchedWithUnknownAttributeAnnotation.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params); assertThat(decryptedAttributes, AttrMatcher.match(attributes)); } @Test public void testSignOnlyWithUnknownAttributeAnnotation() { Map<String, AttributeValue> attributes = new HashMap<>(attribs); attributes.put("newAttribute", new AttributeValue().withS("foobar")); Parameters<? extends SignOnlyWithUnknownAttributeAnnotation> params = FakeParameters.getInstance( SignOnlyWithUnknownAttributeAnnotationWithNewAttribute.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attributes)); assertAttrEquals(new AttributeValue().withS("foobar"), encryptedAttributes.get("newAttribute")); params = FakeParameters.getInstance( SignOnlyWithUnknownAttributeAnnotation.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params); assertThat(decryptedAttributes, AttrMatcher.match(attributes)); } @Test(expectedExceptions = DynamoDBMappingException.class) public void testSignOnlyWithUnknownAttributeAnnotationBadSignature() { Map<String, AttributeValue> attributes = new HashMap<>(attribs); attributes.put("newAttribute", new AttributeValue().withS("foo")); Parameters<? extends SignOnlyWithUnknownAttributeAnnotation> params = FakeParameters.getInstance( SignOnlyWithUnknownAttributeAnnotationWithNewAttribute.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attributes)); assertAttrEquals(new AttributeValue().withS("foo"), encryptedAttributes.get("newAttribute")); params = FakeParameters.getInstance( SignOnlyWithUnknownAttributeAnnotation.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); encryptedAttributes.get("newAttribute").setS("bar"); encryptor.untransform(params); } @Test public void testEncryptWithUnknownAttributeAnnotation() { Map<String, AttributeValue> attributes = new HashMap<>(attribs); attributes.put("newAttribute", new AttributeValue().withS("foo")); Parameters<? extends BaseClassWithUnknownAttributeAnnotation> params = FakeParameters.getInstance( BaseClassWithNewAttribute.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attributes)); params = FakeParameters.getInstance( BaseClassWithUnknownAttributeAnnotation.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params); assertThat(decryptedAttributes, AttrMatcher.match(attributes)); } @Test(expectedExceptions = DynamoDBMappingException.class) public void testEncryptWithUnknownAttributeAnnotationBadSignature() { Map<String, AttributeValue> attributes = new HashMap<>(attribs); attributes.put("newAttribute", new AttributeValue().withS("foo")); Parameters<? extends BaseClassWithUnknownAttributeAnnotation> params = FakeParameters.getInstance( BaseClassWithNewAttribute.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attributes)); params = FakeParameters.getInstance( BaseClassWithUnknownAttributeAnnotation.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); encryptedAttributes.get("newAttribute").setB(ByteBuffer.allocate(0)); encryptor.untransform(params); } @Test public void testEncryptWithFieldLevelDoNotEncryptAnnotation() { Map<String, AttributeValue> attributes = new HashMap<>(attribs); attributes.put("value", new AttributeValue().withN("100")); Parameters<? extends DoNotEncryptField> params = FakeParameters.getInstance( DoNotEncryptField.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attributes)); assertAttrEquals(attributes.get("value"), encryptedAttributes.get("value")); params = FakeParameters.getInstance( DoNotEncryptField.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params); assertThat(decryptedAttributes, AttrMatcher.match(attributes)); } @Test public void testEncryptWithFieldLevelDoNotEncryptAnnotationWithChangedDoNotTouchSuperClass() { Map<String, AttributeValue> attributes = new HashMap<>(attribs); attributes.put("value", new AttributeValue().withN("100")); Parameters<? extends DoNotEncryptField> params = FakeParameters.getInstance( DoNotEncryptField.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attributes)); assertAttrEquals(attributes.get("value"), encryptedAttributes.get("value")); params = FakeParameters.getInstance( DoNotEncryptField.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); // Change a DoNotTouch value on Mixed super class encryptedAttributes.put("intValue", new AttributeValue().withN("666")); Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params); Map<String, AttributeValue> modifiedAttributes = new HashMap<>(attributes); modifiedAttributes.put("intValue", new AttributeValue().withN("666")); assertThat(decryptedAttributes, AttrMatcher.match(modifiedAttributes)); } @Test(expectedExceptions = DynamoDBMappingException.class) public void testEncryptWithFieldLevelDoNotEncryptAnnotationBadSignature() { Map<String, AttributeValue> attributes = new HashMap<>(attribs); attributes.put("value", new AttributeValue().withN("100")); Parameters<? extends DoNotEncryptField> params = FakeParameters.getInstance( DoNotEncryptField.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attributes)); assertAttrEquals(attributes.get("value"), encryptedAttributes.get("value")); params = FakeParameters.getInstance( DoNotEncryptField.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); encryptedAttributes.put("value", new AttributeValue().withN("200")); encryptor.untransform(params); } @Test(expectedExceptions = DynamoDBMappingException.class) public void testEncryptWithFieldLevelDoNotEncryptAnnotationBadSignatureSuperClass() { Map<String, AttributeValue> attributes = new HashMap<>(attribs); attributes.put("value", new AttributeValue().withN("100")); Parameters<? extends DoNotEncryptField> params = FakeParameters.getInstance( DoNotEncryptField.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attributes)); assertAttrEquals(attributes.get("value"), encryptedAttributes.get("value")); params = FakeParameters.getInstance( DoNotEncryptField.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); // Change DoNotEncrypt value on Mixed super class encryptedAttributes.put("doubleValue", new AttributeValue().withN("200")); encryptor.untransform(params); } @Test public void testEncryptWithFieldLevelDoNotTouchAnnotation() { Map<String, AttributeValue> attributes = new HashMap<>(attribs); attributes.put("value", new AttributeValue().withN("100")); Parameters<? extends DoNotTouchField> params = FakeParameters.getInstance( DoNotTouchField.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attributes)); assertAttrEquals(attributes.get("value"), encryptedAttributes.get("value")); params = FakeParameters.getInstance( DoNotTouchField.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params); assertThat(decryptedAttributes, AttrMatcher.match(attributes)); } @Test public void testEncryptWithFieldLevelDoNotTouchAnnotationChangeValue() { Map<String, AttributeValue> attributes = new HashMap<>(attribs); attributes.put("value", new AttributeValue().withN("100")); Parameters<? extends DoNotTouchField> params = FakeParameters.getInstance( DoNotTouchField.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attributes)); assertAttrEquals(attributes.get("value"), encryptedAttributes.get("value")); params = FakeParameters.getInstance( DoNotTouchField.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); encryptedAttributes.put("value", new AttributeValue().withN("200")); Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params); assertThat(decryptedAttributes, AttrMatcher.invert(attributes)); assertAttrEquals(new AttributeValue().withN("200"), decryptedAttributes.get("value")); // Change a DoNotTouch value on Mixed super class encryptedAttributes.put("intValue", new AttributeValue().withN("666")); decryptedAttributes = encryptor.untransform(params); Map<String, AttributeValue> modifiedAttributes = new HashMap<>(attributes); modifiedAttributes.put("intValue", new AttributeValue().withN("666")); modifiedAttributes.put("value", new AttributeValue().withN("200")); assertThat(decryptedAttributes, AttrMatcher.match(modifiedAttributes)); } @Test(expectedExceptions = DynamoDBMappingException.class) public void testEncryptWithFieldLevelDoNotTouchAnnotationBadSignatureSuperClass() { Map<String, AttributeValue> attributes = new HashMap<>(attribs); attributes.put("value", new AttributeValue().withN("100")); Parameters<? extends DoNotTouchField> params = FakeParameters.getInstance( DoNotTouchField.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params); assertThat(encryptedAttributes, AttrMatcher.invert(attributes)); assertAttrEquals(attributes.get("value"), encryptedAttributes.get("value")); params = FakeParameters.getInstance( DoNotTouchField.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY); Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params); assertThat(decryptedAttributes, AttrMatcher.match(attributes)); // Change DoNotEncrypt value on Mixed super class encryptedAttributes.put("doubleValue", new AttributeValue().withN("200")); encryptor.untransform(params); } private void assertAttrEquals(AttributeValue o1, AttributeValue o2) { Assert.assertEquals(o1.getB(), o2.getB()); assertSetsEqual(o1.getBS(), o2.getBS()); Assert.assertEquals(o1.getN(), o2.getN()); assertSetsEqual(o1.getNS(), o2.getNS()); Assert.assertEquals(o1.getS(), o2.getS()); assertSetsEqual(o1.getSS(), o2.getSS()); } private <T> void assertSetsEqual(Collection<T> c1, Collection<T> c2) { Assert.assertFalse(c1 == null ^ c2 == null); if (c1 != null) { Set<T> s1 = new HashSet<T>(c1); Set<T> s2 = new HashSet<T>(c2); Assert.assertEquals(s1, s2); } } }
4,287
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/DynamoDBSignerTest.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.datamodeling.encryption; import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.security.Key; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.Security; import java.security.SignatureException; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.crypto.KeyGenerator; import org.bouncycastle.jce.ECNamedCurveTable; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.ECParameterSpec; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class DynamoDBSignerTest { // These use the Key type (rather than PublicKey, PrivateKey, and SecretKey) // to test the routing logic within the signer. private static Key pubKeyRsa; private static Key privKeyRsa; private static Key macKey; private DynamoDBSigner signerRsa; private DynamoDBSigner signerEcdsa; private static Key pubKeyEcdsa; private static Key privKeyEcdsa; @BeforeClass public static void setUpClass() throws Exception { // RSA key generation KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA"); rsaGen.initialize(2048, Utils.getRng()); KeyPair sigPair = rsaGen.generateKeyPair(); pubKeyRsa = sigPair.getPublic(); privKeyRsa = sigPair.getPrivate(); KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256"); macGen.init(256, Utils.getRng()); macKey = macGen.generateKey(); Security.addProvider(new BouncyCastleProvider()); ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp384r1"); KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC"); g.initialize(ecSpec, Utils.getRng()); KeyPair keypair = g.generateKeyPair(); pubKeyEcdsa = keypair.getPublic(); privKeyEcdsa = keypair.getPrivate(); } @BeforeMethod public void setUp() { signerRsa = DynamoDBSigner.getInstance("SHA256withRSA", Utils.getRng()); signerEcdsa = DynamoDBSigner.getInstance("SHA384withECDSA", Utils.getRng()); } @Test public void mac() throws GeneralSecurityException { Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>(); Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>(); itemAttributes.put("Key1", new AttributeValue().withS("Value1")); attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put("Key2", new AttributeValue().withN("100")); attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put( "Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3}))); attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT)); byte[] signature = signerRsa.calculateSignature(itemAttributes, attributeFlags, new byte[0], macKey); signerRsa.verifySignature( itemAttributes, attributeFlags, new byte[0], macKey, ByteBuffer.wrap(signature)); } @Test public void macLists() throws GeneralSecurityException { Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>(); Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>(); itemAttributes.put("Key1", new AttributeValue().withSS("Value1", "Value2", "Value3")); attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put("Key2", new AttributeValue().withNS("100", "200", "300")); attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put( "Key3", new AttributeValue() .withBS( ByteBuffer.wrap(new byte[] {0, 1, 2, 3}), ByteBuffer.wrap(new byte[] {3, 2, 1}))); attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT)); byte[] signature = signerRsa.calculateSignature(itemAttributes, attributeFlags, new byte[0], macKey); signerRsa.verifySignature( itemAttributes, attributeFlags, new byte[0], macKey, ByteBuffer.wrap(signature)); } @Test public void macListsUnsorted() throws GeneralSecurityException { Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>(); Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>(); itemAttributes.put("Key1", new AttributeValue().withSS("Value3", "Value1", "Value2")); attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put("Key2", new AttributeValue().withNS("100", "300", "200")); attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put( "Key3", new AttributeValue() .withBS( ByteBuffer.wrap(new byte[] {3, 2, 1}), ByteBuffer.wrap(new byte[] {0, 1, 2, 3}))); attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT)); byte[] signature = signerRsa.calculateSignature(itemAttributes, attributeFlags, new byte[0], macKey); Map<String, AttributeValue> scrambledAttributes = new HashMap<String, AttributeValue>(); scrambledAttributes.put("Key1", new AttributeValue().withSS("Value1", "Value2", "Value3")); scrambledAttributes.put("Key2", new AttributeValue().withNS("100", "200", "300")); scrambledAttributes.put( "Key3", new AttributeValue() .withBS( ByteBuffer.wrap(new byte[] {0, 1, 2, 3}), ByteBuffer.wrap(new byte[] {3, 2, 1}))); signerRsa.verifySignature( scrambledAttributes, attributeFlags, new byte[0], macKey, ByteBuffer.wrap(signature)); } @Test public void macNoAdMatchesEmptyAd() throws GeneralSecurityException { Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>(); Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>(); itemAttributes.put("Key1", new AttributeValue().withS("Value1")); attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put("Key2", new AttributeValue().withN("100")); attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put( "Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3}))); attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT)); byte[] signature = signerRsa.calculateSignature(itemAttributes, attributeFlags, null, macKey); signerRsa.verifySignature( itemAttributes, attributeFlags, new byte[0], macKey, ByteBuffer.wrap(signature)); } @Test public void macWithIgnoredChange() throws GeneralSecurityException { Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>(); Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>(); itemAttributes.put("Key1", new AttributeValue().withS("Value1")); attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put("Key2", new AttributeValue().withN("100")); attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put( "Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3}))); attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT)); itemAttributes.put("Key4", new AttributeValue().withS("Ignored Value")); byte[] signature = signerRsa.calculateSignature(itemAttributes, attributeFlags, new byte[0], macKey); itemAttributes.put("Key4", new AttributeValue().withS("New Ignored Value")); signerRsa.verifySignature( itemAttributes, attributeFlags, new byte[0], macKey, ByteBuffer.wrap(signature)); } @Test(expectedExceptions = SignatureException.class) public void macChangedValue() throws GeneralSecurityException { Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>(); Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>(); itemAttributes.put("Key1", new AttributeValue().withS("Value1")); attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put("Key2", new AttributeValue().withN("100")); attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put( "Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3}))); attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT)); byte[] signature = signerRsa.calculateSignature(itemAttributes, attributeFlags, new byte[0], macKey); itemAttributes.get("Key2").setN("99"); signerRsa.verifySignature( itemAttributes, attributeFlags, new byte[0], macKey, ByteBuffer.wrap(signature)); } @Test(expectedExceptions = SignatureException.class) public void macChangedFlag() throws GeneralSecurityException { Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>(); Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>(); itemAttributes.put("Key1", new AttributeValue().withS("Value1")); attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put("Key2", new AttributeValue().withN("100")); attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put( "Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3}))); attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT)); byte[] signature = signerRsa.calculateSignature(itemAttributes, attributeFlags, new byte[0], macKey); attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN)); signerRsa.verifySignature( itemAttributes, attributeFlags, new byte[0], macKey, ByteBuffer.wrap(signature)); } @Test(expectedExceptions = SignatureException.class) public void macChangedAssociatedData() throws GeneralSecurityException { Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>(); Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>(); itemAttributes.put("Key1", new AttributeValue().withS("Value1")); attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put("Key2", new AttributeValue().withN("100")); attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put( "Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3}))); attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT)); byte[] signature = signerRsa.calculateSignature(itemAttributes, attributeFlags, new byte[] {3, 2, 1}, macKey); signerRsa.verifySignature( itemAttributes, attributeFlags, new byte[] {1, 2, 3}, macKey, ByteBuffer.wrap(signature)); } @Test public void sig() throws GeneralSecurityException { Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>(); Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>(); itemAttributes.put("Key1", new AttributeValue().withS("Value1")); attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put("Key2", new AttributeValue().withN("100")); attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put( "Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3}))); attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT)); byte[] signature = signerRsa.calculateSignature(itemAttributes, attributeFlags, new byte[0], privKeyRsa); signerRsa.verifySignature( itemAttributes, attributeFlags, new byte[0], pubKeyRsa, ByteBuffer.wrap(signature)); } @Test public void sigWithReadOnlySignature() throws GeneralSecurityException { Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>(); Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>(); itemAttributes.put("Key1", new AttributeValue().withS("Value1")); attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put("Key2", new AttributeValue().withN("100")); attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put( "Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3}))); attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT)); byte[] signature = signerRsa.calculateSignature(itemAttributes, attributeFlags, new byte[0], privKeyRsa); signerRsa.verifySignature( itemAttributes, attributeFlags, new byte[0], pubKeyRsa, ByteBuffer.wrap(signature).asReadOnlyBuffer()); } @Test public void sigNoAdMatchesEmptyAd() throws GeneralSecurityException { Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>(); Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>(); itemAttributes.put("Key1", new AttributeValue().withS("Value1")); attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put("Key2", new AttributeValue().withN("100")); attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put( "Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3}))); attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT)); byte[] signature = signerRsa.calculateSignature(itemAttributes, attributeFlags, null, privKeyRsa); signerRsa.verifySignature( itemAttributes, attributeFlags, new byte[0], pubKeyRsa, ByteBuffer.wrap(signature)); } @Test public void sigWithIgnoredChange() throws GeneralSecurityException { Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>(); Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>(); itemAttributes.put("Key1", new AttributeValue().withS("Value1")); attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put("Key2", new AttributeValue().withN("100")); attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put( "Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3}))); attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT)); itemAttributes.put("Key4", new AttributeValue().withS("Ignored Value")); byte[] signature = signerRsa.calculateSignature(itemAttributes, attributeFlags, new byte[0], privKeyRsa); itemAttributes.put("Key4", new AttributeValue().withS("New Ignored Value")); signerRsa.verifySignature( itemAttributes, attributeFlags, new byte[0], pubKeyRsa, ByteBuffer.wrap(signature)); } @Test(expectedExceptions = SignatureException.class) public void sigChangedValue() throws GeneralSecurityException { Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>(); Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>(); itemAttributes.put("Key1", new AttributeValue().withS("Value1")); attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put("Key2", new AttributeValue().withN("100")); attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put( "Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3}))); attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT)); byte[] signature = signerRsa.calculateSignature(itemAttributes, attributeFlags, new byte[0], privKeyRsa); itemAttributes.get("Key2").setN("99"); signerRsa.verifySignature( itemAttributes, attributeFlags, new byte[0], pubKeyRsa, ByteBuffer.wrap(signature)); } @Test(expectedExceptions = SignatureException.class) public void sigChangedFlag() throws GeneralSecurityException { Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>(); Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>(); itemAttributes.put("Key1", new AttributeValue().withS("Value1")); attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put("Key2", new AttributeValue().withN("100")); attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put( "Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3}))); attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT)); byte[] signature = signerRsa.calculateSignature(itemAttributes, attributeFlags, new byte[0], privKeyRsa); attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN)); signerRsa.verifySignature( itemAttributes, attributeFlags, new byte[0], pubKeyRsa, ByteBuffer.wrap(signature)); } @Test(expectedExceptions = SignatureException.class) public void sigChangedAssociatedData() throws GeneralSecurityException { Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>(); Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>(); itemAttributes.put("Key1", new AttributeValue().withS("Value1")); attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put("Key2", new AttributeValue().withN("100")); attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put( "Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3}))); attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT)); byte[] signature = signerRsa.calculateSignature(itemAttributes, attributeFlags, new byte[0], privKeyRsa); signerRsa.verifySignature( itemAttributes, attributeFlags, new byte[] {1, 2, 3}, pubKeyRsa, ByteBuffer.wrap(signature)); } @Test public void sigEcdsa() throws GeneralSecurityException { Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>(); Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>(); itemAttributes.put("Key1", new AttributeValue().withS("Value1")); attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put("Key2", new AttributeValue().withN("100")); attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put( "Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3}))); attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN)); byte[] signature = signerEcdsa.calculateSignature(itemAttributes, attributeFlags, new byte[0], privKeyEcdsa); signerEcdsa.verifySignature( itemAttributes, attributeFlags, new byte[0], pubKeyEcdsa, ByteBuffer.wrap(signature)); } @Test public void sigEcdsaWithReadOnlySignature() throws GeneralSecurityException { Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>(); Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>(); itemAttributes.put("Key1", new AttributeValue().withS("Value1")); attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put("Key2", new AttributeValue().withN("100")); attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put( "Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3}))); attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN)); byte[] signature = signerEcdsa.calculateSignature(itemAttributes, attributeFlags, new byte[0], privKeyEcdsa); signerEcdsa.verifySignature( itemAttributes, attributeFlags, new byte[0], pubKeyEcdsa, ByteBuffer.wrap(signature).asReadOnlyBuffer()); } @Test public void sigEcdsaNoAdMatchesEmptyAd() throws GeneralSecurityException { Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>(); Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>(); itemAttributes.put("Key1", new AttributeValue().withS("Value1")); attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put("Key2", new AttributeValue().withN("100")); attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put( "Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3}))); attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN)); byte[] signature = signerEcdsa.calculateSignature(itemAttributes, attributeFlags, null, privKeyEcdsa); signerEcdsa.verifySignature( itemAttributes, attributeFlags, new byte[0], pubKeyEcdsa, ByteBuffer.wrap(signature)); } @Test public void sigEcdsaWithIgnoredChange() throws GeneralSecurityException { Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>(); Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>(); itemAttributes.put("Key1", new AttributeValue().withS("Value1")); attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put("Key2", new AttributeValue().withN("100")); attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put( "Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3}))); attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put("Key4", new AttributeValue().withS("Ignored Value")); byte[] signature = signerEcdsa.calculateSignature(itemAttributes, attributeFlags, new byte[0], privKeyEcdsa); itemAttributes.put("Key4", new AttributeValue().withS("New Ignored Value")); signerEcdsa.verifySignature( itemAttributes, attributeFlags, new byte[0], pubKeyEcdsa, ByteBuffer.wrap(signature)); } @Test(expectedExceptions = SignatureException.class) public void sigEcdsaChangedValue() throws GeneralSecurityException { Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>(); Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>(); itemAttributes.put("Key1", new AttributeValue().withS("Value1")); attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put("Key2", new AttributeValue().withN("100")); attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put( "Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3}))); attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN)); byte[] signature = signerEcdsa.calculateSignature(itemAttributes, attributeFlags, new byte[0], privKeyEcdsa); itemAttributes.get("Key2").setN("99"); signerEcdsa.verifySignature( itemAttributes, attributeFlags, new byte[0], pubKeyEcdsa, ByteBuffer.wrap(signature)); } @Test(expectedExceptions = SignatureException.class) public void sigEcdsaChangedAssociatedData() throws GeneralSecurityException { Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>(); Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>(); itemAttributes.put("Key1", new AttributeValue().withS("Value1")); attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put("Key2", new AttributeValue().withN("100")); attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN)); itemAttributes.put( "Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3}))); attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN)); byte[] signature = signerEcdsa.calculateSignature(itemAttributes, attributeFlags, new byte[0], privKeyEcdsa); signerEcdsa.verifySignature( itemAttributes, attributeFlags, new byte[] {1, 2, 3}, pubKeyEcdsa, ByteBuffer.wrap(signature)); } }
4,288
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/DelegatedEnvelopeEncryptionTest.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.datamodeling.encryption; import static org.hamcrest.MatcherAssert.assertThat; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.EncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.SymmetricStaticProvider; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.WrappedMaterialsProvider; import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.testing.AttrMatcher; import com.amazonaws.services.dynamodbv2.testing.TestDelegatedKey; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.SignatureException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.crypto.spec.SecretKeySpec; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class DelegatedEnvelopeEncryptionTest { private static SecretKeySpec rawEncryptionKey; private static SecretKeySpec rawMacKey; private static DelegatedKey encryptionKey; private static DelegatedKey macKey; private EncryptionMaterialsProvider prov; private DynamoDBEncryptor encryptor; private Map<String, AttributeValue> attribs; private EncryptionContext context; @BeforeClass public static void setupClass() throws Exception { rawEncryptionKey = new SecretKeySpec(Utils.getRandom(32), "AES"); encryptionKey = new TestDelegatedKey(rawEncryptionKey); rawMacKey = new SecretKeySpec(Utils.getRandom(32), "HmacSHA256"); macKey = new TestDelegatedKey(rawMacKey); } @BeforeMethod public void setUp() throws Exception { prov = new WrappedMaterialsProvider( encryptionKey, encryptionKey, macKey, Collections.<String, String>emptyMap()); encryptor = DynamoDBEncryptor.getInstance(prov, "encryptor-"); attribs = new HashMap<String, AttributeValue>(); attribs.put("intValue", new AttributeValue().withN("123")); attribs.put("stringValue", new AttributeValue().withS("Hello world!")); attribs.put( "byteArrayValue", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5}))); attribs.put("stringSet", new AttributeValue().withSS("Goodbye", "Cruel", "World", "?")); attribs.put("intSet", new AttributeValue().withNS("1", "200", "10", "15", "0")); attribs.put("hashKey", new AttributeValue().withN("5")); attribs.put("rangeKey", new AttributeValue().withN("7")); attribs.put("version", new AttributeValue().withN("0")); context = new EncryptionContext.Builder() .withTableName("TableName") .withHashKeyName("hashKey") .withRangeKeyName("rangeKey") .build(); } @Test public void testSetSignatureFieldName() { assertNotNull(encryptor.getSignatureFieldName()); encryptor.setSignatureFieldName("A different value"); assertEquals("A different value", encryptor.getSignatureFieldName()); } @Test public void testSetMaterialDescriptionFieldName() { assertNotNull(encryptor.getMaterialDescriptionFieldName()); encryptor.setMaterialDescriptionFieldName("A different value"); assertEquals("A different value", encryptor.getMaterialDescriptionFieldName()); } @Test public void fullEncryption() throws GeneralSecurityException { Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept( Collections.unmodifiableMap(attribs), context, "hashKey", "rangeKey", "version"); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); Map<String, AttributeValue> decryptedAttributes = encryptor.decryptAllFieldsExcept( Collections.unmodifiableMap(encryptedAttributes), context, "hashKey", "rangeKey", "version"); assertThat(decryptedAttributes, AttrMatcher.match(attribs)); // Make sure keys and version are not encrypted assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey")); assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey")); assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version")); // Make sure String has been encrypted (we'll assume the others are correct as well) assertTrue(encryptedAttributes.containsKey("stringValue")); assertNull(encryptedAttributes.get("stringValue").getS()); assertNotNull(encryptedAttributes.get("stringValue").getB()); } @Test(expectedExceptions = SignatureException.class) public void fullEncryptionBadSignature() throws GeneralSecurityException { Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept( Collections.unmodifiableMap(attribs), context, "hashKey", "rangeKey", "version"); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); encryptedAttributes.get("hashKey").setN("666"); encryptor.decryptAllFieldsExcept( Collections.unmodifiableMap(encryptedAttributes), context, "hashKey", "rangeKey", "version"); } @Test(expectedExceptions = IllegalArgumentException.class) public void badVersionNumber() throws GeneralSecurityException { Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept( Collections.unmodifiableMap(attribs), context, "hashKey", "rangeKey", "version"); ByteBuffer materialDescription = encryptedAttributes.get(encryptor.getMaterialDescriptionFieldName()).getB(); byte[] rawArray = materialDescription.array(); assertEquals(0, rawArray[0]); // This will need to be kept in sync with the current version. rawArray[0] = 100; encryptedAttributes.put( encryptor.getMaterialDescriptionFieldName(), new AttributeValue().withB(ByteBuffer.wrap(rawArray))); encryptor.decryptAllFieldsExcept( Collections.unmodifiableMap(encryptedAttributes), context, "hashKey", "rangeKey", "version"); } @Test public void signedOnly() throws GeneralSecurityException { Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0])); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); Map<String, AttributeValue> decryptedAttributes = encryptor.decryptAllFieldsExcept( encryptedAttributes, context, attribs.keySet().toArray(new String[0])); assertThat(decryptedAttributes, AttrMatcher.match(attribs)); // Make sure keys and version are not encrypted assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey")); assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey")); assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version")); // Make sure String has not been encrypted (we'll assume the others are correct as well) assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue")); } @Test public void signedOnlyNullCryptoKey() throws GeneralSecurityException { prov = new SymmetricStaticProvider(null, macKey, Collections.<String, String>emptyMap()); encryptor = DynamoDBEncryptor.getInstance(prov, "encryptor-"); Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0])); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); Map<String, AttributeValue> decryptedAttributes = encryptor.decryptAllFieldsExcept( encryptedAttributes, context, attribs.keySet().toArray(new String[0])); assertThat(decryptedAttributes, AttrMatcher.match(attribs)); // Make sure keys and version are not encrypted assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey")); assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey")); assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version")); // Make sure String has not been encrypted (we'll assume the others are correct as well) assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue")); } @Test(expectedExceptions = SignatureException.class) public void signedOnlyBadSignature() throws GeneralSecurityException { Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0])); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); encryptedAttributes.get("hashKey").setN("666"); encryptor.decryptAllFieldsExcept( encryptedAttributes, context, attribs.keySet().toArray(new String[0])); } @Test(expectedExceptions = SignatureException.class) public void signedOnlyNoSignature() throws GeneralSecurityException { Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0])); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); encryptedAttributes.remove(encryptor.getSignatureFieldName()); encryptor.decryptAllFieldsExcept( encryptedAttributes, context, attribs.keySet().toArray(new String[0])); } @Test public void RsaSignedOnly() throws GeneralSecurityException { KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA"); rsaGen.initialize(2048, Utils.getRng()); KeyPair sigPair = rsaGen.generateKeyPair(); encryptor = DynamoDBEncryptor.getInstance( new SymmetricStaticProvider( encryptionKey, sigPair, Collections.<String, String>emptyMap()), "encryptor-"); Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0])); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); Map<String, AttributeValue> decryptedAttributes = encryptor.decryptAllFieldsExcept( encryptedAttributes, context, attribs.keySet().toArray(new String[0])); assertThat(decryptedAttributes, AttrMatcher.match(attribs)); // Make sure keys and version are not encrypted assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey")); assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey")); assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version")); // Make sure String has not been encrypted (we'll assume the others are correct as well) assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue")); } @Test(expectedExceptions = SignatureException.class) public void RsaSignedOnlyBadSignature() throws GeneralSecurityException { KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA"); rsaGen.initialize(2048, Utils.getRng()); KeyPair sigPair = rsaGen.generateKeyPair(); encryptor = DynamoDBEncryptor.getInstance( new SymmetricStaticProvider( encryptionKey, sigPair, Collections.<String, String>emptyMap()), "encryptor-"); Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0])); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); encryptedAttributes.get("hashKey").setN("666"); encryptor.decryptAllFieldsExcept( encryptedAttributes, context, attribs.keySet().toArray(new String[0])); } private void assertAttrEquals(AttributeValue o1, AttributeValue o2) { Assert.assertEquals(o1.getB(), o2.getB()); assertSetsEqual(o1.getBS(), o2.getBS()); Assert.assertEquals(o1.getN(), o2.getN()); assertSetsEqual(o1.getNS(), o2.getNS()); Assert.assertEquals(o1.getS(), o2.getS()); assertSetsEqual(o1.getSS(), o2.getSS()); } private <T> void assertSetsEqual(Collection<T> c1, Collection<T> c2) { Assert.assertFalse(c1 == null ^ c2 == null); if (c1 != null) { Set<T> s1 = new HashSet<T>(c1); Set<T> s2 = new HashSet<T>(c2); Assert.assertEquals(s1, s2); } } }
4,289
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/DynamoDBEncryptorTest.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.datamodeling.encryption; import static com.amazonaws.services.dynamodbv2.datamodeling.encryption.utils.EncryptionContextOperators.overrideEncryptionContextTableName; import static java.util.stream.Collectors.toMap; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.testng.AssertJUnit.assertArrayEquals; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import static org.testng.collections.Sets.newHashSet; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.EncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.SymmetricStaticProvider; import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.testing.AttrMatcher; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Security; import java.security.SignatureException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import org.bouncycastle.jce.ECNamedCurveTable; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.ECParameterSpec; import org.mockito.internal.util.collections.Sets; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class DynamoDBEncryptorTest { private static SecretKey encryptionKey; private static SecretKey macKey; private InstrumentedEncryptionMaterialsProvider prov; private DynamoDBEncryptor encryptor; private Map<String, AttributeValue> attribs; private EncryptionContext context; private static final String OVERRIDDEN_TABLE_NAME = "TheBestTableName"; @BeforeClass public static void setUpClass() throws Exception { KeyGenerator aesGen = KeyGenerator.getInstance("AES"); aesGen.init(128, Utils.getRng()); encryptionKey = aesGen.generateKey(); KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256"); macGen.init(256, Utils.getRng()); macKey = macGen.generateKey(); } @BeforeMethod public void setUp() throws Exception { prov = new InstrumentedEncryptionMaterialsProvider( new SymmetricStaticProvider( encryptionKey, macKey, Collections.<String, String>emptyMap())); encryptor = DynamoDBEncryptor.getInstance(prov, "encryptor-"); attribs = new HashMap<String, AttributeValue>(); attribs.put("intValue", new AttributeValue().withN("123")); attribs.put("stringValue", new AttributeValue().withS("Hello world!")); attribs.put( "byteArrayValue", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5}))); attribs.put("stringSet", new AttributeValue().withSS("Goodbye", "Cruel", "World", "?")); attribs.put("intSet", new AttributeValue().withNS("1", "200", "10", "15", "0")); attribs.put("hashKey", new AttributeValue().withN("5")); attribs.put("rangeKey", new AttributeValue().withN("7")); attribs.put("version", new AttributeValue().withN("0")); // New(er) data types attribs.put("booleanTrue", new AttributeValue().withBOOL(true)); attribs.put("booleanFalse", new AttributeValue().withBOOL(false)); attribs.put("nullValue", new AttributeValue().withNULL(true)); Map<String, AttributeValue> tmpMap = new HashMap<>(attribs); attribs.put( "listValue", new AttributeValue() .withL( new AttributeValue().withS("I'm a string"), new AttributeValue().withN("42"), new AttributeValue().withS("Another string"), new AttributeValue().withNS("1", "4", "7"), new AttributeValue().withM(tmpMap), new AttributeValue() .withL( new AttributeValue().withN("123"), new AttributeValue().withNS("1", "200", "10", "15", "0"), new AttributeValue().withSS("Goodbye", "Cruel", "World", "!")))); tmpMap = new HashMap<>(); tmpMap.put("another string", new AttributeValue().withS("All around the cobbler's bench")); tmpMap.put("next line", new AttributeValue().withSS("the monkey", "chased", "the weasel")); tmpMap.put( "more lyrics", new AttributeValue() .withL( new AttributeValue().withS("the monkey"), new AttributeValue().withS("thought twas"), new AttributeValue().withS("all in fun"))); tmpMap.put( "weasel", new AttributeValue() .withM(Collections.singletonMap("pop", new AttributeValue().withBOOL(true)))); attribs.put("song", new AttributeValue().withM(tmpMap)); context = new EncryptionContext.Builder() .withTableName("TableName") .withHashKeyName("hashKey") .withRangeKeyName("rangeKey") .build(); } @Test public void testSetSignatureFieldName() { assertNotNull(encryptor.getSignatureFieldName()); encryptor.setSignatureFieldName("A different value"); assertEquals("A different value", encryptor.getSignatureFieldName()); } @Test public void testSetMaterialDescriptionFieldName() { assertNotNull(encryptor.getMaterialDescriptionFieldName()); encryptor.setMaterialDescriptionFieldName("A different value"); assertEquals("A different value", encryptor.getMaterialDescriptionFieldName()); } @Test public void fullEncryption() throws GeneralSecurityException { Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept( Collections.unmodifiableMap(attribs), context, "hashKey", "rangeKey", "version"); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); Map<String, AttributeValue> decryptedAttributes = encryptor.decryptAllFieldsExcept( Collections.unmodifiableMap(encryptedAttributes), context, "hashKey", "rangeKey", "version"); assertThat(decryptedAttributes, AttrMatcher.match(attribs)); // Make sure keys and version are not encrypted assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey")); assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey")); assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version")); // Make sure String has been encrypted (we'll assume the others are correct as well) assertTrue(encryptedAttributes.containsKey("stringValue")); assertNull(encryptedAttributes.get("stringValue").getS()); assertNotNull(encryptedAttributes.get("stringValue").getB()); // Make sure we're calling the proper getEncryptionMaterials method assertEquals( "Wrong getEncryptionMaterials() called", 1, prov.getCallCount("getEncryptionMaterials(EncryptionContext context)")); } @Test public void ensureEncryptedAttributesUnmodified() throws GeneralSecurityException { Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept( Collections.unmodifiableMap(attribs), context, "hashKey", "rangeKey", "version"); // Using TreeMap before casting to string to avoid nondeterministic key orders. String encryptedString = new TreeMap<>(encryptedAttributes).toString(); encryptor.decryptAllFieldsExcept( Collections.unmodifiableMap(encryptedAttributes), context, "hashKey", "rangeKey", "version"); assertEquals(encryptedString, new TreeMap<>(encryptedAttributes).toString()); } @Test(expectedExceptions = SignatureException.class) public void fullEncryptionBadSignature() throws GeneralSecurityException { Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept( Collections.unmodifiableMap(attribs), context, "hashKey", "rangeKey", "version"); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); encryptedAttributes.get("hashKey").setN("666"); encryptor.decryptAllFieldsExcept( Collections.unmodifiableMap(encryptedAttributes), context, "hashKey", "rangeKey", "version"); } @Test(expectedExceptions = IllegalArgumentException.class) public void badVersionNumber() throws GeneralSecurityException { Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept( Collections.unmodifiableMap(attribs), context, "hashKey", "rangeKey", "version"); ByteBuffer materialDescription = encryptedAttributes.get(encryptor.getMaterialDescriptionFieldName()).getB(); byte[] rawArray = materialDescription.array(); assertEquals(0, rawArray[0]); // This will need to be kept in sync with the current version. rawArray[0] = 100; encryptedAttributes.put( encryptor.getMaterialDescriptionFieldName(), new AttributeValue().withB(ByteBuffer.wrap(rawArray))); encryptor.decryptAllFieldsExcept( Collections.unmodifiableMap(encryptedAttributes), context, "hashKey", "rangeKey", "version"); } @Test public void signedOnly() throws GeneralSecurityException { Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0])); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); Map<String, AttributeValue> decryptedAttributes = encryptor.decryptAllFieldsExcept( encryptedAttributes, context, attribs.keySet().toArray(new String[0])); assertThat(decryptedAttributes, AttrMatcher.match(attribs)); // Make sure keys and version are not encrypted assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey")); assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey")); assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version")); // Make sure String has not been encrypted (we'll assume the others are correct as well) assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue")); } @Test public void signedOnlyNullCryptoKey() throws GeneralSecurityException { prov = new InstrumentedEncryptionMaterialsProvider( new SymmetricStaticProvider(null, macKey, Collections.<String, String>emptyMap())); encryptor = DynamoDBEncryptor.getInstance(prov, "encryptor-"); Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0])); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); Map<String, AttributeValue> decryptedAttributes = encryptor.decryptAllFieldsExcept( encryptedAttributes, context, attribs.keySet().toArray(new String[0])); assertThat(decryptedAttributes, AttrMatcher.match(attribs)); // Make sure keys and version are not encrypted assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey")); assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey")); assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version")); // Make sure String has not been encrypted (we'll assume the others are correct as well) assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue")); } @Test(expectedExceptions = SignatureException.class) public void signedOnlyBadSignature() throws GeneralSecurityException { Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0])); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); encryptedAttributes.get("hashKey").setN("666"); encryptor.decryptAllFieldsExcept( encryptedAttributes, context, attribs.keySet().toArray(new String[0])); } @Test(expectedExceptions = SignatureException.class) public void signedOnlyNoSignature() throws GeneralSecurityException { Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0])); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); encryptedAttributes.remove(encryptor.getSignatureFieldName()); encryptor.decryptAllFieldsExcept( encryptedAttributes, context, attribs.keySet().toArray(new String[0])); } @Test public void RsaSignedOnly() throws GeneralSecurityException { KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA"); rsaGen.initialize(2048, Utils.getRng()); KeyPair sigPair = rsaGen.generateKeyPair(); encryptor = DynamoDBEncryptor.getInstance( new SymmetricStaticProvider( encryptionKey, sigPair, Collections.<String, String>emptyMap()), "encryptor-"); Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0])); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); Map<String, AttributeValue> decryptedAttributes = encryptor.decryptAllFieldsExcept( encryptedAttributes, context, attribs.keySet().toArray(new String[0])); assertThat(decryptedAttributes, AttrMatcher.match(attribs)); // Make sure keys and version are not encrypted assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey")); assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey")); assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version")); // Make sure String has not been encrypted (we'll assume the others are correct as well) assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue")); } @Test(expectedExceptions = SignatureException.class) public void RsaSignedOnlyBadSignature() throws GeneralSecurityException { KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA"); rsaGen.initialize(2048, Utils.getRng()); KeyPair sigPair = rsaGen.generateKeyPair(); encryptor = DynamoDBEncryptor.getInstance( new SymmetricStaticProvider( encryptionKey, sigPair, Collections.<String, String>emptyMap()), "encryptor-"); Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0])); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); encryptedAttributes.get("hashKey").setN("666"); encryptor.decryptAllFieldsExcept( encryptedAttributes, context, attribs.keySet().toArray(new String[0])); } /** * Tests that no exception is thrown when the encryption context override operator is null * * @throws GeneralSecurityException */ @Test public void testNullEncryptionContextOperator() throws GeneralSecurityException { DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(prov); encryptor.setEncryptionContextOverrideOperator(null); encryptor.encryptAllFieldsExcept(attribs, context, Collections.emptyList()); } /** * Tests decrypt and encrypt with an encryption context override operator * * @throws GeneralSecurityException */ @Test public void testTableNameOverriddenEncryptionContextOperator() throws GeneralSecurityException { // Ensure that the table name is different from what we override the table to. assertThat(context.getTableName(), not(equalTo(OVERRIDDEN_TABLE_NAME))); DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(prov); encryptor.setEncryptionContextOverrideOperator( overrideEncryptionContextTableName(context.getTableName(), OVERRIDDEN_TABLE_NAME)); Map<String, AttributeValue> encryptedItems = encryptor.encryptAllFieldsExcept(attribs, context, Collections.emptyList()); Map<String, AttributeValue> decryptedItems = encryptor.decryptAllFieldsExcept(encryptedItems, context, Collections.emptyList()); assertThat(decryptedItems, AttrMatcher.match(attribs)); } /** * Tests encrypt with an encryption context override operator, and a second encryptor without an * override * * @throws GeneralSecurityException */ @Test public void testTableNameOverriddenEncryptionContextOperatorWithSecondEncryptor() throws GeneralSecurityException { // Ensure that the table name is different from what we override the table to. assertThat(context.getTableName(), not(equalTo(OVERRIDDEN_TABLE_NAME))); DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(prov); DynamoDBEncryptor encryptorWithoutOverride = DynamoDBEncryptor.getInstance(prov); encryptor.setEncryptionContextOverrideOperator( overrideEncryptionContextTableName(context.getTableName(), OVERRIDDEN_TABLE_NAME)); Map<String, AttributeValue> encryptedItems = encryptor.encryptAllFieldsExcept(attribs, context, Collections.emptyList()); EncryptionContext expectedOverriddenContext = new EncryptionContext.Builder(context).withTableName("TheBestTableName").build(); Map<String, AttributeValue> decryptedItems = encryptorWithoutOverride.decryptAllFieldsExcept( encryptedItems, expectedOverriddenContext, Collections.emptyList()); assertThat(decryptedItems, AttrMatcher.match(attribs)); } /** * Tests encrypt with an encryption context override operator, and a second encryptor without an * override * * @throws GeneralSecurityException */ @Test(expectedExceptions = SignatureException.class) public void testTableNameOverriddenEncryptionContextOperatorWithSecondEncryptorButTheOriginalEncryptionContext() throws GeneralSecurityException { // Ensure that the table name is different from what we override the table to. assertThat(context.getTableName(), not(equalTo(OVERRIDDEN_TABLE_NAME))); DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(prov); DynamoDBEncryptor encryptorWithoutOverride = DynamoDBEncryptor.getInstance(prov); encryptor.setEncryptionContextOverrideOperator( overrideEncryptionContextTableName(context.getTableName(), OVERRIDDEN_TABLE_NAME)); Map<String, AttributeValue> encryptedItems = encryptor.encryptAllFieldsExcept(attribs, context, Collections.emptyList()); // Use the original encryption context, and expect a signature failure Map<String, AttributeValue> decryptedItems = encryptorWithoutOverride.decryptAllFieldsExcept( encryptedItems, context, Collections.emptyList()); } @Test public void EcdsaSignedOnly() throws GeneralSecurityException { encryptor = DynamoDBEncryptor.getInstance(getMaterialProviderwithECDSA()); Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0])); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); Map<String, AttributeValue> decryptedAttributes = encryptor.decryptAllFieldsExcept( encryptedAttributes, context, attribs.keySet().toArray(new String[0])); assertThat(decryptedAttributes, AttrMatcher.match(attribs)); // Make sure keys and version are not encrypted assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey")); assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey")); assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version")); // Make sure String has not been encrypted (we'll assume the others are correct as well) assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue")); } @Test(expectedExceptions = SignatureException.class) public void EcdsaSignedOnlyBadSignature() throws GeneralSecurityException { encryptor = DynamoDBEncryptor.getInstance(getMaterialProviderwithECDSA()); Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0])); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); encryptedAttributes.get("hashKey").setN("666"); encryptor.decryptAllFieldsExcept( encryptedAttributes, context, attribs.keySet().toArray(new String[0])); } @Test public void toByteArray() throws ReflectiveOperationException { final byte[] expected = new byte[] {0, 1, 2, 3, 4, 5}; assertToByteArray("Wrap", expected, ByteBuffer.wrap(expected)); assertToByteArray("Wrap-RO", expected, ByteBuffer.wrap(expected).asReadOnlyBuffer()); assertToByteArray( "Wrap-Truncated-Sliced", expected, ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5, 6}, 0, 6).slice()); assertToByteArray( "Wrap-Offset-Sliced", expected, ByteBuffer.wrap(new byte[] {6, 0, 1, 2, 3, 4, 5, 6}, 1, 6).slice()); assertToByteArray( "Wrap-Truncated", expected, ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5, 6}, 0, 6)); assertToByteArray( "Wrap-Offset", expected, ByteBuffer.wrap(new byte[] {6, 0, 1, 2, 3, 4, 5, 6}, 1, 6)); ByteBuffer buff = ByteBuffer.allocate(expected.length + 10); buff.put(expected); buff.flip(); assertToByteArray("Normal", expected, buff); buff = ByteBuffer.allocateDirect(expected.length + 10); buff.put(expected); buff.flip(); assertToByteArray("Direct", expected, buff); } @Test public void testDecryptWithPlaintextItem() throws GeneralSecurityException { Map<String, Set<EncryptionFlags>> attributeWithEmptyEncryptionFlags = attribs.keySet().stream().collect(toMap(k -> k, k -> newHashSet())); Map<String, AttributeValue> decryptedAttributes = encryptor.decryptRecord(attribs, attributeWithEmptyEncryptionFlags, context); assertThat(decryptedAttributes, AttrMatcher.match(attribs)); } /* Test decrypt with a map that contains a new key (not included in attribs) with an encryption flag set that contains ENCRYPT and SIGN. */ @Test public void testDecryptWithPlainTextItemAndAdditionNewAttributeHavingEncryptionFlag() throws GeneralSecurityException { Map<String, Set<EncryptionFlags>> attributeWithEmptyEncryptionFlags = attribs.keySet().stream().collect(toMap(k -> k, k -> newHashSet())); attributeWithEmptyEncryptionFlags.put( "newAttribute", Sets.newSet(EncryptionFlags.ENCRYPT, EncryptionFlags.SIGN)); Map<String, AttributeValue> decryptedAttributes = encryptor.decryptRecord(attribs, attributeWithEmptyEncryptionFlags, context); assertThat(decryptedAttributes, AttrMatcher.match(attribs)); } private void assertToByteArray( final String msg, final byte[] expected, final ByteBuffer testValue) throws ReflectiveOperationException { Method m = DynamoDBEncryptor.class.getDeclaredMethod("toByteArray", ByteBuffer.class); m.setAccessible(true); int oldPosition = testValue.position(); int oldLimit = testValue.limit(); assertArrayEquals(msg + ":Array", expected, (byte[]) m.invoke(null, testValue)); assertEquals(msg + ":Position", oldPosition, testValue.position()); assertEquals(msg + ":Limit", oldLimit, testValue.limit()); } private void assertAttrEquals(AttributeValue o1, AttributeValue o2) { Assert.assertEquals(o1.getB(), o2.getB()); assertSetsEqual(o1.getBS(), o2.getBS()); Assert.assertEquals(o1.getN(), o2.getN()); assertSetsEqual(o1.getNS(), o2.getNS()); Assert.assertEquals(o1.getS(), o2.getS()); assertSetsEqual(o1.getSS(), o2.getSS()); } private <T> void assertSetsEqual(Collection<T> c1, Collection<T> c2) { Assert.assertFalse(c1 == null ^ c2 == null); if (c1 != null) { Set<T> s1 = new HashSet<T>(c1); Set<T> s2 = new HashSet<T>(c2); Assert.assertEquals(s1, s2); } } private EncryptionMaterialsProvider getMaterialProviderwithECDSA() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException { Security.addProvider(new BouncyCastleProvider()); ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp384r1"); KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC"); g.initialize(ecSpec, Utils.getRng()); KeyPair keypair = g.generateKeyPair(); Map<String, String> description = new HashMap<String, String>(); description.put(DynamoDBEncryptor.DEFAULT_SIGNING_ALGORITHM_HEADER, "SHA384withECDSA"); return new SymmetricStaticProvider(null, keypair, description); } private static final class InstrumentedEncryptionMaterialsProvider implements EncryptionMaterialsProvider { private final EncryptionMaterialsProvider delegate; private final ConcurrentHashMap<String, AtomicInteger> calls = new ConcurrentHashMap<>(); public InstrumentedEncryptionMaterialsProvider(EncryptionMaterialsProvider delegate) { this.delegate = delegate; } @Override public DecryptionMaterials getDecryptionMaterials(EncryptionContext context) { incrementMethodCount("getDecryptionMaterials()"); return delegate.getDecryptionMaterials(context); } @Override public EncryptionMaterials getEncryptionMaterials(EncryptionContext context) { incrementMethodCount("getEncryptionMaterials(EncryptionContext context)"); return delegate.getEncryptionMaterials(context); } @Override public void refresh() { incrementMethodCount("refresh()"); delegate.refresh(); } public int getCallCount(String method) { AtomicInteger count = calls.get(method); if (count != null) { return count.intValue(); } else { return 0; } } @SuppressWarnings("unused") public void resetCallCounts() { calls.clear(); } private void incrementMethodCount(String method) { AtomicInteger oldValue = calls.putIfAbsent(method, new AtomicInteger(1)); if (oldValue != null) { oldValue.incrementAndGet(); } } } }
4,290
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/DelegatedEncryptionTest.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.datamodeling.encryption; import static org.hamcrest.MatcherAssert.assertThat; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.EncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.SymmetricStaticProvider; import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.testing.AttrMatcher; import com.amazonaws.services.dynamodbv2.testing.TestDelegatedKey; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.SignatureException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.crypto.spec.SecretKeySpec; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class DelegatedEncryptionTest { private static SecretKeySpec rawEncryptionKey; private static SecretKeySpec rawMacKey; private static DelegatedKey encryptionKey; private static DelegatedKey macKey; private EncryptionMaterialsProvider prov; private DynamoDBEncryptor encryptor; private Map<String, AttributeValue> attribs; private EncryptionContext context; @BeforeClass public static void setupClass() throws Exception { rawEncryptionKey = new SecretKeySpec(Utils.getRandom(32), "AES"); encryptionKey = new TestDelegatedKey(rawEncryptionKey); rawMacKey = new SecretKeySpec(Utils.getRandom(32), "HmacSHA256"); macKey = new TestDelegatedKey(rawMacKey); } @BeforeMethod public void setUp() throws Exception { prov = new SymmetricStaticProvider(encryptionKey, macKey, Collections.<String, String>emptyMap()); encryptor = DynamoDBEncryptor.getInstance(prov, "encryptor-"); attribs = new HashMap<String, AttributeValue>(); attribs.put("intValue", new AttributeValue().withN("123")); attribs.put("stringValue", new AttributeValue().withS("Hello world!")); attribs.put( "byteArrayValue", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5}))); attribs.put("stringSet", new AttributeValue().withSS("Goodbye", "Cruel", "World", "?")); attribs.put("intSet", new AttributeValue().withNS("1", "200", "10", "15", "0")); attribs.put("hashKey", new AttributeValue().withN("5")); attribs.put("rangeKey", new AttributeValue().withN("7")); attribs.put("version", new AttributeValue().withN("0")); context = new EncryptionContext.Builder() .withTableName("TableName") .withHashKeyName("hashKey") .withRangeKeyName("rangeKey") .build(); } @Test public void testSetSignatureFieldName() { assertNotNull(encryptor.getSignatureFieldName()); encryptor.setSignatureFieldName("A different value"); assertEquals("A different value", encryptor.getSignatureFieldName()); } @Test public void testSetMaterialDescriptionFieldName() { assertNotNull(encryptor.getMaterialDescriptionFieldName()); encryptor.setMaterialDescriptionFieldName("A different value"); assertEquals("A different value", encryptor.getMaterialDescriptionFieldName()); } @Test public void fullEncryption() throws GeneralSecurityException { Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept( Collections.unmodifiableMap(attribs), context, "hashKey", "rangeKey", "version"); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); Map<String, AttributeValue> decryptedAttributes = encryptor.decryptAllFieldsExcept( Collections.unmodifiableMap(encryptedAttributes), context, "hashKey", "rangeKey", "version"); assertThat(decryptedAttributes, AttrMatcher.match(attribs)); // Make sure keys and version are not encrypted assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey")); assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey")); assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version")); // Make sure String has been encrypted (we'll assume the others are correct as well) assertTrue(encryptedAttributes.containsKey("stringValue")); assertNull(encryptedAttributes.get("stringValue").getS()); assertNotNull(encryptedAttributes.get("stringValue").getB()); } @Test(expectedExceptions = SignatureException.class) public void fullEncryptionBadSignature() throws GeneralSecurityException { Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept( Collections.unmodifiableMap(attribs), context, "hashKey", "rangeKey", "version"); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); encryptedAttributes.get("hashKey").setN("666"); encryptor.decryptAllFieldsExcept( Collections.unmodifiableMap(encryptedAttributes), context, "hashKey", "rangeKey", "version"); } @Test(expectedExceptions = IllegalArgumentException.class) public void badVersionNumber() throws GeneralSecurityException { Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept( Collections.unmodifiableMap(attribs), context, "hashKey", "rangeKey", "version"); ByteBuffer materialDescription = encryptedAttributes.get(encryptor.getMaterialDescriptionFieldName()).getB(); byte[] rawArray = materialDescription.array(); assertEquals(0, rawArray[0]); // This will need to be kept in sync with the current version. rawArray[0] = 100; encryptedAttributes.put( encryptor.getMaterialDescriptionFieldName(), new AttributeValue().withB(ByteBuffer.wrap(rawArray))); encryptor.decryptAllFieldsExcept( Collections.unmodifiableMap(encryptedAttributes), context, "hashKey", "rangeKey", "version"); } @Test public void signedOnly() throws GeneralSecurityException { Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0])); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); Map<String, AttributeValue> decryptedAttributes = encryptor.decryptAllFieldsExcept( encryptedAttributes, context, attribs.keySet().toArray(new String[0])); assertThat(decryptedAttributes, AttrMatcher.match(attribs)); // Make sure keys and version are not encrypted assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey")); assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey")); assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version")); // Make sure String has not been encrypted (we'll assume the others are correct as well) assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue")); } @Test public void signedOnlyNullCryptoKey() throws GeneralSecurityException { prov = new SymmetricStaticProvider(null, macKey, Collections.<String, String>emptyMap()); encryptor = DynamoDBEncryptor.getInstance(prov, "encryptor-"); Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0])); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); Map<String, AttributeValue> decryptedAttributes = encryptor.decryptAllFieldsExcept( encryptedAttributes, context, attribs.keySet().toArray(new String[0])); assertThat(decryptedAttributes, AttrMatcher.match(attribs)); // Make sure keys and version are not encrypted assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey")); assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey")); assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version")); // Make sure String has not been encrypted (we'll assume the others are correct as well) assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue")); } @Test(expectedExceptions = SignatureException.class) public void signedOnlyBadSignature() throws GeneralSecurityException { Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0])); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); encryptedAttributes.get("hashKey").setN("666"); encryptor.decryptAllFieldsExcept( encryptedAttributes, context, attribs.keySet().toArray(new String[0])); } @Test(expectedExceptions = SignatureException.class) public void signedOnlyNoSignature() throws GeneralSecurityException { Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0])); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); encryptedAttributes.remove(encryptor.getSignatureFieldName()); encryptor.decryptAllFieldsExcept( encryptedAttributes, context, attribs.keySet().toArray(new String[0])); } @Test public void RsaSignedOnly() throws GeneralSecurityException { KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA"); rsaGen.initialize(2048, Utils.getRng()); KeyPair sigPair = rsaGen.generateKeyPair(); encryptor = DynamoDBEncryptor.getInstance( new SymmetricStaticProvider( encryptionKey, sigPair, Collections.<String, String>emptyMap()), "encryptor-"); Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0])); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); Map<String, AttributeValue> decryptedAttributes = encryptor.decryptAllFieldsExcept( encryptedAttributes, context, attribs.keySet().toArray(new String[0])); assertThat(decryptedAttributes, AttrMatcher.match(attribs)); // Make sure keys and version are not encrypted assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey")); assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey")); assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version")); // Make sure String has not been encrypted (we'll assume the others are correct as well) assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue")); } @Test(expectedExceptions = SignatureException.class) public void RsaSignedOnlyBadSignature() throws GeneralSecurityException { KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA"); rsaGen.initialize(2048, Utils.getRng()); KeyPair sigPair = rsaGen.generateKeyPair(); encryptor = DynamoDBEncryptor.getInstance( new SymmetricStaticProvider( encryptionKey, sigPair, Collections.<String, String>emptyMap()), "encryptor-"); Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0])); assertThat(encryptedAttributes, AttrMatcher.invert(attribs)); encryptedAttributes.get("hashKey").setN("666"); encryptor.decryptAllFieldsExcept( encryptedAttributes, context, attribs.keySet().toArray(new String[0])); } private void assertAttrEquals(AttributeValue o1, AttributeValue o2) { Assert.assertEquals(o1.getB(), o2.getB()); assertSetsEqual(o1.getBS(), o2.getBS()); Assert.assertEquals(o1.getN(), o2.getN()); assertSetsEqual(o1.getNS(), o2.getNS()); Assert.assertEquals(o1.getS(), o2.getS()); assertSetsEqual(o1.getSS(), o2.getSS()); } private <T> void assertSetsEqual(Collection<T> c1, Collection<T> c2) { Assert.assertFalse(c1 == null ^ c2 == null); if (c1 != null) { Set<T> s1 = new HashSet<T>(c1); Set<T> s2 = new HashSet<T>(c2); Assert.assertEquals(s1, s2); } } }
4,291
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/materials/AsymmetricRawMaterialsTest.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.HashMap; import java.util.Map; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class AsymmetricRawMaterialsTest { private static SecureRandom rnd; private static KeyPair encryptionPair; private static SecretKey macKey; private static KeyPair sigPair; private Map<String, String> description; @BeforeClass public static void setUpClass() throws NoSuchAlgorithmException { rnd = new SecureRandom(); KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA"); rsaGen.initialize(2048, rnd); encryptionPair = rsaGen.generateKeyPair(); sigPair = rsaGen.generateKeyPair(); KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256"); macGen.init(256, rnd); macKey = macGen.generateKey(); } @BeforeMethod public void setUp() { description = new HashMap<String, String>(); description.put("TestKey", "test value"); } @Test public void macNoDescription() throws GeneralSecurityException { AsymmetricRawMaterials matEncryption = new AsymmetricRawMaterials(encryptionPair, macKey); assertEquals(macKey, matEncryption.getSigningKey()); assertEquals(macKey, matEncryption.getVerificationKey()); assertFalse(matEncryption.getMaterialDescription().isEmpty()); SecretKey envelopeKey = matEncryption.getEncryptionKey(); assertEquals(envelopeKey, matEncryption.getDecryptionKey()); AsymmetricRawMaterials matDecryption = new AsymmetricRawMaterials(encryptionPair, macKey, matEncryption.getMaterialDescription()); assertEquals(macKey, matDecryption.getSigningKey()); assertEquals(macKey, matDecryption.getVerificationKey()); assertEquals(envelopeKey, matDecryption.getEncryptionKey()); assertEquals(envelopeKey, matDecryption.getDecryptionKey()); } @Test public void macWithDescription() throws GeneralSecurityException { AsymmetricRawMaterials matEncryption = new AsymmetricRawMaterials(encryptionPair, macKey, description); assertEquals(macKey, matEncryption.getSigningKey()); assertEquals(macKey, matEncryption.getVerificationKey()); assertFalse(matEncryption.getMaterialDescription().isEmpty()); assertEquals("test value", matEncryption.getMaterialDescription().get("TestKey")); SecretKey envelopeKey = matEncryption.getEncryptionKey(); assertEquals(envelopeKey, matEncryption.getDecryptionKey()); AsymmetricRawMaterials matDecryption = new AsymmetricRawMaterials(encryptionPair, macKey, matEncryption.getMaterialDescription()); assertEquals(macKey, matDecryption.getSigningKey()); assertEquals(macKey, matDecryption.getVerificationKey()); assertEquals(envelopeKey, matDecryption.getEncryptionKey()); assertEquals(envelopeKey, matDecryption.getDecryptionKey()); assertEquals("test value", matDecryption.getMaterialDescription().get("TestKey")); } @Test public void sigNoDescription() throws GeneralSecurityException { AsymmetricRawMaterials matEncryption = new AsymmetricRawMaterials(encryptionPair, sigPair); assertEquals(sigPair.getPrivate(), matEncryption.getSigningKey()); assertEquals(sigPair.getPublic(), matEncryption.getVerificationKey()); assertFalse(matEncryption.getMaterialDescription().isEmpty()); SecretKey envelopeKey = matEncryption.getEncryptionKey(); assertEquals(envelopeKey, matEncryption.getDecryptionKey()); AsymmetricRawMaterials matDecryption = new AsymmetricRawMaterials(encryptionPair, sigPair, matEncryption.getMaterialDescription()); assertEquals(sigPair.getPrivate(), matDecryption.getSigningKey()); assertEquals(sigPair.getPublic(), matDecryption.getVerificationKey()); assertEquals(envelopeKey, matDecryption.getEncryptionKey()); assertEquals(envelopeKey, matDecryption.getDecryptionKey()); } @Test public void sigWithDescription() throws GeneralSecurityException { AsymmetricRawMaterials matEncryption = new AsymmetricRawMaterials(encryptionPair, sigPair, description); assertEquals(sigPair.getPrivate(), matEncryption.getSigningKey()); assertEquals(sigPair.getPublic(), matEncryption.getVerificationKey()); assertFalse(matEncryption.getMaterialDescription().isEmpty()); assertEquals("test value", matEncryption.getMaterialDescription().get("TestKey")); SecretKey envelopeKey = matEncryption.getEncryptionKey(); assertEquals(envelopeKey, matEncryption.getDecryptionKey()); AsymmetricRawMaterials matDecryption = new AsymmetricRawMaterials(encryptionPair, sigPair, matEncryption.getMaterialDescription()); assertEquals(sigPair.getPrivate(), matDecryption.getSigningKey()); assertEquals(sigPair.getPublic(), matDecryption.getVerificationKey()); assertEquals(envelopeKey, matDecryption.getEncryptionKey()); assertEquals(envelopeKey, matDecryption.getDecryptionKey()); assertEquals("test value", matDecryption.getMaterialDescription().get("TestKey")); } }
4,292
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/materials/SymmetricRawMaterialsTest.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.HashMap; import java.util.Map; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class SymmetricRawMaterialsTest { private static SecretKey encryptionKey; private static SecretKey macKey; private static KeyPair sigPair; private static SecureRandom rnd; private Map<String, String> description; @BeforeClass public static void setUpClass() throws NoSuchAlgorithmException { rnd = new SecureRandom(); KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA"); rsaGen.initialize(2048, rnd); sigPair = rsaGen.generateKeyPair(); KeyGenerator aesGen = KeyGenerator.getInstance("AES"); aesGen.init(128, rnd); encryptionKey = aesGen.generateKey(); KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256"); macGen.init(256, rnd); macKey = macGen.generateKey(); } @BeforeMethod public void setUp() { description = new HashMap<String, String>(); description.put("TestKey", "test value"); } @Test public void macNoDescription() throws NoSuchAlgorithmException { SymmetricRawMaterials mat = new SymmetricRawMaterials(encryptionKey, macKey); assertEquals(encryptionKey, mat.getEncryptionKey()); assertEquals(encryptionKey, mat.getDecryptionKey()); assertEquals(macKey, mat.getSigningKey()); assertEquals(macKey, mat.getVerificationKey()); assertTrue(mat.getMaterialDescription().isEmpty()); } @Test public void macWithDescription() throws NoSuchAlgorithmException { SymmetricRawMaterials mat = new SymmetricRawMaterials(encryptionKey, macKey, description); assertEquals(encryptionKey, mat.getEncryptionKey()); assertEquals(encryptionKey, mat.getDecryptionKey()); assertEquals(macKey, mat.getSigningKey()); assertEquals(macKey, mat.getVerificationKey()); assertEquals(description, mat.getMaterialDescription()); assertEquals("test value", mat.getMaterialDescription().get("TestKey")); } @Test public void sigNoDescription() throws NoSuchAlgorithmException { SymmetricRawMaterials mat = new SymmetricRawMaterials(encryptionKey, sigPair); assertEquals(encryptionKey, mat.getEncryptionKey()); assertEquals(encryptionKey, mat.getDecryptionKey()); assertEquals(sigPair.getPrivate(), mat.getSigningKey()); assertEquals(sigPair.getPublic(), mat.getVerificationKey()); assertTrue(mat.getMaterialDescription().isEmpty()); } @Test public void sigWithDescription() throws NoSuchAlgorithmException { SymmetricRawMaterials mat = new SymmetricRawMaterials(encryptionKey, sigPair, description); assertEquals(encryptionKey, mat.getEncryptionKey()); assertEquals(encryptionKey, mat.getDecryptionKey()); assertEquals(sigPair.getPrivate(), mat.getSigningKey()); assertEquals(sigPair.getPublic(), mat.getVerificationKey()); assertEquals(description, mat.getMaterialDescription()); assertEquals("test value", mat.getMaterialDescription().get("TestKey")); } }
4,293
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/DirectKmsMaterialProviderTest.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import com.amazonaws.RequestClientOptions; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.WrappedRawMaterials; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.testing.FakeKMS; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.model.DecryptRequest; import com.amazonaws.services.kms.model.DecryptResult; import com.amazonaws.services.kms.model.GenerateDataKeyRequest; import com.amazonaws.services.kms.model.GenerateDataKeyResult; import com.amazonaws.util.Base64; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.security.Key; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import javax.crypto.SecretKey; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class DirectKmsMaterialProviderTest { private FakeKMS kms; private String keyId; private Map<String, String> description; private EncryptionContext ctx; @BeforeMethod public void setUp() { description = new HashMap<>(); description.put("TestKey", "test value"); description = Collections.unmodifiableMap(description); ctx = new EncryptionContext.Builder().build(); kms = new FakeKMS(); keyId = kms.createKey().getKeyMetadata().getKeyId(); } @Test public void simple() throws GeneralSecurityException { DirectKmsMaterialProvider prov = new DirectKmsMaterialProvider(kms, keyId); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); Key signingKey = eMat.getSigningKey(); assertNotNull(signingKey); DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(signingKey, dMat.getVerificationKey()); String expectedEncAlg = encryptionKey.getAlgorithm() + "/" + (encryptionKey.getEncoded().length * 8); String expectedSigAlg = signingKey.getAlgorithm() + "/" + (signingKey.getEncoded().length * 8); Map<String, String> kmsCtx = kms.getSingleEc(); assertEquals(expectedEncAlg, kmsCtx.get("*" + WrappedRawMaterials.CONTENT_KEY_ALGORITHM + "*")); assertEquals(expectedSigAlg, kmsCtx.get("*amzn-ddb-sig-alg*")); } @Test public void simpleWithKmsEc() throws GeneralSecurityException { DirectKmsMaterialProvider prov = new DirectKmsMaterialProvider(kms, keyId); Map<String, AttributeValue> attrVals = new HashMap<>(); attrVals.put("hk", new AttributeValue("HashKeyValue")); attrVals.put("rk", new AttributeValue("RangeKeyValue")); ctx = new EncryptionContext.Builder() .withHashKeyName("hk") .withRangeKeyName("rk") .withTableName("KmsTableName") .withAttributeValues(attrVals) .build(); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); Key signingKey = eMat.getSigningKey(); assertNotNull(signingKey); Map<String, String> kmsCtx = kms.getSingleEc(); assertEquals("HashKeyValue", kmsCtx.get("hk")); assertEquals("RangeKeyValue", kmsCtx.get("rk")); assertEquals("KmsTableName", kmsCtx.get("*aws-kms-table*")); EncryptionContext dCtx = new EncryptionContext.Builder(ctx(eMat)) .withHashKeyName("hk") .withRangeKeyName("rk") .withTableName("KmsTableName") .withAttributeValues(attrVals) .build(); DecryptionMaterials dMat = prov.getDecryptionMaterials(dCtx); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(signingKey, dMat.getVerificationKey()); } @Test public void simpleWithKmsEc2() throws GeneralSecurityException { DirectKmsMaterialProvider prov = new DirectKmsMaterialProvider(kms, keyId); Map<String, AttributeValue> attrVals = new HashMap<>(); attrVals.put("hk", new AttributeValue().withN("10")); attrVals.put("rk", new AttributeValue().withN("20")); ctx = new EncryptionContext.Builder() .withHashKeyName("hk") .withRangeKeyName("rk") .withTableName("KmsTableName") .withAttributeValues(attrVals) .build(); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); Key signingKey = eMat.getSigningKey(); assertNotNull(signingKey); Map<String, String> kmsCtx = kms.getSingleEc(); assertEquals("10", kmsCtx.get("hk")); assertEquals("20", kmsCtx.get("rk")); assertEquals("KmsTableName", kmsCtx.get("*aws-kms-table*")); EncryptionContext dCtx = new EncryptionContext.Builder(ctx(eMat)) .withHashKeyName("hk") .withRangeKeyName("rk") .withTableName("KmsTableName") .withAttributeValues(attrVals) .build(); DecryptionMaterials dMat = prov.getDecryptionMaterials(dCtx); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(signingKey, dMat.getVerificationKey()); } @Test public void simpleWithKmsEc3() throws GeneralSecurityException { DirectKmsMaterialProvider prov = new DirectKmsMaterialProvider(kms, keyId); Map<String, AttributeValue> attrVals = new HashMap<>(); attrVals.put( "hk", new AttributeValue().withB(ByteBuffer.wrap("Foo".getBytes(StandardCharsets.UTF_8)))); attrVals.put( "rk", new AttributeValue().withB(ByteBuffer.wrap("Bar".getBytes(StandardCharsets.UTF_8)))); ctx = new EncryptionContext.Builder() .withHashKeyName("hk") .withRangeKeyName("rk") .withTableName("KmsTableName") .withAttributeValues(attrVals) .build(); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); Key signingKey = eMat.getSigningKey(); assertNotNull(signingKey); assertNotNull(signingKey); Map<String, String> kmsCtx = kms.getSingleEc(); assertEquals(Base64.encodeAsString("Foo".getBytes(StandardCharsets.UTF_8)), kmsCtx.get("hk")); assertEquals(Base64.encodeAsString("Bar".getBytes(StandardCharsets.UTF_8)), kmsCtx.get("rk")); assertEquals("KmsTableName", kmsCtx.get("*aws-kms-table*")); EncryptionContext dCtx = new EncryptionContext.Builder(ctx(eMat)) .withHashKeyName("hk") .withRangeKeyName("rk") .withTableName("KmsTableName") .withAttributeValues(attrVals) .build(); DecryptionMaterials dMat = prov.getDecryptionMaterials(dCtx); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(signingKey, dMat.getVerificationKey()); } @Test public void randomEnvelopeKeys() throws GeneralSecurityException { DirectKmsMaterialProvider prov = new DirectKmsMaterialProvider(kms, keyId); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); EncryptionMaterials eMat2 = prov.getEncryptionMaterials(ctx); SecretKey encryptionKey2 = eMat2.getEncryptionKey(); assertFalse("Envelope keys must be different", encryptionKey.equals(encryptionKey2)); } @Test public void testRefresh() { // This does nothing, make sure we don't throw and exception. DirectKmsMaterialProvider prov = new DirectKmsMaterialProvider(kms, keyId); prov.refresh(); } @Test public void explicitContentKeyAlgorithm() throws GeneralSecurityException { Map<String, String> desc = new HashMap<>(); desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES"); DirectKmsMaterialProvider prov = new DirectKmsMaterialProvider(kms, keyId, desc); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals( "AES", eMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM)); assertEquals(encryptionKey, dMat.getDecryptionKey()); } @Test public void explicitContentKeyLength128() throws GeneralSecurityException { Map<String, String> desc = new HashMap<>(); desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/128"); DirectKmsMaterialProvider prov = new DirectKmsMaterialProvider(kms, keyId, desc); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); assertEquals(16, encryptionKey.getEncoded().length); // 128 Bits DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals( "AES/128", eMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM)); assertEquals("AES", eMat.getEncryptionKey().getAlgorithm()); assertEquals(encryptionKey, dMat.getDecryptionKey()); } @Test public void explicitContentKeyLength256() throws GeneralSecurityException { Map<String, String> desc = new HashMap<>(); desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/256"); DirectKmsMaterialProvider prov = new DirectKmsMaterialProvider(kms, keyId, desc); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); assertEquals(32, encryptionKey.getEncoded().length); // 256 Bits DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals( "AES/256", eMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM)); assertEquals("AES", eMat.getEncryptionKey().getAlgorithm()); assertEquals(encryptionKey, dMat.getDecryptionKey()); } @Test public void extendedWithDerivedEncryptionKeyId() throws GeneralSecurityException { ExtendedKmsMaterialProvider prov = new ExtendedKmsMaterialProvider(kms, keyId, "encryptionKeyId"); String customKeyId = kms.createKey().getKeyMetadata().getKeyId(); Map<String, AttributeValue> attrVals = new HashMap<>(); attrVals.put("hk", new AttributeValue().withN("10")); attrVals.put("rk", new AttributeValue().withN("20")); attrVals.put("encryptionKeyId", new AttributeValue().withS(customKeyId)); ctx = new EncryptionContext.Builder() .withHashKeyName("hk") .withRangeKeyName("rk") .withTableName("KmsTableName") .withAttributeValues(attrVals) .build(); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); Key signingKey = eMat.getSigningKey(); assertNotNull(signingKey); Map<String, String> kmsCtx = kms.getSingleEc(); assertEquals("10", kmsCtx.get("hk")); assertEquals("20", kmsCtx.get("rk")); assertEquals("KmsTableName", kmsCtx.get("*aws-kms-table*")); EncryptionContext dCtx = new EncryptionContext.Builder(ctx(eMat)) .withHashKeyName("hk") .withRangeKeyName("rk") .withTableName("KmsTableName") .withAttributeValues(attrVals) .build(); DecryptionMaterials dMat = prov.getDecryptionMaterials(dCtx); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(signingKey, dMat.getVerificationKey()); } @Test(expectedExceptions = DynamoDBMappingException.class) public void encryptionKeyIdMismatch() throws GeneralSecurityException { DirectKmsMaterialProvider directProvider = new DirectKmsMaterialProvider(kms, keyId); String customKeyId = kms.createKey().getKeyMetadata().getKeyId(); Map<String, AttributeValue> attrVals = new HashMap<>(); attrVals.put("hk", new AttributeValue().withN("10")); attrVals.put("rk", new AttributeValue().withN("20")); attrVals.put("encryptionKeyId", new AttributeValue().withS(customKeyId)); ctx = new EncryptionContext.Builder() .withHashKeyName("hk") .withRangeKeyName("rk") .withTableName("KmsTableName") .withAttributeValues(attrVals) .build(); EncryptionMaterials eMat = directProvider.getEncryptionMaterials(ctx); EncryptionContext dCtx = new EncryptionContext.Builder(ctx(eMat)) .withHashKeyName("hk") .withRangeKeyName("rk") .withTableName("KmsTableName") .withAttributeValues(attrVals) .build(); ExtendedKmsMaterialProvider extendedProvider = new ExtendedKmsMaterialProvider(kms, keyId, "encryptionKeyId"); extendedProvider.getDecryptionMaterials(dCtx); } @Test(expectedExceptions = DynamoDBMappingException.class) public void missingEncryptionKeyId() throws GeneralSecurityException { ExtendedKmsMaterialProvider prov = new ExtendedKmsMaterialProvider(kms, keyId, "encryptionKeyId"); Map<String, AttributeValue> attrVals = new HashMap<>(); attrVals.put("hk", new AttributeValue().withN("10")); attrVals.put("rk", new AttributeValue().withN("20")); ctx = new EncryptionContext.Builder() .withHashKeyName("hk") .withRangeKeyName("rk") .withTableName("KmsTableName") .withAttributeValues(attrVals) .build(); prov.getEncryptionMaterials(ctx); } @Test public void generateDataKeyIsCalledWith256NumberOfBits() { final AtomicBoolean gdkCalled = new AtomicBoolean(false); AWSKMS kmsSpy = new FakeKMS() { @Override public GenerateDataKeyResult generateDataKey(GenerateDataKeyRequest r) { gdkCalled.set(true); assertEquals((Integer) 32, r.getNumberOfBytes()); assertNull(r.getKeySpec()); return super.generateDataKey(r); } }; assertFalse(gdkCalled.get()); new DirectKmsMaterialProvider(kmsSpy, keyId).getEncryptionMaterials(ctx); assertTrue(gdkCalled.get()); } @Test public void userAgentIsAdded() { AWSKMS kmsSpy = new FakeKMS() { @Override public GenerateDataKeyResult generateDataKey(GenerateDataKeyRequest r) { assertTrue( r.getRequestClientOptions() .getClientMarker(RequestClientOptions.Marker.USER_AGENT) .contains(DirectKmsMaterialProvider.USER_AGENT_PREFIX)); return super.generateDataKey(r); } }; new DirectKmsMaterialProvider(kmsSpy, keyId).getEncryptionMaterials(ctx); } private static class ExtendedKmsMaterialProvider extends DirectKmsMaterialProvider { private final String encryptionKeyIdAttributeName; public ExtendedKmsMaterialProvider( AWSKMS kms, String encryptionKeyId, String encryptionKeyIdAttributeName) { super(kms, encryptionKeyId); this.encryptionKeyIdAttributeName = encryptionKeyIdAttributeName; } @Override protected String selectEncryptionKeyId(EncryptionContext context) throws DynamoDBMappingException { if (!context.getAttributeValues().containsKey(encryptionKeyIdAttributeName)) { throw new DynamoDBMappingException("encryption key attribute is not provided"); } return context.getAttributeValues().get(encryptionKeyIdAttributeName).getS(); } @Override protected void validateEncryptionKeyId(String encryptionKeyId, EncryptionContext context) throws DynamoDBMappingException { if (!context.getAttributeValues().containsKey(encryptionKeyIdAttributeName)) { throw new DynamoDBMappingException("encryption key attribute is not provided"); } String customEncryptionKeyId = context.getAttributeValues().get(encryptionKeyIdAttributeName).getS(); if (!customEncryptionKeyId.equals(encryptionKeyId)) { throw new DynamoDBMappingException("encryption key ids do not match."); } } @Override protected DecryptResult decrypt(DecryptRequest request, EncryptionContext context) { return super.decrypt(request, context); } @Override protected GenerateDataKeyResult generateDataKey( GenerateDataKeyRequest request, EncryptionContext context) { return super.generateDataKey(request, context); } } private static EncryptionContext ctx(EncryptionMaterials mat) { return new EncryptionContext.Builder() .withMaterialDescription(mat.getMaterialDescription()) .build(); } }
4,294
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/KeyStoreMaterialsProviderTest.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.fail; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials; import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils; import com.amazonaws.util.Base64; import java.io.ByteArrayInputStream; import java.security.KeyFactory; import java.security.KeyStore; import java.security.KeyStore.PasswordProtection; import java.security.KeyStore.PrivateKeyEntry; import java.security.KeyStore.SecretKeyEntry; import java.security.PrivateKey; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.spec.PKCS8EncodedKeySpec; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class KeyStoreMaterialsProviderTest { private static final String certPem = "MIIDbTCCAlWgAwIBAgIJANdRvzVsW1CIMA0GCSqGSIb3DQEBBQUAME0xCzAJBgNV" + "BAYTAlVTMRMwEQYDVQQIDApXYXNoaW5ndG9uMQwwCgYDVQQKDANBV1MxGzAZBgNV" + "BAMMEktleVN0b3JlIFRlc3QgQ2VydDAeFw0xMzA1MDgyMzMyMjBaFw0xMzA2MDcy" + "MzMyMjBaME0xCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApXYXNoaW5ndG9uMQwwCgYD" + "VQQKDANBV1MxGzAZBgNVBAMMEktleVN0b3JlIFRlc3QgQ2VydDCCASIwDQYJKoZI" + "hvcNAQEBBQADggEPADCCAQoCggEBAJ8+umOX8x/Ma4OZishtYpcA676bwK5KScf3" + "w+YGM37L12KTdnOyieiGtRW8p0fS0YvnhmVTvaky09I33bH+qy9gliuNL2QkyMxp" + "uu1IwkTKKuB67CaKT6osYJLFxV/OwHcaZnTszzDgbAVg/Z+8IZxhPgxMzMa+7nDn" + "hEm9Jd+EONq3PnRagnFeLNbMIePprdJzXHyNNiZKRRGQ/Mo9rr7mqMLSKnFNsmzB" + "OIfeZM8nXeg+cvlmtXl72obwnGGw2ksJfaxTPm4eEhzRoAgkbjPPLHbwiJlc+GwF" + "i8kh0Y3vQTj/gOFE4nzipkm7ux1lsGHNRVpVDWpjNd8Fl9JFELkCAwEAAaNQME4w" + "HQYDVR0OBBYEFM0oGUuFAWlLXZaMXoJgGZxWqfOxMB8GA1UdIwQYMBaAFM0oGUuF" + "AWlLXZaMXoJgGZxWqfOxMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEB" + "AAXCsXeC8ZRxovP0Wc6C5qv3d7dtgJJVzHwoIRt2YR3yScBa1XI40GKT80jP3MYH" + "8xMu3mBQtcYrgRKZBy4GpHAyxoFTnPcuzq5Fg7dw7fx4E4OKIbWOahdxwtbVxQfZ" + "UHnGG88Z0bq2twj7dALGyJhUDdiccckJGmJPOFMzjqsvoAu0n/p7eS6y5WZ5ewqw" + "p7VwYOP3N9wVV7Podmkh1os+eCcp9GoFf0MHBMFXi2Ps2azKx8wHRIA5D1MZv/Va" + "4L4/oTBKCjORpFlP7EhMksHBYnjqXLDP6awPMAgQNYB5J9zX6GfJsAgly3t4Rjr5" + "cLuNYBmRuByFGo+SOdrj6D8="; private static final String keyPem = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCfPrpjl/MfzGuD" + "mYrIbWKXAOu+m8CuSknH98PmBjN+y9dik3ZzsonohrUVvKdH0tGL54ZlU72pMtPS" + "N92x/qsvYJYrjS9kJMjMabrtSMJEyirgeuwmik+qLGCSxcVfzsB3GmZ07M8w4GwF" + "YP2fvCGcYT4MTMzGvu5w54RJvSXfhDjatz50WoJxXizWzCHj6a3Sc1x8jTYmSkUR" + "kPzKPa6+5qjC0ipxTbJswTiH3mTPJ13oPnL5ZrV5e9qG8JxhsNpLCX2sUz5uHhIc" + "0aAIJG4zzyx28IiZXPhsBYvJIdGN70E4/4DhROJ84qZJu7sdZbBhzUVaVQ1qYzXf" + "BZfSRRC5AgMBAAECggEBAJMwx9eGe5LIwBfDtCPN93LbxwtHq7FtuQS8XrYexTpN" + "76eN5c7LF+11lauh1HzuwAEw32iJHqVl9aQ5PxFm85O3ExbuSP+ngHJwx/bLacVr" + "mHYlKGH3Net1WU5Qvz7vO7bbEBjDSj9DMJVIMSWUHv0MZO25jw2lLX/ufrgpvPf7" + "KXSgXg/8uV7PbnTbBDNlg02u8eOc+IbH4O8XDKAhD+YQ8AE3pxtopJbb912U/cJs" + "Y0hQ01zbkWYH7wL9BeQmR7+TEjjtr/IInNjnXmaOmSX867/rTSTuozaVrl1Ce7r8" + "EmUDg9ZLZeKfoNYovMy08wnxWVX2J+WnNDjNiSOm+IECgYEA0v3jtGrOnKbd0d9E" + "dbyIuhjgnwp+UsgALIiBeJYjhFS9NcWgs+02q/0ztqOK7g088KBBQOmiA+frLIVb" + "uNCt/3jF6kJvHYkHMZ0eBEstxjVSM2UcxzJ6ceHZ68pmrru74382TewVosxccNy0" + "glsUWNN0t5KQDcetaycRYg50MmcCgYEAwTb8klpNyQE8AWxVQlbOIEV24iarXxex" + "7HynIg9lSeTzquZOXjp0m5omQ04psil2gZ08xjiudG+Dm7QKgYQcxQYUtZPQe15K" + "m+2hQM0jA7tRfM1NAZHoTmUlYhzRNX6GWAqQXOgjOqBocT4ySBXRaSQq9zuZu36s" + "fI17knap798CgYArDa2yOf0xEAfBdJqmn7MSrlLfgSenwrHuZGhu78wNi7EUUOBq" + "9qOqUr+DrDmEO+VMgJbwJPxvaZqeehPuUX6/26gfFjFQSI7UO+hNHf4YLPc6D47g" + "wtcjd9+c8q8jRqGfWWz+V4dOsf7G9PJMi0NKoNN3RgvpE+66J72vUZ26TwKBgEUq" + "DdfGA7pEetp3kT2iHT9oHlpuRUJRFRv2s015/WQqVR+EOeF5Q2zADZpiTIK+XPGg" + "+7Rpbem4UYBXPruGM1ZECv3E4AiJhGO0+Nhdln8reswWIc7CEEqf4nXwouNnW2gA" + "wBTB9Hp0GW8QOKedR80/aTH/X9TCT7R2YRnY6JQ5AoGBAKjgPySgrNDhlJkW7jXR" + "WiGpjGSAFPT9NMTvEHDo7oLTQ8AcYzcGQ7ISMRdVXR6GJOlFVsH4NLwuHGtcMTPK" + "zoHbPHJyOn1SgC5tARD/1vm5CsG2hATRpWRQCTJFg5VRJ4R7Pz+HuxY4SoABcPQd" + "K+MP8GlGqTldC6NaB1s7KuAX"; private static SecretKey encryptionKey; private static SecretKey macKey; private static KeyStore keyStore; private static final String password = "Password"; private static final PasswordProtection passwordProtection = new PasswordProtection(password.toCharArray()); private Map<String, String> description; private EncryptionContext ctx; private static PrivateKey privateKey; private static Certificate certificate; @BeforeClass public static void setUpBeforeClass() throws Exception { KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256"); macGen.init(256, Utils.getRng()); macKey = macGen.generateKey(); KeyGenerator aesGen = KeyGenerator.getInstance("AES"); aesGen.init(128, Utils.getRng()); encryptionKey = aesGen.generateKey(); keyStore = KeyStore.getInstance("jceks"); keyStore.load(null, password.toCharArray()); KeyFactory kf = KeyFactory.getInstance("RSA"); PKCS8EncodedKeySpec rsaSpec = new PKCS8EncodedKeySpec(Base64.decode(keyPem)); privateKey = kf.generatePrivate(rsaSpec); CertificateFactory cf = CertificateFactory.getInstance("X509"); certificate = cf.generateCertificate(new ByteArrayInputStream(Base64.decode(certPem))); keyStore.setEntry("enc", new SecretKeyEntry(encryptionKey), passwordProtection); keyStore.setEntry("sig", new SecretKeyEntry(macKey), passwordProtection); keyStore.setEntry( "enc-a", new PrivateKeyEntry(privateKey, new Certificate[] {certificate}), passwordProtection); keyStore.setEntry( "sig-a", new PrivateKeyEntry(privateKey, new Certificate[] {certificate}), passwordProtection); keyStore.setCertificateEntry("trustedCert", certificate); } @BeforeMethod public void setUp() { description = new HashMap<String, String>(); description.put("TestKey", "test value"); description = Collections.unmodifiableMap(description); ctx = new EncryptionContext.Builder().build(); } @Test @SuppressWarnings("unchecked") public void simpleSymMac() throws Exception { KeyStoreMaterialsProvider prov = new KeyStoreMaterialsProvider( keyStore, "enc", "sig", passwordProtection, passwordProtection, Collections.EMPTY_MAP); EncryptionMaterials encryptionMaterials = prov.getEncryptionMaterials(ctx); assertEquals(encryptionKey, encryptionMaterials.getEncryptionKey()); assertEquals(macKey, encryptionMaterials.getSigningKey()); assertEquals( encryptionKey, prov.getDecryptionMaterials(ctx(encryptionMaterials)).getDecryptionKey()); assertEquals( macKey, prov.getDecryptionMaterials(ctx(encryptionMaterials)).getVerificationKey()); } @Test @SuppressWarnings("unchecked") public void simpleSymSig() throws Exception { KeyStoreMaterialsProvider prov = new KeyStoreMaterialsProvider( keyStore, "enc", "sig-a", passwordProtection, passwordProtection, Collections.EMPTY_MAP); EncryptionMaterials encryptionMaterials = prov.getEncryptionMaterials(ctx); assertEquals(encryptionKey, encryptionMaterials.getEncryptionKey()); assertEquals(privateKey, encryptionMaterials.getSigningKey()); assertEquals( encryptionKey, prov.getDecryptionMaterials(ctx(encryptionMaterials)).getDecryptionKey()); assertEquals( certificate.getPublicKey(), prov.getDecryptionMaterials(ctx(encryptionMaterials)).getVerificationKey()); } @Test public void equalSymDescMac() throws Exception { KeyStoreMaterialsProvider prov = new KeyStoreMaterialsProvider( keyStore, "enc", "sig", passwordProtection, passwordProtection, description); EncryptionMaterials encryptionMaterials = prov.getEncryptionMaterials(ctx); assertEquals(encryptionKey, encryptionMaterials.getEncryptionKey()); assertEquals(macKey, encryptionMaterials.getSigningKey()); assertEquals( encryptionKey, prov.getDecryptionMaterials(ctx(encryptionMaterials)).getDecryptionKey()); assertEquals( macKey, prov.getDecryptionMaterials(ctx(encryptionMaterials)).getVerificationKey()); } @Test public void superSetSymDescMac() throws Exception { KeyStoreMaterialsProvider prov = new KeyStoreMaterialsProvider( keyStore, "enc", "sig", passwordProtection, passwordProtection, description); EncryptionMaterials encryptionMaterials = prov.getEncryptionMaterials(ctx); assertEquals(encryptionKey, encryptionMaterials.getEncryptionKey()); assertEquals(macKey, encryptionMaterials.getSigningKey()); Map<String, String> tmpDesc = new HashMap<String, String>(encryptionMaterials.getMaterialDescription()); tmpDesc.put("randomValue", "random"); assertEquals(encryptionKey, prov.getDecryptionMaterials(ctx(tmpDesc)).getDecryptionKey()); assertEquals(macKey, prov.getDecryptionMaterials(ctx(tmpDesc)).getVerificationKey()); } @Test @SuppressWarnings("unchecked") public void subSetSymDescMac() throws Exception { KeyStoreMaterialsProvider prov = new KeyStoreMaterialsProvider( keyStore, "enc", "sig", passwordProtection, passwordProtection, description); EncryptionMaterials encryptionMaterials = prov.getEncryptionMaterials(ctx); assertEquals(encryptionKey, encryptionMaterials.getEncryptionKey()); assertEquals(macKey, encryptionMaterials.getSigningKey()); assertNull(prov.getDecryptionMaterials(ctx(Collections.EMPTY_MAP))); } @Test public void noMatchSymDescMac() throws Exception { KeyStoreMaterialsProvider prov = new KeyStoreMaterialsProvider( keyStore, "enc", "sig", passwordProtection, passwordProtection, description); EncryptionMaterials encryptionMaterials = prov.getEncryptionMaterials(ctx); assertEquals(encryptionKey, encryptionMaterials.getEncryptionKey()); assertEquals(macKey, encryptionMaterials.getSigningKey()); Map<String, String> tmpDesc = new HashMap<String, String>(); tmpDesc.put("randomValue", "random"); assertNull(prov.getDecryptionMaterials(ctx(tmpDesc))); } @Test public void testRefresh() throws Exception { // Mostly make sure we don't throw an exception KeyStoreMaterialsProvider prov = new KeyStoreMaterialsProvider( keyStore, "enc", "sig", passwordProtection, passwordProtection, description); prov.refresh(); } @Test public void asymSimpleMac() throws Exception { KeyStoreMaterialsProvider prov = new KeyStoreMaterialsProvider( keyStore, "enc-a", "sig", passwordProtection, passwordProtection, description); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); assertEquals(macKey, eMat.getSigningKey()); DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(macKey, dMat.getVerificationKey()); } @Test public void asymSimpleSig() throws Exception { KeyStoreMaterialsProvider prov = new KeyStoreMaterialsProvider( keyStore, "enc-a", "sig-a", passwordProtection, passwordProtection, description); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); assertEquals(privateKey, eMat.getSigningKey()); DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(certificate.getPublicKey(), dMat.getVerificationKey()); } @Test public void asymSigVerifyOnly() throws Exception { KeyStoreMaterialsProvider prov = new KeyStoreMaterialsProvider( keyStore, "enc-a", "trustedCert", passwordProtection, null, description); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); assertNull(eMat.getSigningKey()); DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(certificate.getPublicKey(), dMat.getVerificationKey()); } @Test public void asymSigEncryptOnly() throws Exception { KeyStoreMaterialsProvider prov = new KeyStoreMaterialsProvider( keyStore, "trustedCert", "sig-a", null, passwordProtection, description); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); assertEquals(privateKey, eMat.getSigningKey()); try { prov.getDecryptionMaterials(ctx(eMat)); fail("Expected exception"); } catch (IllegalStateException ex) { assertEquals("No private decryption key provided.", ex.getMessage()); } } private static EncryptionContext ctx(EncryptionMaterials mat) { return ctx(mat.getMaterialDescription()); } private static EncryptionContext ctx(Map<String, String> desc) { return new EncryptionContext.Builder().withMaterialDescription(desc).build(); } }
4,295
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/SymmetricStaticProviderTest.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials; import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class SymmetricStaticProviderTest { private static SecretKey encryptionKey; private static SecretKey macKey; private static KeyPair sigPair; private Map<String, String> description; private EncryptionContext ctx; @BeforeClass public static void setUpClass() throws Exception { KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA"); rsaGen.initialize(2048, Utils.getRng()); sigPair = rsaGen.generateKeyPair(); KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256"); macGen.init(256, Utils.getRng()); macKey = macGen.generateKey(); KeyGenerator aesGen = KeyGenerator.getInstance("AES"); aesGen.init(128, Utils.getRng()); encryptionKey = aesGen.generateKey(); } @BeforeMethod public void setUp() { description = new HashMap<String, String>(); description.put("TestKey", "test value"); description = Collections.unmodifiableMap(description); ctx = new EncryptionContext.Builder().build(); } @Test public void simpleMac() { SymmetricStaticProvider prov = new SymmetricStaticProvider(encryptionKey, macKey, Collections.<String, String>emptyMap()); assertEquals(encryptionKey, prov.getEncryptionMaterials(ctx).getEncryptionKey()); assertEquals(macKey, prov.getEncryptionMaterials(ctx).getSigningKey()); assertEquals( encryptionKey, prov.getDecryptionMaterials(ctx(Collections.<String, String>emptyMap())) .getDecryptionKey()); assertEquals( macKey, prov.getDecryptionMaterials(ctx(Collections.<String, String>emptyMap())) .getVerificationKey()); } @Test public void simpleSig() { SymmetricStaticProvider prov = new SymmetricStaticProvider(encryptionKey, sigPair, Collections.<String, String>emptyMap()); assertEquals(encryptionKey, prov.getEncryptionMaterials(ctx).getEncryptionKey()); assertEquals(sigPair.getPrivate(), prov.getEncryptionMaterials(ctx).getSigningKey()); assertEquals( encryptionKey, prov.getDecryptionMaterials(ctx(Collections.<String, String>emptyMap())) .getDecryptionKey()); assertEquals( sigPair.getPublic(), prov.getDecryptionMaterials(ctx(Collections.<String, String>emptyMap())) .getVerificationKey()); } @Test public void equalDescMac() { SymmetricStaticProvider prov = new SymmetricStaticProvider(encryptionKey, macKey, description); assertEquals(encryptionKey, prov.getEncryptionMaterials(ctx).getEncryptionKey()); assertEquals(macKey, prov.getEncryptionMaterials(ctx).getSigningKey()); assertTrue( prov.getEncryptionMaterials(ctx) .getMaterialDescription() .entrySet() .containsAll(description.entrySet())); assertEquals(encryptionKey, prov.getDecryptionMaterials(ctx(description)).getDecryptionKey()); assertEquals(macKey, prov.getDecryptionMaterials(ctx(description)).getVerificationKey()); } @Test public void supersetDescMac() { SymmetricStaticProvider prov = new SymmetricStaticProvider(encryptionKey, macKey, description); assertEquals(encryptionKey, prov.getEncryptionMaterials(ctx).getEncryptionKey()); assertEquals(macKey, prov.getEncryptionMaterials(ctx).getSigningKey()); assertTrue( prov.getEncryptionMaterials(ctx) .getMaterialDescription() .entrySet() .containsAll(description.entrySet())); Map<String, String> superSet = new HashMap<String, String>(description); superSet.put("NewValue", "super!"); assertEquals(encryptionKey, prov.getDecryptionMaterials(ctx(superSet)).getDecryptionKey()); assertEquals(macKey, prov.getDecryptionMaterials(ctx(superSet)).getVerificationKey()); } @Test public void subsetDescMac() { SymmetricStaticProvider prov = new SymmetricStaticProvider(encryptionKey, macKey, description); assertEquals(encryptionKey, prov.getEncryptionMaterials(ctx).getEncryptionKey()); assertEquals(macKey, prov.getEncryptionMaterials(ctx).getSigningKey()); assertTrue( prov.getEncryptionMaterials(ctx) .getMaterialDescription() .entrySet() .containsAll(description.entrySet())); assertNull(prov.getDecryptionMaterials(ctx(Collections.<String, String>emptyMap()))); } @Test public void noMatchDescMac() { SymmetricStaticProvider prov = new SymmetricStaticProvider(encryptionKey, macKey, description); assertEquals(encryptionKey, prov.getEncryptionMaterials(ctx).getEncryptionKey()); assertEquals(macKey, prov.getEncryptionMaterials(ctx).getSigningKey()); assertTrue( prov.getEncryptionMaterials(ctx) .getMaterialDescription() .entrySet() .containsAll(description.entrySet())); Map<String, String> noMatch = new HashMap<String, String>(); noMatch.put("NewValue", "no match!"); assertNull(prov.getDecryptionMaterials(ctx(noMatch))); } @Test public void testRefresh() { // This does nothing, make sure we don't throw and exception. SymmetricStaticProvider prov = new SymmetricStaticProvider(encryptionKey, macKey, description); prov.refresh(); } @SuppressWarnings("unused") private static EncryptionContext ctx(EncryptionMaterials mat) { return ctx(mat.getMaterialDescription()); } private static EncryptionContext ctx(Map<String, String> desc) { return new EncryptionContext.Builder().withMaterialDescription(desc).build(); } }
4,296
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/AsymmetricStaticProviderTest.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials; import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class AsymmetricStaticProviderTest { private static KeyPair encryptionPair; private static SecretKey macKey; private static KeyPair sigPair; private Map<String, String> description; private EncryptionContext ctx; @BeforeClass public static void setUpClass() throws Exception { KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA"); rsaGen.initialize(2048, Utils.getRng()); sigPair = rsaGen.generateKeyPair(); encryptionPair = rsaGen.generateKeyPair(); KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256"); macGen.init(256, Utils.getRng()); macKey = macGen.generateKey(); } @BeforeMethod public void setUp() { description = new HashMap<String, String>(); description.put("TestKey", "test value"); description = Collections.unmodifiableMap(description); ctx = new EncryptionContext.Builder().build(); } @Test public void constructWithMac() throws GeneralSecurityException { AsymmetricStaticProvider prov = new AsymmetricStaticProvider( encryptionPair, macKey, Collections.<String, String>emptyMap()); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); assertEquals(macKey, eMat.getSigningKey()); DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(macKey, dMat.getVerificationKey()); } @Test public void constructWithSigPair() throws GeneralSecurityException { AsymmetricStaticProvider prov = new AsymmetricStaticProvider( encryptionPair, sigPair, Collections.<String, String>emptyMap()); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); assertEquals(sigPair.getPrivate(), eMat.getSigningKey()); DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(sigPair.getPublic(), dMat.getVerificationKey()); } @Test public void randomEnvelopeKeys() throws GeneralSecurityException { AsymmetricStaticProvider prov = new AsymmetricStaticProvider( encryptionPair, macKey, Collections.<String, String>emptyMap()); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); assertEquals(macKey, eMat.getSigningKey()); EncryptionMaterials eMat2 = prov.getEncryptionMaterials(ctx); SecretKey encryptionKey2 = eMat2.getEncryptionKey(); assertEquals(macKey, eMat.getSigningKey()); assertFalse("Envelope keys must be different", encryptionKey.equals(encryptionKey2)); } @Test public void testRefresh() { // This does nothing, make sure we don't throw and exception. AsymmetricStaticProvider prov = new AsymmetricStaticProvider(encryptionPair, macKey, description); prov.refresh(); } private static EncryptionContext ctx(EncryptionMaterials mat) { return new EncryptionContext.Builder() .withMaterialDescription(mat.getMaterialDescription()) .build(); } }
4,297
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/WrappedMaterialsProviderTest.java
package com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.WrappedRawMaterials; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class WrappedMaterialsProviderTest { private static SecretKey symEncryptionKey; private static SecretKey macKey; private static KeyPair sigPair; private static KeyPair encryptionPair; private static SecureRandom rnd; private Map<String, String> description; private EncryptionContext ctx; @BeforeClass public static void setUpClass() throws NoSuchAlgorithmException { rnd = new SecureRandom(); KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA"); rsaGen.initialize(2048, rnd); sigPair = rsaGen.generateKeyPair(); encryptionPair = rsaGen.generateKeyPair(); KeyGenerator aesGen = KeyGenerator.getInstance("AES"); aesGen.init(128, rnd); symEncryptionKey = aesGen.generateKey(); KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256"); macGen.init(256, rnd); macKey = macGen.generateKey(); } @BeforeMethod public void setUp() { description = new HashMap<String, String>(); description.put("TestKey", "test value"); ctx = new EncryptionContext.Builder().build(); } @Test public void simpleMac() throws GeneralSecurityException { WrappedMaterialsProvider prov = new WrappedMaterialsProvider( symEncryptionKey, symEncryptionKey, macKey, Collections.emptyMap()); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey contentEncryptionKey = eMat.getEncryptionKey(); assertNotNull(contentEncryptionKey); assertEquals(macKey, eMat.getSigningKey()); DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals(contentEncryptionKey, dMat.getDecryptionKey()); assertEquals(macKey, dMat.getVerificationKey()); } @Test public void simpleSigPair() throws GeneralSecurityException { WrappedMaterialsProvider prov = new WrappedMaterialsProvider( symEncryptionKey, symEncryptionKey, sigPair, Collections.emptyMap()); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey contentEncryptionKey = eMat.getEncryptionKey(); assertNotNull(contentEncryptionKey); assertEquals(sigPair.getPrivate(), eMat.getSigningKey()); DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals(contentEncryptionKey, dMat.getDecryptionKey()); assertEquals(sigPair.getPublic(), dMat.getVerificationKey()); } @Test public void randomEnvelopeKeys() throws GeneralSecurityException { WrappedMaterialsProvider prov = new WrappedMaterialsProvider( symEncryptionKey, symEncryptionKey, macKey, Collections.emptyMap()); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey contentEncryptionKey = eMat.getEncryptionKey(); assertNotNull(contentEncryptionKey); assertEquals(macKey, eMat.getSigningKey()); EncryptionMaterials eMat2 = prov.getEncryptionMaterials(ctx); SecretKey contentEncryptionKey2 = eMat2.getEncryptionKey(); assertEquals(macKey, eMat.getSigningKey()); assertFalse( "Envelope keys must be different", contentEncryptionKey.equals(contentEncryptionKey2)); } @Test public void testRefresh() { // This does nothing, make sure we don't throw an exception. WrappedMaterialsProvider prov = new WrappedMaterialsProvider( symEncryptionKey, symEncryptionKey, macKey, Collections.emptyMap()); prov.refresh(); } @Test public void wrapUnwrapAsymMatExplicitWrappingAlgorithmPkcs1() throws GeneralSecurityException { Map<String, String> desc = new HashMap<String, String>(); desc.put(WrappedRawMaterials.KEY_WRAPPING_ALGORITHM, "RSA/ECB/PKCS1Padding"); WrappedMaterialsProvider prov = new WrappedMaterialsProvider( encryptionPair.getPublic(), encryptionPair.getPrivate(), sigPair, desc); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey contentEncryptionKey = eMat.getEncryptionKey(); assertNotNull(contentEncryptionKey); assertEquals(sigPair.getPrivate(), eMat.getSigningKey()); DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals( "RSA/ECB/PKCS1Padding", eMat.getMaterialDescription().get(WrappedRawMaterials.KEY_WRAPPING_ALGORITHM)); assertEquals(contentEncryptionKey, dMat.getDecryptionKey()); assertEquals(sigPair.getPublic(), dMat.getVerificationKey()); } @Test public void wrapUnwrapAsymMatExplicitWrappingAlgorithmPkcs2() throws GeneralSecurityException { Map<String, String> desc = new HashMap<String, String>(); desc.put(WrappedRawMaterials.KEY_WRAPPING_ALGORITHM, "RSA/ECB/OAEPWithSHA-256AndMGF1Padding"); WrappedMaterialsProvider prov = new WrappedMaterialsProvider( encryptionPair.getPublic(), encryptionPair.getPrivate(), sigPair, desc); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey contentEncryptionKey = eMat.getEncryptionKey(); assertNotNull(contentEncryptionKey); assertEquals(sigPair.getPrivate(), eMat.getSigningKey()); DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals( "RSA/ECB/OAEPWithSHA-256AndMGF1Padding", eMat.getMaterialDescription().get(WrappedRawMaterials.KEY_WRAPPING_ALGORITHM)); assertEquals(contentEncryptionKey, dMat.getDecryptionKey()); assertEquals(sigPair.getPublic(), dMat.getVerificationKey()); } @Test public void wrapUnwrapAsymMatExplicitContentKeyAlgorithm() throws GeneralSecurityException { Map<String, String> desc = new HashMap<String, String>(); desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES"); WrappedMaterialsProvider prov = new WrappedMaterialsProvider( encryptionPair.getPublic(), encryptionPair.getPrivate(), sigPair, Collections.emptyMap()); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey contentEncryptionKey = eMat.getEncryptionKey(); assertNotNull(contentEncryptionKey); assertEquals("AES", contentEncryptionKey.getAlgorithm()); assertEquals( "AES", eMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM)); assertEquals(sigPair.getPrivate(), eMat.getSigningKey()); DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals( "AES", dMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM)); assertEquals(contentEncryptionKey, dMat.getDecryptionKey()); assertEquals(sigPair.getPublic(), dMat.getVerificationKey()); } @Test public void wrapUnwrapAsymMatExplicitContentKeyLength128() throws GeneralSecurityException { Map<String, String> desc = new HashMap<String, String>(); desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/128"); WrappedMaterialsProvider prov = new WrappedMaterialsProvider( encryptionPair.getPublic(), encryptionPair.getPrivate(), sigPair, desc); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey contentEncryptionKey = eMat.getEncryptionKey(); assertNotNull(contentEncryptionKey); assertEquals("AES", contentEncryptionKey.getAlgorithm()); assertEquals( "AES", eMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM)); assertEquals(16, contentEncryptionKey.getEncoded().length); // 128 Bits assertEquals(sigPair.getPrivate(), eMat.getSigningKey()); DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals( "AES", dMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM)); assertEquals(contentEncryptionKey, dMat.getDecryptionKey()); assertEquals(sigPair.getPublic(), dMat.getVerificationKey()); } @Test public void wrapUnwrapAsymMatExplicitContentKeyLength256() throws GeneralSecurityException { Map<String, String> desc = new HashMap<String, String>(); desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/256"); WrappedMaterialsProvider prov = new WrappedMaterialsProvider( encryptionPair.getPublic(), encryptionPair.getPrivate(), sigPair, desc); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey contentEncryptionKey = eMat.getEncryptionKey(); assertNotNull(contentEncryptionKey); assertEquals("AES", contentEncryptionKey.getAlgorithm()); assertEquals( "AES", eMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM)); assertEquals(32, contentEncryptionKey.getEncoded().length); // 256 Bits assertEquals(sigPair.getPrivate(), eMat.getSigningKey()); DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals( "AES", dMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM)); assertEquals(contentEncryptionKey, dMat.getDecryptionKey()); assertEquals(sigPair.getPublic(), dMat.getVerificationKey()); } @Test public void unwrapAsymMatExplicitEncAlgAes128() throws GeneralSecurityException { Map<String, String> desc = new HashMap<String, String>(); desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/128"); WrappedMaterialsProvider prov = new WrappedMaterialsProvider( encryptionPair.getPublic(), encryptionPair.getPrivate(), sigPair, desc); // Get materials we can test unwrapping on EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); // Ensure "AES/128" on the created materials creates the expected key Map<String, String> aes128Desc = eMat.getMaterialDescription(); aes128Desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/128"); EncryptionContext aes128Ctx = new EncryptionContext.Builder().withMaterialDescription(aes128Desc).build(); DecryptionMaterials dMat = prov.getDecryptionMaterials(aes128Ctx); assertEquals( "AES/128", dMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM)); assertEquals("AES", dMat.getDecryptionKey().getAlgorithm()); assertEquals(eMat.getEncryptionKey(), dMat.getDecryptionKey()); assertEquals(sigPair.getPublic(), dMat.getVerificationKey()); } @Test public void unwrapAsymMatExplicitEncAlgAes256() throws GeneralSecurityException { Map<String, String> desc = new HashMap<String, String>(); desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/256"); WrappedMaterialsProvider prov = new WrappedMaterialsProvider( encryptionPair.getPublic(), encryptionPair.getPrivate(), sigPair, desc); // Get materials we can test unwrapping on EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); // Ensure "AES/256" on the created materials creates the expected key Map<String, String> aes256Desc = eMat.getMaterialDescription(); aes256Desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/256"); EncryptionContext aes256Ctx = new EncryptionContext.Builder().withMaterialDescription(aes256Desc).build(); DecryptionMaterials dMat = prov.getDecryptionMaterials(aes256Ctx); assertEquals( "AES/256", dMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM)); assertEquals("AES", dMat.getDecryptionKey().getAlgorithm()); assertEquals(eMat.getEncryptionKey(), dMat.getDecryptionKey()); assertEquals(sigPair.getPublic(), dMat.getVerificationKey()); } @Test public void wrapUnwrapSymMatExplicitContentKeyAlgorithm() throws GeneralSecurityException { Map<String, String> desc = new HashMap<String, String>(); desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES"); WrappedMaterialsProvider prov = new WrappedMaterialsProvider(symEncryptionKey, symEncryptionKey, macKey, desc); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey contentEncryptionKey = eMat.getEncryptionKey(); assertNotNull(contentEncryptionKey); assertEquals("AES", contentEncryptionKey.getAlgorithm()); assertEquals( "AES", eMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM)); assertEquals(macKey, eMat.getSigningKey()); DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals( "AES", dMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM)); assertEquals(contentEncryptionKey, dMat.getDecryptionKey()); assertEquals(macKey, dMat.getVerificationKey()); } @Test public void wrapUnwrapSymMatExplicitContentKeyLength128() throws GeneralSecurityException { Map<String, String> desc = new HashMap<String, String>(); desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/128"); WrappedMaterialsProvider prov = new WrappedMaterialsProvider(symEncryptionKey, symEncryptionKey, macKey, desc); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey contentEncryptionKey = eMat.getEncryptionKey(); assertNotNull(contentEncryptionKey); assertEquals("AES", contentEncryptionKey.getAlgorithm()); assertEquals( "AES", eMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM)); assertEquals(16, contentEncryptionKey.getEncoded().length); // 128 Bits assertEquals(macKey, eMat.getSigningKey()); DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals( "AES", dMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM)); assertEquals(contentEncryptionKey, dMat.getDecryptionKey()); assertEquals(macKey, dMat.getVerificationKey()); } @Test public void wrapUnwrapSymMatExplicitContentKeyLength256() throws GeneralSecurityException { Map<String, String> desc = new HashMap<String, String>(); desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/256"); WrappedMaterialsProvider prov = new WrappedMaterialsProvider(symEncryptionKey, symEncryptionKey, macKey, desc); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey contentEncryptionKey = eMat.getEncryptionKey(); assertNotNull(contentEncryptionKey); assertEquals("AES", contentEncryptionKey.getAlgorithm()); assertEquals( "AES", eMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM)); assertEquals(32, contentEncryptionKey.getEncoded().length); // 256 Bits assertEquals(macKey, eMat.getSigningKey()); DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals( "AES", dMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM)); assertEquals(contentEncryptionKey, dMat.getDecryptionKey()); assertEquals(macKey, dMat.getVerificationKey()); } @Test public void unwrapSymMatExplicitEncAlgAes128() throws GeneralSecurityException { Map<String, String> desc = new HashMap<String, String>(); desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/128"); WrappedMaterialsProvider prov = new WrappedMaterialsProvider(symEncryptionKey, symEncryptionKey, macKey, desc); // Get materials we can test unwrapping on EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); // Ensure "AES/128" on the created materials creates the expected key Map<String, String> aes128Desc = eMat.getMaterialDescription(); aes128Desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/128"); EncryptionContext aes128Ctx = new EncryptionContext.Builder().withMaterialDescription(aes128Desc).build(); DecryptionMaterials dMat = prov.getDecryptionMaterials(aes128Ctx); assertEquals( "AES/128", dMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM)); assertEquals("AES", dMat.getDecryptionKey().getAlgorithm()); assertEquals(eMat.getEncryptionKey(), dMat.getDecryptionKey()); assertEquals(macKey, dMat.getVerificationKey()); } @Test public void unwrapSymMatExplicitEncAlgAes256() throws GeneralSecurityException { Map<String, String> desc = new HashMap<String, String>(); desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/256"); WrappedMaterialsProvider prov = new WrappedMaterialsProvider(symEncryptionKey, symEncryptionKey, macKey, desc); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); Map<String, String> aes256Desc = eMat.getMaterialDescription(); aes256Desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/256"); EncryptionContext aes256Ctx = new EncryptionContext.Builder().withMaterialDescription(aes256Desc).build(); DecryptionMaterials dMat = prov.getDecryptionMaterials(aes256Ctx); assertEquals( "AES/256", dMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM)); assertEquals("AES", dMat.getDecryptionKey().getAlgorithm()); assertEquals(eMat.getEncryptionKey(), dMat.getDecryptionKey()); assertEquals(macKey, dMat.getVerificationKey()); } private static EncryptionContext ctx(EncryptionMaterials mat) { return new EncryptionContext.Builder() .withMaterialDescription(mat.getMaterialDescription()) .build(); } }
4,298
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/CachingMostRecentProviderTests.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.store.MetaStore; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.store.ProviderStore; import com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class CachingMostRecentProviderTests { private static final String TABLE_NAME = "keystoreTable"; private static final String MATERIAL_NAME = "material"; private static final String MATERIAL_PARAM = "materialName"; private static final SecretKey AES_KEY = new SecretKeySpec(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, "AES"); private static final SecretKey HMAC_KEY = new SecretKeySpec(new byte[] {0, 1, 2, 3, 4, 5, 6, 7}, "HmacSHA256"); private static final EncryptionMaterialsProvider BASE_PROVIDER = new SymmetricStaticProvider(AES_KEY, HMAC_KEY); private static final DynamoDBEncryptor ENCRYPTOR = DynamoDBEncryptor.getInstance(BASE_PROVIDER); private AmazonDynamoDB client; private Map<String, Integer> methodCalls; private ProviderStore store; private EncryptionContext ctx; @BeforeMethod public void setup() { methodCalls = new HashMap<String, Integer>(); client = instrument(DynamoDBEmbedded.create(), AmazonDynamoDB.class, methodCalls); MetaStore.createTable(client, TABLE_NAME, new ProvisionedThroughput(1L, 1L)); store = new MetaStore(client, TABLE_NAME, ENCRYPTOR); ctx = new EncryptionContext.Builder().build(); methodCalls.clear(); } @Test public void testConstructors() { final CachingMostRecentProvider prov = new CachingMostRecentProvider(store, MATERIAL_NAME, 100, 1000); assertEquals(MATERIAL_NAME, prov.getMaterialName()); assertEquals(100, prov.getTtlInMills()); assertEquals(-1, prov.getCurrentVersion()); assertEquals(0, prov.getLastUpdated()); final CachingMostRecentProvider prov2 = new CachingMostRecentProvider(store, MATERIAL_NAME, 500); assertEquals(MATERIAL_NAME, prov2.getMaterialName()); assertEquals(500, prov2.getTtlInMills()); assertEquals(-1, prov2.getCurrentVersion()); assertEquals(0, prov2.getLastUpdated()); } @Test public void testSmallMaxCacheSize() { final Map<String, AttributeValue> attr1 = Collections.singletonMap(MATERIAL_PARAM, new AttributeValue("material1")); final EncryptionContext ctx1 = ctx(attr1); final Map<String, AttributeValue> attr2 = Collections.singletonMap(MATERIAL_PARAM, new AttributeValue("material2")); final EncryptionContext ctx2 = ctx(attr2); final CachingMostRecentProvider prov = new ExtendedProvider(store, 500, 1); assertNull(methodCalls.get("putItem")); final EncryptionMaterials eMat1_1 = prov.getEncryptionMaterials(ctx1); // It's a new provider, so we see a single putItem assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0)); methodCalls.clear(); final EncryptionMaterials eMat1_2 = prov.getEncryptionMaterials(ctx2); // It's a new provider, so we see a single putItem assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0)); methodCalls.clear(); // Ensure the two materials are, in fact, different assertFalse(eMat1_1.getSigningKey().equals(eMat1_2.getSigningKey())); // Ensure the second set of materials are cached final EncryptionMaterials eMat2_2 = prov.getEncryptionMaterials(ctx2); assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty()); // Ensure the first set of materials are no longer cached, due to being the LRU final EncryptionMaterials eMat2_1 = prov.getEncryptionMaterials(ctx1); assertEquals(1, (int) methodCalls.getOrDefault("query", 0)); // To find current version assertEquals(1, (int) methodCalls.getOrDefault("getItem", 0)); assertEquals(0, store.getVersionFromMaterialDescription(eMat1_2.getMaterialDescription())); assertEquals(0, store.getVersionFromMaterialDescription(eMat2_2.getMaterialDescription())); } @Test public void testSingleVersion() throws InterruptedException { final CachingMostRecentProvider prov = new CachingMostRecentProvider(store, MATERIAL_NAME, 500); assertNull(methodCalls.get("putItem")); final EncryptionMaterials eMat1 = prov.getEncryptionMaterials(ctx); // It's a new provider, so we see a single putItem assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0)); methodCalls.clear(); // Ensure the cache is working final EncryptionMaterials eMat2 = prov.getEncryptionMaterials(ctx); assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty()); assertEquals(0, store.getVersionFromMaterialDescription(eMat1.getMaterialDescription())); assertEquals(0, store.getVersionFromMaterialDescription(eMat2.getMaterialDescription())); // Let the TTL be exceeded Thread.sleep(500); final EncryptionMaterials eMat3 = prov.getEncryptionMaterials(ctx); assertEquals(2, methodCalls.size()); assertEquals(1, (int) methodCalls.getOrDefault("query", 0)); // To find current version assertEquals(1, (int) methodCalls.getOrDefault("getItem", 0)); // To get provider assertEquals(0, store.getVersionFromMaterialDescription(eMat3.getMaterialDescription())); assertEquals(eMat1.getSigningKey(), eMat2.getSigningKey()); assertEquals(eMat1.getSigningKey(), eMat3.getSigningKey()); // Check algorithms. Right now we only support AES and HmacSHA256 assertEquals("AES", eMat1.getEncryptionKey().getAlgorithm()); assertEquals("HmacSHA256", eMat1.getSigningKey().getAlgorithm()); // Ensure we can decrypt all of them without hitting ddb more than the minimum final CachingMostRecentProvider prov2 = new CachingMostRecentProvider(store, MATERIAL_NAME, 500); final DecryptionMaterials dMat1 = prov2.getDecryptionMaterials(ctx(eMat1)); methodCalls.clear(); assertEquals(eMat1.getEncryptionKey(), dMat1.getDecryptionKey()); assertEquals(eMat1.getSigningKey(), dMat1.getVerificationKey()); final DecryptionMaterials dMat2 = prov2.getDecryptionMaterials(ctx(eMat2)); assertEquals(eMat2.getEncryptionKey(), dMat2.getDecryptionKey()); assertEquals(eMat2.getSigningKey(), dMat2.getVerificationKey()); final DecryptionMaterials dMat3 = prov2.getDecryptionMaterials(ctx(eMat3)); assertEquals(eMat3.getEncryptionKey(), dMat3.getDecryptionKey()); assertEquals(eMat3.getSigningKey(), dMat3.getVerificationKey()); assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty()); } @Test public void testSingleVersionWithRefresh() throws InterruptedException { final CachingMostRecentProvider prov = new CachingMostRecentProvider(store, MATERIAL_NAME, 500); assertNull(methodCalls.get("putItem")); final EncryptionMaterials eMat1 = prov.getEncryptionMaterials(ctx); // It's a new provider, so we see a single putItem assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0)); methodCalls.clear(); // Ensure the cache is working final EncryptionMaterials eMat2 = prov.getEncryptionMaterials(ctx); assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty()); assertEquals(0, store.getVersionFromMaterialDescription(eMat1.getMaterialDescription())); assertEquals(0, store.getVersionFromMaterialDescription(eMat2.getMaterialDescription())); prov.refresh(); final EncryptionMaterials eMat3 = prov.getEncryptionMaterials(ctx); assertEquals(1, (int) methodCalls.getOrDefault("query", 0)); // To find current version assertEquals(1, (int) methodCalls.getOrDefault("getItem", 0)); assertEquals(0, store.getVersionFromMaterialDescription(eMat3.getMaterialDescription())); prov.refresh(); assertEquals(eMat1.getSigningKey(), eMat2.getSigningKey()); assertEquals(eMat1.getSigningKey(), eMat3.getSigningKey()); // Ensure that after cache refresh we only get one more hit as opposed to multiple prov.getEncryptionMaterials(ctx); Thread.sleep(700); // Force refresh prov.getEncryptionMaterials(ctx); methodCalls.clear(); // Check to ensure no more hits assertEquals(eMat1.getSigningKey(), prov.getEncryptionMaterials(ctx).getSigningKey()); assertEquals(eMat1.getSigningKey(), prov.getEncryptionMaterials(ctx).getSigningKey()); assertEquals(eMat1.getSigningKey(), prov.getEncryptionMaterials(ctx).getSigningKey()); assertEquals(eMat1.getSigningKey(), prov.getEncryptionMaterials(ctx).getSigningKey()); assertEquals(eMat1.getSigningKey(), prov.getEncryptionMaterials(ctx).getSigningKey()); assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty()); // Ensure we can decrypt all of them without hitting ddb more than the minimum final CachingMostRecentProvider prov2 = new CachingMostRecentProvider(store, MATERIAL_NAME, 500); final DecryptionMaterials dMat1 = prov2.getDecryptionMaterials(ctx(eMat1)); methodCalls.clear(); assertEquals(eMat1.getEncryptionKey(), dMat1.getDecryptionKey()); assertEquals(eMat1.getSigningKey(), dMat1.getVerificationKey()); final DecryptionMaterials dMat2 = prov2.getDecryptionMaterials(ctx(eMat2)); assertEquals(eMat2.getEncryptionKey(), dMat2.getDecryptionKey()); assertEquals(eMat2.getSigningKey(), dMat2.getVerificationKey()); final DecryptionMaterials dMat3 = prov2.getDecryptionMaterials(ctx(eMat3)); assertEquals(eMat3.getEncryptionKey(), dMat3.getDecryptionKey()); assertEquals(eMat3.getSigningKey(), dMat3.getVerificationKey()); assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty()); } @Test public void testTwoVersions() throws InterruptedException { final CachingMostRecentProvider prov = new CachingMostRecentProvider(store, MATERIAL_NAME, 500); assertNull(methodCalls.get("putItem")); final EncryptionMaterials eMat1 = prov.getEncryptionMaterials(ctx); // It's a new provider, so we see a single putItem assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0)); methodCalls.clear(); // Create the new material store.newProvider(MATERIAL_NAME); methodCalls.clear(); // Ensure the cache is working final EncryptionMaterials eMat2 = prov.getEncryptionMaterials(ctx); assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty()); assertEquals(0, store.getVersionFromMaterialDescription(eMat1.getMaterialDescription())); assertEquals(0, store.getVersionFromMaterialDescription(eMat2.getMaterialDescription())); assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty()); // Let the TTL be exceeded Thread.sleep(500); final EncryptionMaterials eMat3 = prov.getEncryptionMaterials(ctx); assertEquals(1, (int) methodCalls.getOrDefault("query", 0)); // To find current version assertEquals(1, (int) methodCalls.getOrDefault("getItem", 0)); // To retrieve current version assertNull(methodCalls.get("putItem")); // No attempt to create a new item assertEquals(1, store.getVersionFromMaterialDescription(eMat3.getMaterialDescription())); assertEquals(eMat1.getSigningKey(), eMat2.getSigningKey()); assertFalse(eMat1.getSigningKey().equals(eMat3.getSigningKey())); // Ensure we can decrypt all of them without hitting ddb more than the minimum final CachingMostRecentProvider prov2 = new CachingMostRecentProvider(store, MATERIAL_NAME, 500); final DecryptionMaterials dMat1 = prov2.getDecryptionMaterials(ctx(eMat1)); methodCalls.clear(); assertEquals(eMat1.getEncryptionKey(), dMat1.getDecryptionKey()); assertEquals(eMat1.getSigningKey(), dMat1.getVerificationKey()); final DecryptionMaterials dMat2 = prov2.getDecryptionMaterials(ctx(eMat2)); assertEquals(eMat2.getEncryptionKey(), dMat2.getDecryptionKey()); assertEquals(eMat2.getSigningKey(), dMat2.getVerificationKey()); final DecryptionMaterials dMat3 = prov2.getDecryptionMaterials(ctx(eMat3)); assertEquals(eMat3.getEncryptionKey(), dMat3.getDecryptionKey()); assertEquals(eMat3.getSigningKey(), dMat3.getVerificationKey()); // Get item will be hit once for the one old key assertEquals(1, methodCalls.size()); assertEquals(1, (int) methodCalls.getOrDefault("getItem", 0)); } @Test public void testTwoVersionsWithRefresh() throws InterruptedException { final CachingMostRecentProvider prov = new CachingMostRecentProvider(store, MATERIAL_NAME, 100); assertNull(methodCalls.get("putItem")); final EncryptionMaterials eMat1 = prov.getEncryptionMaterials(ctx); // It's a new provider, so we see a single putItem assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0)); methodCalls.clear(); // Create the new material store.newProvider(MATERIAL_NAME); methodCalls.clear(); // Ensure the cache is working final EncryptionMaterials eMat2 = prov.getEncryptionMaterials(ctx); assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty()); assertEquals(0, store.getVersionFromMaterialDescription(eMat1.getMaterialDescription())); assertEquals(0, store.getVersionFromMaterialDescription(eMat2.getMaterialDescription())); prov.refresh(); final EncryptionMaterials eMat3 = prov.getEncryptionMaterials(ctx); assertEquals(1, (int) methodCalls.getOrDefault("query", 0)); // To find current version assertEquals(1, (int) methodCalls.getOrDefault("getItem", 0)); assertEquals(1, store.getVersionFromMaterialDescription(eMat3.getMaterialDescription())); assertEquals(eMat1.getSigningKey(), eMat2.getSigningKey()); assertFalse(eMat1.getSigningKey().equals(eMat3.getSigningKey())); // Ensure we can decrypt all of them without hitting ddb more than the minimum final CachingMostRecentProvider prov2 = new CachingMostRecentProvider(store, MATERIAL_NAME, 500); final DecryptionMaterials dMat1 = prov2.getDecryptionMaterials(ctx(eMat1)); methodCalls.clear(); assertEquals(eMat1.getEncryptionKey(), dMat1.getDecryptionKey()); assertEquals(eMat1.getSigningKey(), dMat1.getVerificationKey()); final DecryptionMaterials dMat2 = prov2.getDecryptionMaterials(ctx(eMat2)); assertEquals(eMat2.getEncryptionKey(), dMat2.getDecryptionKey()); assertEquals(eMat2.getSigningKey(), dMat2.getVerificationKey()); final DecryptionMaterials dMat3 = prov2.getDecryptionMaterials(ctx(eMat3)); assertEquals(eMat3.getEncryptionKey(), dMat3.getDecryptionKey()); assertEquals(eMat3.getSigningKey(), dMat3.getVerificationKey()); // Get item will be hit once for the one old key assertEquals(1, methodCalls.size()); assertEquals(1, (int) methodCalls.getOrDefault("getItem", 0)); } @Test public void testSingleVersionTwoMaterials() throws InterruptedException { final Map<String, AttributeValue> attr1 = Collections.singletonMap(MATERIAL_PARAM, new AttributeValue("material1")); final EncryptionContext ctx1 = ctx(attr1); final Map<String, AttributeValue> attr2 = Collections.singletonMap(MATERIAL_PARAM, new AttributeValue("material2")); final EncryptionContext ctx2 = ctx(attr2); final CachingMostRecentProvider prov = new ExtendedProvider(store, 500, 100); assertNull(methodCalls.get("putItem")); final EncryptionMaterials eMat1_1 = prov.getEncryptionMaterials(ctx1); // It's a new provider, so we see a single putItem assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0)); methodCalls.clear(); final EncryptionMaterials eMat1_2 = prov.getEncryptionMaterials(ctx2); // It's a new provider, so we see a single putItem assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0)); methodCalls.clear(); // Ensure the two materials are, in fact, different assertFalse(eMat1_1.getSigningKey().equals(eMat1_2.getSigningKey())); // Ensure the cache is working final EncryptionMaterials eMat2_1 = prov.getEncryptionMaterials(ctx1); assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty()); assertEquals(0, store.getVersionFromMaterialDescription(eMat1_1.getMaterialDescription())); assertEquals(0, store.getVersionFromMaterialDescription(eMat2_1.getMaterialDescription())); final EncryptionMaterials eMat2_2 = prov.getEncryptionMaterials(ctx2); assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty()); assertEquals(0, store.getVersionFromMaterialDescription(eMat1_2.getMaterialDescription())); assertEquals(0, store.getVersionFromMaterialDescription(eMat2_2.getMaterialDescription())); // Let the TTL be exceeded Thread.sleep(500); final EncryptionMaterials eMat3_1 = prov.getEncryptionMaterials(ctx1); assertEquals(2, methodCalls.size()); assertEquals(1, (int) methodCalls.get("query")); // To find current version assertEquals(1, (int) methodCalls.get("getItem")); // To get the provider assertEquals(0, store.getVersionFromMaterialDescription(eMat3_1.getMaterialDescription())); methodCalls.clear(); final EncryptionMaterials eMat3_2 = prov.getEncryptionMaterials(ctx2); assertEquals(2, methodCalls.size()); assertEquals(1, (int) methodCalls.get("query")); // To find current version assertEquals(1, (int) methodCalls.get("getItem")); // To get the provider assertEquals(0, store.getVersionFromMaterialDescription(eMat3_2.getMaterialDescription())); assertEquals(eMat1_1.getSigningKey(), eMat2_1.getSigningKey()); assertEquals(eMat1_2.getSigningKey(), eMat2_2.getSigningKey()); assertEquals(eMat1_1.getSigningKey(), eMat3_1.getSigningKey()); assertEquals(eMat1_2.getSigningKey(), eMat3_2.getSigningKey()); // Check algorithms. Right now we only support AES and HmacSHA256 assertEquals("AES", eMat1_1.getEncryptionKey().getAlgorithm()); assertEquals("AES", eMat1_2.getEncryptionKey().getAlgorithm()); assertEquals("HmacSHA256", eMat1_1.getSigningKey().getAlgorithm()); assertEquals("HmacSHA256", eMat1_2.getSigningKey().getAlgorithm()); // Ensure we can decrypt all of them without hitting ddb more than the minimum final CachingMostRecentProvider prov2 = new ExtendedProvider(store, 500, 100); final DecryptionMaterials dMat1_1 = prov2.getDecryptionMaterials(ctx(eMat1_1, attr1)); final DecryptionMaterials dMat1_2 = prov2.getDecryptionMaterials(ctx(eMat1_2, attr2)); methodCalls.clear(); assertEquals(eMat1_1.getEncryptionKey(), dMat1_1.getDecryptionKey()); assertEquals(eMat1_2.getEncryptionKey(), dMat1_2.getDecryptionKey()); assertEquals(eMat1_1.getSigningKey(), dMat1_1.getVerificationKey()); assertEquals(eMat1_2.getSigningKey(), dMat1_2.getVerificationKey()); final DecryptionMaterials dMat2_1 = prov2.getDecryptionMaterials(ctx(eMat2_1, attr1)); final DecryptionMaterials dMat2_2 = prov2.getDecryptionMaterials(ctx(eMat2_2, attr2)); assertEquals(eMat2_1.getEncryptionKey(), dMat2_1.getDecryptionKey()); assertEquals(eMat2_2.getEncryptionKey(), dMat2_2.getDecryptionKey()); assertEquals(eMat2_1.getSigningKey(), dMat2_1.getVerificationKey()); assertEquals(eMat2_2.getSigningKey(), dMat2_2.getVerificationKey()); final DecryptionMaterials dMat3_1 = prov2.getDecryptionMaterials(ctx(eMat3_1, attr1)); final DecryptionMaterials dMat3_2 = prov2.getDecryptionMaterials(ctx(eMat3_2, attr2)); assertEquals(eMat3_1.getEncryptionKey(), dMat3_1.getDecryptionKey()); assertEquals(eMat3_2.getEncryptionKey(), dMat3_2.getDecryptionKey()); assertEquals(eMat3_1.getSigningKey(), dMat3_1.getVerificationKey()); assertEquals(eMat3_2.getSigningKey(), dMat3_2.getVerificationKey()); assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty()); } @Test public void testSingleVersionWithTwoMaterialsWithRefresh() throws InterruptedException { final Map<String, AttributeValue> attr1 = Collections.singletonMap(MATERIAL_PARAM, new AttributeValue("material1")); final EncryptionContext ctx1 = ctx(attr1); final Map<String, AttributeValue> attr2 = Collections.singletonMap(MATERIAL_PARAM, new AttributeValue("material2")); final EncryptionContext ctx2 = ctx(attr2); final CachingMostRecentProvider prov = new ExtendedProvider(store, 500, 100); assertNull(methodCalls.get("putItem")); final EncryptionMaterials eMat1_1 = prov.getEncryptionMaterials(ctx1); // It's a new provider, so we see a single putItem assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0)); methodCalls.clear(); final EncryptionMaterials eMat1_2 = prov.getEncryptionMaterials(ctx2); // It's a new provider, so we see a single putItem assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0)); methodCalls.clear(); // Ensure the two materials are, in fact, different assertFalse(eMat1_1.getSigningKey().equals(eMat1_2.getSigningKey())); // Ensure the cache is working final EncryptionMaterials eMat2_1 = prov.getEncryptionMaterials(ctx1); assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty()); assertEquals(0, store.getVersionFromMaterialDescription(eMat1_1.getMaterialDescription())); assertEquals(0, store.getVersionFromMaterialDescription(eMat2_1.getMaterialDescription())); final EncryptionMaterials eMat2_2 = prov.getEncryptionMaterials(ctx2); assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty()); assertEquals(0, store.getVersionFromMaterialDescription(eMat1_2.getMaterialDescription())); assertEquals(0, store.getVersionFromMaterialDescription(eMat2_2.getMaterialDescription())); prov.refresh(); final EncryptionMaterials eMat3_1 = prov.getEncryptionMaterials(ctx1); assertEquals(1, (int) methodCalls.getOrDefault("query", 0)); // To find current version assertEquals(1, (int) methodCalls.getOrDefault("getItem", 0)); final EncryptionMaterials eMat3_2 = prov.getEncryptionMaterials(ctx2); assertEquals(2, (int) methodCalls.getOrDefault("query", 0)); // To find current version assertEquals(2, (int) methodCalls.getOrDefault("getItem", 0)); assertEquals(0, store.getVersionFromMaterialDescription(eMat3_1.getMaterialDescription())); assertEquals(0, store.getVersionFromMaterialDescription(eMat3_2.getMaterialDescription())); prov.refresh(); assertEquals(eMat1_1.getSigningKey(), eMat2_1.getSigningKey()); assertEquals(eMat1_1.getSigningKey(), eMat3_1.getSigningKey()); assertEquals(eMat1_2.getSigningKey(), eMat2_2.getSigningKey()); assertEquals(eMat1_2.getSigningKey(), eMat3_2.getSigningKey()); // Ensure that after cache refresh we only get one more hit as opposed to multiple prov.getEncryptionMaterials(ctx1); prov.getEncryptionMaterials(ctx2); Thread.sleep(700); // Force refresh prov.getEncryptionMaterials(ctx1); prov.getEncryptionMaterials(ctx2); methodCalls.clear(); // Check to ensure no more hits assertEquals(eMat1_1.getSigningKey(), prov.getEncryptionMaterials(ctx1).getSigningKey()); assertEquals(eMat1_1.getSigningKey(), prov.getEncryptionMaterials(ctx1).getSigningKey()); assertEquals(eMat1_1.getSigningKey(), prov.getEncryptionMaterials(ctx1).getSigningKey()); assertEquals(eMat1_1.getSigningKey(), prov.getEncryptionMaterials(ctx1).getSigningKey()); assertEquals(eMat1_1.getSigningKey(), prov.getEncryptionMaterials(ctx1).getSigningKey()); assertEquals(eMat1_2.getSigningKey(), prov.getEncryptionMaterials(ctx2).getSigningKey()); assertEquals(eMat1_2.getSigningKey(), prov.getEncryptionMaterials(ctx2).getSigningKey()); assertEquals(eMat1_2.getSigningKey(), prov.getEncryptionMaterials(ctx2).getSigningKey()); assertEquals(eMat1_2.getSigningKey(), prov.getEncryptionMaterials(ctx2).getSigningKey()); assertEquals(eMat1_2.getSigningKey(), prov.getEncryptionMaterials(ctx2).getSigningKey()); assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty()); // Ensure we can decrypt all of them without hitting ddb more than the minimum final CachingMostRecentProvider prov2 = new ExtendedProvider(store, 500, 100); final DecryptionMaterials dMat1_1 = prov2.getDecryptionMaterials(ctx(eMat1_1, attr1)); final DecryptionMaterials dMat1_2 = prov2.getDecryptionMaterials(ctx(eMat1_2, attr2)); methodCalls.clear(); assertEquals(eMat1_1.getEncryptionKey(), dMat1_1.getDecryptionKey()); assertEquals(eMat1_2.getEncryptionKey(), dMat1_2.getDecryptionKey()); assertEquals(eMat1_1.getSigningKey(), dMat1_1.getVerificationKey()); assertEquals(eMat1_2.getSigningKey(), dMat1_2.getVerificationKey()); final DecryptionMaterials dMat2_1 = prov2.getDecryptionMaterials(ctx(eMat2_1, attr1)); final DecryptionMaterials dMat2_2 = prov2.getDecryptionMaterials(ctx(eMat2_2, attr2)); assertEquals(eMat2_1.getEncryptionKey(), dMat2_1.getDecryptionKey()); assertEquals(eMat2_2.getEncryptionKey(), dMat2_2.getDecryptionKey()); assertEquals(eMat2_1.getSigningKey(), dMat2_1.getVerificationKey()); assertEquals(eMat2_2.getSigningKey(), dMat2_2.getVerificationKey()); final DecryptionMaterials dMat3_1 = prov2.getDecryptionMaterials(ctx(eMat3_1, attr1)); final DecryptionMaterials dMat3_2 = prov2.getDecryptionMaterials(ctx(eMat3_2, attr2)); assertEquals(eMat3_1.getEncryptionKey(), dMat3_1.getDecryptionKey()); assertEquals(eMat3_2.getEncryptionKey(), dMat3_2.getDecryptionKey()); assertEquals(eMat3_1.getSigningKey(), dMat3_1.getVerificationKey()); assertEquals(eMat3_2.getSigningKey(), dMat3_2.getVerificationKey()); assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty()); } @Test public void testTwoVersionsWithTwoMaterialsWithRefresh() throws InterruptedException { final Map<String, AttributeValue> attr1 = Collections.singletonMap(MATERIAL_PARAM, new AttributeValue("material1")); final EncryptionContext ctx1 = ctx(attr1); final Map<String, AttributeValue> attr2 = Collections.singletonMap(MATERIAL_PARAM, new AttributeValue("material2")); final EncryptionContext ctx2 = ctx(attr2); final CachingMostRecentProvider prov = new ExtendedProvider(store, 500, 100); assertNull(methodCalls.get("putItem")); final EncryptionMaterials eMat1_1 = prov.getEncryptionMaterials(ctx1); // It's a new provider, so we see a single putItem assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0)); methodCalls.clear(); final EncryptionMaterials eMat1_2 = prov.getEncryptionMaterials(ctx2); // It's a new provider, so we see a single putItem assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0)); methodCalls.clear(); // Create the new material store.newProvider("material1"); store.newProvider("material2"); methodCalls.clear(); // Ensure the cache is working final EncryptionMaterials eMat2_1 = prov.getEncryptionMaterials(ctx1); final EncryptionMaterials eMat2_2 = prov.getEncryptionMaterials(ctx2); assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty()); assertEquals(0, store.getVersionFromMaterialDescription(eMat1_1.getMaterialDescription())); assertEquals(0, store.getVersionFromMaterialDescription(eMat2_1.getMaterialDescription())); assertEquals(0, store.getVersionFromMaterialDescription(eMat1_2.getMaterialDescription())); assertEquals(0, store.getVersionFromMaterialDescription(eMat2_2.getMaterialDescription())); prov.refresh(); final EncryptionMaterials eMat3_1 = prov.getEncryptionMaterials(ctx1); final EncryptionMaterials eMat3_2 = prov.getEncryptionMaterials(ctx2); assertEquals(2, (int) methodCalls.getOrDefault("query", 0)); // To find current version assertEquals(2, (int) methodCalls.getOrDefault("getItem", 0)); assertEquals(1, store.getVersionFromMaterialDescription(eMat3_1.getMaterialDescription())); assertEquals(1, store.getVersionFromMaterialDescription(eMat3_2.getMaterialDescription())); assertEquals(eMat1_1.getSigningKey(), eMat2_1.getSigningKey()); assertFalse(eMat1_1.getSigningKey().equals(eMat3_1.getSigningKey())); assertEquals(eMat1_2.getSigningKey(), eMat2_2.getSigningKey()); assertFalse(eMat1_2.getSigningKey().equals(eMat3_2.getSigningKey())); // Ensure we can decrypt all of them without hitting ddb more than the minimum final CachingMostRecentProvider prov2 = new ExtendedProvider(store, 500, 100); final DecryptionMaterials dMat1_1 = prov2.getDecryptionMaterials(ctx(eMat1_1, attr1)); final DecryptionMaterials dMat1_2 = prov2.getDecryptionMaterials(ctx(eMat1_2, attr2)); methodCalls.clear(); assertEquals(eMat1_1.getEncryptionKey(), dMat1_1.getDecryptionKey()); assertEquals(eMat1_2.getEncryptionKey(), dMat1_2.getDecryptionKey()); assertEquals(eMat1_1.getSigningKey(), dMat1_1.getVerificationKey()); assertEquals(eMat1_2.getSigningKey(), dMat1_2.getVerificationKey()); final DecryptionMaterials dMat2_1 = prov2.getDecryptionMaterials(ctx(eMat2_1, attr1)); final DecryptionMaterials dMat2_2 = prov2.getDecryptionMaterials(ctx(eMat2_2, attr2)); assertEquals(eMat2_1.getEncryptionKey(), dMat2_1.getDecryptionKey()); assertEquals(eMat2_2.getEncryptionKey(), dMat2_2.getDecryptionKey()); assertEquals(eMat2_1.getSigningKey(), dMat2_1.getVerificationKey()); assertEquals(eMat2_2.getSigningKey(), dMat2_2.getVerificationKey()); final DecryptionMaterials dMat3_1 = prov2.getDecryptionMaterials(ctx(eMat3_1, attr1)); final DecryptionMaterials dMat3_2 = prov2.getDecryptionMaterials(ctx(eMat3_2, attr2)); assertEquals(eMat3_1.getEncryptionKey(), dMat3_1.getDecryptionKey()); assertEquals(eMat3_2.getEncryptionKey(), dMat3_2.getDecryptionKey()); assertEquals(eMat3_1.getSigningKey(), dMat3_1.getVerificationKey()); assertEquals(eMat3_2.getSigningKey(), dMat3_2.getVerificationKey()); // Get item will be hit twice, once for each old key assertEquals(1, methodCalls.size()); assertEquals(2, (int) methodCalls.getOrDefault("getItem", 0)); } private static EncryptionContext ctx(final Map<String, AttributeValue> attr) { return new EncryptionContext.Builder().withAttributeValues(attr).build(); } private static EncryptionContext ctx( final EncryptionMaterials mat, Map<String, AttributeValue> attr) { return new EncryptionContext.Builder() .withAttributeValues(attr) .withMaterialDescription(mat.getMaterialDescription()) .build(); } private static EncryptionContext ctx(final EncryptionMaterials mat) { return new EncryptionContext.Builder() .withMaterialDescription(mat.getMaterialDescription()) .build(); } private static class ExtendedProvider extends CachingMostRecentProvider { public ExtendedProvider(ProviderStore keystore, long ttlInMillis, int maxCacheSize) { super(keystore, null, ttlInMillis, maxCacheSize); } @Override public long getCurrentVersion() { throw new UnsupportedOperationException(); } @Override protected String getMaterialName(final EncryptionContext context) { return context.getAttributeValues().get(MATERIAL_PARAM).getS(); } } @SuppressWarnings("unchecked") private static <T> T instrument( final T obj, final Class<T> clazz, final Map<String, Integer> map) { return (T) Proxy.newProxyInstance( clazz.getClassLoader(), new Class[] {clazz}, new InvocationHandler() { private final Object lock = new Object(); @Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { synchronized (lock) { try { final Integer oldCount = map.get(method.getName()); if (oldCount != null) { map.put(method.getName(), oldCount + 1); } else { map.put(method.getName(), 1); } return method.invoke(obj, args); } catch (final InvocationTargetException ex) { throw ex.getCause(); } } } }); } }
4,299