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-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers
Create_ds/aws-dynamodb-encryption-java/sdk1/src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/store/MetaStoreTests.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.datamodeling.encryption.providers.store; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.fail; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; 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.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.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.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class MetaStoreTests { private static final String SOURCE_TABLE_NAME = "keystoreTable"; private static final String DESTINATION_TABLE_NAME = "keystoreDestinationTable"; private static final String MATERIAL_NAME = "material"; 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 TARGET_AES_KEY = new SecretKeySpec( new byte[] {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30}, "AES"); private static final SecretKey HMAC_KEY = new SecretKeySpec(new byte[] {0, 1, 2, 3, 4, 5, 6, 7}, "HmacSHA256"); private static final SecretKey TARGET_HMAC_KEY = new SecretKeySpec(new byte[] {0, 2, 4, 6, 8, 10, 12, 14}, "HmacSHA256"); private static final EncryptionMaterialsProvider BASE_PROVIDER = new SymmetricStaticProvider(AES_KEY, HMAC_KEY); private static final EncryptionMaterialsProvider TARGET_BASE_PROVIDER = new SymmetricStaticProvider(TARGET_AES_KEY, TARGET_HMAC_KEY); private static final DynamoDBEncryptor ENCRYPTOR = DynamoDBEncryptor.getInstance(BASE_PROVIDER); private static final DynamoDBEncryptor TARGET_ENCRYPTOR = DynamoDBEncryptor.getInstance(TARGET_BASE_PROVIDER); private AmazonDynamoDB client; private AmazonDynamoDB targetClient; private MetaStore store; private MetaStore targetStore; private EncryptionContext ctx; private static class TestExtraDataSupplier implements MetaStore.ExtraDataSupplier { private final Map<String, AttributeValue> attributeValueMap; private final Set<String> signedOnlyFieldNames; public TestExtraDataSupplier( final Map<String, AttributeValue> attributeValueMap, final Set<String> signedOnlyFieldNames) { this.attributeValueMap = attributeValueMap; this.signedOnlyFieldNames = signedOnlyFieldNames; } @Override public Map<String, AttributeValue> getAttributes(String materialName, long version) { return this.attributeValueMap; } @Override public Set<String> getSignedOnlyFieldNames() { return this.signedOnlyFieldNames; } } @BeforeMethod public void setup() { client = synchronize(DynamoDBEmbedded.create(), AmazonDynamoDB.class); targetClient = synchronize(DynamoDBEmbedded.create(), AmazonDynamoDB.class); MetaStore.createTable(client, SOURCE_TABLE_NAME, new ProvisionedThroughput(1L, 1L)); // Creating Targeted DynamoDB Object MetaStore.createTable(targetClient, DESTINATION_TABLE_NAME, new ProvisionedThroughput(1L, 1L)); store = new MetaStore(client, SOURCE_TABLE_NAME, ENCRYPTOR); targetStore = new MetaStore(targetClient, DESTINATION_TABLE_NAME, TARGET_ENCRYPTOR); ctx = new EncryptionContext.Builder().build(); } @Test public void testNoMaterials() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); } @Test public void singleMaterial() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov = store.newProvider(MATERIAL_NAME); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); final DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals(0, store.getVersionFromMaterialDescription(eMat.getMaterialDescription())); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test public void singleMaterialExplicitAccess() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov1 = store.newProvider(MATERIAL_NAME); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov2 = store.getProvider(MATERIAL_NAME); final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); final DecryptionMaterials dMat = prov2.getDecryptionMaterials(ctx(eMat)); assertEquals(0, store.getVersionFromMaterialDescription(eMat.getMaterialDescription())); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test public void singleMaterialExplicitAccessWithVersion() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov1 = store.newProvider(MATERIAL_NAME); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov2 = store.getProvider(MATERIAL_NAME, 0); final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); final DecryptionMaterials dMat = prov2.getDecryptionMaterials(ctx(eMat)); assertEquals(0, store.getVersionFromMaterialDescription(eMat.getMaterialDescription())); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test public void singleMaterialWithImplicitCreation() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov = store.getProvider(MATERIAL_NAME); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); final DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals(0, store.getVersionFromMaterialDescription(eMat.getMaterialDescription())); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test public void twoDifferentMaterials() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov1 = store.newProvider(MATERIAL_NAME); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov2 = store.newProvider(MATERIAL_NAME); assertEquals(1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx); assertEquals(0, store.getVersionFromMaterialDescription(eMat.getMaterialDescription())); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); try { prov2.getDecryptionMaterials(ctx(eMat)); fail("Missing expected exception"); } catch (final DynamoDBMappingException ex) { // Expected Exception } final EncryptionMaterials eMat2 = prov2.getEncryptionMaterials(ctx); assertEquals(1, store.getVersionFromMaterialDescription(eMat2.getMaterialDescription())); } @Test public void getOrCreateCollision() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov1 = store.getOrCreate(MATERIAL_NAME, 0); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov2 = store.getOrCreate(MATERIAL_NAME, 0); final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); final DecryptionMaterials dMat = prov2.getDecryptionMaterials(ctx(eMat)); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test public void getOrCreateWithContextSupplier() { final Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("CustomKeyId", new AttributeValue().withS("testCustomKeyId")); attributeValueMap.put("KeyToken", new AttributeValue().withS("testKeyToken")); final Set<String> signedOnlyAttributes = new HashSet<>(); signedOnlyAttributes.add("CustomKeyId"); final TestExtraDataSupplier extraDataSupplier = new TestExtraDataSupplier(attributeValueMap, signedOnlyAttributes); final MetaStore metaStore = new MetaStore(client, SOURCE_TABLE_NAME, ENCRYPTOR, extraDataSupplier); assertEquals(-1, metaStore.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov1 = metaStore.getOrCreate(MATERIAL_NAME, 0); assertEquals(0, metaStore.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov2 = metaStore.getOrCreate(MATERIAL_NAME, 0); final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); final DecryptionMaterials dMat = prov2.getDecryptionMaterials(ctx(eMat)); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test public void replicateIntermediateKeysTest() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov1 = store.getOrCreate(MATERIAL_NAME, 0); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); store.replicate(MATERIAL_NAME, 0, targetStore); assertEquals(0, targetStore.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx); final DecryptionMaterials dMat = targetStore.getProvider(MATERIAL_NAME, 0).getDecryptionMaterials(ctx(eMat)); assertEquals(eMat.getEncryptionKey(), dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test(expectedExceptions = IndexOutOfBoundsException.class) public void replicateIntermediateKeysWhenMaterialNotFoundTest() { store.replicate(MATERIAL_NAME, 0, targetStore); } @Test public void newProviderCollision() throws InterruptedException { final SlowNewProvider slowProv = new SlowNewProvider(); assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); assertEquals(-1, slowProv.slowStore.getMaxVersion(MATERIAL_NAME)); slowProv.start(); Thread.sleep(100); final EncryptionMaterialsProvider prov1 = store.newProvider(MATERIAL_NAME); slowProv.join(); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); assertEquals(0, slowProv.slowStore.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov2 = slowProv.result; final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); final DecryptionMaterials dMat = prov2.getDecryptionMaterials(ctx(eMat)); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test(expectedExceptions = IndexOutOfBoundsException.class) public void invalidVersion() { store.getProvider(MATERIAL_NAME, 1000); } @Test(expectedExceptions = IllegalArgumentException.class) public void invalidSignedOnlyField() { final Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("enc", new AttributeValue().withS("testEncryptionKey")); final Set<String> signedOnlyAttributes = new HashSet<>(); signedOnlyAttributes.add("enc"); final TestExtraDataSupplier extraDataSupplier = new TestExtraDataSupplier(attributeValueMap, signedOnlyAttributes); new MetaStore(client, SOURCE_TABLE_NAME, ENCRYPTOR, extraDataSupplier); } private static EncryptionContext ctx(final EncryptionMaterials mat) { return new EncryptionContext.Builder() .withMaterialDescription(mat.getMaterialDescription()) .build(); } private class SlowNewProvider extends Thread { public volatile EncryptionMaterialsProvider result; public ProviderStore slowStore = new MetaStore(client, SOURCE_TABLE_NAME, ENCRYPTOR) { @Override public EncryptionMaterialsProvider newProvider(final String materialName) { final long nextId = getMaxVersion(materialName) + 1; try { Thread.sleep(1000); } catch (final InterruptedException e) { // Ignored } return getOrCreate(materialName, nextId); } }; @Override public void run() { result = slowStore.newProvider(MATERIAL_NAME); } } @SuppressWarnings("unchecked") private static <T> T synchronize(final T obj, final Class<T> clazz) { 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 { return method.invoke(obj, args); } catch (final InvocationTargetException ex) { throw ex.getCause(); } } } }); } }
4,300
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/utils/EncryptionContextOperatorsTest.java
package com.amazonaws.services.dynamodbv2.datamodeling.encryption.utils; import static com.amazonaws.services.dynamodbv2.datamodeling.encryption.utils.EncryptionContextOperators.overrideEncryptionContextTableName; import static com.amazonaws.services.dynamodbv2.datamodeling.encryption.utils.EncryptionContextOperators.overrideEncryptionContextTableNameUsingMap; import static org.testng.AssertJUnit.assertEquals; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import java.util.HashMap; import java.util.Map; import java.util.function.Function; import org.testng.annotations.Test; public class EncryptionContextOperatorsTest { @Test public void testCreateEncryptionContextTableNameOverride_expectedOverride() { Function<EncryptionContext, EncryptionContext> myNewTableName = overrideEncryptionContextTableName("OriginalTableName", "MyNewTableName"); EncryptionContext context = new EncryptionContext.Builder().withTableName("OriginalTableName").build(); EncryptionContext newContext = myNewTableName.apply(context); assertEquals("OriginalTableName", context.getTableName()); assertEquals("MyNewTableName", newContext.getTableName()); } /** * Some pretty clear repetition in null cases. May make sense to replace with data providers or * parameterized classes for null cases */ @Test public void testNullCasesCreateEncryptionContextTableNameOverride_nullOriginalTableName() { assertEncryptionContextUnchanged( new EncryptionContext.Builder().withTableName("example").build(), null, "MyNewTableName"); } @Test public void testCreateEncryptionContextTableNameOverride_differentOriginalTableName() { assertEncryptionContextUnchanged( new EncryptionContext.Builder().withTableName("example").build(), "DifferentTableName", "MyNewTableName"); } @Test public void testNullCasesCreateEncryptionContextTableNameOverride_nullEncryptionContext() { assertEncryptionContextUnchanged(null, "DifferentTableName", "MyNewTableName"); } @Test public void testCreateEncryptionContextTableNameOverrideMap_expectedOverride() { Map<String, String> tableNameOverrides = new HashMap<>(); tableNameOverrides.put("OriginalTableName", "MyNewTableName"); Function<EncryptionContext, EncryptionContext> nameOverrideMap = overrideEncryptionContextTableNameUsingMap(tableNameOverrides); EncryptionContext context = new EncryptionContext.Builder().withTableName("OriginalTableName").build(); EncryptionContext newContext = nameOverrideMap.apply(context); assertEquals("OriginalTableName", context.getTableName()); assertEquals("MyNewTableName", newContext.getTableName()); } @Test public void testCreateEncryptionContextTableNameOverrideMap_multipleOverrides() { Map<String, String> tableNameOverrides = new HashMap<>(); tableNameOverrides.put("OriginalTableName1", "MyNewTableName1"); tableNameOverrides.put("OriginalTableName2", "MyNewTableName2"); Function<EncryptionContext, EncryptionContext> overrideOperator = overrideEncryptionContextTableNameUsingMap(tableNameOverrides); EncryptionContext context = new EncryptionContext.Builder().withTableName("OriginalTableName1").build(); EncryptionContext newContext = overrideOperator.apply(context); assertEquals("OriginalTableName1", context.getTableName()); assertEquals("MyNewTableName1", newContext.getTableName()); EncryptionContext context2 = new EncryptionContext.Builder().withTableName("OriginalTableName2").build(); EncryptionContext newContext2 = overrideOperator.apply(context2); assertEquals("OriginalTableName2", context2.getTableName()); assertEquals("MyNewTableName2", newContext2.getTableName()); } @Test public void testNullCasesCreateEncryptionContextTableNameOverrideFromMap_nullEncryptionContextTableName() { Map<String, String> tableNameOverrides = new HashMap<>(); tableNameOverrides.put("DifferentTableName", "MyNewTableName"); assertEncryptionContextUnchangedFromMap( new EncryptionContext.Builder().build(), tableNameOverrides); } @Test public void testNullCasesCreateEncryptionContextTableNameOverrideFromMap_nullEncryptionContext() { Map<String, String> tableNameOverrides = new HashMap<>(); tableNameOverrides.put("DifferentTableName", "MyNewTableName"); assertEncryptionContextUnchangedFromMap(null, tableNameOverrides); } @Test public void testNullCasesCreateEncryptionContextTableNameOverrideFromMap_nullOriginalTableName() { Map<String, String> tableNameOverrides = new HashMap<>(); tableNameOverrides.put(null, "MyNewTableName"); assertEncryptionContextUnchangedFromMap( new EncryptionContext.Builder().withTableName("example").build(), tableNameOverrides); } @Test public void testNullCasesCreateEncryptionContextTableNameOverrideFromMap_nullNewTableName() { Map<String, String> tableNameOverrides = new HashMap<>(); tableNameOverrides.put("MyOriginalTableName", null); assertEncryptionContextUnchangedFromMap( new EncryptionContext.Builder().withTableName("MyOriginalTableName").build(), tableNameOverrides); } @Test public void testNullCasesCreateEncryptionContextTableNameOverrideFromMap_nullMap() { assertEncryptionContextUnchangedFromMap( new EncryptionContext.Builder().withTableName("MyOriginalTableName").build(), null); } private void assertEncryptionContextUnchanged( EncryptionContext encryptionContext, String originalTableName, String newTableName) { Function<EncryptionContext, EncryptionContext> encryptionContextTableNameOverride = overrideEncryptionContextTableName(originalTableName, newTableName); EncryptionContext newEncryptionContext = encryptionContextTableNameOverride.apply(encryptionContext); assertEquals(encryptionContext, newEncryptionContext); } private void assertEncryptionContextUnchangedFromMap( EncryptionContext encryptionContext, Map<String, String> overrideMap) { Function<EncryptionContext, EncryptionContext> encryptionContextTableNameOverrideFromMap = overrideEncryptionContextTableNameUsingMap(overrideMap); EncryptionContext newEncryptionContext = encryptionContextTableNameOverrideFromMap.apply(encryptionContext); assertEquals(encryptionContext, newEncryptionContext); } }
4,301
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/internal/ByteBufferInputStreamTest.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.internal; import static org.testng.AssertJUnit.assertArrayEquals; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import java.io.IOException; import java.nio.ByteBuffer; import org.testng.annotations.Test; public class ByteBufferInputStreamTest { @Test public void testRead() throws IOException { ByteBufferInputStream bis = new ByteBufferInputStream(ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9})); for (int x = 0; x < 10; ++x) { assertEquals(10 - x, bis.available()); assertEquals(x, bis.read()); } assertEquals(0, bis.available()); bis.close(); } @Test public void testReadByteArray() throws IOException { ByteBufferInputStream bis = new ByteBufferInputStream(ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9})); assertEquals(10, bis.available()); byte[] buff = new byte[4]; int len = bis.read(buff); assertEquals(4, len); assertEquals(6, bis.available()); assertArrayEquals(new byte[] {0, 1, 2, 3}, buff); len = bis.read(buff); assertEquals(4, len); assertEquals(2, bis.available()); assertArrayEquals(new byte[] {4, 5, 6, 7}, buff); len = bis.read(buff); assertEquals(2, len); assertEquals(0, bis.available()); assertArrayEquals(new byte[] {8, 9, 6, 7}, buff); bis.close(); } @Test public void testSkip() throws IOException { ByteBufferInputStream bis = new ByteBufferInputStream( ByteBuffer.wrap(new byte[] {(byte) 0xFA, 15, 15, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9})); assertEquals(13, bis.available()); assertEquals(0xFA, bis.read()); assertEquals(12, bis.available()); bis.skip(2); assertEquals(10, bis.available()); for (int x = 0; x < 10; ++x) { assertEquals(x, bis.read()); } assertEquals(0, bis.available()); assertEquals(-1, bis.read()); bis.close(); } @Test public void testMarkSupported() throws IOException { try (ByteBufferInputStream bis = new ByteBufferInputStream(ByteBuffer.allocate(0))) { assertFalse(bis.markSupported()); } } }
4,302
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/internal/LRUCacheTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.services.dynamodbv2.datamodeling.internal; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import org.testng.annotations.Test; public class LRUCacheTest { @Test public void test() { final LRUCache<String> cache = new LRUCache<String>(3); assertEquals(0, cache.size()); assertEquals(3, cache.getMaxSize()); cache.add("k1", "v1"); assertTrue(cache.size() == 1); cache.add("k1", "v11"); assertTrue(cache.size() == 1); cache.add("k2", "v2"); assertTrue(cache.size() == 2); cache.add("k3", "v3"); assertTrue(cache.size() == 3); assertEquals("v11", cache.get("k1")); assertEquals("v2", cache.get("k2")); assertEquals("v3", cache.get("k3")); cache.add("k4", "v4"); assertTrue(cache.size() == 3); assertNull(cache.get("k1")); assertEquals("v4", cache.get("k4")); assertEquals("v2", cache.get("k2")); assertEquals("v3", cache.get("k3")); assertTrue(cache.size() == 3); cache.add("k5", "v5"); assertNull(cache.get("k4")); assertEquals("v5", cache.get("k5")); assertEquals("v2", cache.get("k2")); assertEquals("v3", cache.get("k3")); cache.clear(); assertEquals(0, cache.size()); } @Test public void testRemove() { final LRUCache<String> cache = new LRUCache<String>(3); assertEquals(0, cache.size()); assertEquals(3, cache.getMaxSize()); cache.add("k1", "v1"); assertTrue(cache.size() == 1); final String oldValue = cache.remove("k1"); assertTrue(cache.size() == 0); assertEquals("v1", oldValue); assertNull(cache.get("k1")); final String emptyValue = cache.remove("k1"); assertTrue(cache.size() == 0); assertNull(emptyValue); assertNull(cache.get("k1")); } @Test public void testClear() { final LRUCache<String> cache = new LRUCache<String>(3); assertEquals(0, cache.size()); cache.clear(); assertEquals(0, cache.size()); cache.add("k1", "v1"); cache.add("k2", "v2"); cache.add("k3", "v3"); assertTrue(cache.size() == 3); cache.clear(); assertTrue(cache.size() == 0); assertNull(cache.get("k1")); assertNull(cache.get("k2")); assertNull(cache.get("k3")); } @Test(expectedExceptions = IllegalArgumentException.class) public void testZeroSize() { new LRUCache<Object>(0); } @Test(expectedExceptions = IllegalArgumentException.class) public void testIllegalArgument() { new LRUCache<Object>(-1); } @Test public void testSingleEntry() { final LRUCache<String> cache = new LRUCache<String>(1); assertTrue(cache.size() == 0); cache.add("k1", "v1"); assertTrue(cache.size() == 1); cache.add("k1", "v11"); assertTrue(cache.size() == 1); assertEquals("v11", cache.get("k1")); cache.add("k2", "v2"); assertTrue(cache.size() == 1); assertEquals("v2", cache.get("k2")); assertNull(cache.get("k1")); cache.add("k3", "v3"); assertTrue(cache.size() == 1); assertEquals("v3", cache.get("k3")); assertNull(cache.get("k2")); } }
4,303
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/internal/AttributeValueMarshallerTest.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.internal; import static com.amazonaws.services.dynamodbv2.datamodeling.internal.AttributeValueMarshaller.marshall; import static com.amazonaws.services.dynamodbv2.datamodeling.internal.AttributeValueMarshaller.unmarshall; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.util.Base64; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.testng.Assert; import org.testng.AssertJUnit; import org.testng.annotations.Test; public class AttributeValueMarshallerTest { @Test(expectedExceptions = IllegalArgumentException.class) public void testEmpty() { AttributeValue av = new AttributeValue(); marshall(av); } @Test public void testNumber() { AttributeValue av = new AttributeValue().withN("1337"); assertEquals(av, unmarshall(marshall(av))); } @Test public void testString() { AttributeValue av = new AttributeValue().withS("1337"); assertEquals(av, unmarshall(marshall(av))); } @Test public void testByteBuffer() { AttributeValue av = new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5})); assertEquals(av, unmarshall(marshall(av))); } // We can't use straight .equals for comparison because Attribute Values represents Sets // as Lists and so incorrectly does an ordered comparison @Test public void testNumberS() { AttributeValue av = new AttributeValue().withNS(Collections.unmodifiableList(Arrays.asList("1337", "1", "5"))); assertEquals(av, unmarshall(marshall(av))); } @Test public void testNumberSOrdering() { AttributeValue av1 = new AttributeValue().withNS(Collections.unmodifiableList(Arrays.asList("1337", "1", "5"))); AttributeValue av2 = new AttributeValue().withNS(Collections.unmodifiableList(Arrays.asList("1", "5", "1337"))); assertEquals(av1, av2); ByteBuffer buff1 = marshall(av1); ByteBuffer buff2 = marshall(av2); Assert.assertEquals(buff1, buff2); } @Test public void testStringS() { AttributeValue av = new AttributeValue().withSS(Collections.unmodifiableList(Arrays.asList("Bob", "Ann", "5"))); assertEquals(av, unmarshall(marshall(av))); } @Test public void testStringSOrdering() { AttributeValue av1 = new AttributeValue().withSS(Collections.unmodifiableList(Arrays.asList("Bob", "Ann", "5"))); AttributeValue av2 = new AttributeValue().withSS(Collections.unmodifiableList(Arrays.asList("Ann", "Bob", "5"))); assertEquals(av1, av2); ByteBuffer buff1 = marshall(av1); ByteBuffer buff2 = marshall(av2); Assert.assertEquals(buff1, buff2); } @Test public void testByteBufferS() { AttributeValue av = new AttributeValue() .withBS( Collections.unmodifiableList( Arrays.asList( ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5}), ByteBuffer.wrap(new byte[] {5, 4, 3, 2, 1, 0, 0, 0, 5, 6, 7})))); assertEquals(av, unmarshall(marshall(av))); } @Test public void testByteBufferSOrdering() { AttributeValue av1 = new AttributeValue() .withBS( Collections.unmodifiableList( Arrays.asList( ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5}), ByteBuffer.wrap(new byte[] {5, 4, 3, 2, 1, 0, 0, 0, 5, 6, 7})))); AttributeValue av2 = new AttributeValue() .withBS( Collections.unmodifiableList( Arrays.asList( ByteBuffer.wrap(new byte[] {5, 4, 3, 2, 1, 0, 0, 0, 5, 6, 7}), ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5})))); assertEquals(av1, av2); ByteBuffer buff1 = marshall(av1); ByteBuffer buff2 = marshall(av2); Assert.assertEquals(buff1, buff2); } @Test public void testBoolTrue() { AttributeValue av = new AttributeValue().withBOOL(Boolean.TRUE); assertEquals(av, unmarshall(marshall(av))); } @Test public void testBoolFalse() { AttributeValue av = new AttributeValue().withBOOL(Boolean.FALSE); assertEquals(av, unmarshall(marshall(av))); } @Test public void testNULL() { AttributeValue av = new AttributeValue().withNULL(Boolean.TRUE); assertEquals(av, unmarshall(marshall(av))); } @Test(expectedExceptions = NullPointerException.class) public void testActualNULL() { unmarshall(marshall(null)); } @Test public void testEmptyList() { AttributeValue av = new AttributeValue().withL(); assertEquals(av, unmarshall(marshall(av))); } @Test public void testListOfString() { AttributeValue av = new AttributeValue().withL(new AttributeValue().withS("StringValue")); assertEquals(av, unmarshall(marshall(av))); } @Test public void testList() { AttributeValue av = new AttributeValue() .withL( new AttributeValue().withS("StringValue"), new AttributeValue().withN("1000"), new AttributeValue().withBOOL(Boolean.TRUE)); assertEquals(av, unmarshall(marshall(av))); } @Test public void testListWithNull() { final AttributeValue av = new AttributeValue() .withL( new AttributeValue().withS("StringValue"), new AttributeValue().withN("1000"), new AttributeValue().withBOOL(Boolean.TRUE), null); try { marshall(av); Assert.fail("Unexpected success"); } catch (final NullPointerException npe) { Assert.assertEquals( "Encountered null list entry value while marshalling attribute value {L: [{S: StringValue,}, {N: 1000,}, {BOOL: true}, null],}", npe.getMessage()); } } @Test public void testListDuplicates() { AttributeValue av = new AttributeValue() .withL( new AttributeValue().withN("1000"), new AttributeValue().withN("1000"), new AttributeValue().withN("1000"), new AttributeValue().withN("1000")); AttributeValue result = unmarshall(marshall(av)); assertEquals(av, result); Assert.assertEquals(4, result.getL().size()); } @Test public void testComplexList() { final List<AttributeValue> list1 = Arrays.asList( new AttributeValue().withS("StringValue"), new AttributeValue().withN("1000"), new AttributeValue().withBOOL(Boolean.TRUE)); final List<AttributeValue> list22 = Arrays.asList( new AttributeValue().withS("AWS"), new AttributeValue().withN("-3700"), new AttributeValue().withBOOL(Boolean.FALSE)); final List<AttributeValue> list2 = Arrays.asList( new AttributeValue().withL(list22), new AttributeValue().withNULL(Boolean.TRUE)); AttributeValue av = new AttributeValue() .withL( new AttributeValue().withS("StringValue1"), new AttributeValue().withL(list1), new AttributeValue().withN("50"), new AttributeValue().withL(list2)); assertEquals(av, unmarshall(marshall(av))); } @Test public void testEmptyMap() { Map<String, AttributeValue> map = new HashMap<String, AttributeValue>(); AttributeValue av = new AttributeValue().withM(map); assertEquals(av, unmarshall(marshall(av))); } @Test public void testSimpleMap() { Map<String, AttributeValue> map = new HashMap<String, AttributeValue>(); map.put("KeyValue", new AttributeValue().withS("ValueValue")); AttributeValue av = new AttributeValue().withM(map); assertEquals(av, unmarshall(marshall(av))); } @Test public void testSimpleMapWithNull() { final Map<String, AttributeValue> map = new HashMap<String, AttributeValue>(); map.put("KeyValue", new AttributeValue().withS("ValueValue")); map.put("NullKeyValue", null); final AttributeValue av = new AttributeValue().withM(map); try { marshall(av); Assert.fail("Unexpected success"); } catch (final NullPointerException npe) { // Map entries may permute under nondeterministic Java API String npeMessage = npe.getMessage(); String common = "Encountered null map value for key NullKeyValue while marshalling attribute value "; String case1 = common + "{M: {KeyValue={S: ValueValue,}, NullKeyValue=null},}"; String case2 = common + "{M: {NullKeyValue=null, KeyValue={S: ValueValue,}},}"; Assert.assertTrue(case1.equals(npeMessage) || case2.equals(npeMessage)); } } @Test public void testMapOrdering() { LinkedHashMap<String, AttributeValue> m1 = new LinkedHashMap<String, AttributeValue>(); LinkedHashMap<String, AttributeValue> m2 = new LinkedHashMap<String, AttributeValue>(); m1.put("Value1", new AttributeValue().withN("1")); m1.put("Value2", new AttributeValue().withBOOL(Boolean.TRUE)); m2.put("Value2", new AttributeValue().withBOOL(Boolean.TRUE)); m2.put("Value1", new AttributeValue().withN("1")); AttributeValue av1 = new AttributeValue().withM(m1); AttributeValue av2 = new AttributeValue().withM(m2); ByteBuffer buff1 = marshall(av1); ByteBuffer buff2 = marshall(av2); Assert.assertEquals(buff1, buff2); assertEquals(av1, unmarshall(buff1)); assertEquals(av1, unmarshall(buff2)); assertEquals(av2, unmarshall(buff1)); assertEquals(av2, unmarshall(buff2)); } @Test public void testComplexMap() { AttributeValue av = buildComplexAttributeValue(); assertEquals(av, unmarshall(marshall(av))); } // This test ensures that an AttributeValue marshalled by an older // version of this library still unmarshalls correctly. It also // ensures that old and new marshalling is identical. @Test public void testVersioningCompatibility() { AttributeValue newObject = buildComplexAttributeValue(); byte[] oldBytes = Base64.decode(COMPLEX_ATTRIBUTE_MARSHALLED); byte[] newBytes = marshall(newObject).array(); AssertJUnit.assertArrayEquals(oldBytes, newBytes); AttributeValue oldObject = unmarshall(ByteBuffer.wrap(oldBytes)); assertEquals(oldObject, newObject); } private static final String COMPLEX_ATTRIBUTE_MARSHALLED = "AE0AAAADAHM" + "AAAAJSW5uZXJMaXN0AEwAAAAGAHMAAAALQ29tcGxleExpc3QAbgAAAAE1AGIAA" + "AAGAAECAwQFAEwAAAAFAD8BAAAAAABMAAAAAQA/AABNAAAAAwBzAAAABFBpbms" + "AcwAAAAVGbG95ZABzAAAABFRlc3QAPwEAcwAAAAdWZXJzaW9uAG4AAAABMQAAA" + "E0AAAADAHMAAAAETGlzdABMAAAABQBuAAAAATUAbgAAAAE0AG4AAAABMwBuAAA" + "AATIAbgAAAAExAHMAAAADTWFwAE0AAAABAHMAAAAGTmVzdGVkAD8BAHMAAAAEV" + "HJ1ZQA/AQBzAAAACVNpbmdsZU1hcABNAAAAAQBzAAAAA0ZPTwBzAAAAA0JBUgB" + "zAAAACVN0cmluZ1NldABTAAAAAwAAAANiYXIAAAADYmF6AAAAA2Zvbw=="; private static AttributeValue buildComplexAttributeValue() { Map<String, AttributeValue> floydMap = new HashMap<String, AttributeValue>(); floydMap.put("Pink", new AttributeValue().withS("Floyd")); floydMap.put("Version", new AttributeValue().withN("1")); floydMap.put("Test", new AttributeValue().withBOOL(Boolean.TRUE)); List<AttributeValue> floydList = Arrays.asList( new AttributeValue().withBOOL(Boolean.TRUE), new AttributeValue().withNULL(Boolean.TRUE), new AttributeValue().withNULL(Boolean.TRUE), new AttributeValue().withL(new AttributeValue().withBOOL(Boolean.FALSE)), new AttributeValue().withM(floydMap)); List<AttributeValue> nestedList = Arrays.asList( new AttributeValue().withN("5"), new AttributeValue().withN("4"), new AttributeValue().withN("3"), new AttributeValue().withN("2"), new AttributeValue().withN("1")); Map<String, AttributeValue> nestedMap = new HashMap<String, AttributeValue>(); nestedMap.put("True", new AttributeValue().withBOOL(Boolean.TRUE)); nestedMap.put("List", new AttributeValue().withL(nestedList)); nestedMap.put( "Map", new AttributeValue() .withM( Collections.singletonMap("Nested", new AttributeValue().withBOOL(Boolean.TRUE)))); List<AttributeValue> innerList = Arrays.asList( new AttributeValue().withS("ComplexList"), new AttributeValue().withN("5"), new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5})), new AttributeValue().withL(floydList), new AttributeValue().withNULL(Boolean.TRUE), new AttributeValue().withM(nestedMap)); AttributeValue av = new AttributeValue(); av.addMEntry( "SingleMap", new AttributeValue() .withM(Collections.singletonMap("FOO", new AttributeValue().withS("BAR")))); av.addMEntry("InnerList", new AttributeValue().withL(innerList)); av.addMEntry("StringSet", new AttributeValue().withSS("foo", "bar", "baz")); return av; } private void assertEquals(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()); Assert.assertEquals(o1.getBOOL(), o2.getBOOL()); Assert.assertEquals(o1.getNULL(), o2.getNULL()); if (o1.getL() != null) { Assert.assertNotNull(o2.getL()); final List<AttributeValue> l1 = o1.getL(); final List<AttributeValue> l2 = o2.getL(); Assert.assertEquals(l1.size(), l2.size()); for (int x = 0; x < l1.size(); ++x) { assertEquals(l1.get(x), l2.get(x)); } } if (o1.getM() != null) { Assert.assertNotNull(o2.getM()); final Map<String, AttributeValue> m1 = o1.getM(); final Map<String, AttributeValue> m2 = o2.getM(); Assert.assertEquals(m1.size(), m2.size()); for (Map.Entry<String, AttributeValue> entry : m1.entrySet()) { assertEquals(entry.getValue(), m2.get(entry.getKey())); } } } 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,304
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/internal/Base64Tests.java
/* * Copyright 2019 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.internal; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.quicktheories.QuickTheory.qt; import static org.quicktheories.generators.Generate.byteArrays; import static org.quicktheories.generators.Generate.bytes; import static org.quicktheories.generators.SourceDSL.integers; import java.nio.charset.StandardCharsets; import java.util.Arrays; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.Test; /** Tests for the Base64 interface used by the DynamoDBEncryptionClient */ public class Base64Tests { @Test public void testBase64EncodeEquivalence() { qt().forAll( byteArrays( integers().between(0, 1000000), bytes(Byte.MIN_VALUE, Byte.MAX_VALUE, (byte) 0))) .check( (a) -> { // Base64 encode using both implementations and check for equality of output // in case one version produces different output String sdk1Base64 = com.amazonaws.util.Base64.encodeAsString(a); String encryptionClientBase64 = Base64.encodeToString(a); return StringUtils.equals(sdk1Base64, encryptionClientBase64); }); } @Test public void testBase64DecodeEquivalence() { qt().forAll( byteArrays( integers().between(0, 10000), bytes(Byte.MIN_VALUE, Byte.MAX_VALUE, (byte) 0))) .as((b) -> java.util.Base64.getMimeEncoder().encodeToString(b)) .check( (s) -> { // Check for equality using the MimeEncoder, which inserts newlines // The encryptionClient's decoder is expected to ignore them byte[] sdk1Bytes = com.amazonaws.util.Base64.decode(s); byte[] encryptionClientBase64 = Base64.decode(s); return Arrays.equals(sdk1Bytes, encryptionClientBase64); }); } @Test public void testNullDecodeBehavior() { byte[] decoded = Base64.decode(null); assertThat(decoded, equalTo(null)); } @Test public void testNullDecodeBehaviorSdk1() { byte[] decoded = com.amazonaws.util.Base64.decode((String) null); assertThat(decoded, equalTo(null)); byte[] decoded2 = com.amazonaws.util.Base64.decode((byte[]) null); assertThat(decoded2, equalTo(null)); } @Test public void testBase64PaddingBehavior() { String testInput = "another one bites the dust"; String expectedEncoding = "YW5vdGhlciBvbmUgYml0ZXMgdGhlIGR1c3Q="; assertThat( Base64.encodeToString(testInput.getBytes(StandardCharsets.UTF_8)), equalTo(expectedEncoding)); String encodingWithoutPadding = "YW5vdGhlciBvbmUgYml0ZXMgdGhlIGR1c3Q"; assertThat(Base64.decode(encodingWithoutPadding), equalTo(testInput.getBytes())); } @Test(expectedExceptions = IllegalArgumentException.class) public void testBase64PaddingBehaviorSdk1() { String testInput = "another one bites the dust"; String encodingWithoutPadding = "YW5vdGhlciBvbmUgYml0ZXMgdGhlIGR1c3Q"; com.amazonaws.util.Base64.decode(encodingWithoutPadding); } @Test public void rfc4648TestVectors() { assertThat(Base64.encodeToString("".getBytes(StandardCharsets.UTF_8)), equalTo("")); assertThat(Base64.encodeToString("f".getBytes(StandardCharsets.UTF_8)), equalTo("Zg==")); assertThat(Base64.encodeToString("fo".getBytes(StandardCharsets.UTF_8)), equalTo("Zm8=")); assertThat(Base64.encodeToString("foo".getBytes(StandardCharsets.UTF_8)), equalTo("Zm9v")); assertThat(Base64.encodeToString("foob".getBytes(StandardCharsets.UTF_8)), equalTo("Zm9vYg==")); assertThat( Base64.encodeToString("fooba".getBytes(StandardCharsets.UTF_8)), equalTo("Zm9vYmE=")); assertThat( Base64.encodeToString("foobar".getBytes(StandardCharsets.UTF_8)), equalTo("Zm9vYmFy")); } }
4,305
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/internal/HkdfTests.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.datamodeling.internal; import static org.testng.AssertJUnit.assertArrayEquals; import org.testng.annotations.Test; public class HkdfTests { private static final testCase[] testCases = new testCase[] { new testCase( "HmacSHA256", fromCHex( "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b" + "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"), fromCHex("\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c"), fromCHex("\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9"), fromHex( "3CB25F25FAACD57A90434F64D0362F2A2D2D0A90CF1A5A4C5DB02D56ECC4C5BF34007208D5B887185865")), new testCase( "HmacSHA256", fromCHex( "\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d" + "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b" + "\\x1c\\x1d\\x1e\\x1f\\x20\\x21\\x22\\x23\\x24\\x25\\x26\\x27\\x28\\x29" + "\\x2a\\x2b\\x2c\\x2d\\x2e\\x2f\\x30\\x31\\x32\\x33\\x34\\x35\\x36\\x37" + "\\x38\\x39\\x3a\\x3b\\x3c\\x3d\\x3e\\x3f\\x40\\x41\\x42\\x43\\x44\\x45" + "\\x46\\x47\\x48\\x49\\x4a\\x4b\\x4c\\x4d\\x4e\\x4f"), fromCHex( "\\x60\\x61\\x62\\x63\\x64\\x65\\x66\\x67\\x68\\x69\\x6a\\x6b\\x6c\\x6d" + "\\x6e\\x6f\\x70\\x71\\x72\\x73\\x74\\x75\\x76\\x77\\x78\\x79\\x7a\\x7b" + "\\x7c\\x7d\\x7e\\x7f\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89" + "\\x8a\\x8b\\x8c\\x8d\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97" + "\\x98\\x99\\x9a\\x9b\\x9c\\x9d\\x9e\\x9f\\xa0\\xa1\\xa2\\xa3\\xa4\\xa5" + "\\xa6\\xa7\\xa8\\xa9\\xaa\\xab\\xac\\xad\\xae\\xaf"), fromCHex( "\\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7\\xb8\\xb9\\xba\\xbb\\xbc\\xbd" + "\\xbe\\xbf\\xc0\\xc1\\xc2\\xc3\\xc4\\xc5\\xc6\\xc7\\xc8\\xc9\\xca\\xcb" + "\\xcc\\xcd\\xce\\xcf\\xd0\\xd1\\xd2\\xd3\\xd4\\xd5\\xd6\\xd7\\xd8\\xd9" + "\\xda\\xdb\\xdc\\xdd\\xde\\xdf\\xe0\\xe1\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7" + "\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5" + "\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd\\xfe\\xff"), fromHex( "B11E398DC80327A1C8E7F78C596A4934" + "4F012EDA2D4EFAD8A050CC4C19AFA97C" + "59045A99CAC7827271CB41C65E590E09" + "DA3275600C2F09B8367793A9ACA3DB71" + "CC30C58179EC3E87C14C01D5C1F3434F" + "1D87")), new testCase( "HmacSHA256", fromCHex( "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b" + "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"), new byte[0], new byte[0], fromHex( "8DA4E775A563C18F715F802A063C5A31" + "B8A11F5C5EE1879EC3454E5F3C738D2D" + "9D201395FAA4B61A96C8")), new testCase( "HmacSHA1", fromCHex("\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"), fromCHex("\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c"), fromCHex("\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9"), fromHex( "085A01EA1B10F36933068B56EFA5AD81" + "A4F14B822F5B091568A9CDD4F155FDA2" + "C22E422478D305F3F896")), new testCase( "HmacSHA1", fromCHex( "\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d" + "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b" + "\\x1c\\x1d\\x1e\\x1f\\x20\\x21\\x22\\x23\\x24\\x25\\x26\\x27\\x28\\x29" + "\\x2a\\x2b\\x2c\\x2d\\x2e\\x2f\\x30\\x31\\x32\\x33\\x34\\x35\\x36\\x37" + "\\x38\\x39\\x3a\\x3b\\x3c\\x3d\\x3e\\x3f\\x40\\x41\\x42\\x43\\x44\\x45" + "\\x46\\x47\\x48\\x49\\x4a\\x4b\\x4c\\x4d\\x4e\\x4f"), fromCHex( "\\x60\\x61\\x62\\x63\\x64\\x65\\x66\\x67\\x68\\x69\\x6A\\x6B\\x6C\\x6D" + "\\x6E\\x6F\\x70\\x71\\x72\\x73\\x74\\x75\\x76\\x77\\x78\\x79\\x7A\\x7B" + "\\x7C\\x7D\\x7E\\x7F\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89" + "\\x8A\\x8B\\x8C\\x8D\\x8E\\x8F\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97" + "\\x98\\x99\\x9A\\x9B\\x9C\\x9D\\x9E\\x9F\\xA0\\xA1\\xA2\\xA3\\xA4\\xA5" + "\\xA6\\xA7\\xA8\\xA9\\xAA\\xAB\\xAC\\xAD\\xAE\\xAF"), fromCHex( "\\xB0\\xB1\\xB2\\xB3\\xB4\\xB5\\xB6\\xB7\\xB8\\xB9\\xBA\\xBB\\xBC\\xBD" + "\\xBE\\xBF\\xC0\\xC1\\xC2\\xC3\\xC4\\xC5\\xC6\\xC7\\xC8\\xC9\\xCA\\xCB" + "\\xCC\\xCD\\xCE\\xCF\\xD0\\xD1\\xD2\\xD3\\xD4\\xD5\\xD6\\xD7\\xD8\\xD9" + "\\xDA\\xDB\\xDC\\xDD\\xDE\\xDF\\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE6\\xE7" + "\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF\\xF0\\xF1\\xF2\\xF3\\xF4\\xF5" + "\\xF6\\xF7\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFE\\xFF"), fromHex( "0BD770A74D1160F7C9F12CD5912A06EB" + "FF6ADCAE899D92191FE4305673BA2FFE" + "8FA3F1A4E5AD79F3F334B3B202B2173C" + "486EA37CE3D397ED034C7F9DFEB15C5E" + "927336D0441F4C4300E2CFF0D0900B52D3B4")), new testCase( "HmacSHA1", fromCHex( "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b" + "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"), new byte[0], new byte[0], fromHex("0AC1AF7002B3D761D1E55298DA9D0506" + "B9AE52057220A306E07B6B87E8DF21D0")), new testCase( "HmacSHA1", fromCHex( "\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c" + "\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c"), null, new byte[0], fromHex( "2C91117204D745F3500D636A62F64F0A" + "B3BAE548AA53D423B0D1F27EBBA6F5E5" + "673A081D70CCE7ACFC48")) }; @Test public void rfc5869Tests() throws Exception { for (int x = 0; x < testCases.length; x++) { testCase trial = testCases[x]; System.out.println("Test case A." + (x + 1)); Hkdf kdf = Hkdf.getInstance(trial.algo); kdf.init(trial.ikm, trial.salt); byte[] result = kdf.deriveKey(trial.info, trial.expected.length); assertArrayEquals("Trial A." + x, trial.expected, result); } } @Test public void nullTests() throws Exception { testCase trial = testCases[0]; Hkdf kdf = Hkdf.getInstance(trial.algo); kdf.init(trial.ikm, trial.salt); // Just ensuring no exceptions are thrown kdf.deriveKey((String) null, 16); kdf.deriveKey((byte[]) null, 16); } @Test public void defaultSalt() throws Exception { // Tests all the different ways to get the default salt testCase trial = testCases[0]; Hkdf kdf1 = Hkdf.getInstance(trial.algo); kdf1.init(trial.ikm, null); Hkdf kdf2 = Hkdf.getInstance(trial.algo); kdf2.init(trial.ikm, new byte[0]); Hkdf kdf3 = Hkdf.getInstance(trial.algo); kdf3.init(trial.ikm); Hkdf kdf4 = Hkdf.getInstance(trial.algo); kdf4.init(trial.ikm, new byte[32]); byte[] key1 = kdf1.deriveKey("Test", 16); byte[] key2 = kdf2.deriveKey("Test", 16); byte[] key3 = kdf3.deriveKey("Test", 16); byte[] key4 = kdf4.deriveKey("Test", 16); assertArrayEquals(key1, key2); assertArrayEquals(key1, key3); assertArrayEquals(key1, key4); } private static byte[] fromHex(String data) { byte[] result = new byte[data.length() / 2]; for (int x = 0; x < result.length; x++) { result[x] = (byte) Integer.parseInt(data.substring(2 * x, 2 * x + 2), 16); } return result; } private static byte[] fromCHex(String data) { byte[] result = new byte[data.length() / 4]; for (int x = 0; x < result.length; x++) { result[x] = (byte) Integer.parseInt(data.substring(4 * x + 2, 4 * x + 4), 16); } return result; } private static class testCase { public final String algo; public final byte[] ikm; public final byte[] salt; public final byte[] info; public final byte[] expected; public testCase(String algo, byte[] ikm, byte[] salt, byte[] info, byte[] expected) { super(); this.algo = algo; this.ikm = ikm; this.salt = salt; this.info = info; this.expected = expected; } } }
4,306
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/internal/TTLCacheTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.services.dynamodbv2.datamodeling.internal; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.testng.Assert.assertThrows; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.util.concurrent.TimeUnit; import java.util.function.Function; import org.testng.annotations.Test; public class TTLCacheTest { private static final long TTL_GRACE_IN_NANO = TimeUnit.MILLISECONDS.toNanos(500); @Test(expectedExceptions = IllegalArgumentException.class) public void testInvalidSize() { final TTLCache<String> cache = new TTLCache<String>(0, 1000, mock(TTLCache.EntryLoader.class)); } @Test(expectedExceptions = IllegalArgumentException.class) public void testInvalidTTL() { final TTLCache<String> cache = new TTLCache<String>(3, 0, mock(TTLCache.EntryLoader.class)); } @Test(expectedExceptions = NullPointerException.class) public void testNullLoader() { final TTLCache<String> cache = new TTLCache<String>(3, 1000, null); } @Test public void testConstructor() { final TTLCache<String> cache = new TTLCache<String>(1000, 1000, mock(TTLCache.EntryLoader.class)); assertEquals(0, cache.size()); assertEquals(1000, cache.getMaxSize()); } @Test public void testLoadPastMaxSize() { final String loadedValue = "loaded value"; final long ttlInMillis = 1000; final int maxSize = 1; TTLCache.EntryLoader loader = spy(TTLCache.EntryLoader.class); when(loader.load(any())).thenReturn(loadedValue); MsClock clock = mock(MsClock.class); when(clock.timestampNano()).thenReturn((long) 0); final TTLCache<String> cache = new TTLCache<String>(maxSize, ttlInMillis, loader); cache.clock = clock; assertEquals(0, cache.size()); assertEquals(maxSize, cache.getMaxSize()); cache.load("k1"); verify(loader, times(1)).load("k1"); assertTrue(cache.size() == 1); String result = cache.load("k2"); verify(loader, times(1)).load("k2"); assertTrue(cache.size() == 1); assertEquals(loadedValue, result); // to verify result is in the cache, load one more time // and expect the loader to not be called String cachedValue = cache.load("k2"); verifyNoMoreInteractions(loader); assertTrue(cache.size() == 1); assertEquals(loadedValue, cachedValue); } @Test public void testLoadNoExistingEntry() { final String loadedValue = "loaded value"; final long ttlInMillis = 1000; final int maxSize = 3; TTLCache.EntryLoader loader = spy(TTLCache.EntryLoader.class); when(loader.load(any())).thenReturn(loadedValue); MsClock clock = mock(MsClock.class); when(clock.timestampNano()).thenReturn((long) 0); final TTLCache<String> cache = new TTLCache<String>(maxSize, ttlInMillis, loader); cache.clock = clock; assertEquals(0, cache.size()); assertEquals(maxSize, cache.getMaxSize()); String result = cache.load("k1"); verify(loader, times(1)).load("k1"); assertTrue(cache.size() == 1); assertEquals(loadedValue, result); // to verify result is in the cache, load one more time // and expect the loader to not be called String cachedValue = cache.load("k1"); verifyNoMoreInteractions(loader); assertTrue(cache.size() == 1); assertEquals(loadedValue, cachedValue); } @Test public void testLoadNotExpired() { final String loadedValue = "loaded value"; final long ttlInMillis = 1000; final int maxSize = 3; TTLCache.EntryLoader loader = spy(TTLCache.EntryLoader.class); when(loader.load(any())).thenReturn(loadedValue); MsClock clock = mock(MsClock.class); final TTLCache<String> cache = new TTLCache<String>(maxSize, ttlInMillis, loader); cache.clock = clock; assertEquals(0, cache.size()); assertEquals(maxSize, cache.getMaxSize()); // when first creating the entry, time is 0 when(clock.timestampNano()).thenReturn((long) 0); cache.load("k1"); assertTrue(cache.size() == 1); verify(loader, times(1)).load("k1"); // on load, time is within TTL when(clock.timestampNano()).thenReturn(TimeUnit.MILLISECONDS.toNanos(ttlInMillis)); String result = cache.load("k1"); verifyNoMoreInteractions(loader); assertTrue(cache.size() == 1); assertEquals(loadedValue, result); } @Test public void testLoadInGrace() { final String loadedValue = "loaded value"; final long ttlInMillis = 1000; final int maxSize = 3; TTLCache.EntryLoader loader = spy(TTLCache.EntryLoader.class); when(loader.load(any())).thenReturn(loadedValue); MsClock clock = mock(MsClock.class); final TTLCache<String> cache = new TTLCache<String>(maxSize, ttlInMillis, loader); cache.clock = clock; assertEquals(0, cache.size()); assertEquals(maxSize, cache.getMaxSize()); // when first creating the entry, time is zero when(clock.timestampNano()).thenReturn((long) 0); cache.load("k1"); assertTrue(cache.size() == 1); verify(loader, times(1)).load("k1"); // on load, time is past TTL but within the grace period when(clock.timestampNano()).thenReturn(TimeUnit.MILLISECONDS.toNanos(ttlInMillis) + 1); String result = cache.load("k1"); // Because this is tested in a single thread, // this is expected to obtain the lock and load the new value verify(loader, times(2)).load("k1"); verifyNoMoreInteractions(loader); assertTrue(cache.size() == 1); assertEquals(loadedValue, result); } @Test public void testLoadExpired() { final String loadedValue = "loaded value"; final long ttlInMillis = 1000; final int maxSize = 3; TTLCache.EntryLoader loader = spy(TTLCache.EntryLoader.class); when(loader.load(any())).thenReturn(loadedValue); MsClock clock = mock(MsClock.class); final TTLCache<String> cache = new TTLCache<String>(maxSize, ttlInMillis, loader); cache.clock = clock; assertEquals(0, cache.size()); assertEquals(maxSize, cache.getMaxSize()); // when first creating the entry, time is zero when(clock.timestampNano()).thenReturn((long) 0); cache.load("k1"); assertTrue(cache.size() == 1); verify(loader, times(1)).load("k1"); // on load, time is past TTL and grace period when(clock.timestampNano()) .thenReturn(TimeUnit.MILLISECONDS.toNanos(ttlInMillis) + TTL_GRACE_IN_NANO + 1); String result = cache.load("k1"); verify(loader, times(2)).load("k1"); verifyNoMoreInteractions(loader); assertTrue(cache.size() == 1); assertEquals(loadedValue, result); } @Test public void testLoadExpiredEviction() { final String loadedValue = "loaded value"; final long ttlInMillis = 1000; final int maxSize = 3; TTLCache.EntryLoader loader = spy(TTLCache.EntryLoader.class); when(loader.load(any())) .thenReturn(loadedValue) .thenThrow(new IllegalStateException("This loader is mocked to throw a failure.")); MsClock clock = mock(MsClock.class); final TTLCache<String> cache = new TTLCache<String>(maxSize, ttlInMillis, loader); cache.clock = clock; assertEquals(0, cache.size()); assertEquals(maxSize, cache.getMaxSize()); // when first creating the entry, time is zero when(clock.timestampNano()).thenReturn((long) 0); cache.load("k1"); verify(loader, times(1)).load("k1"); assertTrue(cache.size() == 1); // on load, time is past TTL and grace period when(clock.timestampNano()) .thenReturn(TimeUnit.MILLISECONDS.toNanos(ttlInMillis) + TTL_GRACE_IN_NANO + 1); assertThrows(IllegalStateException.class, () -> cache.load("k1")); verify(loader, times(2)).load("k1"); verifyNoMoreInteractions(loader); assertTrue(cache.size() == 0); } @Test public void testLoadWithFunction() { final String loadedValue = "loaded value"; final String functionValue = "function value"; final long ttlInMillis = 1000; final int maxSize = 3; final Function<String, String> function = spy(Function.class); when(function.apply(any())).thenReturn(functionValue); TTLCache.EntryLoader loader = spy(TTLCache.EntryLoader.class); when(loader.load(any())) .thenReturn(loadedValue) .thenThrow(new IllegalStateException("This loader is mocked to throw a failure.")); MsClock clock = mock(MsClock.class); when(clock.timestampNano()).thenReturn((long) 0); final TTLCache<String> cache = new TTLCache<String>(maxSize, ttlInMillis, loader); cache.clock = clock; assertEquals(0, cache.size()); assertEquals(maxSize, cache.getMaxSize()); String result = cache.load("k1", function); verify(function, times(1)).apply("k1"); assertTrue(cache.size() == 1); assertEquals(functionValue, result); // to verify result is in the cache, load one more time // and expect the loader to not be called String cachedValue = cache.load("k1"); verifyNoMoreInteractions(function); verifyNoMoreInteractions(loader); assertTrue(cache.size() == 1); assertEquals(functionValue, cachedValue); } @Test public void testClear() { final String loadedValue = "loaded value"; final long ttlInMillis = 1000; final int maxSize = 3; TTLCache.EntryLoader loader = spy(TTLCache.EntryLoader.class); when(loader.load(any())).thenReturn(loadedValue); final TTLCache<String> cache = new TTLCache<String>(maxSize, ttlInMillis, loader); assertTrue(cache.size() == 0); cache.load("k1"); cache.load("k2"); assertTrue(cache.size() == 2); cache.clear(); assertTrue(cache.size() == 0); } @Test public void testPut() { final long ttlInMillis = 1000; final int maxSize = 3; TTLCache.EntryLoader loader = spy(TTLCache.EntryLoader.class); MsClock clock = mock(MsClock.class); when(clock.timestampNano()).thenReturn((long) 0); final TTLCache<String> cache = new TTLCache<String>(maxSize, ttlInMillis, loader); cache.clock = clock; assertEquals(0, cache.size()); assertEquals(maxSize, cache.getMaxSize()); String oldValue = cache.put("k1", "v1"); assertNull(oldValue); assertTrue(cache.size() == 1); String oldValue2 = cache.put("k1", "v11"); assertEquals("v1", oldValue2); assertTrue(cache.size() == 1); } @Test public void testExpiredPut() { final long ttlInMillis = 1000; final int maxSize = 3; TTLCache.EntryLoader loader = spy(TTLCache.EntryLoader.class); MsClock clock = mock(MsClock.class); when(clock.timestampNano()).thenReturn((long) 0); final TTLCache<String> cache = new TTLCache<String>(maxSize, ttlInMillis, loader); cache.clock = clock; assertEquals(0, cache.size()); assertEquals(maxSize, cache.getMaxSize()); // First put is at time 0 String oldValue = cache.put("k1", "v1"); assertNull(oldValue); assertTrue(cache.size() == 1); // Second put is at time past TTL and grace period when(clock.timestampNano()) .thenReturn(TimeUnit.MILLISECONDS.toNanos(ttlInMillis) + TTL_GRACE_IN_NANO + 1); String oldValue2 = cache.put("k1", "v11"); assertNull(oldValue2); assertTrue(cache.size() == 1); } @Test public void testPutPastMaxSize() { final String loadedValue = "loaded value"; final long ttlInMillis = 1000; final int maxSize = 1; TTLCache.EntryLoader loader = spy(TTLCache.EntryLoader.class); when(loader.load(any())).thenReturn(loadedValue); MsClock clock = mock(MsClock.class); when(clock.timestampNano()).thenReturn((long) 0); final TTLCache<String> cache = new TTLCache<String>(maxSize, ttlInMillis, loader); cache.clock = clock; assertEquals(0, cache.size()); assertEquals(maxSize, cache.getMaxSize()); cache.put("k1", "v1"); assertTrue(cache.size() == 1); cache.put("k2", "v2"); assertTrue(cache.size() == 1); // to verify put value is in the cache, load // and expect the loader to not be called String cachedValue = cache.load("k2"); verifyNoMoreInteractions(loader); assertTrue(cache.size() == 1); assertEquals(cachedValue, "v2"); } }
4,307
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/internal/ConcurrentTTLCacheTest.java
package com.amazonaws.services.dynamodbv2.datamodeling.internal; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import edu.umd.cs.mtc.MultithreadedTestCase; import edu.umd.cs.mtc.TestFramework; import java.util.concurrent.TimeUnit; import org.testng.annotations.Test; /* Test specific thread interleavings with behaviors we care about in the * TTLCache. */ public class ConcurrentTTLCacheTest { private static final long TTL_GRACE_IN_NANO = TimeUnit.MILLISECONDS.toNanos(500); private static final long ttlInMillis = 1000; @Test public void testGracePeriodCase() throws Throwable { TestFramework.runOnce(new GracePeriodCase()); } @Test public void testExpiredCase() throws Throwable { TestFramework.runOnce(new ExpiredCase()); } @Test public void testNewEntryCase() throws Throwable { TestFramework.runOnce(new NewEntryCase()); } @Test public void testPutLoadCase() throws Throwable { TestFramework.runOnce(new PutLoadCase()); } // Ensure the loader is only called once if two threads attempt to load during the grace period class GracePeriodCase extends MultithreadedTestCase { TTLCache<String> cache; TTLCache.EntryLoader loader; MsClock clock = mock(MsClock.class); @Override public void initialize() { loader = spy( new TTLCache.EntryLoader<String>() { @Override public String load(String entryKey) { // Wait until thread2 finishes to complete load waitForTick(2); return "loadedValue"; } }); when(clock.timestampNano()).thenReturn((long) 0); cache = new TTLCache<>(3, ttlInMillis, loader); cache.clock = clock; // Put an initial value into the cache at time 0 cache.put("k1", "v1"); } // The thread that first calls load in the grace period and acquires the lock public void thread1() { when(clock.timestampNano()).thenReturn(TimeUnit.MILLISECONDS.toNanos(ttlInMillis) + 1); String loadedValue = cache.load("k1"); assertTick(2); // Expect to get back the value calculated from load assertEquals("loadedValue", loadedValue); } // The thread that calls load in the grace period after the lock has been acquired public void thread2() { // Wait until the first thread acquires the lock and starts load waitForTick(1); when(clock.timestampNano()).thenReturn(TimeUnit.MILLISECONDS.toNanos(ttlInMillis) + 1); String loadedValue = cache.load("k1"); // Expect to get back the original value in the cache assertEquals("v1", loadedValue); } @Override public void finish() { // Ensure the loader was only called once verify(loader, times(1)).load("k1"); } } // Ensure the loader is only called once if two threads attempt to load an expired entry. class ExpiredCase extends MultithreadedTestCase { TTLCache<String> cache; TTLCache.EntryLoader loader; MsClock clock = mock(MsClock.class); @Override public void initialize() { loader = spy( new TTLCache.EntryLoader<String>() { @Override public String load(String entryKey) { // Wait until thread2 is waiting for the lock to complete load waitForTick(2); return "loadedValue"; } }); when(clock.timestampNano()).thenReturn((long) 0); cache = new TTLCache<>(3, ttlInMillis, loader); cache.clock = clock; // Put an initial value into the cache at time 0 cache.put("k1", "v1"); } // The thread that first calls load after expiration public void thread1() { when(clock.timestampNano()) .thenReturn(TimeUnit.MILLISECONDS.toNanos(ttlInMillis) + TTL_GRACE_IN_NANO + 1); String loadedValue = cache.load("k1"); assertTick(2); // Expect to get back the value calculated from load assertEquals("loadedValue", loadedValue); } // The thread that calls load after expiration, // after the first thread calls load, but before // the new value is put into the cache. public void thread2() { // Wait until the first thread acquires the lock and starts load waitForTick(1); when(clock.timestampNano()) .thenReturn(TimeUnit.MILLISECONDS.toNanos(ttlInMillis) + TTL_GRACE_IN_NANO + 1); String loadedValue = cache.load("k1"); // Expect to get back the newly loaded value assertEquals("loadedValue", loadedValue); // assert that this thread only finishes once the first thread's load does assertTick(2); } @Override public void finish() { // Ensure the loader was only called once verify(loader, times(1)).load("k1"); } } // Ensure the loader is only called once if two threads attempt to load the same new entry. class NewEntryCase extends MultithreadedTestCase { TTLCache<String> cache; TTLCache.EntryLoader loader; MsClock clock = mock(MsClock.class); @Override public void initialize() { loader = spy( new TTLCache.EntryLoader<String>() { @Override public String load(String entryKey) { // Wait until thread2 is blocked to complete load waitForTick(2); return "loadedValue"; } }); when(clock.timestampNano()).thenReturn((long) 0); cache = new TTLCache<>(3, ttlInMillis, loader); cache.clock = clock; } // The thread that first calls load public void thread1() { String loadedValue = cache.load("k1"); assertTick(2); // Expect to get back the value calculated from load assertEquals("loadedValue", loadedValue); } // The thread that calls load after the first thread calls load, // but before the new value is put into the cache. public void thread2() { // Wait until the first thread acquires the lock and starts load waitForTick(1); String loadedValue = cache.load("k1"); // Expect to get back the newly loaded value assertEquals("loadedValue", loadedValue); // assert that this thread only finishes once the first thread's load does assertTick(2); } @Override public void finish() { // Ensure the loader was only called once verify(loader, times(1)).load("k1"); } } // Ensure the loader blocks put on load/put of the same new entry class PutLoadCase extends MultithreadedTestCase { TTLCache<String> cache; TTLCache.EntryLoader loader; MsClock clock = mock(MsClock.class); @Override public void initialize() { loader = spy( new TTLCache.EntryLoader<String>() { @Override public String load(String entryKey) { // Wait until the put blocks to complete load waitForTick(2); return "loadedValue"; } }); when(clock.timestampNano()).thenReturn((long) 0); cache = new TTLCache<>(3, ttlInMillis, loader); cache.clock = clock; } // The thread that first calls load public void thread1() { String loadedValue = cache.load("k1"); // Expect to get back the value calculated from load assertEquals("loadedValue", loadedValue); verify(loader, times(1)).load("k1"); } // The thread that calls put during the first thread's load public void thread2() { // Wait until the first thread is loading waitForTick(1); String previousValue = cache.put("k1", "v1"); // Expect to get back the value loaded into the cache by thread1 assertEquals("loadedValue", previousValue); // assert that this thread was blocked by the first thread assertTick(2); } } }
4,308
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/AttributeEncryptor.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 com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.SaveBehavior; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingsRegistry.Mapping; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingsRegistry.Mappings; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotEncrypt; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotTouch; 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.datamodeling.encryption.HandleUnknownAttributes; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.TableAadOverride; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.EncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * Encrypts all non-key fields prior to storing them in DynamoDB. <em>This must be used with {@link * SaveBehavior#PUT} or {@link SaveBehavior#CLOBBER}.</em> * * <p>For guidance on performing a safe data model change procedure, please see <a * href="https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/data-model.html" * target="_blank"> DynamoDB Encryption Client Developer Guide: Changing your data model</a> * * @author Greg Rubin */ public class AttributeEncryptor implements AttributeTransformer { private final DynamoDBEncryptor encryptor; private final Map<Class<?>, ModelClassMetadata> metadataCache = new ConcurrentHashMap<>(); public AttributeEncryptor(final DynamoDBEncryptor encryptor) { this.encryptor = encryptor; } public AttributeEncryptor(final EncryptionMaterialsProvider encryptionMaterialsProvider) { encryptor = DynamoDBEncryptor.getInstance(encryptionMaterialsProvider); } public DynamoDBEncryptor getEncryptor() { return encryptor; } @Override public Map<String, AttributeValue> transform(final Parameters<?> parameters) { // one map of attributeFlags per model class final ModelClassMetadata metadata = getModelClassMetadata(parameters); final Map<String, AttributeValue> attributeValues = parameters.getAttributeValues(); // If this class is marked as "DoNotTouch" then we know our encryptor will not change it at all // so we may as well fast-return and do nothing. This also avoids emitting errors when they // would not apply. if (metadata.doNotTouch) { return attributeValues; } // When AttributeEncryptor is used without SaveBehavior.PUT or CLOBBER, it is trying to // transform only a subset // of the actual fields stored in DynamoDB. This means that the generated signature will not // cover any // unmodified fields. Thus, upon untransform, the signature verification will fail as it won't // cover all // expected fields. if (parameters.isPartialUpdate()) { throw new DynamoDBMappingException( "Use of AttributeEncryptor without SaveBehavior.PUT or SaveBehavior.CLOBBER is an error " + "and can result in data-corruption. This occured while trying to save " + parameters.getModelClass()); } try { return encryptor.encryptRecord( attributeValues, metadata.getEncryptionFlags(), paramsToContext(parameters)); } catch (Exception ex) { throw new DynamoDBMappingException(ex); } } @Override public Map<String, AttributeValue> untransform(final Parameters<?> parameters) { final Map<String, Set<EncryptionFlags>> attributeFlags = getEncryptionFlags(parameters); try { return encryptor.decryptRecord( parameters.getAttributeValues(), attributeFlags, paramsToContext(parameters)); } catch (Exception ex) { throw new DynamoDBMappingException(ex); } } /* * For any attributes we see from DynamoDB that aren't modeled in the mapper class, * we either ignore them (the default behavior), or include them for encryption/signing * based on the presence of the @HandleUnknownAttributes annotation (unless the class * has @DoNotTouch, then we don't include them). */ private Map<String, Set<EncryptionFlags>> getEncryptionFlags(final Parameters<?> parameters) { final ModelClassMetadata metadata = getModelClassMetadata(parameters); // If the class is annotated with @DoNotTouch, then none of the attributes are // encrypted or signed, so we don't need to bother looking for unknown attributes. if (metadata.getDoNotTouch()) { return metadata.getEncryptionFlags(); } final Set<EncryptionFlags> unknownAttributeBehavior = metadata.getUnknownAttributeBehavior(); final Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<>(); attributeFlags.putAll(metadata.getEncryptionFlags()); for (final String attributeName : parameters.getAttributeValues().keySet()) { if (!attributeFlags.containsKey(attributeName) && !encryptor.getSignatureFieldName().equals(attributeName) && !encryptor.getMaterialDescriptionFieldName().equals(attributeName)) { attributeFlags.put(attributeName, unknownAttributeBehavior); } } return attributeFlags; } private <T> ModelClassMetadata getModelClassMetadata(Parameters<T> parameters) { // Due to the lack of explicit synchronization, it is possible that // elements in the cache will be added multiple times. Since they will // all be identical, this is okay. Avoiding explicit synchronization // means that in the general (retrieval) case, should never block and // should be extremely fast. final Class<T> clazz = parameters.getModelClass(); ModelClassMetadata metadata = metadataCache.get(clazz); if (metadata == null) { Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<>(); final boolean handleUnknownAttributes = handleUnknownAttributes(clazz); final EnumSet<EncryptionFlags> unknownAttributeBehavior = EnumSet.noneOf(EncryptionFlags.class); if (shouldTouch(clazz)) { Mappings mappings = DynamoDBMappingsRegistry.instance().mappingsOf(clazz); for (Mapping mapping : mappings.getMappings()) { final EnumSet<EncryptionFlags> flags = EnumSet.noneOf(EncryptionFlags.class); StandardAnnotationMaps.FieldMap<?> fieldMap = StandardAnnotationMaps.of(mapping.getter(), null); if (shouldTouch(fieldMap)) { if (shouldEncryptAttribute(clazz, mapping, fieldMap)) { flags.add(EncryptionFlags.ENCRYPT); } flags.add(EncryptionFlags.SIGN); } attributeFlags.put(mapping.getAttributeName(), Collections.unmodifiableSet(flags)); } if (handleUnknownAttributes) { unknownAttributeBehavior.add(EncryptionFlags.SIGN); if (shouldEncrypt(clazz)) { unknownAttributeBehavior.add(EncryptionFlags.ENCRYPT); } } } metadata = new ModelClassMetadata( Collections.unmodifiableMap(attributeFlags), doNotTouch(clazz), Collections.unmodifiableSet(unknownAttributeBehavior)); metadataCache.put(clazz, metadata); } return metadata; } /** @return True if {@link DoNotTouch} is not present on the class level. False otherwise */ private boolean shouldTouch(Class<?> clazz) { return !doNotTouch(clazz); } /** @return True if {@link DoNotTouch} is not present on the getter level. False otherwise. */ private boolean shouldTouch(StandardAnnotationMaps.FieldMap<?> fieldMap) { return !doNotTouch(fieldMap); } /** @return True if {@link DoNotTouch} IS present on the class level. False otherwise. */ private boolean doNotTouch(Class<?> clazz) { return clazz.isAnnotationPresent(DoNotTouch.class); } /** @return True if {@link DoNotTouch} IS present on the getter level. False otherwise. */ private boolean doNotTouch(StandardAnnotationMaps.FieldMap<?> fieldMap) { return fieldMap.actualOf(DoNotTouch.class) != null; } /** @return True if {@link DoNotEncrypt} is NOT present on the class level. False otherwise. */ private boolean shouldEncrypt(Class<?> clazz) { return !doNotEncrypt(clazz); } /** @return True if {@link DoNotEncrypt} IS present on the class level. False otherwise. */ private boolean doNotEncrypt(Class<?> clazz) { return clazz.isAnnotationPresent(DoNotEncrypt.class); } /** @return True if {@link DoNotEncrypt} IS present on the getter level. False otherwise. */ private boolean doNotEncrypt(StandardAnnotationMaps.FieldMap<?> fieldMap) { return fieldMap.actualOf(DoNotEncrypt.class) != null; } /** @return True if the attribute should be encrypted, false otherwise. */ private boolean shouldEncryptAttribute( final Class<?> clazz, final Mapping mapping, final StandardAnnotationMaps.FieldMap<?> fieldMap) { return !(doNotEncrypt(clazz) || doNotEncrypt(fieldMap) || mapping.isPrimaryKey() || mapping.isVersion()); } private static EncryptionContext paramsToContext(Parameters<?> params) { final Class<?> clazz = params.getModelClass(); final TableAadOverride override = clazz.getAnnotation(TableAadOverride.class); final String tableName = ((override == null) ? params.getTableName() : override.tableName()); return new EncryptionContext.Builder() .withHashKeyName(params.getHashKeyName()) .withRangeKeyName(params.getRangeKeyName()) .withTableName(tableName) .withModeledClass(params.getModelClass()) .withAttributeValues(params.getAttributeValues()) .build(); } private boolean handleUnknownAttributes(Class<?> clazz) { return clazz.getAnnotation(HandleUnknownAttributes.class) != null; } private static class ModelClassMetadata { private final Map<String, Set<EncryptionFlags>> encryptionFlags; private final boolean doNotTouch; private final Set<EncryptionFlags> unknownAttributeBehavior; public ModelClassMetadata( Map<String, Set<EncryptionFlags>> encryptionFlags, boolean doNotTouch, Set<EncryptionFlags> unknownAttributeBehavior) { this.encryptionFlags = encryptionFlags; this.doNotTouch = doNotTouch; this.unknownAttributeBehavior = unknownAttributeBehavior; } public Map<String, Set<EncryptionFlags>> getEncryptionFlags() { return encryptionFlags; } public boolean getDoNotTouch() { return doNotTouch; } public Set<EncryptionFlags> getUnknownAttributeBehavior() { return unknownAttributeBehavior; } } }
4,309
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/DynamoDBSigner.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.AttributeValueMarshaller; import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.security.GeneralSecurityException; import java.security.Key; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Signature; import java.security.SignatureException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; /** * For guidance on performing a safe data model change procedure, please see <a * href="https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/data-model.html" * target="_blank"> DynamoDB Encryption Client Developer Guide: Changing your data model</a> * * @author Greg Rubin */ // NOTE: This class must remain thread-safe. class DynamoDBSigner { private static final ConcurrentHashMap<String, DynamoDBSigner> cache = new ConcurrentHashMap<String, DynamoDBSigner>(); protected static final Charset UTF8 = Charset.forName("UTF-8"); private final SecureRandom rnd; private final SecretKey hmacComparisonKey; private final String signingAlgorithm; /** * @param signingAlgorithm is the algorithm used for asymmetric signing (ex: SHA256withRSA). This * is ignored for symmetric HMACs as that algorithm is fully specified by the key. */ static DynamoDBSigner getInstance(String signingAlgorithm, SecureRandom rnd) { DynamoDBSigner result = cache.get(signingAlgorithm); if (result == null) { result = new DynamoDBSigner(signingAlgorithm, rnd); cache.putIfAbsent(signingAlgorithm, result); } return result; } /** * @param signingAlgorithm is the algorithm used for asymmetric signing (ex: SHA256withRSA). This * is ignored for symmetric HMACs as that algorithm is fully specified by the key. */ private DynamoDBSigner(String signingAlgorithm, SecureRandom rnd) { if (rnd == null) { rnd = Utils.getRng(); } this.rnd = rnd; this.signingAlgorithm = signingAlgorithm; // Shorter than the output of SHA256 to avoid weak keys. // http://cs.nyu.edu/~dodis/ps/h-of-h.pdf // http://link.springer.com/chapter/10.1007%2F978-3-642-32009-5_21 byte[] tmpKey = new byte[31]; rnd.nextBytes(tmpKey); hmacComparisonKey = new SecretKeySpec(tmpKey, "HmacSHA256"); } void verifySignature( Map<String, AttributeValue> itemAttributes, Map<String, Set<EncryptionFlags>> attributeFlags, byte[] associatedData, Key verificationKey, ByteBuffer signature) throws GeneralSecurityException { if (verificationKey instanceof DelegatedKey) { DelegatedKey dKey = (DelegatedKey) verificationKey; byte[] stringToSign = calculateStringToSign(itemAttributes, attributeFlags, associatedData); if (!dKey.verify(stringToSign, toByteArray(signature), dKey.getAlgorithm())) { throw new SignatureException("Bad signature"); } } else if (verificationKey instanceof SecretKey) { byte[] calculatedSig = calculateSignature( itemAttributes, attributeFlags, associatedData, (SecretKey) verificationKey); if (!safeEquals(signature, calculatedSig)) { throw new SignatureException("Bad signature"); } } else if (verificationKey instanceof PublicKey) { PublicKey integrityKey = (PublicKey) verificationKey; byte[] stringToSign = calculateStringToSign(itemAttributes, attributeFlags, associatedData); Signature sig = Signature.getInstance(getSigningAlgorithm()); sig.initVerify(integrityKey); sig.update(stringToSign); if (!sig.verify(toByteArray(signature))) { throw new SignatureException("Bad signature"); } } else { throw new IllegalArgumentException("No integrity key provided"); } } static byte[] calculateStringToSign( Map<String, AttributeValue> itemAttributes, Map<String, Set<EncryptionFlags>> attributeFlags, byte[] associatedData) throws NoSuchAlgorithmException { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); List<String> attrNames = new ArrayList<String>(itemAttributes.keySet()); Collections.sort(attrNames); MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); if (associatedData != null) { out.write(sha256.digest(associatedData)); } else { out.write(sha256.digest()); } sha256.reset(); for (String name : attrNames) { Set<EncryptionFlags> set = attributeFlags.get(name); if (set != null && set.contains(EncryptionFlags.SIGN)) { AttributeValue tmp = itemAttributes.get(name); out.write(sha256.digest(name.getBytes(UTF8))); sha256.reset(); if (set.contains(EncryptionFlags.ENCRYPT)) { sha256.update("ENCRYPTED".getBytes(UTF8)); } else { sha256.update("PLAINTEXT".getBytes(UTF8)); } out.write(sha256.digest()); sha256.reset(); sha256.update(AttributeValueMarshaller.marshall(tmp)); out.write(sha256.digest()); sha256.reset(); } } return out.toByteArray(); } catch (IOException ex) { // Due to the objects in use, an IOException is not possible. throw new RuntimeException("Unexpected exception", ex); } } /** The itemAttributes have already been encrypted, if necessary, before the signing. */ byte[] calculateSignature( Map<String, AttributeValue> itemAttributes, Map<String, Set<EncryptionFlags>> attributeFlags, byte[] associatedData, Key key) throws GeneralSecurityException { if (key instanceof DelegatedKey) { return calculateSignature(itemAttributes, attributeFlags, associatedData, (DelegatedKey) key); } else if (key instanceof SecretKey) { return calculateSignature(itemAttributes, attributeFlags, associatedData, (SecretKey) key); } else if (key instanceof PrivateKey) { return calculateSignature(itemAttributes, attributeFlags, associatedData, (PrivateKey) key); } else { throw new IllegalArgumentException("No integrity key provided"); } } byte[] calculateSignature( Map<String, AttributeValue> itemAttributes, Map<String, Set<EncryptionFlags>> attributeFlags, byte[] associatedData, DelegatedKey key) throws GeneralSecurityException { byte[] stringToSign = calculateStringToSign(itemAttributes, attributeFlags, associatedData); return key.sign(stringToSign, key.getAlgorithm()); } byte[] calculateSignature( Map<String, AttributeValue> itemAttributes, Map<String, Set<EncryptionFlags>> attributeFlags, byte[] associatedData, SecretKey key) throws GeneralSecurityException { if (key instanceof DelegatedKey) { return calculateSignature(itemAttributes, attributeFlags, associatedData, (DelegatedKey) key); } byte[] stringToSign = calculateStringToSign(itemAttributes, attributeFlags, associatedData); Mac hmac = Mac.getInstance(key.getAlgorithm()); hmac.init(key); hmac.update(stringToSign); return hmac.doFinal(); } byte[] calculateSignature( Map<String, AttributeValue> itemAttributes, Map<String, Set<EncryptionFlags>> attributeFlags, byte[] associatedData, PrivateKey key) throws GeneralSecurityException { byte[] stringToSign = calculateStringToSign(itemAttributes, attributeFlags, associatedData); Signature sig = Signature.getInstance(signingAlgorithm); sig.initSign(key, rnd); sig.update(stringToSign); return sig.sign(); } String getSigningAlgorithm() { return signingAlgorithm; } /** Constant-time equality check. */ private boolean safeEquals(ByteBuffer signature, byte[] calculatedSig) { try { signature.rewind(); Mac hmac = Mac.getInstance(hmacComparisonKey.getAlgorithm()); hmac.init(hmacComparisonKey); hmac.update(signature); byte[] signatureHash = hmac.doFinal(); hmac.reset(); hmac.update(calculatedSig); byte[] calculatedHash = hmac.doFinal(); return MessageDigest.isEqual(signatureHash, calculatedHash); } catch (GeneralSecurityException ex) { // We've hardcoded these algorithms, so the error should not be possible. throw new RuntimeException("Unexpected exception", ex); } } private static byte[] toByteArray(ByteBuffer buffer) { if (buffer.hasArray()) { byte[] result = buffer.array(); buffer.rewind(); return result; } else { byte[] result = new byte[buffer.remaining()]; buffer.get(result); buffer.rewind(); return result; } } }
4,310
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/TableAadOverride.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.datamodeling.encryption; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Overrides the default tablename used as part of the data signature with {@code tableName} * instead. This can be useful when multiple tables are used interchangably and data should be able * to be copied or moved between them without needing to be reencrypted. * * <p>For guidance on performing a safe data model change procedure, please see <a * href="https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/data-model.html" * target="_blank"> DynamoDB Encryption Client Developer Guide: Changing your data model</a> * * @author Greg Rubin */ @Target(value = {ElementType.TYPE}) @Retention(value = RetentionPolicy.RUNTIME) public @interface TableAadOverride { String tableName(); }
4,311
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/DynamoDBEncryptor.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.AttributeEncryptor; 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.internal.AttributeValueMarshaller; import com.amazonaws.services.dynamodbv2.datamodeling.internal.ByteBufferInputStream; import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.security.GeneralSecurityException; import java.security.PrivateKey; import java.security.SignatureException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; /** * The low-level API used by {@link AttributeEncryptor} to perform crypto operations on the record * attributes. * * <p>For guidance on performing a safe data model change procedure, please see <a * href="https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/data-model.html" * target="_blank"> DynamoDB Encryption Client Developer Guide: Changing your data model</a> * * @author Greg Rubin */ public class DynamoDBEncryptor { private static final String DEFAULT_SIGNATURE_ALGORITHM = "SHA256withRSA"; private static final String DEFAULT_METADATA_FIELD = "*amzn-ddb-map-desc*"; private static final String DEFAULT_SIGNATURE_FIELD = "*amzn-ddb-map-sig*"; private static final String DEFAULT_DESCRIPTION_BASE = "amzn-ddb-map-"; // Same as the Mapper private static final Charset UTF8 = Charset.forName("UTF-8"); private static final String SYMMETRIC_ENCRYPTION_MODE = "/CBC/PKCS5Padding"; private static final ConcurrentHashMap<String, Integer> BLOCK_SIZE_CACHE = new ConcurrentHashMap<>(); private static final Function<String, Integer> BLOCK_SIZE_CALCULATOR = (transformation) -> { try { final Cipher c = Cipher.getInstance(transformation); return c.getBlockSize(); } catch (final GeneralSecurityException ex) { throw new IllegalArgumentException("Algorithm does not exist", ex); } }; private static final int CURRENT_VERSION = 0; private String signatureFieldName = DEFAULT_SIGNATURE_FIELD; private String materialDescriptionFieldName = DEFAULT_METADATA_FIELD; private EncryptionMaterialsProvider encryptionMaterialsProvider; private final String descriptionBase; private final String symmetricEncryptionModeHeader; private final String signingAlgorithmHeader; public static final String DEFAULT_SIGNING_ALGORITHM_HEADER = DEFAULT_DESCRIPTION_BASE + "signingAlg"; private Function<EncryptionContext, EncryptionContext> encryptionContextOverrideOperator; protected DynamoDBEncryptor(EncryptionMaterialsProvider provider, String descriptionBase) { this.encryptionMaterialsProvider = provider; this.descriptionBase = descriptionBase; symmetricEncryptionModeHeader = this.descriptionBase + "sym-mode"; signingAlgorithmHeader = this.descriptionBase + "signingAlg"; } public static DynamoDBEncryptor getInstance( EncryptionMaterialsProvider provider, String descriptionbase) { return new DynamoDBEncryptor(provider, descriptionbase); } public static DynamoDBEncryptor getInstance(EncryptionMaterialsProvider provider) { return getInstance(provider, DEFAULT_DESCRIPTION_BASE); } /** * Returns a decrypted version of the provided DynamoDb record. The signature is verified across * all provided fields. All fields (except those listed in <code>doNotEncrypt</code> are * decrypted. * * @param itemAttributes the DynamoDbRecord * @param context additional information used to successfully select the encryption materials and * decrypt the data. This should include (at least) the tableName and the materialDescription. * @param doNotDecrypt those fields which should not be encrypted * @return a plaintext version of the DynamoDb record * @throws SignatureException if the signature is invalid or cannot be verified * @throws GeneralSecurityException */ public Map<String, AttributeValue> decryptAllFieldsExcept( Map<String, AttributeValue> itemAttributes, EncryptionContext context, String... doNotDecrypt) throws GeneralSecurityException { return decryptAllFieldsExcept(itemAttributes, context, Arrays.asList(doNotDecrypt)); } /** @see #decryptAllFieldsExcept(Map, EncryptionContext, String...) */ public Map<String, AttributeValue> decryptAllFieldsExcept( Map<String, AttributeValue> itemAttributes, EncryptionContext context, Collection<String> doNotDecrypt) throws GeneralSecurityException { Map<String, Set<EncryptionFlags>> attributeFlags = allDecryptionFlagsExcept(itemAttributes, doNotDecrypt); return decryptRecord(itemAttributes, attributeFlags, context); } /** * Returns the decryption flags for all item attributes except for those explicitly specified to * be excluded. * * @param doNotDecrypt fields to be excluded */ public Map<String, Set<EncryptionFlags>> allDecryptionFlagsExcept( Map<String, AttributeValue> itemAttributes, String... doNotDecrypt) { return allDecryptionFlagsExcept(itemAttributes, Arrays.asList(doNotDecrypt)); } /** * Returns the decryption flags for all item attributes except for those explicitly specified to * be excluded. * * @param doNotDecrypt fields to be excluded */ public Map<String, Set<EncryptionFlags>> allDecryptionFlagsExcept( Map<String, AttributeValue> itemAttributes, Collection<String> doNotDecrypt) { Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>(); for (String fieldName : doNotDecrypt) { attributeFlags.put(fieldName, EnumSet.of(EncryptionFlags.SIGN)); } for (String fieldName : itemAttributes.keySet()) { if (!attributeFlags.containsKey(fieldName) && !fieldName.equals(getMaterialDescriptionFieldName()) && !fieldName.equals(getSignatureFieldName())) { attributeFlags.put(fieldName, EnumSet.of(EncryptionFlags.ENCRYPT, EncryptionFlags.SIGN)); } } return attributeFlags; } /** * Returns an encrypted version of the provided DynamoDb record. All fields are signed. All fields * (except those listed in <code>doNotEncrypt</code>) are encrypted. * * @param itemAttributes a DynamoDb Record * @param context additional information used to successfully select the encryption materials and * encrypt the data. This should include (at least) the tableName. * @param doNotEncrypt those fields which should not be encrypted * @return a ciphertext version of the DynamoDb record * @throws GeneralSecurityException */ public Map<String, AttributeValue> encryptAllFieldsExcept( Map<String, AttributeValue> itemAttributes, EncryptionContext context, String... doNotEncrypt) throws GeneralSecurityException { return encryptAllFieldsExcept(itemAttributes, context, Arrays.asList(doNotEncrypt)); } public Map<String, AttributeValue> encryptAllFieldsExcept( Map<String, AttributeValue> itemAttributes, EncryptionContext context, Collection<String> doNotEncrypt) throws GeneralSecurityException { Map<String, Set<EncryptionFlags>> attributeFlags = allEncryptionFlagsExcept(itemAttributes, doNotEncrypt); return encryptRecord(itemAttributes, attributeFlags, context); } /** * Returns the encryption flags for all item attributes except for those explicitly specified to * be excluded. * * @param doNotEncrypt fields to be excluded */ public Map<String, Set<EncryptionFlags>> allEncryptionFlagsExcept( Map<String, AttributeValue> itemAttributes, String... doNotEncrypt) { return allEncryptionFlagsExcept(itemAttributes, Arrays.asList(doNotEncrypt)); } /** * Returns the encryption flags for all item attributes except for those explicitly specified to * be excluded. * * @param doNotEncrypt fields to be excluded */ public Map<String, Set<EncryptionFlags>> allEncryptionFlagsExcept( Map<String, AttributeValue> itemAttributes, Collection<String> doNotEncrypt) { Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>(); for (String fieldName : doNotEncrypt) { attributeFlags.put(fieldName, EnumSet.of(EncryptionFlags.SIGN)); } for (String fieldName : itemAttributes.keySet()) { if (!attributeFlags.containsKey(fieldName)) { attributeFlags.put(fieldName, EnumSet.of(EncryptionFlags.ENCRYPT, EncryptionFlags.SIGN)); } } return attributeFlags; } public Map<String, AttributeValue> decryptRecord( Map<String, AttributeValue> itemAttributes, Map<String, Set<EncryptionFlags>> attributeFlags, EncryptionContext context) throws GeneralSecurityException { if (!itemContainsFieldsToDecryptOrSign(itemAttributes.keySet(), attributeFlags)) { return itemAttributes; } // Copy to avoid changing anyone elses objects itemAttributes = new HashMap<String, AttributeValue>(itemAttributes); Map<String, String> materialDescription = Collections.emptyMap(); DecryptionMaterials materials; SecretKey decryptionKey; DynamoDBSigner signer = DynamoDBSigner.getInstance(DEFAULT_SIGNATURE_ALGORITHM, Utils.getRng()); if (itemAttributes.containsKey(materialDescriptionFieldName)) { materialDescription = unmarshallDescription(itemAttributes.get(materialDescriptionFieldName)); } // Copy the material description and attribute values into the context context = new EncryptionContext.Builder(context) .withMaterialDescription(materialDescription) .withAttributeValues(itemAttributes) .build(); Function<EncryptionContext, EncryptionContext> encryptionContextOverrideOperator = getEncryptionContextOverrideOperator(); if (encryptionContextOverrideOperator != null) { context = encryptionContextOverrideOperator.apply(context); } materials = encryptionMaterialsProvider.getDecryptionMaterials(context); decryptionKey = materials.getDecryptionKey(); if (materialDescription.containsKey(signingAlgorithmHeader)) { String signingAlg = materialDescription.get(signingAlgorithmHeader); signer = DynamoDBSigner.getInstance(signingAlg, Utils.getRng()); } ByteBuffer signature; if (!itemAttributes.containsKey(signatureFieldName) || itemAttributes.get(signatureFieldName).getB() == null) { signature = ByteBuffer.allocate(0); } else { signature = itemAttributes.get(signatureFieldName).getB().asReadOnlyBuffer(); } itemAttributes.remove(signatureFieldName); String associatedData = "TABLE>" + context.getTableName() + "<TABLE"; signer.verifySignature( itemAttributes, attributeFlags, associatedData.getBytes(UTF8), materials.getVerificationKey(), signature); itemAttributes.remove(materialDescriptionFieldName); actualDecryption(itemAttributes, attributeFlags, decryptionKey, materialDescription); return itemAttributes; } private boolean itemContainsFieldsToDecryptOrSign( Set<String> attributeNamesToCheck, Map<String, Set<EncryptionFlags>> attributeFlags) { return attributeNamesToCheck.stream() .filter(attributeFlags::containsKey) .anyMatch(attributeName -> !attributeFlags.get(attributeName).isEmpty()); } /** * Returns the encrypted (and signed) record, which is a map of item attributes. There is no side * effect on the input parameters upon calling this method. * * @param itemAttributes the input record * @param attributeFlags the corresponding encryption flags * @param context encryption context * @return a new instance of item attributes encrypted as necessary * @throws GeneralSecurityException if failed to encrypt the record */ public Map<String, AttributeValue> encryptRecord( Map<String, AttributeValue> itemAttributes, Map<String, Set<EncryptionFlags>> attributeFlags, EncryptionContext context) throws GeneralSecurityException { if (attributeFlags.isEmpty()) { return itemAttributes; } // Copy to avoid changing anyone elses objects itemAttributes = new HashMap<String, AttributeValue>(itemAttributes); // Copy the attribute values into the context context = new EncryptionContext.Builder(context).withAttributeValues(itemAttributes).build(); Function<EncryptionContext, EncryptionContext> encryptionContextOverrideOperator = getEncryptionContextOverrideOperator(); if (encryptionContextOverrideOperator != null) { context = encryptionContextOverrideOperator.apply(context); } EncryptionMaterials materials = encryptionMaterialsProvider.getEncryptionMaterials(context); // We need to copy this because we modify it to record other encryption details Map<String, String> materialDescription = new HashMap<String, String>(materials.getMaterialDescription()); SecretKey encryptionKey = materials.getEncryptionKey(); actualEncryption(itemAttributes, attributeFlags, materialDescription, encryptionKey); // The description must be stored after encryption because its data // is necessary for proper decryption. final String signingAlgo = materialDescription.get(signingAlgorithmHeader); DynamoDBSigner signer; if (signingAlgo != null) { signer = DynamoDBSigner.getInstance(signingAlgo, Utils.getRng()); } else { signer = DynamoDBSigner.getInstance(DEFAULT_SIGNATURE_ALGORITHM, Utils.getRng()); } if (materials.getSigningKey() instanceof PrivateKey) { materialDescription.put(signingAlgorithmHeader, signer.getSigningAlgorithm()); } if (!materialDescription.isEmpty()) { itemAttributes.put(materialDescriptionFieldName, marshallDescription(materialDescription)); } String associatedData = "TABLE>" + context.getTableName() + "<TABLE"; byte[] signature = signer.calculateSignature( itemAttributes, attributeFlags, associatedData.getBytes(UTF8), materials.getSigningKey()); AttributeValue signatureAttribute = new AttributeValue(); signatureAttribute.setB(ByteBuffer.wrap(signature)); itemAttributes.put(signatureFieldName, signatureAttribute); return itemAttributes; } private void actualDecryption( Map<String, AttributeValue> itemAttributes, Map<String, Set<EncryptionFlags>> attributeFlags, SecretKey encryptionKey, Map<String, String> materialDescription) throws GeneralSecurityException { final String encryptionMode = encryptionKey != null ? encryptionKey.getAlgorithm() + materialDescription.get(symmetricEncryptionModeHeader) : null; Cipher cipher = null; int blockSize = -1; for (Map.Entry<String, AttributeValue> entry : itemAttributes.entrySet()) { Set<EncryptionFlags> flags = attributeFlags.get(entry.getKey()); if (flags != null && flags.contains(EncryptionFlags.ENCRYPT)) { if (!flags.contains(EncryptionFlags.SIGN)) { throw new IllegalArgumentException( "All encrypted fields must be signed. Bad field: " + entry.getKey()); } ByteBuffer plainText; ByteBuffer cipherText = entry.getValue().getB().asReadOnlyBuffer(); cipherText.rewind(); if (encryptionKey instanceof DelegatedKey) { plainText = ByteBuffer.wrap( ((DelegatedKey) encryptionKey) .decrypt(toByteArray(cipherText), null, encryptionMode)); } else { if (cipher == null) { blockSize = getBlockSize(encryptionMode); cipher = Cipher.getInstance(encryptionMode); } byte[] iv = new byte[blockSize]; cipherText.get(iv); cipher.init(Cipher.DECRYPT_MODE, encryptionKey, new IvParameterSpec(iv), Utils.getRng()); plainText = ByteBuffer.allocate(cipher.getOutputSize(cipherText.remaining())); cipher.doFinal(cipherText, plainText); plainText.rewind(); } entry.setValue(AttributeValueMarshaller.unmarshall(plainText)); } } } protected static int getBlockSize(final String encryptionMode) { return BLOCK_SIZE_CACHE.computeIfAbsent(encryptionMode, BLOCK_SIZE_CALCULATOR); } /** * This method has the side effect of replacing the plaintext attribute-values of "itemAttributes" * with ciphertext attribute-values (which are always in the form of ByteBuffer) as per the * corresponding attribute flags. */ private void actualEncryption( Map<String, AttributeValue> itemAttributes, Map<String, Set<EncryptionFlags>> attributeFlags, Map<String, String> materialDescription, SecretKey encryptionKey) throws GeneralSecurityException { String encryptionMode = null; if (encryptionKey != null) { materialDescription.put(this.symmetricEncryptionModeHeader, SYMMETRIC_ENCRYPTION_MODE); encryptionMode = encryptionKey.getAlgorithm() + SYMMETRIC_ENCRYPTION_MODE; } Cipher cipher = null; int blockSize = -1; for (Map.Entry<String, AttributeValue> entry : itemAttributes.entrySet()) { Set<EncryptionFlags> flags = attributeFlags.get(entry.getKey()); if (flags != null && flags.contains(EncryptionFlags.ENCRYPT)) { if (!flags.contains(EncryptionFlags.SIGN)) { throw new IllegalArgumentException( "All encrypted fields must be signed. Bad field: " + entry.getKey()); } ByteBuffer plainText = AttributeValueMarshaller.marshall(entry.getValue()); plainText.rewind(); ByteBuffer cipherText; if (encryptionKey instanceof DelegatedKey) { DelegatedKey dk = (DelegatedKey) encryptionKey; cipherText = ByteBuffer.wrap(dk.encrypt(toByteArray(plainText), null, encryptionMode)); } else { if (cipher == null) { blockSize = getBlockSize(encryptionMode); cipher = Cipher.getInstance(encryptionMode); } // Encryption format: <iv><ciphertext> // Note a unique iv is generated per attribute cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, Utils.getRng()); cipherText = ByteBuffer.allocate(blockSize + cipher.getOutputSize(plainText.remaining())); cipherText.position(blockSize); cipher.doFinal(plainText, cipherText); cipherText.flip(); final byte[] iv = cipher.getIV(); if (iv.length != blockSize) { throw new IllegalStateException( String.format( "Generated IV length (%d) not equal to block size (%d)", iv.length, blockSize)); } cipherText.put(iv); cipherText.rewind(); } // Replace the plaintext attribute value with the encrypted content entry.setValue(new AttributeValue().withB(cipherText)); } } } /** * Get the name of the DynamoDB field used to store the signature. Defaults to {@link * #DEFAULT_SIGNATURE_FIELD}. * * @return the name of the DynamoDB field used to store the signature */ public String getSignatureFieldName() { return signatureFieldName; } /** * Set the name of the DynamoDB field used to store the signature. * * @param signatureFieldName */ public void setSignatureFieldName(final String signatureFieldName) { this.signatureFieldName = signatureFieldName; } /** * Get the name of the DynamoDB field used to store metadata used by the DynamoDBEncryptedMapper. * Defaults to {@link #DEFAULT_METADATA_FIELD}. * * @return the name of the DynamoDB field used to store metadata used by the * DynamoDBEncryptedMapper */ public String getMaterialDescriptionFieldName() { return materialDescriptionFieldName; } /** * Set the name of the DynamoDB field used to store metadata used by the DynamoDBEncryptedMapper * * @param materialDescriptionFieldName */ public void setMaterialDescriptionFieldName(final String materialDescriptionFieldName) { this.materialDescriptionFieldName = materialDescriptionFieldName; } /** * Marshalls the <code>description</code> into a ByteBuffer by outputting each key (modified * UTF-8) followed by its value (also in modified UTF-8). * * @param description * @return the description encoded as an AttributeValue with a ByteBuffer value * @see java.io.DataOutput#writeUTF(String) */ protected static AttributeValue marshallDescription(Map<String, String> description) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(bos); out.writeInt(CURRENT_VERSION); for (Map.Entry<String, String> entry : description.entrySet()) { byte[] bytes = entry.getKey().getBytes(UTF8); out.writeInt(bytes.length); out.write(bytes); bytes = entry.getValue().getBytes(UTF8); out.writeInt(bytes.length); out.write(bytes); } out.close(); AttributeValue result = new AttributeValue(); result.setB(ByteBuffer.wrap(bos.toByteArray())); return result; } catch (IOException ex) { // Due to the objects in use, an IOException is not possible. throw new RuntimeException("Unexpected exception", ex); } } public String getSigningAlgorithmHeader() { return signingAlgorithmHeader; } /** @see #marshallDescription(Map) */ protected static Map<String, String> unmarshallDescription(AttributeValue attributeValue) { attributeValue.getB().mark(); try (DataInputStream in = new DataInputStream(new ByteBufferInputStream(attributeValue.getB()))) { Map<String, String> result = new HashMap<String, String>(); int version = in.readInt(); if (version != CURRENT_VERSION) { throw new IllegalArgumentException("Unsupported description version"); } String key, value; int keyLength, valueLength; try { while (in.available() > 0) { keyLength = in.readInt(); byte[] bytes = new byte[keyLength]; if (in.read(bytes) != keyLength) { throw new IllegalArgumentException("Malformed description"); } key = new String(bytes, UTF8); valueLength = in.readInt(); bytes = new byte[valueLength]; if (in.read(bytes) != valueLength) { throw new IllegalArgumentException("Malformed description"); } value = new String(bytes, UTF8); result.put(key, value); } } catch (EOFException eof) { throw new IllegalArgumentException("Malformed description", eof); } return result; } catch (IOException ex) { // Due to the objects in use, an IOException is not possible. throw new RuntimeException("Unexpected exception", ex); } finally { attributeValue.getB().reset(); } } /** * @param encryptionContextOverrideOperator the nullable operator which will be used to override * the EncryptionContext. * @see com.amazonaws.services.dynamodbv2.datamodeling.encryption.utils.EncryptionContextOperators */ public final void setEncryptionContextOverrideOperator( Function<EncryptionContext, EncryptionContext> encryptionContextOverrideOperator) { this.encryptionContextOverrideOperator = encryptionContextOverrideOperator; } /** * @return the operator used to override the EncryptionContext * @see #setEncryptionContextOverrideOperator(Function) */ public final Function<EncryptionContext, EncryptionContext> getEncryptionContextOverrideOperator() { return encryptionContextOverrideOperator; } private static byte[] toByteArray(ByteBuffer buffer) { buffer = buffer.duplicate(); // We can only return the array directly if: // 1. The ByteBuffer exposes an array // 2. The ByteBuffer starts at the beginning of the array // 3. The ByteBuffer uses the entire array if (buffer.hasArray() && buffer.arrayOffset() == 0) { byte[] result = buffer.array(); if (buffer.remaining() == result.length) { return result; } } byte[] result = new byte[buffer.remaining()]; buffer.get(result); return result; } }
4,312
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/DoNotTouch.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.DynamoDB; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Prevents the associated item from being encrypted or signed. * * <p>For guidance on performing a safe data model change procedure, please see <a * href="https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/data-model.html" * target="_blank"> DynamoDB Encryption Client Developer Guide: Changing your data model</a> * * @author Greg Rubin */ @DynamoDB @Target(value = {ElementType.TYPE, ElementType.METHOD, ElementType.FIELD}) @Retention(value = RetentionPolicy.RUNTIME) public @interface DoNotTouch {}
4,313
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/DoNotEncrypt.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.DynamoDB; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Prevents the associated item (class or attribute) from being encrypted. * * <p>For guidance on performing a safe data model change procedure, please see <a * href="https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/data-model.html" * target="_blank"> DynamoDB Encryption Client Developer Guide: Changing your data model</a> * * @author Greg Rubin */ @DynamoDB @Target(value = {ElementType.TYPE, ElementType.METHOD, ElementType.FIELD}) @Retention(value = RetentionPolicy.RUNTIME) public @interface DoNotEncrypt {}
4,314
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/EncryptionContext.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.DynamoDBMapper; 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.model.AttributeValue; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * This class serves to provide additional useful data to {@link EncryptionMaterialsProvider}s so * they can more intelligently select the proper {@link EncryptionMaterials} or {@link * DecryptionMaterials} for use. Any of the methods are permitted to return null. * * <p>For the simplest cases, all a developer needs to provide in the context are: * * <ul> * <li>TableName * <li>HashKeyName * <li>RangeKeyName (if present) * </ul> * * This class is immutable. * * @author Greg Rubin */ public final class EncryptionContext { private final String tableName; private final Map<String, AttributeValue> attributeValues; private final Class<?> modeledClass; private final Object developerContext; private final String hashKeyName; private final String rangeKeyName; private final Map<String, String> materialDescription; private EncryptionContext(Builder builder) { tableName = builder.getTableName(); attributeValues = builder.getAttributeValues(); modeledClass = builder.getModeledClass(); developerContext = builder.getDeveloperContext(); hashKeyName = builder.getHashKeyName(); rangeKeyName = builder.getRangeKeyName(); materialDescription = builder.getMaterialDescription(); } /** Returns the name of the DynamoDB Table this record is associated with. */ public String getTableName() { return tableName; } /** Returns the DynamoDB record about to be encrypted/decrypted. */ public Map<String, AttributeValue> getAttributeValues() { return attributeValues; } /** * When used for an object mapping layer (such as {@link DynamoDBMapper}) this represents the * class being mapped to/from DynamoDB. */ public Class<?> getModeledClass() { return modeledClass; } /** * This object has no meaning (and will not be set or examined) by any core libraries. It exists * to allow custom object mappers and data access layers to pass data to {@link * EncryptionMaterialsProvider}s through the {@link DynamoDBEncryptor}. */ public Object getDeveloperContext() { return developerContext; } /** Returns the name of the HashKey attribute for the record to be encrypted/decrypted. */ public String getHashKeyName() { return hashKeyName; } /** Returns the name of the RangeKey attribute for the record to be encrypted/decrypted. */ public String getRangeKeyName() { return rangeKeyName; } public Map<String, String> getMaterialDescription() { return materialDescription; } /** * Builder class for {@link EncryptionContext}. Mutable objects (other than <code>developerContext * </code>) will undergo a defensive copy prior to being stored in the builder. * * <p>This class is <em>not</em> thread-safe. */ public static final class Builder { private String tableName = null; private Map<String, AttributeValue> attributeValues = null; private Class<?> modeledClass = null; private Object developerContext = null; private String hashKeyName = null; private String rangeKeyName = null; private Map<String, String> materialDescription = null; /** Defaults all fields to <code>null</code>. */ public Builder() {} /** Copy constructor. This will perform a shallow copy of the <code>DeveloperContext</code>. */ public Builder(EncryptionContext context) { tableName = context.getTableName(); attributeValues = context.getAttributeValues(); modeledClass = context.getModeledClass(); developerContext = context.getDeveloperContext(); hashKeyName = context.getHashKeyName(); rangeKeyName = context.getRangeKeyName(); materialDescription = context.getMaterialDescription(); } public EncryptionContext build() { return new EncryptionContext(this); } public Builder withTableName(String tableName) { this.tableName = tableName; return this; } public Builder withAttributeValues(Map<String, AttributeValue> attributeValues) { this.attributeValues = Collections.unmodifiableMap(new HashMap<String, AttributeValue>(attributeValues)); return this; } public Builder withModeledClass(Class<?> modeledClass) { this.modeledClass = modeledClass; return this; } public Builder withDeveloperContext(Object developerContext) { this.developerContext = developerContext; return this; } public Builder withHashKeyName(String hashKeyName) { this.hashKeyName = hashKeyName; return this; } public Builder withRangeKeyName(String rangeKeyName) { this.rangeKeyName = rangeKeyName; return this; } public Builder withMaterialDescription(Map<String, String> materialDescription) { this.materialDescription = Collections.unmodifiableMap(new HashMap<String, String>(materialDescription)); return this; } public String getTableName() { return tableName; } public Map<String, AttributeValue> getAttributeValues() { return attributeValues; } public Class<?> getModeledClass() { return modeledClass; } public Object getDeveloperContext() { return developerContext; } public String getHashKeyName() { return hashKeyName; } public String getRangeKeyName() { return rangeKeyName; } public Map<String, String> getMaterialDescription() { return materialDescription; } } @Override public String toString() { return "EncryptionContext [tableName=" + tableName + ", attributeValues=" + attributeValues + ", modeledClass=" + modeledClass + ", developerContext=" + developerContext + ", hashKeyName=" + hashKeyName + ", rangeKeyName=" + rangeKeyName + ", materialDescription=" + materialDescription + "]"; } }
4,315
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/DelegatedKey.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 java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; /** * Identifies keys which should not be used directly with {@link Cipher} but instead contain their * own cryptographic logic. This can be used to wrap more complex logic, HSM integration, or * service-calls. * * <p>Most delegated keys will only support a subset of these operations. (For example, AES keys * will generally not support {@link #sign(byte[], String)} or {@link #verify(byte[], byte[], * String)} and HMAC keys will generally not support anything except <code>sign</code> and <code> * verify</code>.) {@link UnsupportedOperationException} should be thrown in these cases. * * @author Greg Rubin */ public interface DelegatedKey extends SecretKey { /** * Encrypts the provided plaintext and returns a byte-array containing the ciphertext. * * @param plainText * @param additionalAssociatedData Optional additional data which must then also be provided for * successful decryption. Both <code>null</code> and arrays of length 0 are treated * identically. Not all keys will support this parameter. * @param algorithm the transformation to be used when encrypting the data * @return ciphertext the ciphertext produced by this encryption operation * @throws UnsupportedOperationException if encryption is not supported or if <code> * additionalAssociatedData</code> is provided, but not supported. */ public byte[] encrypt(byte[] plainText, byte[] additionalAssociatedData, String algorithm) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException; /** * Decrypts the provided ciphertext and returns a byte-array containing the plaintext. * * @param cipherText * @param additionalAssociatedData Optional additional data which was provided during encryption. * Both <code>null</code> and arrays of length 0 are treated identically. Not all keys will * support this parameter. * @param algorithm the transformation to be used when decrypting the data * @return plaintext the result of decrypting the input ciphertext * @throws UnsupportedOperationException if decryption is not supported or if <code> * additionalAssociatedData</code> is provided, but not supported. */ public byte[] decrypt(byte[] cipherText, byte[] additionalAssociatedData, String algorithm) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException; /** * Wraps (encrypts) the provided <code>key</code> to make it safe for storage or transmission. * * @param key * @param additionalAssociatedData Optional additional data which must then also be provided for * successful unwrapping. Both <code>null</code> and arrays of length 0 are treated * identically. Not all keys will support this parameter. * @param algorithm the transformation to be used when wrapping the key * @return the wrapped key * @throws UnsupportedOperationException if wrapping is not supported or if <code> * additionalAssociatedData</code> is provided, but not supported. */ public byte[] wrap(Key key, byte[] additionalAssociatedData, String algorithm) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException; /** * Unwraps (decrypts) the provided <code>wrappedKey</code> to recover the original key. * * @param wrappedKey * @param additionalAssociatedData Optional additional data which was provided during wrapping. * Both <code>null</code> and arrays of length 0 are treated identically. Not all keys will * support this parameter. * @param algorithm the transformation to be used when unwrapping the key * @return the unwrapped key * @throws UnsupportedOperationException if wrapping is not supported or if <code> * additionalAssociatedData</code> is provided, but not supported. */ public Key unwrap( byte[] wrappedKey, String wrappedKeyAlgorithm, int wrappedKeyType, byte[] additionalAssociatedData, String algorithm) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException; /** * Calculates and returns a signature for <code>dataToSign</code>. * * @param dataToSign * @param algorithm * @return the signature * @throws UnsupportedOperationException if signing is not supported */ public byte[] sign(byte[] dataToSign, String algorithm) throws GeneralSecurityException; /** * Checks the provided signature for correctness. * * @param dataToSign * @param signature * @param algorithm * @return true if and only if the <code>signature</code> matches the <code>dataToSign</code>. * @throws UnsupportedOperationException if signature validation is not supported */ public boolean verify(byte[] dataToSign, byte[] signature, String algorithm); }
4,316
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/EncryptionFlags.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; /** @author Greg Rubin */ public enum EncryptionFlags { ENCRYPT, SIGN }
4,317
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/HandleUnknownAttributes.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.datamodeling.encryption; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marker annotation that indicates that attributes found during unmarshalling that are in the * DynamoDB item but not modeled in the mapper model class should be included in for * decryption/signature verification. The default behavior (without this annotation) is to ignore * them, which can lead to signature verification failures when attributes are removed from model * classes. * * <p>If this annotation is added to a class with @DoNotEncrypt, then the unknown attributes will * only be included in the signature calculation, and if it's added to a class with default * encryption behavior, the unknown attributes will be signed and decrypted. * * <p>For guidance on performing a safe data model change procedure, please see <a * href="https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/data-model.html" * target="_blank"> DynamoDB Encryption Client Developer Guide: Changing your data model</a> * * @author Dan Cavallaro */ @Target(value = {ElementType.TYPE}) @Retention(value = RetentionPolicy.RUNTIME) public @interface HandleUnknownAttributes {}
4,318
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/materials/WrappedRawMaterials.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 com.amazonaws.services.dynamodbv2.datamodeling.encryption.DelegatedKey; import com.amazonaws.services.dynamodbv2.datamodeling.internal.Base64; import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.Key; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; import java.util.Collections; import java.util.Map; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; /** * Represents cryptographic materials used to manage unique record-level keys. This class * specifically implements Envelope Encryption where a unique content key is randomly generated each * time this class is constructed which is then encrypted with the Wrapping Key and then persisted * in the Description. If a wrapped key is present in the Description, then that content key is * unwrapped and used to decrypt the actual data in the record. * * <p>Other possibly implementations might use a Key-Derivation Function to derive a unique key per * record. * * @author Greg Rubin */ public class WrappedRawMaterials extends AbstractRawMaterials { /** * The key-name in the Description which contains the algorithm use to wrap content key. Example * values are "AESWrap", or "RSA/ECB/OAEPWithSHA-256AndMGF1Padding". */ public static final String KEY_WRAPPING_ALGORITHM = "amzn-ddb-wrap-alg"; /** * The key-name in the Description which contains the algorithm used by the content key. Example * values are "AES", or "Blowfish". */ public static final String CONTENT_KEY_ALGORITHM = "amzn-ddb-env-alg"; /** The key-name in the Description which which contains the wrapped content key. */ public static final String ENVELOPE_KEY = "amzn-ddb-env-key"; private static final String DEFAULT_ALGORITHM = "AES/256"; protected final Key wrappingKey; protected final Key unwrappingKey; private final SecretKey envelopeKey; public WrappedRawMaterials(Key wrappingKey, Key unwrappingKey, KeyPair signingPair) throws GeneralSecurityException { this(wrappingKey, unwrappingKey, signingPair, Collections.<String, String>emptyMap()); } public WrappedRawMaterials( Key wrappingKey, Key unwrappingKey, KeyPair signingPair, Map<String, String> description) throws GeneralSecurityException { super(signingPair, description); this.wrappingKey = wrappingKey; this.unwrappingKey = unwrappingKey; this.envelopeKey = initEnvelopeKey(); } public WrappedRawMaterials(Key wrappingKey, Key unwrappingKey, SecretKey macKey) throws GeneralSecurityException { this(wrappingKey, unwrappingKey, macKey, Collections.<String, String>emptyMap()); } public WrappedRawMaterials( Key wrappingKey, Key unwrappingKey, SecretKey macKey, Map<String, String> description) throws GeneralSecurityException { super(macKey, description); this.wrappingKey = wrappingKey; this.unwrappingKey = unwrappingKey; this.envelopeKey = initEnvelopeKey(); } @Override public SecretKey getDecryptionKey() { return envelopeKey; } @Override public SecretKey getEncryptionKey() { return envelopeKey; } /** * Called by the constructors. If there is already a key associated with this record (usually * signified by a value stored in the description in the key {@link #ENVELOPE_KEY}) it extracts it * and returns it. Otherwise it generates a new key, stores a wrapped version in the Description, * and returns the key to the caller. * * @return the content key (which is returned by both {@link #getDecryptionKey()} and {@link * #getEncryptionKey()}. * @throws GeneralSecurityException */ protected SecretKey initEnvelopeKey() throws GeneralSecurityException { Map<String, String> description = getMaterialDescription(); if (description.containsKey(ENVELOPE_KEY)) { if (unwrappingKey == null) { throw new IllegalStateException("No private decryption key provided."); } byte[] encryptedKey = Base64.decode(description.get(ENVELOPE_KEY)); String wrappingAlgorithm = unwrappingKey.getAlgorithm(); if (description.containsKey(KEY_WRAPPING_ALGORITHM)) { wrappingAlgorithm = description.get(KEY_WRAPPING_ALGORITHM); } return unwrapKey(description, encryptedKey, wrappingAlgorithm); } else { SecretKey key = description.containsKey(CONTENT_KEY_ALGORITHM) ? generateContentKey(description.get(CONTENT_KEY_ALGORITHM)) : generateContentKey(DEFAULT_ALGORITHM); String wrappingAlg = description.containsKey(KEY_WRAPPING_ALGORITHM) ? description.get(KEY_WRAPPING_ALGORITHM) : getTransformation(wrappingKey.getAlgorithm()); byte[] encryptedKey = wrapKey(key, wrappingAlg); description.put(ENVELOPE_KEY, Base64.encodeToString(encryptedKey)); description.put(CONTENT_KEY_ALGORITHM, key.getAlgorithm()); description.put(KEY_WRAPPING_ALGORITHM, wrappingAlg); setMaterialDescription(description); return key; } } public byte[] wrapKey(SecretKey key, String wrappingAlg) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException { if (wrappingKey instanceof DelegatedKey) { return ((DelegatedKey) wrappingKey).wrap(key, null, wrappingAlg); } else { Cipher cipher = Cipher.getInstance(wrappingAlg); cipher.init(Cipher.WRAP_MODE, wrappingKey, Utils.getRng()); byte[] encryptedKey = cipher.wrap(key); return encryptedKey; } } protected SecretKey unwrapKey( Map<String, String> description, byte[] encryptedKey, String wrappingAlgorithm) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { if (unwrappingKey instanceof DelegatedKey) { return (SecretKey) ((DelegatedKey) unwrappingKey) .unwrap( encryptedKey, description.get(CONTENT_KEY_ALGORITHM), Cipher.SECRET_KEY, null, wrappingAlgorithm); } else { Cipher cipher = Cipher.getInstance(wrappingAlgorithm); // This can be of the form "AES/256" as well as "AES" e.g., // but we want to set the SecretKey with just "AES" in either case String[] algPieces = description.get(CONTENT_KEY_ALGORITHM).split("/", 2); String contentKeyAlgorithm = algPieces[0]; cipher.init(Cipher.UNWRAP_MODE, unwrappingKey, Utils.getRng()); return (SecretKey) cipher.unwrap(encryptedKey, contentKeyAlgorithm, Cipher.SECRET_KEY); } } protected SecretKey generateContentKey(final String algorithm) throws NoSuchAlgorithmException { String[] pieces = algorithm.split("/", 2); KeyGenerator kg = KeyGenerator.getInstance(pieces[0]); int keyLen = 0; if (pieces.length == 2) { try { keyLen = Integer.parseInt(pieces[1]); } catch (NumberFormatException ex) { keyLen = 0; } } if (keyLen > 0) { kg.init(keyLen, Utils.getRng()); } else { kg.init(Utils.getRng()); } return kg.generateKey(); } private static String getTransformation(final String algorithm) { if (algorithm.equalsIgnoreCase("RSA")) { return "RSA/ECB/OAEPWithSHA-256AndMGF1Padding"; } else if (algorithm.equalsIgnoreCase("AES")) { return "AESWrap"; } else { return algorithm; } } }
4,319
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/materials/AbstractRawMaterials.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 java.security.Key; import java.security.KeyPair; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.crypto.SecretKey; /** @author Greg Rubin */ public abstract class AbstractRawMaterials implements DecryptionMaterials, EncryptionMaterials { private Map<String, String> description; private final Key signingKey; private final Key verificationKey; @SuppressWarnings("unchecked") protected AbstractRawMaterials(KeyPair signingPair) { this(signingPair, Collections.EMPTY_MAP); } protected AbstractRawMaterials(KeyPair signingPair, Map<String, String> description) { this.signingKey = signingPair.getPrivate(); this.verificationKey = signingPair.getPublic(); setMaterialDescription(description); } @SuppressWarnings("unchecked") protected AbstractRawMaterials(SecretKey macKey) { this(macKey, Collections.EMPTY_MAP); } protected AbstractRawMaterials(SecretKey macKey, Map<String, String> description) { this.signingKey = macKey; this.verificationKey = macKey; this.description = Collections.unmodifiableMap(new HashMap<String, String>(description)); } @Override public Map<String, String> getMaterialDescription() { return new HashMap<String, String>(description); } public void setMaterialDescription(Map<String, String> description) { this.description = Collections.unmodifiableMap(new HashMap<String, String>(description)); } @Override public Key getSigningKey() { return signingKey; } @Override public Key getVerificationKey() { return verificationKey; } }
4,320
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/materials/EncryptionMaterials.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 java.security.Key; import javax.crypto.SecretKey; /** @author Greg Rubin */ public interface EncryptionMaterials extends CryptographicMaterials { public SecretKey getEncryptionKey(); public Key getSigningKey(); }
4,321
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/materials/AsymmetricRawMaterials.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 java.security.GeneralSecurityException; import java.security.KeyPair; import java.util.Collections; import java.util.Map; import javax.crypto.SecretKey; /** @author Greg Rubin */ public class AsymmetricRawMaterials extends WrappedRawMaterials { @SuppressWarnings("unchecked") public AsymmetricRawMaterials(KeyPair encryptionKey, KeyPair signingPair) throws GeneralSecurityException { this(encryptionKey, signingPair, Collections.EMPTY_MAP); } public AsymmetricRawMaterials( KeyPair encryptionKey, KeyPair signingPair, Map<String, String> description) throws GeneralSecurityException { super(encryptionKey.getPublic(), encryptionKey.getPrivate(), signingPair, description); } @SuppressWarnings("unchecked") public AsymmetricRawMaterials(KeyPair encryptionKey, SecretKey macKey) throws GeneralSecurityException { this(encryptionKey, macKey, Collections.EMPTY_MAP); } public AsymmetricRawMaterials( KeyPair encryptionKey, SecretKey macKey, Map<String, String> description) throws GeneralSecurityException { super(encryptionKey.getPublic(), encryptionKey.getPrivate(), macKey, description); } }
4,322
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/materials/SymmetricRawMaterials.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 java.security.KeyPair; import java.util.Collections; import java.util.Map; import javax.crypto.SecretKey; /** @author Greg Rubin */ public class SymmetricRawMaterials extends AbstractRawMaterials { private final SecretKey cryptoKey; @SuppressWarnings("unchecked") public SymmetricRawMaterials(SecretKey encryptionKey, KeyPair signingPair) { this(encryptionKey, signingPair, Collections.EMPTY_MAP); } public SymmetricRawMaterials( SecretKey encryptionKey, KeyPair signingPair, Map<String, String> description) { super(signingPair, description); this.cryptoKey = encryptionKey; } @SuppressWarnings("unchecked") public SymmetricRawMaterials(SecretKey encryptionKey, SecretKey macKey) { this(encryptionKey, macKey, Collections.EMPTY_MAP); } public SymmetricRawMaterials( SecretKey encryptionKey, SecretKey macKey, Map<String, String> description) { super(macKey, description); this.cryptoKey = encryptionKey; } @Override public SecretKey getEncryptionKey() { return cryptoKey; } @Override public SecretKey getDecryptionKey() { return cryptoKey; } }
4,323
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/materials/DecryptionMaterials.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 java.security.Key; import javax.crypto.SecretKey; /** @author Greg Rubin */ public interface DecryptionMaterials extends CryptographicMaterials { public SecretKey getDecryptionKey(); public Key getVerificationKey(); }
4,324
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/materials/CryptographicMaterials.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 java.util.Map; /** @author Greg Rubin */ public interface CryptographicMaterials { public Map<String, String> getMaterialDescription(); }
4,325
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/SymmetricStaticProvider.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 com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.CryptographicMaterials; 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.SymmetricRawMaterials; import java.security.KeyPair; import java.util.Collections; import java.util.Map; import javax.crypto.SecretKey; /** * A provider which always returns the same provided symmetric encryption/decryption key and the * same signing/verification key(s). * * @author Greg Rubin */ public class SymmetricStaticProvider implements EncryptionMaterialsProvider { private final SymmetricRawMaterials materials; /** * @param encryptionKey the value to be returned by {@link * #getEncryptionMaterials(EncryptionContext)} and {@link * #getDecryptionMaterials(EncryptionContext)} * @param signingPair the keypair used to sign/verify the data stored in Dynamo. If only the * public key is provided, then this provider may be used for decryption, but not encryption. */ public SymmetricStaticProvider(SecretKey encryptionKey, KeyPair signingPair) { this(encryptionKey, signingPair, Collections.<String, String>emptyMap()); } /** * @param encryptionKey the value to be returned by {@link * #getEncryptionMaterials(EncryptionContext)} and {@link * #getDecryptionMaterials(EncryptionContext)} * @param signingPair the keypair used to sign/verify the data stored in Dynamo. If only the * public key is provided, then this provider may be used for decryption, but not encryption. * @param description the value to be returned by {@link * CryptographicMaterials#getMaterialDescription()} for any {@link CryptographicMaterials} * returned by this object. */ public SymmetricStaticProvider( SecretKey encryptionKey, KeyPair signingPair, Map<String, String> description) { materials = new SymmetricRawMaterials(encryptionKey, signingPair, description); } /** * @param encryptionKey the value to be returned by {@link * #getEncryptionMaterials(EncryptionContext)} and {@link * #getDecryptionMaterials(EncryptionContext)} * @param macKey the key used to sign/verify the data stored in Dynamo. */ public SymmetricStaticProvider(SecretKey encryptionKey, SecretKey macKey) { this(encryptionKey, macKey, Collections.<String, String>emptyMap()); } /** * @param encryptionKey the value to be returned by {@link * #getEncryptionMaterials(EncryptionContext)} and {@link * #getDecryptionMaterials(EncryptionContext)} * @param macKey the key used to sign/verify the data stored in Dynamo. * @param description the value to be returned by {@link * CryptographicMaterials#getMaterialDescription()} for any {@link CryptographicMaterials} * returned by this object. */ public SymmetricStaticProvider( SecretKey encryptionKey, SecretKey macKey, Map<String, String> description) { materials = new SymmetricRawMaterials(encryptionKey, macKey, description); } /** * Returns the <code>encryptionKey</code> provided to the constructor if and only if <code> * materialDescription</code> is a super-set (may be equal) to the <code>description</code> * provided to the constructor. */ @Override public DecryptionMaterials getDecryptionMaterials(EncryptionContext context) { if (context .getMaterialDescription() .entrySet() .containsAll(materials.getMaterialDescription().entrySet())) { return materials; } else { return null; } } /** Returns the <code>encryptionKey</code> provided to the constructor. */ @Override public EncryptionMaterials getEncryptionMaterials(EncryptionContext context) { return materials; } /** Does nothing. */ @Override public void refresh() { // Do Nothing } }
4,326
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/WrappedMaterialsProvider.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 com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.CryptographicMaterials; 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.Key; import java.security.KeyPair; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.crypto.SecretKey; /** * This provider will use create a unique (random) symmetric key upon each call to {@link * #getEncryptionMaterials(EncryptionContext)}. Practically, this means each record in DynamoDB will * be encrypted under a unique record key. A wrapped/encrypted copy of this record key is stored in * the MaterialsDescription field of that record and is unwrapped/decrypted upon reading that * record. * * <p>This is generally a more secure way of encrypting data than with the {@link * SymmetricStaticProvider}. * * @see WrappedRawMaterials * @author Greg Rubin */ public class WrappedMaterialsProvider implements EncryptionMaterialsProvider { private final Key wrappingKey; private final Key unwrappingKey; private final KeyPair sigPair; private final SecretKey macKey; private final Map<String, String> description; /** * @param wrappingKey The key used to wrap/encrypt the symmetric record key. (May be the same as * the <code>unwrappingKey</code>.) * @param unwrappingKey The key used to unwrap/decrypt the symmetric record key. (May be the same * as the <code>wrappingKey</code>.) If null, then this provider may only be used for * decryption, but not encryption. * @param signingPair the keypair used to sign/verify the data stored in Dynamo. If only the * public key is provided, then this provider may only be used for decryption, but not * encryption. */ public WrappedMaterialsProvider(Key wrappingKey, Key unwrappingKey, KeyPair signingPair) { this(wrappingKey, unwrappingKey, signingPair, Collections.<String, String>emptyMap()); } /** * @param wrappingKey The key used to wrap/encrypt the symmetric record key. (May be the same as * the <code>unwrappingKey</code>.) * @param unwrappingKey The key used to unwrap/decrypt the symmetric record key. (May be the same * as the <code>wrappingKey</code>.) If null, then this provider may only be used for * decryption, but not encryption. * @param signingPair the keypair used to sign/verify the data stored in Dynamo. If only the * public key is provided, then this provider may only be used for decryption, but not * encryption. * @param description description the value to be returned by {@link * CryptographicMaterials#getMaterialDescription()} for any {@link CryptographicMaterials} * returned by this object. */ public WrappedMaterialsProvider( Key wrappingKey, Key unwrappingKey, KeyPair signingPair, Map<String, String> description) { this.wrappingKey = wrappingKey; this.unwrappingKey = unwrappingKey; this.sigPair = signingPair; this.macKey = null; this.description = Collections.unmodifiableMap(new HashMap<String, String>(description)); } /** * @param wrappingKey The key used to wrap/encrypt the symmetric record key. (May be the same as * the <code>unwrappingKey</code>.) * @param unwrappingKey The key used to unwrap/decrypt the symmetric record key. (May be the same * as the <code>wrappingKey</code>.) If null, then this provider may only be used for * decryption, but not encryption. * @param macKey the key used to sign/verify the data stored in Dynamo. */ public WrappedMaterialsProvider(Key wrappingKey, Key unwrappingKey, SecretKey macKey) { this(wrappingKey, unwrappingKey, macKey, Collections.<String, String>emptyMap()); } /** * @param wrappingKey The key used to wrap/encrypt the symmetric record key. (May be the same as * the <code>unwrappingKey</code>.) * @param unwrappingKey The key used to unwrap/decrypt the symmetric record key. (May be the same * as the <code>wrappingKey</code>.) If null, then this provider may only be used for * decryption, but not encryption. * @param macKey the key used to sign/verify the data stored in Dynamo. * @param description description the value to be returned by {@link * CryptographicMaterials#getMaterialDescription()} for any {@link CryptographicMaterials} * returned by this object. */ public WrappedMaterialsProvider( Key wrappingKey, Key unwrappingKey, SecretKey macKey, Map<String, String> description) { this.wrappingKey = wrappingKey; this.unwrappingKey = unwrappingKey; this.sigPair = null; this.macKey = macKey; this.description = Collections.unmodifiableMap(new HashMap<String, String>(description)); } @Override public DecryptionMaterials getDecryptionMaterials(EncryptionContext context) { try { if (macKey != null) { return new WrappedRawMaterials( wrappingKey, unwrappingKey, macKey, context.getMaterialDescription()); } else { return new WrappedRawMaterials( wrappingKey, unwrappingKey, sigPair, context.getMaterialDescription()); } } catch (GeneralSecurityException ex) { throw new DynamoDBMappingException("Unable to decrypt envelope key", ex); } } @Override public EncryptionMaterials getEncryptionMaterials(EncryptionContext context) { try { if (macKey != null) { return new WrappedRawMaterials(wrappingKey, unwrappingKey, macKey, description); } else { return new WrappedRawMaterials(wrappingKey, unwrappingKey, sigPair, description); } } catch (GeneralSecurityException ex) { throw new DynamoDBMappingException("Unable to encrypt envelope key", ex); } } @Override public void refresh() { // Do nothing } }
4,327
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/CachingMostRecentProvider.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 com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils.checkNotNull; 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.ProviderStore; import com.amazonaws.services.dynamodbv2.datamodeling.internal.TTLCache; import com.amazonaws.services.dynamodbv2.datamodeling.internal.TTLCache.EntryLoader; import java.util.concurrent.TimeUnit; /** * This meta-Provider encrypts data with the most recent version of keying materials from a {@link * ProviderStore} and decrypts using whichever version is appropriate. It also caches the results * from the {@link ProviderStore} to avoid excessive load on the backing systems. */ public class CachingMostRecentProvider implements EncryptionMaterialsProvider { private static final long INITIAL_VERSION = 0; private static final String PROVIDER_CACHE_KEY_DELIM = "#"; private static final int DEFAULT_CACHE_MAX_SIZE = 1000; private final long ttlInNanos; private final ProviderStore keystore; protected final String defaultMaterialName; private final TTLCache<EncryptionMaterialsProvider> providerCache; private final TTLCache<Long> versionCache; private final EntryLoader<Long> versionLoader = new EntryLoader<Long>() { @Override public Long load(String entryKey) { return keystore.getMaxVersion(entryKey); } }; private final EntryLoader<EncryptionMaterialsProvider> providerLoader = new EntryLoader<EncryptionMaterialsProvider>() { @Override public EncryptionMaterialsProvider load(String entryKey) { final String[] parts = entryKey.split(PROVIDER_CACHE_KEY_DELIM, 2); if (parts.length != 2) { throw new IllegalStateException("Invalid cache key for provider cache: " + entryKey); } return keystore.getProvider(parts[0], Long.parseLong(parts[1])); } }; /** * Creates a new {@link CachingMostRecentProvider}. * * @param keystore The key store that this provider will use to determine which material and which * version of material to use * @param materialName The name of the materials associated with this provider * @param ttlInMillis The length of time in milliseconds to cache the most recent provider */ public CachingMostRecentProvider( final ProviderStore keystore, final String materialName, final long ttlInMillis) { this(keystore, materialName, ttlInMillis, DEFAULT_CACHE_MAX_SIZE); } /** * Creates a new {@link CachingMostRecentProvider}. * * @param keystore The key store that this provider will use to determine which material and which * version of material to use * @param materialName The name of the materials associated with this provider * @param ttlInMillis The length of time in milliseconds to cache the most recent provider * @param maxCacheSize The maximum size of the underlying caches this provider uses. Entries will * be evicted from the cache once this size is exceeded. */ public CachingMostRecentProvider( final ProviderStore keystore, final String materialName, final long ttlInMillis, final int maxCacheSize) { this.keystore = checkNotNull(keystore, "keystore must not be null"); this.defaultMaterialName = materialName; this.ttlInNanos = TimeUnit.MILLISECONDS.toNanos(ttlInMillis); this.providerCache = new TTLCache<>(maxCacheSize, ttlInMillis, providerLoader); this.versionCache = new TTLCache<>(maxCacheSize, ttlInMillis, versionLoader); } @Override public EncryptionMaterials getEncryptionMaterials(EncryptionContext context) { final String materialName = getMaterialName(context); final long currentVersion = versionCache.load(materialName); if (currentVersion < 0) { // The material hasn't been created yet, so specify a loading function // to create the first version of materials and update both caches. // We want this to be done as part of the cache load to ensure that this logic // only happens once in a multithreaded environment, // in order to limit calls to the keystore's dependencies. final String cacheKey = buildCacheKey(materialName, INITIAL_VERSION); EncryptionMaterialsProvider newProvider = providerCache.load( cacheKey, s -> { // Create the new material in the keystore final String[] parts = s.split(PROVIDER_CACHE_KEY_DELIM, 2); if (parts.length != 2) { throw new IllegalStateException("Invalid cache key for provider cache: " + s); } EncryptionMaterialsProvider provider = keystore.getOrCreate(parts[0], Long.parseLong(parts[1])); // We now should have version 0 in our keystore. // Update the version cache for this material as a side effect versionCache.put(materialName, INITIAL_VERSION); // Return the new materials to be put into the cache return provider; }); return newProvider.getEncryptionMaterials(context); } else { final String cacheKey = buildCacheKey(materialName, currentVersion); return providerCache.load(cacheKey).getEncryptionMaterials(context); } } public DecryptionMaterials getDecryptionMaterials(EncryptionContext context) { final long version = keystore.getVersionFromMaterialDescription(context.getMaterialDescription()); final String materialName = getMaterialName(context); final String cacheKey = buildCacheKey(materialName, version); EncryptionMaterialsProvider provider = providerCache.load(cacheKey); return provider.getDecryptionMaterials(context); } /** Completely empties the cache of both the current and old versions. */ @Override public void refresh() { versionCache.clear(); providerCache.clear(); } public String getMaterialName() { return defaultMaterialName; } public long getTtlInMills() { return TimeUnit.NANOSECONDS.toMillis(ttlInNanos); } /** * The current version of the materials being used for encryption. Returns -1 if we do not * currently have a current version. */ public long getCurrentVersion() { return versionCache.load(getMaterialName()); } /** * The last time the current version was updated. Returns 0 if we do not currently have a current * version. */ public long getLastUpdated() { // We cache a version of -1 to mean that there is not a current version if (versionCache.load(getMaterialName()) < 0) { return 0; } // Otherwise, return the last update time of that entry return TimeUnit.NANOSECONDS.toMillis(versionCache.getLastUpdated(getMaterialName())); } protected String getMaterialName(final EncryptionContext context) { return defaultMaterialName; } private static String buildCacheKey(final String materialName, final long version) { StringBuilder result = new StringBuilder(materialName); result.append(PROVIDER_CACHE_KEY_DELIM); result.append(version); return result.toString(); } }
4,328
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/EncryptionMaterialsProvider.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 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; /** * Interface for providing encryption materials. Implementations are free to use any strategy for * providing encryption materials, such as simply providing static material that doesn't change, or * more complicated implementations, such as integrating with existing key management systems. * * @author Greg Rubin */ public interface EncryptionMaterialsProvider { /** * Retrieves encryption materials matching the specified description from some source. * * @param context Information to assist in selecting a the proper return value. The implementation * is free to determine the minimum necessary for successful processing. * @return The encryption materials that match the description, or null if no matching encryption * materials found. */ public DecryptionMaterials getDecryptionMaterials(EncryptionContext context); /** * Returns EncryptionMaterials which the caller can use for encryption. Each implementation of * EncryptionMaterialsProvider can choose its own strategy for loading encryption material. For * example, an implementation might load encryption material from an existing key management * system, or load new encryption material when keys are rotated. * * @param context Information to assist in selecting a the proper return value. The implementation * is free to determine the minimum necessary for successful processing. * @return EncryptionMaterials which the caller can use to encrypt or decrypt data. */ public EncryptionMaterials getEncryptionMaterials(EncryptionContext context); /** * Forces this encryption materials provider to refresh its encryption material. For many * implementations of encryption materials provider, this may simply be a no-op, such as any * encryption materials provider implementation that vends static/non-changing encryption * material. For other implementations that vend different encryption material throughout their * lifetime, this method should force the encryption materials provider to refresh its encryption * material. */ public void refresh(); }
4,329
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/KeyStoreMaterialsProvider.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 com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.AsymmetricRawMaterials; 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.SymmetricRawMaterials; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyStore; import java.security.KeyStore.Entry; import java.security.KeyStore.PrivateKeyEntry; import java.security.KeyStore.ProtectionParameter; import java.security.KeyStore.SecretKeyEntry; import java.security.KeyStore.TrustedCertificateEntry; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.UnrecoverableEntryException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; /** @author Greg Rubin */ public class KeyStoreMaterialsProvider implements EncryptionMaterialsProvider { private final Map<String, String> description; private final String encryptionAlias; private final String signingAlias; private final ProtectionParameter encryptionProtection; private final ProtectionParameter signingProtection; private final KeyStore keyStore; private final AtomicReference<CurrentMaterials> currMaterials = new AtomicReference<KeyStoreMaterialsProvider.CurrentMaterials>(); public KeyStoreMaterialsProvider( KeyStore keyStore, String encryptionAlias, String signingAlias, Map<String, String> description) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { this(keyStore, encryptionAlias, signingAlias, null, null, description); } public KeyStoreMaterialsProvider( KeyStore keyStore, String encryptionAlias, String signingAlias, ProtectionParameter encryptionProtection, ProtectionParameter signingProtection, Map<String, String> description) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { super(); this.keyStore = keyStore; this.encryptionAlias = encryptionAlias; this.signingAlias = signingAlias; this.encryptionProtection = encryptionProtection; this.signingProtection = signingProtection; this.description = Collections.unmodifiableMap(new HashMap<String, String>(description)); validateKeys(); loadKeys(); } @Override public DecryptionMaterials getDecryptionMaterials(EncryptionContext context) { CurrentMaterials materials = currMaterials.get(); if (context.getMaterialDescription().entrySet().containsAll(description.entrySet())) { if (materials.encryptionEntry instanceof SecretKeyEntry) { return materials.symRawMaterials; } else { try { return makeAsymMaterials(materials, context.getMaterialDescription()); } catch (GeneralSecurityException ex) { throw new DynamoDBMappingException("Unable to decrypt envelope key", ex); } } } else { return null; } } @Override public EncryptionMaterials getEncryptionMaterials(EncryptionContext context) { CurrentMaterials materials = currMaterials.get(); if (materials.encryptionEntry instanceof SecretKeyEntry) { return materials.symRawMaterials; } else { try { return makeAsymMaterials(materials, description); } catch (GeneralSecurityException ex) { throw new DynamoDBMappingException("Unable to encrypt envelope key", ex); } } } private AsymmetricRawMaterials makeAsymMaterials( CurrentMaterials materials, Map<String, String> description) throws GeneralSecurityException { KeyPair encryptionPair = entry2Pair(materials.encryptionEntry); if (materials.signingEntry instanceof SecretKeyEntry) { return new AsymmetricRawMaterials( encryptionPair, ((SecretKeyEntry) materials.signingEntry).getSecretKey(), description); } else { return new AsymmetricRawMaterials( encryptionPair, entry2Pair(materials.signingEntry), description); } } private static KeyPair entry2Pair(Entry entry) { PublicKey pub = null; PrivateKey priv = null; if (entry instanceof PrivateKeyEntry) { PrivateKeyEntry pk = (PrivateKeyEntry) entry; if (pk.getCertificate() != null) { pub = pk.getCertificate().getPublicKey(); } priv = pk.getPrivateKey(); } else if (entry instanceof TrustedCertificateEntry) { TrustedCertificateEntry tc = (TrustedCertificateEntry) entry; pub = tc.getTrustedCertificate().getPublicKey(); } else { throw new IllegalArgumentException( "Only entry types PrivateKeyEntry and TrustedCertificateEntry are supported."); } return new KeyPair(pub, priv); } /** * Reloads the keys from the underlying keystore by calling {@link KeyStore#getEntry(String, * ProtectionParameter)} again for each of them. */ @Override public void refresh() { try { loadKeys(); } catch (GeneralSecurityException ex) { throw new DynamoDBMappingException("Unable to load keys from keystore", ex); } } private void validateKeys() throws KeyStoreException { if (!keyStore.containsAlias(encryptionAlias)) { throw new IllegalArgumentException("Keystore does not contain alias: " + encryptionAlias); } if (!keyStore.containsAlias(signingAlias)) { throw new IllegalArgumentException("Keystore does not contain alias: " + signingAlias); } } private void loadKeys() throws NoSuchAlgorithmException, UnrecoverableEntryException, KeyStoreException { Entry encryptionEntry = keyStore.getEntry(encryptionAlias, encryptionProtection); Entry signingEntry = keyStore.getEntry(signingAlias, signingProtection); CurrentMaterials newMaterials = new CurrentMaterials(encryptionEntry, signingEntry); currMaterials.set(newMaterials); } private class CurrentMaterials { public final Entry encryptionEntry; public final Entry signingEntry; public final SymmetricRawMaterials symRawMaterials; public CurrentMaterials(Entry encryptionEntry, Entry signingEntry) { super(); this.encryptionEntry = encryptionEntry; this.signingEntry = signingEntry; if (encryptionEntry instanceof SecretKeyEntry) { if (signingEntry instanceof SecretKeyEntry) { this.symRawMaterials = new SymmetricRawMaterials( ((SecretKeyEntry) encryptionEntry).getSecretKey(), ((SecretKeyEntry) signingEntry).getSecretKey(), description); } else { this.symRawMaterials = new SymmetricRawMaterials( ((SecretKeyEntry) encryptionEntry).getSecretKey(), entry2Pair(signingEntry), description); } } else { this.symRawMaterials = null; } } } }
4,330
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/AsymmetricStaticProvider.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 java.security.KeyPair; import java.util.Collections; import java.util.Map; import javax.crypto.SecretKey; /** * This is a thin wrapper around the {@link WrappedMaterialsProvider}, using the provided <code> * encryptionKey</code> for wrapping and unwrapping the record key. Please see that class for * detailed documentation. * * @author Greg Rubin */ public class AsymmetricStaticProvider extends WrappedMaterialsProvider { public AsymmetricStaticProvider(KeyPair encryptionKey, KeyPair signingPair) { this(encryptionKey, signingPair, Collections.<String, String>emptyMap()); } public AsymmetricStaticProvider(KeyPair encryptionKey, SecretKey macKey) { this(encryptionKey, macKey, Collections.<String, String>emptyMap()); } public AsymmetricStaticProvider( KeyPair encryptionKey, KeyPair signingPair, Map<String, String> description) { super(encryptionKey.getPublic(), encryptionKey.getPrivate(), signingPair, description); } public AsymmetricStaticProvider( KeyPair encryptionKey, SecretKey macKey, Map<String, String> description) { super(encryptionKey.getPublic(), encryptionKey.getPrivate(), macKey, description); } }
4,331
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/DirectKmsMaterialProvider.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 com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.WrappedRawMaterials.CONTENT_KEY_ALGORITHM; import static com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.WrappedRawMaterials.ENVELOPE_KEY; import static com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.WrappedRawMaterials.KEY_WRAPPING_ALGORITHM; import static com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils.loadVersion; import com.amazonaws.AmazonWebServiceRequest; 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.SymmetricRawMaterials; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.WrappedRawMaterials; import com.amazonaws.services.dynamodbv2.datamodeling.internal.Base64; import com.amazonaws.services.dynamodbv2.datamodeling.internal.Hkdf; import com.amazonaws.services.dynamodbv2.model.AttributeValue; 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.StringUtils; import java.nio.ByteBuffer; import java.security.NoSuchAlgorithmException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; /** * Generates a unique data key for each record in DynamoDB and protects that key using {@link * AWSKMS}. Currently, the HashKey, RangeKey, and TableName will be included in the KMS * EncryptionContext for wrapping/unwrapping the key. This means that records cannot be copied/moved * between tables without re-encryption. * * @see <a href="http://docs.aws.amazon.com/kms/latest/developerguide/encrypt-context.html">KMS * Encryption Context</a> */ public class DirectKmsMaterialProvider implements EncryptionMaterialsProvider { static final String USER_AGENT_PREFIX = "DynamodbEncryptionSdkJava/"; private static final String USER_AGENT = USER_AGENT_PREFIX + loadVersion(); private static final String COVERED_ATTR_CTX_KEY = "aws-kms-ec-attr"; private static final String SIGNING_KEY_ALGORITHM = "amzn-ddb-sig-alg"; private static final String TABLE_NAME_EC_KEY = "*aws-kms-table*"; private static final String DEFAULT_ENC_ALG = "AES/256"; private static final String DEFAULT_SIG_ALG = "HmacSHA256/256"; private static final String KEY_COVERAGE = "*keys*"; private static final String KDF_ALG = "HmacSHA256"; private static final String KDF_SIG_INFO = "Signing"; private static final String KDF_ENC_INFO = "Encryption"; private final AWSKMS kms; private final String encryptionKeyId; private final Map<String, String> description; private final String dataKeyAlg; private final int dataKeyLength; private final String dataKeyDesc; private final String sigKeyAlg; private final int sigKeyLength; private final String sigKeyDesc; public DirectKmsMaterialProvider(AWSKMS kms) { this(kms, null); } public DirectKmsMaterialProvider( AWSKMS kms, String encryptionKeyId, Map<String, String> materialDescription) { this.kms = kms; this.encryptionKeyId = encryptionKeyId; this.description = materialDescription != null ? Collections.unmodifiableMap(new HashMap<>(materialDescription)) : Collections.<String, String>emptyMap(); dataKeyDesc = description.containsKey(WrappedRawMaterials.CONTENT_KEY_ALGORITHM) ? description.get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM) : DEFAULT_ENC_ALG; String[] parts = dataKeyDesc.split("/", 2); this.dataKeyAlg = parts[0]; this.dataKeyLength = parts.length == 2 ? Integer.parseInt(parts[1]) : 256; sigKeyDesc = description.containsKey(SIGNING_KEY_ALGORITHM) ? description.get(SIGNING_KEY_ALGORITHM) : DEFAULT_SIG_ALG; parts = sigKeyDesc.split("/", 2); this.sigKeyAlg = parts[0]; this.sigKeyLength = parts.length == 2 ? Integer.parseInt(parts[1]) : 256; } public DirectKmsMaterialProvider(AWSKMS kms, String encryptionKeyId) { this(kms, encryptionKeyId, Collections.<String, String>emptyMap()); } @Override public DecryptionMaterials getDecryptionMaterials(EncryptionContext context) { final Map<String, String> materialDescription = context.getMaterialDescription(); final Map<String, String> ec = new HashMap<>(); final String providedEncAlg = materialDescription.get(CONTENT_KEY_ALGORITHM); final String providedSigAlg = materialDescription.get(SIGNING_KEY_ALGORITHM); ec.put("*" + CONTENT_KEY_ALGORITHM + "*", providedEncAlg); ec.put("*" + SIGNING_KEY_ALGORITHM + "*", providedSigAlg); populateKmsEcFromEc(context, ec); DecryptRequest request = appendUserAgent(new DecryptRequest()); request.setCiphertextBlob( ByteBuffer.wrap(Base64.decode(materialDescription.get(ENVELOPE_KEY)))); request.setEncryptionContext(ec); final DecryptResult decryptResult = decrypt(request, context); validateEncryptionKeyId(decryptResult.getKeyId(), context); final Hkdf kdf; try { kdf = Hkdf.getInstance(KDF_ALG); } catch (NoSuchAlgorithmException e) { throw new DynamoDBMappingException(e); } kdf.init(toArray(decryptResult.getPlaintext())); final String[] encAlgParts = providedEncAlg.split("/", 2); int encLength = encAlgParts.length == 2 ? Integer.parseInt(encAlgParts[1]) : 256; final String[] sigAlgParts = providedSigAlg.split("/", 2); int sigLength = sigAlgParts.length == 2 ? Integer.parseInt(sigAlgParts[1]) : 256; final SecretKey encryptionKey = new SecretKeySpec(kdf.deriveKey(KDF_ENC_INFO, encLength / 8), encAlgParts[0]); final SecretKey macKey = new SecretKeySpec(kdf.deriveKey(KDF_SIG_INFO, sigLength / 8), sigAlgParts[0]); return new SymmetricRawMaterials(encryptionKey, macKey, materialDescription); } @Override public EncryptionMaterials getEncryptionMaterials(EncryptionContext context) { final Map<String, String> ec = new HashMap<>(); ec.put("*" + CONTENT_KEY_ALGORITHM + "*", dataKeyDesc); ec.put("*" + SIGNING_KEY_ALGORITHM + "*", sigKeyDesc); populateKmsEcFromEc(context, ec); final String keyId = selectEncryptionKeyId(context); if (StringUtils.isNullOrEmpty(keyId)) { throw new DynamoDBMappingException("Encryption key id is empty."); } final GenerateDataKeyRequest req = appendUserAgent(new GenerateDataKeyRequest()); req.setKeyId(keyId); // NumberOfBytes parameter is used because we're not using this key as an AES-256 key, // we're using it as an HKDF-SHA256 key. req.setNumberOfBytes(256 / 8); req.setEncryptionContext(ec); final GenerateDataKeyResult dataKeyResult = generateDataKey(req, context); final Map<String, String> materialDescription = new HashMap<>(); materialDescription.putAll(description); materialDescription.put(COVERED_ATTR_CTX_KEY, KEY_COVERAGE); materialDescription.put(KEY_WRAPPING_ALGORITHM, "kms"); materialDescription.put(CONTENT_KEY_ALGORITHM, dataKeyDesc); materialDescription.put(SIGNING_KEY_ALGORITHM, sigKeyDesc); materialDescription.put( ENVELOPE_KEY, Base64.encodeToString(toArray(dataKeyResult.getCiphertextBlob()))); final Hkdf kdf; try { kdf = Hkdf.getInstance(KDF_ALG); } catch (NoSuchAlgorithmException e) { throw new DynamoDBMappingException(e); } kdf.init(toArray(dataKeyResult.getPlaintext())); final SecretKey encryptionKey = new SecretKeySpec(kdf.deriveKey(KDF_ENC_INFO, dataKeyLength / 8), dataKeyAlg); final SecretKey signatureKey = new SecretKeySpec(kdf.deriveKey(KDF_SIG_INFO, sigKeyLength / 8), sigKeyAlg); return new SymmetricRawMaterials(encryptionKey, signatureKey, materialDescription); } /** * Get encryption key id that is used to create the {@link EncryptionMaterials}. * * @return encryption key id. */ protected String getEncryptionKeyId() { return this.encryptionKeyId; } /** * Select encryption key id to be used to generate data key. The default implementation of this * method returns {@link DirectKmsMaterialProvider#encryptionKeyId}. * * @param context encryption context. * @return the encryptionKeyId. * @throws DynamoDBMappingException when we fails to select a valid encryption key id. */ protected String selectEncryptionKeyId(EncryptionContext context) throws DynamoDBMappingException { return getEncryptionKeyId(); } /** * Validate the encryption key id. The default implementation of this method does not validate * encryption key id. * * @param encryptionKeyId encryption key id from {@link DecryptResult}. * @param context encryption context. * @throws DynamoDBMappingException when encryptionKeyId is invalid. */ protected void validateEncryptionKeyId(String encryptionKeyId, EncryptionContext context) throws DynamoDBMappingException { // No action taken. } /** * Decrypts ciphertext. The default implementation calls KMS to decrypt the ciphertext using the * parameters provided in the {@link DecryptRequest}. Subclass can override the default * implementation to provide additional request parameters using attributes within the {@link * EncryptionContext}. * * @param request request parameters to decrypt the given ciphertext. * @param context additional useful data to decrypt the ciphertext. * @return the decrypted plaintext for the given ciphertext. */ protected DecryptResult decrypt(final DecryptRequest request, final EncryptionContext context) { return kms.decrypt(request); } /** * Returns a data encryption key that you can use in your application to encrypt data locally. The * default implementation calls KMS to generate the data key using the parameters provided in the * {@link GenerateDataKeyRequest}. Subclass can override the default implementation to provide * additional request parameters using attributes within the {@link EncryptionContext}. * * @param request request parameters to generate the data key. * @param context additional useful data to generate the data key. * @return the newly generated data key which includes both the plaintext and ciphertext. */ protected GenerateDataKeyResult generateDataKey( final GenerateDataKeyRequest request, final EncryptionContext context) { return kms.generateDataKey(request); } /** * Extracts relevant information from {@code context} and uses it to populate fields in {@code * kmsEc}. Subclass can override the default implementation to provide an alternative encryption * context in calls to KMS. Currently, the default implementation includes these fields: * * <dl> * <dt>{@code HashKeyName} * <dd>{@code HashKeyValue} * <dt>{@code RangeKeyName} * <dd>{@code RangeKeyValue} * <dt>{@link #TABLE_NAME_EC_KEY} * <dd>{@code TableName} * </dl> */ protected void populateKmsEcFromEc(EncryptionContext context, Map<String, String> kmsEc) { final String hashKeyName = context.getHashKeyName(); if (hashKeyName != null) { final AttributeValue hashKey = context.getAttributeValues().get(hashKeyName); if (hashKey.getN() != null) { kmsEc.put(hashKeyName, hashKey.getN()); } else if (hashKey.getS() != null) { kmsEc.put(hashKeyName, hashKey.getS()); } else if (hashKey.getB() != null) { kmsEc.put(hashKeyName, Base64.encodeToString(toArray(hashKey.getB()))); } else { throw new UnsupportedOperationException( "DirectKmsMaterialProvider only supports String, Number, and Binary HashKeys"); } } final String rangeKeyName = context.getRangeKeyName(); if (rangeKeyName != null) { final AttributeValue rangeKey = context.getAttributeValues().get(rangeKeyName); if (rangeKey.getN() != null) { kmsEc.put(rangeKeyName, rangeKey.getN()); } else if (rangeKey.getS() != null) { kmsEc.put(rangeKeyName, rangeKey.getS()); } else if (rangeKey.getB() != null) { kmsEc.put(rangeKeyName, Base64.encodeToString(toArray(rangeKey.getB()))); } else { throw new UnsupportedOperationException( "DirectKmsMaterialProvider only supports String, Number, and Binary RangeKeys"); } } final String tableName = context.getTableName(); if (tableName != null) { kmsEc.put(TABLE_NAME_EC_KEY, tableName); } } private static byte[] toArray(final ByteBuffer buff) { final ByteBuffer dup = buff.asReadOnlyBuffer(); byte[] result = new byte[dup.remaining()]; dup.get(result); return result; } private static <X extends AmazonWebServiceRequest> X appendUserAgent(final X request) { request.getRequestClientOptions().appendUserAgent(USER_AGENT); return request; } @Override public void refresh() { // No action needed } }
4,332
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/store/ProviderStore.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.datamodeling.encryption.providers.store; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.EncryptionMaterialsProvider; import java.util.Map; /** * Provides a standard way to retrieve and optionally create {@link EncryptionMaterialsProvider}s * backed by some form of persistent storage. * * @author rubin */ public abstract class ProviderStore { /** * Returns the most recent provider with the specified name. If there are no providers with this * name, it will create one with version 0. */ public EncryptionMaterialsProvider getProvider(final String materialName) { final long currVersion = getMaxVersion(materialName); if (currVersion >= 0) { return getProvider(materialName, currVersion); } else { return getOrCreate(materialName, 0); } } /** * Returns the provider with the specified name and version. * * @throws IndexOutOfBoundsException if {@code version} is not a valid version */ public abstract EncryptionMaterialsProvider getProvider( final String materialName, final long version); /** * Creates a new provider with a version one greater than the current max version. If multiple * clients attempt to create a provider with this same version simultaneously, they will properly * coordinate and the result will be that a single provider is created and that all ProviderStores * return the same one. */ public EncryptionMaterialsProvider newProvider(final String materialName) { final long nextId = getMaxVersion(materialName) + 1; return getOrCreate(materialName, nextId); } /** * Returns the provider with the specified name and version and creates it if it doesn't exist. * * @throws UnsupportedOperationException if a new provider cannot be created */ public EncryptionMaterialsProvider getOrCreate(final String materialName, final long nextId) { try { return getProvider(materialName, nextId); } catch (final IndexOutOfBoundsException ex) { throw new UnsupportedOperationException("This ProviderStore does not support creation.", ex); } } /** * Returns the maximum version number associated with {@code materialName}. If there are no * versions, returns -1. */ public abstract long getMaxVersion(final String materialName); /** Extracts the material version from {@code description}. */ public abstract long getVersionFromMaterialDescription(final Map<String, String> description); }
4,333
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/store/MetaStore.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.datamodeling.encryption.providers.store; import com.amazonaws.AmazonClientException; 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.providers.EncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.WrappedMaterialsProvider; import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils; 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.ConditionalCheckFailedException; import com.amazonaws.services.dynamodbv2.model.CreateTableResult; import com.amazonaws.services.dynamodbv2.model.ExpectedAttributeValue; import com.amazonaws.services.dynamodbv2.model.GetItemRequest; 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.QueryRequest; import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; /** * Provides a simple collection of EncryptionMaterialProviders backed by an encrypted DynamoDB * table. This can be used to build key hierarchies or meta providers. * * <p>Currently, this only supports AES-256 in AESWrap mode and HmacSHA256 for the providers * persisted in the table. * * @author rubin */ public class MetaStore extends ProviderStore { private static final String INTEGRITY_ALGORITHM_FIELD = "intAlg"; private static final String INTEGRITY_KEY_FIELD = "int"; private static final String ENCRYPTION_ALGORITHM_FIELD = "encAlg"; private static final String ENCRYPTION_KEY_FIELD = "enc"; private static final Pattern COMBINED_PATTERN = Pattern.compile("([^#]+)#(\\d*)"); private static final String DEFAULT_INTEGRITY = "HmacSHA256"; private static final String DEFAULT_ENCRYPTION = "AES"; private static final String MATERIAL_TYPE_VERSION = "t"; private static final String META_ID = "amzn-ddb-meta-id"; private static final String DEFAULT_HASH_KEY = "N"; private static final String DEFAULT_RANGE_KEY = "V"; /** Default no-op implementation of {@link ExtraDataSupplier}. */ private static final EmptyExtraDataSupplier EMPTY_EXTRA_DATA_SUPPLIER = new EmptyExtraDataSupplier(); /** DDB fields that must be encrypted. */ private static final Set<String> ENCRYPTED_FIELDS; static { final Set<String> tempEncryptedFields = new HashSet<>(); tempEncryptedFields.add(MATERIAL_TYPE_VERSION); tempEncryptedFields.add(ENCRYPTION_KEY_FIELD); tempEncryptedFields.add(ENCRYPTION_ALGORITHM_FIELD); tempEncryptedFields.add(INTEGRITY_KEY_FIELD); tempEncryptedFields.add(INTEGRITY_ALGORITHM_FIELD); ENCRYPTED_FIELDS = tempEncryptedFields; } private final Map<String, ExpectedAttributeValue> doesNotExist; private final Set<String> doNotEncrypt; private final String tableName; private final AmazonDynamoDB ddb; private final DynamoDBEncryptor encryptor; private final EncryptionContext ddbCtx; private final ExtraDataSupplier extraDataSupplier; /** Provides extra data that should be persisted along with the standard material data. */ public interface ExtraDataSupplier { /** * Gets the extra data attributes for the specified material name. * * @param materialName material name. * @param version version number. * @return plain text of the extra data. */ Map<String, AttributeValue> getAttributes(final String materialName, final long version); /** * Gets the extra data field names that should be signed only but not encrypted. * * @return signed only fields. */ Set<String> getSignedOnlyFieldNames(); } /** * Create a new MetaStore with specified table name. * * @param ddb Interface for accessing DynamoDB. * @param tableName DynamoDB table name for this {@link MetaStore}. * @param encryptor used to perform crypto operations on the record attributes. */ public MetaStore( final AmazonDynamoDB ddb, final String tableName, final DynamoDBEncryptor encryptor) { this(ddb, tableName, encryptor, EMPTY_EXTRA_DATA_SUPPLIER); } /** * Create a new MetaStore with specified table name and extra data supplier. * * @param ddb Interface for accessing DynamoDB. * @param tableName DynamoDB table name for this {@link MetaStore}. * @param encryptor used to perform crypto operations on the record attributes * @param extraDataSupplier provides extra data that should be stored along with the material. */ public MetaStore( final AmazonDynamoDB ddb, final String tableName, final DynamoDBEncryptor encryptor, final ExtraDataSupplier extraDataSupplier) { this.ddb = checkNotNull(ddb, "ddb must not be null"); this.tableName = checkNotNull(tableName, "tableName must not be null"); this.encryptor = checkNotNull(encryptor, "encryptor must not be null"); this.extraDataSupplier = checkNotNull(extraDataSupplier, "extraDataSupplier must not be null"); this.ddbCtx = new EncryptionContext.Builder() .withTableName(this.tableName) .withHashKeyName(DEFAULT_HASH_KEY) .withRangeKeyName(DEFAULT_RANGE_KEY) .build(); final Map<String, ExpectedAttributeValue> tmpExpected = new HashMap<>(); tmpExpected.put(DEFAULT_HASH_KEY, new ExpectedAttributeValue().withExists(false)); tmpExpected.put(DEFAULT_RANGE_KEY, new ExpectedAttributeValue().withExists(false)); doesNotExist = Collections.unmodifiableMap(tmpExpected); this.doNotEncrypt = getSignedOnlyFields(extraDataSupplier); } @Override public EncryptionMaterialsProvider getProvider(final String materialName, final long version) { Map<String, AttributeValue> item = getMaterialItem(materialName, version); return decryptProvider(item); } @Override public EncryptionMaterialsProvider getOrCreate(final String materialName, final long nextId) { final Map<String, AttributeValue> plaintext = createMaterialItem(materialName, nextId); final Map<String, AttributeValue> ciphertext = conditionalPut(getEncryptedText(plaintext)); return decryptProvider(ciphertext); } @Override public long getMaxVersion(final String materialName) { final List<Map<String, AttributeValue>> items = ddb.query( new QueryRequest() .withTableName(tableName) .withConsistentRead(Boolean.TRUE) .withKeyConditions( Collections.singletonMap( DEFAULT_HASH_KEY, new Condition() .withComparisonOperator(ComparisonOperator.EQ) .withAttributeValueList(new AttributeValue().withS(materialName)))) .withLimit(1) .withScanIndexForward(false) .withAttributesToGet(DEFAULT_RANGE_KEY)) .getItems(); if (items.isEmpty()) { return -1L; } else { return Long.parseLong(items.get(0).get(DEFAULT_RANGE_KEY).getN()); } } @Override public long getVersionFromMaterialDescription(final Map<String, String> description) { final Matcher m = COMBINED_PATTERN.matcher(description.get(META_ID)); if (m.matches()) { return Long.parseLong(m.group(2)); } else { throw new IllegalArgumentException("No meta id found"); } } /** * This API retrieves the intermediate keys from the source region and replicates it in the target * region. * * @param materialName material name of the encryption material. * @param version version of the encryption material. * @param targetMetaStore target MetaStore where the encryption material to be stored. */ public void replicate( final String materialName, final long version, final MetaStore targetMetaStore) { try { Map<String, AttributeValue> item = getMaterialItem(materialName, version); final Map<String, AttributeValue> plainText = getPlainText(item); final Map<String, AttributeValue> encryptedText = targetMetaStore.getEncryptedText(plainText); final PutItemRequest put = new PutItemRequest() .withTableName(targetMetaStore.tableName) .withItem(encryptedText) .withExpected(doesNotExist); targetMetaStore.ddb.putItem(put); } catch (ConditionalCheckFailedException e) { // Item already present. } } private Map<String, AttributeValue> getMaterialItem( final String materialName, final long version) { final Map<String, AttributeValue> ddbKey = new HashMap<>(); ddbKey.put(DEFAULT_HASH_KEY, new AttributeValue().withS(materialName)); ddbKey.put(DEFAULT_RANGE_KEY, new AttributeValue().withN(Long.toString(version))); final Map<String, AttributeValue> item = ddbGet(ddbKey); if (item == null || item.isEmpty()) { throw new IndexOutOfBoundsException("No material found: " + materialName + "#" + version); } return item; } /** * Creates a DynamoDB Table with the correct properties to be used with a ProviderStore. * * @param ddb interface for accessing DynamoDB * @param tableName name of table that stores the meta data of the material. * @param provisionedThroughput required provisioned throughput of the this table. * @return result of create table request. */ public static CreateTableResult createTable( final AmazonDynamoDB ddb, final String tableName, final ProvisionedThroughput provisionedThroughput) { return ddb.createTable( Arrays.asList( new AttributeDefinition(DEFAULT_HASH_KEY, ScalarAttributeType.S), new AttributeDefinition(DEFAULT_RANGE_KEY, ScalarAttributeType.N)), tableName, Arrays.asList( new KeySchemaElement(DEFAULT_HASH_KEY, KeyType.HASH), new KeySchemaElement(DEFAULT_RANGE_KEY, KeyType.RANGE)), provisionedThroughput); } /** * Empty extra data supplier. This default class is intended to simplify the default * implementation of {@link MetaStore}. */ private static class EmptyExtraDataSupplier implements ExtraDataSupplier { @Override public Map<String, AttributeValue> getAttributes(String materialName, long version) { return Collections.emptyMap(); } @Override public Set<String> getSignedOnlyFieldNames() { return Collections.emptySet(); } } /** * Get a set of fields that must be signed but not encrypted. * * @param extraDataSupplier extra data supplier that is used to return sign only field names. * @return fields that must be signed. */ private static Set<String> getSignedOnlyFields(final ExtraDataSupplier extraDataSupplier) { final Set<String> signedOnlyFields = extraDataSupplier.getSignedOnlyFieldNames(); for (final String signedOnlyField : signedOnlyFields) { if (ENCRYPTED_FIELDS.contains(signedOnlyField)) { throw new IllegalArgumentException(signedOnlyField + " must be encrypted"); } } // fields that should not be encrypted final Set<String> doNotEncryptFields = new HashSet<>(); doNotEncryptFields.add(DEFAULT_HASH_KEY); doNotEncryptFields.add(DEFAULT_RANGE_KEY); doNotEncryptFields.addAll(signedOnlyFields); return Collections.unmodifiableSet(doNotEncryptFields); } private Map<String, AttributeValue> conditionalPut(final Map<String, AttributeValue> item) { try { final PutItemRequest put = new PutItemRequest().withTableName(tableName).withItem(item).withExpected(doesNotExist); ddb.putItem(put); return item; } catch (final ConditionalCheckFailedException ex) { final Map<String, AttributeValue> ddbKey = new HashMap<>(); ddbKey.put(DEFAULT_HASH_KEY, item.get(DEFAULT_HASH_KEY)); ddbKey.put(DEFAULT_RANGE_KEY, item.get(DEFAULT_RANGE_KEY)); return ddbGet(ddbKey); } } private Map<String, AttributeValue> ddbGet(final Map<String, AttributeValue> ddbKey) { return ddb.getItem( new GetItemRequest().withTableName(tableName).withConsistentRead(true).withKey(ddbKey)) .getItem(); } /** * Build an material item for a given material name and version with newly generated encryption * and integrity keys. * * @param materialName material name. * @param version version of the material. * @return newly generated plaintext material item. */ private Map<String, AttributeValue> createMaterialItem( final String materialName, final long version) { final SecretKeySpec encryptionKey = new SecretKeySpec(Utils.getRandom(32), DEFAULT_ENCRYPTION); final SecretKeySpec integrityKey = new SecretKeySpec(Utils.getRandom(32), DEFAULT_INTEGRITY); final Map<String, AttributeValue> plaintext = new HashMap<String, AttributeValue>(); plaintext.put(DEFAULT_HASH_KEY, new AttributeValue().withS(materialName)); plaintext.put(DEFAULT_RANGE_KEY, new AttributeValue().withN(Long.toString(version))); plaintext.put(MATERIAL_TYPE_VERSION, new AttributeValue().withS("0")); plaintext.put( ENCRYPTION_KEY_FIELD, new AttributeValue().withB(ByteBuffer.wrap(encryptionKey.getEncoded()))); plaintext.put( ENCRYPTION_ALGORITHM_FIELD, new AttributeValue().withS(encryptionKey.getAlgorithm())); plaintext.put( INTEGRITY_KEY_FIELD, new AttributeValue().withB(ByteBuffer.wrap(integrityKey.getEncoded()))); plaintext.put( INTEGRITY_ALGORITHM_FIELD, new AttributeValue().withS(integrityKey.getAlgorithm())); plaintext.putAll(extraDataSupplier.getAttributes(materialName, version)); return plaintext; } private EncryptionMaterialsProvider decryptProvider(final Map<String, AttributeValue> item) { final Map<String, AttributeValue> plaintext = getPlainText(item); final String type = plaintext.get(MATERIAL_TYPE_VERSION).getS(); final SecretKey encryptionKey; final SecretKey integrityKey; // This switch statement is to make future extensibility easier and more obvious switch (type) { case "0": // Only currently supported type encryptionKey = new SecretKeySpec( plaintext.get(ENCRYPTION_KEY_FIELD).getB().array(), plaintext.get(ENCRYPTION_ALGORITHM_FIELD).getS()); integrityKey = new SecretKeySpec( plaintext.get(INTEGRITY_KEY_FIELD).getB().array(), plaintext.get(INTEGRITY_ALGORITHM_FIELD).getS()); break; default: throw new IllegalStateException("Unsupported material type: " + type); } return new WrappedMaterialsProvider( encryptionKey, encryptionKey, integrityKey, buildDescription(plaintext)); } /** * Decrypts attributes in the ciphertext item using {@link DynamoDBEncryptor}. except the * attribute names specified in doNotEncrypt. * * @param ciphertext the ciphertext to be decrypted. * @throws AmazonClientException when failed to decrypt material item. * @return decrypted item. */ private Map<String, AttributeValue> getPlainText(final Map<String, AttributeValue> ciphertext) { try { return encryptor.decryptAllFieldsExcept(ciphertext, ddbCtx, doNotEncrypt); } catch (final GeneralSecurityException e) { throw new AmazonClientException(e); } } /** * Encrypts attributes in the plaintext item using {@link DynamoDBEncryptor}. except the attribute * names specified in doNotEncrypt. * * @throws AmazonClientException when failed to encrypt material item. * @param plaintext plaintext to be encrypted. */ private Map<String, AttributeValue> getEncryptedText(Map<String, AttributeValue> plaintext) { try { return encryptor.encryptAllFieldsExcept(plaintext, ddbCtx, doNotEncrypt); } catch (final GeneralSecurityException e) { throw new AmazonClientException(e); } } private Map<String, String> buildDescription(final Map<String, AttributeValue> plaintext) { return Collections.singletonMap( META_ID, plaintext.get(DEFAULT_HASH_KEY).getS() + "#" + plaintext.get(DEFAULT_RANGE_KEY).getN()); } private static <V> V checkNotNull(final V ref, final String errMsg) { if (ref == null) { throw new NullPointerException(errMsg); } else { return ref; } } }
4,334
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/utils/EncryptionContextOperators.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.datamodeling.encryption.utils; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import java.util.Map; import java.util.function.UnaryOperator; /** Implementations of common operators for overriding the EncryptionContext */ public class EncryptionContextOperators { // Prevent instantiation private EncryptionContextOperators() {} /** * An operator for overriding EncryptionContext's table name for a specific DynamoDBEncryptor. If * any table names or the encryption context itself is null, then it returns the original * EncryptionContext. * * @param originalTableName the name of the table that should be overridden in the Encryption * Context * @param newTableName the table name that should be used in the Encryption Context * @return A UnaryOperator that produces a new EncryptionContext with the supplied table name */ public static UnaryOperator<EncryptionContext> overrideEncryptionContextTableName( String originalTableName, String newTableName) { return encryptionContext -> { if (encryptionContext == null || encryptionContext.getTableName() == null || originalTableName == null || newTableName == null) { return encryptionContext; } if (originalTableName.equals(encryptionContext.getTableName())) { return new EncryptionContext.Builder(encryptionContext).withTableName(newTableName).build(); } else { return encryptionContext; } }; } /** * An operator for mapping multiple table names in the Encryption Context to a new table name. If * the table name for a given EncryptionContext is missing, then it returns the original * EncryptionContext. Similarly, it returns the original EncryptionContext if the value it is * overridden to is null, or if the original table name is null. * * @param tableNameOverrideMap a map specifying the names of tables that should be overridden, and * the values to which they should be overridden. If the given table name corresponds to null, * or isn't in the map, then the table name won't be overridden. * @return A UnaryOperator that produces a new EncryptionContext with the supplied table name */ public static UnaryOperator<EncryptionContext> overrideEncryptionContextTableNameUsingMap( Map<String, String> tableNameOverrideMap) { return encryptionContext -> { if (tableNameOverrideMap == null || encryptionContext == null || encryptionContext.getTableName() == null) { return encryptionContext; } String newTableName = tableNameOverrideMap.get(encryptionContext.getTableName()); if (newTableName != null) { return new EncryptionContext.Builder(encryptionContext).withTableName(newTableName).build(); } else { return encryptionContext; } }; } }
4,335
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/internal/TTLCache.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.services.dynamodbv2.datamodeling.internal; import static com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils.checkNotNull; import com.amazonaws.annotation.ThreadSafe; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Function; /** * A cache, backed by an LRUCache, that uses a loader to calculate values on cache miss or expired * TTL. * * <p>Note that this cache does not proactively evict expired entries, however will immediately * evict entries discovered to be expired on load. * * @param <T> value type */ @ThreadSafe public final class TTLCache<T> { /** Used for the internal cache. */ private final LRUCache<LockedState<T>> cache; /** Time to live for entries in the cache. */ private final long ttlInNanos; /** Used for loading new values into the cache on cache miss or expiration. */ private final EntryLoader<T> defaultLoader; // Mockable time source, to allow us to test TTL behavior. // package access for tests MsClock clock = MsClock.WALLCLOCK; private static final long TTL_GRACE_IN_NANO = TimeUnit.MILLISECONDS.toNanos(500); /** * @param maxSize the maximum number of entries of the cache * @param ttlInMillis the time to live value for entries of the cache, in milliseconds */ public TTLCache(final int maxSize, final long ttlInMillis, final EntryLoader<T> loader) { if (maxSize < 1) { throw new IllegalArgumentException("maxSize " + maxSize + " must be at least 1"); } if (ttlInMillis < 1) { throw new IllegalArgumentException("ttlInMillis " + maxSize + " must be at least 1"); } this.ttlInNanos = TimeUnit.MILLISECONDS.toNanos(ttlInMillis); this.cache = new LRUCache<>(maxSize); this.defaultLoader = checkNotNull(loader, "loader must not be null"); } /** * Uses the default loader to calculate the value at key and insert it into the cache, if it * doesn't already exist or is expired according to the TTL. * * <p>This immediately evicts entries past the TTL such that a load failure results in the removal * of the entry. * * <p>Entries that are not expired according to the TTL are returned without recalculating the * value. * * <p>Within a grace period past the TTL, the cache may either return the cached value without * recalculating or use the loader to recalculate the value. This is implemented such that, in a * multi-threaded environment, only one thread per cache key uses the loader to recalculate the * value at one time. * * @param key The cache key to load the value at * @return The value of the given value (already existing or re-calculated). */ public T load(final String key) { return load(key, defaultLoader::load); } /** * Uses the inputted function to calculate the value at key and insert it into the cache, if it * doesn't already exist or is expired according to the TTL. * * <p>This immediately evicts entries past the TTL such that a load failure results in the removal * of the entry. * * <p>Entries that are not expired according to the TTL are returned without recalculating the * value. * * <p>Within a grace period past the TTL, the cache may either return the cached value without * recalculating or use the loader to recalculate the value. This is implemented such that, in a * multi-threaded environment, only one thread per cache key uses the loader to recalculate the * value at one time. * * <p>Returns the value of the given key (already existing or re-calculated). * * @param key The cache key to load the value at * @param f The function to use to load the value, given key as input * @return The value of the given value (already existing or re-calculated). */ public T load(final String key, Function<String, T> f) { final LockedState<T> ls = cache.get(key); if (ls == null) { // The entry doesn't exist yet, so load a new one. return loadNewEntryIfAbsent(key, f); } else if (clock.timestampNano() - ls.getState().lastUpdatedNano > ttlInNanos + TTL_GRACE_IN_NANO) { // The data has expired past the grace period. // Evict the old entry and load a new entry. cache.remove(key); return loadNewEntryIfAbsent(key, f); } else if (clock.timestampNano() - ls.getState().lastUpdatedNano <= ttlInNanos) { // The data hasn't expired. Return as-is from the cache. return ls.getState().data; } else if (!ls.tryLock()) { // We are in the TTL grace period. If we couldn't grab the lock, then some other // thread is currently loading the new value. Because we are in the grace period, // use the cached data instead of waiting for the lock. return ls.getState().data; } // We are in the grace period and have acquired a lock. // Update the cache with the value determined by the loading function. try { T loadedData = f.apply(key); ls.update(loadedData, clock.timestampNano()); return ls.getState().data; } finally { ls.unlock(); } } // Synchronously calculate the value for a new entry in the cache if it doesn't already exist. // Otherwise return the cached value. // It is important that this is the only place where we use the loader for a new entry, // given that we don't have the entry yet to lock on. // This ensures that the loading function is only called once if multiple threads // attempt to add a new entry for the same key at the same time. private synchronized T loadNewEntryIfAbsent(final String key, Function<String, T> f) { // If the entry already exists in the cache, return it final LockedState<T> cachedState = cache.get(key); if (cachedState != null) { return cachedState.getState().data; } // Otherwise, load the data and create a new entry T loadedData = f.apply(key); LockedState<T> ls = new LockedState<>(loadedData, clock.timestampNano()); cache.add(key, ls); return loadedData; } /** * Put a new entry in the cache. Returns the value previously at that key in the cache, or null if * the entry previously didn't exist or is expired. */ public synchronized T put(final String key, final T value) { LockedState<T> ls = new LockedState<>(value, clock.timestampNano()); LockedState<T> oldLockedState = cache.add(key, ls); if (oldLockedState == null || clock.timestampNano() - oldLockedState.getState().lastUpdatedNano > ttlInNanos + TTL_GRACE_IN_NANO) { return null; } return oldLockedState.getState().data; } /** * Get when the entry at this key was last updated. Returns 0 if the entry doesn't exist at key. */ public long getLastUpdated(String key) { LockedState<T> ls = cache.get(key); if (ls == null) { return 0; } return ls.getState().lastUpdatedNano; } /** Returns the current size of the cache. */ public int size() { return cache.size(); } /** Returns the maximum size of the cache. */ public int getMaxSize() { return cache.getMaxSize(); } /** Clears all entries from the cache. */ public void clear() { cache.clear(); } @Override public String toString() { return cache.toString(); } public interface EntryLoader<T> { T load(String entryKey); } // An object which stores a state alongside a lock, // and performs updates to that state atomically. // The state may only be updated if the lock is acquired by the current thread. private static class LockedState<T> { private final ReentrantLock lock = new ReentrantLock(true); private final AtomicReference<State<T>> state; public LockedState(T data, long createTimeNano) { state = new AtomicReference<>(new State<>(data, createTimeNano)); } public State<T> getState() { return state.get(); } public void unlock() { lock.unlock(); } public boolean tryLock() { return lock.tryLock(); } public void update(T data, long createTimeNano) { if (!lock.isHeldByCurrentThread()) { throw new IllegalStateException("Lock not held by current thread"); } state.set(new State<>(data, createTimeNano)); } } // An object that holds some data and the time at which this object was created private static class State<T> { public final T data; public final long lastUpdatedNano; public State(T data, long lastUpdatedNano) { this.data = data; this.lastUpdatedNano = lastUpdatedNano; } } }
4,336
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/internal/Hkdf.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.internal; import com.amazonaws.util.StringUtils; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Provider; import java.util.Arrays; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.ShortBufferException; import javax.crypto.spec.SecretKeySpec; /** * HMAC-based Key Derivation Function. * * @see <a href="http://tools.ietf.org/html/rfc5869">RFC 5869</a> */ public final class Hkdf { private static final byte[] EMPTY_ARRAY = new byte[0]; private final String algorithm; private final Provider provider; private SecretKey prk = null; /** * Returns an <code>Hkdf</code> object using the specified algorithm. * * @param algorithm the standard name of the requested MAC algorithm. See the Mac section in the * <a href= * "http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#Mac" > * Java Cryptography Architecture Standard Algorithm Name Documentation</a> for information * about standard algorithm names. * @return the new <code>Hkdf</code> object * @throws NoSuchAlgorithmException if no Provider supports a MacSpi implementation for the * specified algorithm. */ public static Hkdf getInstance(final String algorithm) throws NoSuchAlgorithmException { // Constructed specifically to sanity-test arguments. Mac mac = Mac.getInstance(algorithm); return new Hkdf(algorithm, mac.getProvider()); } /** * Returns an <code>Hkdf</code> object using the specified algorithm. * * @param algorithm the standard name of the requested MAC algorithm. See the Mac section in the * <a href= * "http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#Mac" > * Java Cryptography Architecture Standard Algorithm Name Documentation</a> for information * about standard algorithm names. * @param provider the name of the provider * @return the new <code>Hkdf</code> object * @throws NoSuchAlgorithmException if a MacSpi implementation for the specified algorithm is not * available from the specified provider. * @throws NoSuchProviderException if the specified provider is not registered in the security * provider list. */ public static Hkdf getInstance(final String algorithm, final String provider) throws NoSuchAlgorithmException, NoSuchProviderException { // Constructed specifically to sanity-test arguments. Mac mac = Mac.getInstance(algorithm, provider); return new Hkdf(algorithm, mac.getProvider()); } /** * Returns an <code>Hkdf</code> object using the specified algorithm. * * @param algorithm the standard name of the requested MAC algorithm. See the Mac section in the * <a href= * "http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#Mac" > * Java Cryptography Architecture Standard Algorithm Name Documentation</a> for information * about standard algorithm names. * @param provider the provider * @return the new <code>Hkdf</code> object * @throws NoSuchAlgorithmException if a MacSpi implementation for the specified algorithm is not * available from the specified provider. */ public static Hkdf getInstance(final String algorithm, final Provider provider) throws NoSuchAlgorithmException { // Constructed specifically to sanity-test arguments. Mac mac = Mac.getInstance(algorithm, provider); return new Hkdf(algorithm, mac.getProvider()); } /** * Initializes this Hkdf with input keying material. A default salt of HashLen zeros will be used * (where HashLen is the length of the return value of the supplied algorithm). * * @param ikm the Input Keying Material */ public void init(final byte[] ikm) { init(ikm, null); } /** * Initializes this Hkdf with input keying material and a salt. If <code> * salt</code> is <code>null</code> or of length 0, then a default salt of HashLen zeros will be * used (where HashLen is the length of the return value of the supplied algorithm). * * @param salt the salt used for key extraction (optional) * @param ikm the Input Keying Material */ public void init(final byte[] ikm, final byte[] salt) { byte[] realSalt = (salt == null) ? EMPTY_ARRAY : salt.clone(); byte[] rawKeyMaterial = EMPTY_ARRAY; try { Mac extractionMac = Mac.getInstance(algorithm, provider); if (realSalt.length == 0) { realSalt = new byte[extractionMac.getMacLength()]; Arrays.fill(realSalt, (byte) 0); } extractionMac.init(new SecretKeySpec(realSalt, algorithm)); rawKeyMaterial = extractionMac.doFinal(ikm); SecretKeySpec key = new SecretKeySpec(rawKeyMaterial, algorithm); Arrays.fill(rawKeyMaterial, (byte) 0); // Zeroize temporary array unsafeInitWithoutKeyExtraction(key); } catch (GeneralSecurityException e) { // We've already checked all of the parameters so no exceptions // should be possible here. throw new RuntimeException("Unexpected exception", e); } finally { Arrays.fill(rawKeyMaterial, (byte) 0); // Zeroize temporary array } } /** * Initializes this Hkdf to use the provided key directly for creation of new keys. If <code> * rawKey</code> is not securely generated and uniformly distributed over the total key-space, * then this will result in an insecure key derivation function (KDF). <em>DO NOT USE THIS UNLESS * YOU ARE ABSOLUTELY POSITIVE THIS IS THE CORRECT THING TO DO.</em> * * @param rawKey the pseudorandom key directly used to derive keys * @throws InvalidKeyException if the algorithm for <code>rawKey</code> does not match the * algorithm this Hkdf was created with */ public void unsafeInitWithoutKeyExtraction(final SecretKey rawKey) throws InvalidKeyException { if (!rawKey.getAlgorithm().equals(algorithm)) { throw new InvalidKeyException( "Algorithm for the provided key must match the algorithm for this Hkdf. Expected " + algorithm + " but found " + rawKey.getAlgorithm()); } this.prk = rawKey; } private Hkdf(final String algorithm, final Provider provider) { if (!algorithm.startsWith("Hmac")) { throw new IllegalArgumentException( "Invalid algorithm " + algorithm + ". Hkdf may only be used with Hmac algorithms."); } this.algorithm = algorithm; this.provider = provider; } /** * Returns a pseudorandom key of <code>length</code> bytes. * * @param info optional context and application specific information (can be a zero-length * string). This will be treated as UTF-8. * @param length the length of the output key in bytes * @return a pseudorandom key of <code>length</code> bytes. * @throws IllegalStateException if this object has not been initialized */ public byte[] deriveKey(final String info, final int length) throws IllegalStateException { return deriveKey((info != null ? info.getBytes(StringUtils.UTF8) : null), length); } /** * Returns a pseudorandom key of <code>length</code> bytes. * * @param info optional context and application specific information (can be a zero-length array). * @param length the length of the output key in bytes * @return a pseudorandom key of <code>length</code> bytes. * @throws IllegalStateException if this object has not been initialized */ public byte[] deriveKey(final byte[] info, final int length) throws IllegalStateException { byte[] result = new byte[length]; try { deriveKey(info, length, result, 0); } catch (ShortBufferException ex) { // This exception is impossible as we ensure the buffer is long // enough throw new RuntimeException(ex); } return result; } /** * Derives a pseudorandom key of <code>length</code> bytes and stores the result in <code>output * </code>. * * @param info optional context and application specific information (can be a zero-length array). * @param length the length of the output key in bytes * @param output the buffer where the pseudorandom key will be stored * @param offset the offset in <code>output</code> where the key will be stored * @throws ShortBufferException if the given output buffer is too small to hold the result * @throws IllegalStateException if this object has not been initialized */ public void deriveKey(final byte[] info, final int length, final byte[] output, final int offset) throws ShortBufferException, IllegalStateException { assertInitialized(); if (length < 0) { throw new IllegalArgumentException("Length must be a non-negative value."); } if (output.length < offset + length) { throw new ShortBufferException(); } Mac mac = createMac(); if (length > 255 * mac.getMacLength()) { throw new IllegalArgumentException( "Requested keys may not be longer than 255 times the underlying HMAC length."); } byte[] t = EMPTY_ARRAY; try { int loc = 0; byte i = 1; while (loc < length) { mac.update(t); mac.update(info); mac.update(i); t = mac.doFinal(); for (int x = 0; x < t.length && loc < length; x++, loc++) { output[loc] = t[x]; } i++; } } finally { Arrays.fill(t, (byte) 0); // Zeroize temporary array } } private Mac createMac() { try { Mac mac = Mac.getInstance(algorithm, provider); mac.init(prk); return mac; } catch (NoSuchAlgorithmException ex) { // We've already validated that this algorithm is correct. throw new RuntimeException(ex); } catch (InvalidKeyException ex) { // We've already validated that this key is correct. throw new RuntimeException(ex); } } /** * Throws an <code>IllegalStateException</code> if this object has not been initialized. * * @throws IllegalStateException if this object has not been initialized */ private void assertInitialized() throws IllegalStateException { if (prk == null) { throw new IllegalStateException("Hkdf has not been initialized"); } } }
4,337
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/internal/Base64.java
/* * Copyright 2019 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.internal; import java.util.Base64.Decoder; import java.util.Base64.Encoder; /** A class for decoding Base64 strings and encoding bytes as Base64 strings. */ public class Base64 { private static final Decoder DECODER = java.util.Base64.getMimeDecoder(); private static final Encoder ENCODER = java.util.Base64.getEncoder(); private Base64() {} /** * Encode the bytes as a Base64 string. * * <p>See the Basic encoder in {@link java.util.Base64} */ public static String encodeToString(byte[] bytes) { return ENCODER.encodeToString(bytes); } /** * Decode the Base64 string as bytes, ignoring illegal characters. * * <p>See the Mime Decoder in {@link java.util.Base64} */ public static byte[] decode(String str) { if (str == null) { return null; } return DECODER.decode(str); } }
4,338
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/internal/Utils.java
/* * Copyright 2016 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.internal; import java.io.IOException; import java.security.SecureRandom; import java.util.Properties; public class Utils { private static final ThreadLocal<SecureRandom> RND = new ThreadLocal<SecureRandom>() { @Override protected SecureRandom initialValue() { final SecureRandom result = new SecureRandom(); result.nextBoolean(); // Force seeding return result; } }; private Utils() { // Prevent instantiation } public static SecureRandom getRng() { return RND.get(); } public static byte[] getRandom(int len) { final byte[] result = new byte[len]; getRng().nextBytes(result); return result; } public static <V> V checkNotNull(final V ref, final String errMsg) { if (ref == null) { throw new NullPointerException(errMsg); } else { return ref; } } /* * Loads the version of the library */ public static String loadVersion() { try { final Properties properties = new Properties(); final ClassLoader loader = Utils.class.getClassLoader(); properties.load(loader.getResourceAsStream("project.properties")); return properties.getProperty("version"); } catch (final IOException ex) { return "unknown"; } } }
4,339
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/internal/LRUCache.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.services.dynamodbv2.datamodeling.internal; import com.amazonaws.annotation.ThreadSafe; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; /** * A bounded cache that has a LRU eviction policy when the cache is full. * * @param <T> value type */ @ThreadSafe public final class LRUCache<T> { /** Used for the internal cache. */ private final Map<String, T> map; /** Maximum size of the cache. */ private final int maxSize; /** @param maxSize the maximum number of entries of the cache */ public LRUCache(final int maxSize) { if (maxSize < 1) { throw new IllegalArgumentException("maxSize " + maxSize + " must be at least 1"); } this.maxSize = maxSize; map = Collections.synchronizedMap(new LRUHashMap<>(maxSize)); } /** Adds an entry to the cache, evicting the earliest entry if necessary. */ public T add(final String key, final T value) { return map.put(key, value); } /** Returns the value of the given key; or null of no such entry exists. */ public T get(final String key) { return map.get(key); } /** Returns the current size of the cache. */ public int size() { return map.size(); } /** Returns the maximum size of the cache. */ public int getMaxSize() { return maxSize; } public void clear() { map.clear(); } public T remove(String key) { return map.remove(key); } @Override public String toString() { return map.toString(); } @SuppressWarnings("serial") private static class LRUHashMap<T> extends LinkedHashMap<String, T> { private final int maxSize; private LRUHashMap(final int maxSize) { super(10, 0.75F, true); this.maxSize = maxSize; } @Override protected boolean removeEldestEntry(final Entry<String, T> eldest) { return size() > maxSize; } } }
4,340
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/internal/MsClock.java
/* * Copyright 2020 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.internal; interface MsClock { MsClock WALLCLOCK = System::nanoTime; public long timestampNano(); }
4,341
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/internal/AttributeValueMarshaller.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.internal; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** @author Greg Rubin */ public class AttributeValueMarshaller { private static final Charset UTF8 = Charset.forName("UTF-8"); private static final int TRUE_FLAG = 1; private static final int FALSE_FLAG = 0; private AttributeValueMarshaller() { // Prevent instantiation } /** * Marshalls the data using a TLV (Tag-Length-Value) encoding. The tag may be 'b', 'n', 's', '?', * '\0' to represent a ByteBuffer, Number, String, Boolean, or Null respectively. The tag may also * be capitalized (for 'b', 'n', and 's',) to represent an array of that type. If an array is * stored, then a four-byte big-endian integer is written representing the number of array * elements. If a ByteBuffer is stored, the length of the buffer is stored as a four-byte * big-endian integer and the buffer then copied directly. Both Numbers and Strings are treated * identically and are stored as UTF8 encoded Unicode, proceeded by the length of the encoded * string (in bytes) as a four-byte big-endian integer. Boolean is encoded as a single byte, 0 for * <code>false</code> and 1 for <code>true</code> (and so has no Length parameter). The Null tag * ('\0') takes neither a Length nor a Value parameter. * * <p>The tags 'L' and 'M' are for the document types List and Map respectively. These are encoded * recursively with the Length being the size of the collection. In the case of List, the value is * a Length number of marshalled AttributeValues. If the case of Map, the value is a Length number * of AttributeValue Pairs where the first must always have a String value. * * <p>This implementation does <em>not</em> recognize loops. If an AttributeValue contains itself * (even indirectly) this code will recurse infinitely. * * @param attributeValue * @return the serialized AttributeValue * @see java.io.DataInput */ public static ByteBuffer marshall(final AttributeValue attributeValue) { try (ByteArrayOutputStream resultBytes = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(resultBytes); ) { marshall(attributeValue, out); out.close(); resultBytes.close(); return ByteBuffer.wrap(resultBytes.toByteArray()); } catch (final IOException ex) { // Due to the objects in use, an IOException is not possible. throw new RuntimeException("Unexpected exception", ex); } } private static void marshall(final AttributeValue attributeValue, final DataOutputStream out) throws IOException { if (attributeValue.getB() != null) { out.writeChar('b'); writeBytes(attributeValue.getB(), out); } else if (attributeValue.getBS() != null) { out.writeChar('B'); writeBytesList(attributeValue.getBS(), out); } else if (attributeValue.getN() != null) { out.writeChar('n'); writeString(trimZeros(attributeValue.getN()), out); } else if (attributeValue.getNS() != null) { out.writeChar('N'); final List<String> ns = new ArrayList<String>(attributeValue.getNS().size()); for (final String n : attributeValue.getNS()) { ns.add(trimZeros(n)); } writeStringList(ns, out); } else if (attributeValue.getS() != null) { out.writeChar('s'); writeString(attributeValue.getS(), out); } else if (attributeValue.getSS() != null) { out.writeChar('S'); writeStringList(attributeValue.getSS(), out); } else if (attributeValue.getBOOL() != null) { out.writeChar('?'); out.writeByte((attributeValue.getBOOL() ? TRUE_FLAG : FALSE_FLAG)); } else if (Boolean.TRUE.equals(attributeValue.getNULL())) { out.writeChar('\0'); } else if (attributeValue.getL() != null) { final List<AttributeValue> l = attributeValue.getL(); out.writeChar('L'); out.writeInt(l.size()); for (final AttributeValue attr : l) { if (attr == null) { throw new NullPointerException( "Encountered null list entry value while marshalling attribute value " + attributeValue); } marshall(attr, out); } } else if (attributeValue.getM() != null) { final Map<String, AttributeValue> m = attributeValue.getM(); final List<String> mKeys = new ArrayList<String>(m.keySet()); Collections.sort(mKeys); out.writeChar('M'); out.writeInt(m.size()); for (final String mKey : mKeys) { marshall(new AttributeValue().withS(mKey), out); final AttributeValue mValue = m.get(mKey); if (mValue == null) { throw new NullPointerException( "Encountered null map value for key " + mKey + " while marshalling attribute value " + attributeValue); } marshall(mValue, out); } } else { throw new IllegalArgumentException( "A seemingly empty AttributeValue is indicative of invalid input or potential errors"); } } /** @see #marshall(AttributeValue) */ public static AttributeValue unmarshall(final ByteBuffer plainText) { try (final DataInputStream in = new DataInputStream(new ByteBufferInputStream(plainText.asReadOnlyBuffer()))) { return unmarshall(in); } catch (IOException ex) { // Due to the objects in use, an IOException is not possible. throw new RuntimeException("Unexpected exception", ex); } } private static AttributeValue unmarshall(final DataInputStream in) throws IOException { char type = in.readChar(); AttributeValue result = new AttributeValue(); switch (type) { case '\0': result.setNULL(Boolean.TRUE); break; case 'b': result.setB(readBytes(in)); break; case 'B': result.setBS(readBytesList(in)); break; case 'n': result.setN(readString(in)); break; case 'N': result.setNS(readStringList(in)); break; case 's': result.setS(readString(in)); break; case 'S': result.setSS(readStringList(in)); break; case '?': final byte boolValue = in.readByte(); if (boolValue == TRUE_FLAG) { result.setBOOL(Boolean.TRUE); } else if (boolValue == FALSE_FLAG) { result.setBOOL(Boolean.FALSE); } else { throw new IllegalArgumentException("Improperly formatted data"); } break; case 'L': final int lCount = in.readInt(); final List<AttributeValue> l = new ArrayList<AttributeValue>(lCount); for (int lIdx = 0; lIdx < lCount; lIdx++) { l.add(unmarshall(in)); } result.setL(l); break; case 'M': final int mCount = in.readInt(); final Map<String, AttributeValue> m = new HashMap<String, AttributeValue>(); for (int mIdx = 0; mIdx < mCount; mIdx++) { final AttributeValue key = unmarshall(in); if (key.getS() == null) { throw new IllegalArgumentException("Improperly formatted data"); } AttributeValue value = unmarshall(in); m.put(key.getS(), value); } result.setM(m); break; default: throw new IllegalArgumentException("Unsupported data encoding"); } return result; } private static String trimZeros(final String n) { BigDecimal number = new BigDecimal(n); if (number.compareTo(BigDecimal.ZERO) == 0) { return "0"; } return number.stripTrailingZeros().toPlainString(); } private static void writeStringList(List<String> values, final DataOutputStream out) throws IOException { final List<String> sorted = new ArrayList<String>(values); Collections.sort(sorted); out.writeInt(sorted.size()); for (final String v : sorted) { writeString(v, out); } } private static List<String> readStringList(final DataInputStream in) throws IOException, IllegalArgumentException { final int nCount = in.readInt(); List<String> ns = new ArrayList<String>(nCount); for (int nIdx = 0; nIdx < nCount; nIdx++) { ns.add(readString(in)); } return ns; } private static void writeString(String value, final DataOutputStream out) throws IOException { final byte[] bytes = value.getBytes(UTF8); out.writeInt(bytes.length); out.write(bytes); } private static String readString(final DataInputStream in) throws IOException, IllegalArgumentException { byte[] bytes; int length; length = in.readInt(); bytes = new byte[length]; if (in.read(bytes) != length) { throw new IllegalArgumentException("Improperly formatted data"); } String tmp = new String(bytes, UTF8); return tmp; } private static void writeBytesList(List<ByteBuffer> values, final DataOutputStream out) throws IOException { final List<ByteBuffer> sorted = new ArrayList<ByteBuffer>(values); Collections.sort(sorted); out.writeInt(sorted.size()); for (final ByteBuffer v : sorted) { writeBytes(v, out); } } private static List<ByteBuffer> readBytesList(final DataInputStream in) throws IOException { final int bCount = in.readInt(); List<ByteBuffer> bs = new ArrayList<ByteBuffer>(bCount); for (int bIdx = 0; bIdx < bCount; bIdx++) { bs.add(readBytes(in)); } return bs; } private static void writeBytes(ByteBuffer value, final DataOutputStream out) throws IOException { value = value.asReadOnlyBuffer(); value.rewind(); out.writeInt(value.remaining()); while (value.hasRemaining()) { out.writeByte(value.get()); } } private static ByteBuffer readBytes(final DataInputStream in) throws IOException { final int length = in.readInt(); final byte[] buf = new byte[length]; in.readFully(buf); return ByteBuffer.wrap(buf); } }
4,342
0
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling
Create_ds/aws-dynamodb-encryption-java/sdk1/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/internal/ByteBufferInputStream.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.internal; import java.io.InputStream; import java.nio.ByteBuffer; /** @author Greg Rubin */ public class ByteBufferInputStream extends InputStream { private final ByteBuffer buffer; public ByteBufferInputStream(ByteBuffer buffer) { this.buffer = buffer; } @Override public int read() { if (buffer.hasRemaining()) { int tmp = buffer.get(); if (tmp < 0) { tmp += 256; } return tmp; } else { return -1; } } @Override public int read(byte[] b, int off, int len) { if (available() < len) { len = available(); } buffer.get(b, off, len); return len; } @Override public int available() { return buffer.remaining(); } }
4,343
0
Create_ds/aws-dynamodb-encryption-java/examples/src/test/java/com/amazonaws
Create_ds/aws-dynamodb-encryption-java/examples/src/test/java/com/amazonaws/examples/TestUtils.java
package com.amazonaws.examples; import static com.amazonaws.examples.AwsKmsEncryptedObject.*; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.model.*; import java.util.ArrayList; public class TestUtils { private TestUtils() { throw new UnsupportedOperationException( "This class exists to hold static resources and cannot be instantiated."); } /** * These special test keys have been configured to allow Encrypt, Decrypt, and GenerateDataKey * operations from any AWS principal and should be used when adding new KMS tests. * * <p>This should go without saying, but never use these keys for production purposes (as anyone * in the world can decrypt data encrypted using them). */ public static final String US_WEST_2_KEY_ID = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; public static final String US_WEST_2 = "us-west-2"; public static final String US_EAST_1_MRK_KEY_ID = "arn:aws:kms:us-east-1:658956600833:key/mrk-80bd8ecdcd4342aebd84b7dc9da498a7"; public static final String US_WEST_2_MRK_KEY_ID = "arn:aws:kms:us-west-2:658956600833:key/mrk-80bd8ecdcd4342aebd84b7dc9da498a7"; public static void createDDBTable( AmazonDynamoDB ddb, String tableName, String partitionName, String sortName) { ArrayList<AttributeDefinition> attrDef = new ArrayList<AttributeDefinition>(); attrDef.add( new AttributeDefinition() .withAttributeName(partitionName) .withAttributeType(ScalarAttributeType.S)); attrDef.add( new AttributeDefinition() .withAttributeName(sortName) .withAttributeType(ScalarAttributeType.N)); ArrayList<KeySchemaElement> keySchema = new ArrayList<KeySchemaElement>(); keySchema.add( new KeySchemaElement().withAttributeName(partitionName).withKeyType(KeyType.HASH)); keySchema.add(new KeySchemaElement().withAttributeName(sortName).withKeyType(KeyType.RANGE)); ddb.createTable( new CreateTableRequest() .withTableName(tableName) .withAttributeDefinitions(attrDef) .withKeySchema(keySchema) .withProvisionedThroughput(new ProvisionedThroughput(100L, 100L))); } }
4,344
0
Create_ds/aws-dynamodb-encryption-java/examples/src/test/java/com/amazonaws
Create_ds/aws-dynamodb-encryption-java/examples/src/test/java/com/amazonaws/examples/AwsKmsMultiRegionKeyIT.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.examples; import static com.amazonaws.examples.TestUtils.US_EAST_1_MRK_KEY_ID; import static com.amazonaws.examples.TestUtils.US_WEST_2_MRK_KEY_ID; import java.security.GeneralSecurityException; import org.testng.annotations.Test; public class AwsKmsMultiRegionKeyIT { private static final String TABLE_NAME = "ddbec-mrk-testing"; @Test public void testEncryptAndDecrypt() throws GeneralSecurityException { AwsKmsMultiRegionKey.encryptRecord(TABLE_NAME, US_EAST_1_MRK_KEY_ID, US_WEST_2_MRK_KEY_ID); } }
4,345
0
Create_ds/aws-dynamodb-encryption-java/examples/src/test/java/com/amazonaws
Create_ds/aws-dynamodb-encryption-java/examples/src/test/java/com/amazonaws/examples/AwsKmsEncryptedObjectIT.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.examples; import static com.amazonaws.examples.AwsKmsEncryptedObject.EXAMPLE_TABLE_NAME; import static com.amazonaws.examples.AwsKmsEncryptedObject.PARTITION_ATTRIBUTE; import static com.amazonaws.examples.AwsKmsEncryptedObject.SORT_ATTRIBUTE; import static com.amazonaws.examples.TestUtils.US_WEST_2; import static com.amazonaws.examples.TestUtils.US_WEST_2_KEY_ID; import static com.amazonaws.examples.TestUtils.createDDBTable; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.AWSKMSClientBuilder; import org.testng.annotations.Test; public class AwsKmsEncryptedObjectIT { @Test public void testEncryptAndDecrypt() { final AWSKMS kms = AWSKMSClientBuilder.standard().withRegion(US_WEST_2).build(); final AmazonDynamoDB ddb = DynamoDBEmbedded.create(); // Create the table under test createDDBTable(ddb, EXAMPLE_TABLE_NAME, PARTITION_ATTRIBUTE, SORT_ATTRIBUTE); AwsKmsEncryptedObject.encryptRecord(US_WEST_2_KEY_ID, ddb, kms); } }
4,346
0
Create_ds/aws-dynamodb-encryption-java/examples/src/test/java/com/amazonaws
Create_ds/aws-dynamodb-encryption-java/examples/src/test/java/com/amazonaws/examples/EncryptionContextOverridesWithDynamoDBMapperIT.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.examples; import static com.amazonaws.examples.EncryptionContextOverridesWithDynamoDBMapper.PARTITION_ATTRIBUTE; import static com.amazonaws.examples.EncryptionContextOverridesWithDynamoDBMapper.SORT_ATTRIBUTE; import static com.amazonaws.examples.EncryptionContextOverridesWithDynamoDBMapper.TABLE_NAME_TO_OVERRIDE; import static com.amazonaws.examples.TestUtils.US_WEST_2; import static com.amazonaws.examples.TestUtils.US_WEST_2_KEY_ID; import static com.amazonaws.examples.TestUtils.createDDBTable; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.AWSKMSClientBuilder; import java.security.GeneralSecurityException; import org.testng.annotations.Test; public class EncryptionContextOverridesWithDynamoDBMapperIT { private static final String OVERRIDE_TABLE_NAME = "java-ddbec-test-table-encctx-override-example"; @Test public void testEncryptAndDecrypt() throws GeneralSecurityException { final AWSKMS kms = AWSKMSClientBuilder.standard().withRegion(US_WEST_2).build(); final AmazonDynamoDB ddb = DynamoDBEmbedded.create(); // Create the table under test createDDBTable(ddb, TABLE_NAME_TO_OVERRIDE, PARTITION_ATTRIBUTE, SORT_ATTRIBUTE); EncryptionContextOverridesWithDynamoDBMapper.encryptRecord( US_WEST_2_KEY_ID, OVERRIDE_TABLE_NAME, ddb, kms); } }
4,347
0
Create_ds/aws-dynamodb-encryption-java/examples/src/test/java/com/amazonaws
Create_ds/aws-dynamodb-encryption-java/examples/src/test/java/com/amazonaws/examples/MostRecentEncryptedItemIT.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.examples; import static com.amazonaws.examples.MostRecentEncryptedItem.PARTITION_ATTRIBUTE; import static com.amazonaws.examples.MostRecentEncryptedItem.SORT_ATTRIBUTE; import static com.amazonaws.examples.TestUtils.*; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.store.MetaStore; import com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.AWSKMSClientBuilder; import java.security.GeneralSecurityException; import org.testng.annotations.Test; public class MostRecentEncryptedItemIT { private static final String TABLE_NAME = "java-ddbec-test-table-mostrecent-example"; private static final String KEY_TABLE_NAME = "java-ddbec-test-table-mostrecent-example-keys"; private static final String MATERIAL_NAME = "testMaterial"; @Test public void testEncryptAndDecrypt() throws GeneralSecurityException { final AWSKMS kms = AWSKMSClientBuilder.standard().withRegion(US_WEST_2).build(); final AmazonDynamoDB ddb = DynamoDBEmbedded.create(); // Create the key table under test MetaStore.createTable(ddb, KEY_TABLE_NAME, new ProvisionedThroughput(1L, 1L)); // Create the table under test createDDBTable(ddb, TABLE_NAME, PARTITION_ATTRIBUTE, SORT_ATTRIBUTE); MostRecentEncryptedItem.encryptRecord( TABLE_NAME, KEY_TABLE_NAME, US_WEST_2_KEY_ID, MATERIAL_NAME, ddb, kms); } }
4,348
0
Create_ds/aws-dynamodb-encryption-java/examples/src/test/java/com/amazonaws
Create_ds/aws-dynamodb-encryption-java/examples/src/test/java/com/amazonaws/examples/SymmetricEncryptedItemTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.examples; import java.security.GeneralSecurityException; import java.security.SecureRandom; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.testng.annotations.Test; public class SymmetricEncryptedItemTest { private static final String TABLE_NAME = "java-ddbec-test-table-sym-example"; @Test public void testEncryptAndDecrypt() throws GeneralSecurityException { final SecureRandom secureRandom = new SecureRandom(); byte[] rawAes = new byte[32]; byte[] rawHmac = new byte[32]; secureRandom.nextBytes(rawAes); secureRandom.nextBytes(rawHmac); final SecretKey wrappingKey = new SecretKeySpec(rawAes, "AES"); final SecretKey signingKey = new SecretKeySpec(rawHmac, "HmacSHA256"); SymmetricEncryptedItem.encryptRecord(TABLE_NAME, wrappingKey, signingKey); } }
4,349
0
Create_ds/aws-dynamodb-encryption-java/examples/src/test/java/com/amazonaws
Create_ds/aws-dynamodb-encryption-java/examples/src/test/java/com/amazonaws/examples/AsymmetricEncryptedItemTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.examples; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyPairGenerator; import org.testng.annotations.Test; public class AsymmetricEncryptedItemTest { private static final String TABLE_NAME = "java-ddbec-test-table-asym-example"; @Test public void testEncryptAndDecrypt() throws GeneralSecurityException { final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); final KeyPair wrappingKeys = keyGen.generateKeyPair(); final KeyPair signingKeys = keyGen.generateKeyPair(); AsymmetricEncryptedItem.encryptRecord(TABLE_NAME, wrappingKeys, signingKeys); } }
4,350
0
Create_ds/aws-dynamodb-encryption-java/examples/src/test/java/com/amazonaws
Create_ds/aws-dynamodb-encryption-java/examples/src/test/java/com/amazonaws/examples/AwsKmsEncryptedItemIT.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.examples; import static com.amazonaws.examples.TestUtils.US_WEST_2; import static com.amazonaws.examples.TestUtils.US_WEST_2_KEY_ID; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.AWSKMSClientBuilder; import java.security.GeneralSecurityException; import org.testng.annotations.Test; public class AwsKmsEncryptedItemIT { private static final String TABLE_NAME = "java-ddbec-test-table-kms-item-example"; @Test public void testEncryptAndDecrypt() throws GeneralSecurityException { final AWSKMS kms = AWSKMSClientBuilder.standard().withRegion(US_WEST_2).build(); AwsKmsEncryptedItem.encryptRecord(TABLE_NAME, US_WEST_2_KEY_ID, kms); } }
4,351
0
Create_ds/aws-dynamodb-encryption-java/examples/src/main/java/com/amazonaws
Create_ds/aws-dynamodb-encryption-java/examples/src/main/java/com/amazonaws/examples/MostRecentEncryptedItem.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.examples; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; 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.datamodeling.encryption.providers.CachingMostRecentProvider; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.DirectKmsMaterialProvider; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.store.MetaStore; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.AWSKMSClientBuilder; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * This demonstrates how to use the {@link CachingMostRecentProvider} backed by a {@link MetaStore} * and the {@link DirectKmsMaterialProvider} to encrypt your data. Before you can use this, you need * to set up a table to hold the intermediate keys or use --setup mode to construct the table once * and then re-run the example without the --setup mode */ public class MostRecentEncryptedItem { public static final String PARTITION_ATTRIBUTE = "partition_attribute"; public static final String SORT_ATTRIBUTE = "sort_attribute"; private static final String STRING_FIELD_NAME = "example"; private static final String BINARY_FIELD_NAME = "and some binary"; private static final String NUMBER_FIELD_NAME = "some numbers"; private static final String IGNORED_FIELD_NAME = "leave me"; public static void main(String[] args) throws GeneralSecurityException { final String mode = args[0]; final String region = args[1]; final String tableName = args[2]; final String keyTableName = args[3]; final String cmkArn = args[4]; final String materialName = args[5]; if (mode.equalsIgnoreCase("--setup")) { AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.standard().withRegion(region).build(); MetaStore.createTable(ddb, keyTableName, new ProvisionedThroughput(1L, 1L)); return; } AmazonDynamoDB ddb = null; AWSKMS kms = null; try { ddb = AmazonDynamoDBClientBuilder.standard().withRegion(region).build(); kms = AWSKMSClientBuilder.standard().withRegion(region).build(); encryptRecord(tableName, keyTableName, cmkArn, materialName, ddb, kms); } finally { if (ddb != null) { ddb.shutdown(); } if (kms != null) { kms.shutdown(); } } } public static void encryptRecord( String tableName, String keyTableName, String cmkArn, String materialName, AmazonDynamoDB ddbClient, AWSKMS kmsClient) throws GeneralSecurityException { // Sample record to be encrypted final Map<String, AttributeValue> record = new HashMap<>(); record.put(PARTITION_ATTRIBUTE, new AttributeValue().withS("is this")); record.put(SORT_ATTRIBUTE, new AttributeValue().withN("55")); record.put(STRING_FIELD_NAME, new AttributeValue().withS("data")); record.put(NUMBER_FIELD_NAME, new AttributeValue().withN("99")); record.put( BINARY_FIELD_NAME, new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0x00, 0x01, 0x02}))); record.put( IGNORED_FIELD_NAME, new AttributeValue().withS("alone")); // We want to ignore this attribute // Set up our configuration and clients. All of this is thread-safe and can be reused across // calls. // Provider Configuration to protect the data keys // This example assumes we already have a DynamoDB client `ddbClient` and AWS KMS client // `kmsClient` final DirectKmsMaterialProvider kmsProv = new DirectKmsMaterialProvider(kmsClient, cmkArn); final DynamoDBEncryptor keyEncryptor = DynamoDBEncryptor.getInstance(kmsProv); final MetaStore metaStore = new MetaStore(ddbClient, keyTableName, keyEncryptor); // Provider configuration to protect the data final CachingMostRecentProvider cmp = new CachingMostRecentProvider(metaStore, materialName, 60_000); // Encryptor creation final DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(cmp); // Information about the context of our data (normally just Table information) final EncryptionContext encryptionContext = new EncryptionContext.Builder() .withTableName(tableName) .withHashKeyName(PARTITION_ATTRIBUTE) .withRangeKeyName(SORT_ATTRIBUTE) .build(); // Describe what actions need to be taken for each attribute final EnumSet<EncryptionFlags> signOnly = EnumSet.of(EncryptionFlags.SIGN); final EnumSet<EncryptionFlags> encryptAndSign = EnumSet.of(EncryptionFlags.ENCRYPT, EncryptionFlags.SIGN); final Map<String, Set<EncryptionFlags>> actions = new HashMap<>(); for (final String attributeName : record.keySet()) { switch (attributeName) { case PARTITION_ATTRIBUTE: // fall through case SORT_ATTRIBUTE: // Partition and sort keys must not be encrypted but should be signed actions.put(attributeName, signOnly); break; case IGNORED_FIELD_NAME: // For this example, we are neither signing nor encrypting this field break; default: // We want to encrypt and sign everything else actions.put(attributeName, encryptAndSign); break; } } // End set-up // Encrypt the plaintext record directly final Map<String, AttributeValue> encrypted_record = encryptor.encryptRecord(record, actions, encryptionContext); // Encrypted record fields change as expected assert encrypted_record.get(STRING_FIELD_NAME).getB() != null; // the encrypted string is stored as bytes assert encrypted_record.get(NUMBER_FIELD_NAME).getB() != null; // the encrypted number is stored as bytes assert !record .get(BINARY_FIELD_NAME) .getB() .equals(encrypted_record.get(BINARY_FIELD_NAME).getB()); // the encrypted bytes have updated assert record .get(IGNORED_FIELD_NAME) .getS() .equals(encrypted_record.get(IGNORED_FIELD_NAME).getS()); // ignored field is left as is // We could now put the encrypted item to DynamoDB just as we would any other item. // We're skipping it to to keep the example simpler. System.out.println("Plaintext Record: " + record); System.out.println("Encrypted Record: " + encrypted_record); // Decryption is identical. We'll pretend that we retrieved the record from DynamoDB. final Map<String, AttributeValue> decrypted_record = encryptor.decryptRecord(encrypted_record, actions, encryptionContext); System.out.println("Decrypted Record: " + decrypted_record); // The decrypted fields match the original fields before encryption assert record .get(STRING_FIELD_NAME) .getS() .equals(decrypted_record.get(STRING_FIELD_NAME).getS()); assert record .get(NUMBER_FIELD_NAME) .getN() .equals(decrypted_record.get(NUMBER_FIELD_NAME).getN()); assert record .get(BINARY_FIELD_NAME) .getB() .equals(decrypted_record.get(BINARY_FIELD_NAME).getB()); } }
4,352
0
Create_ds/aws-dynamodb-encryption-java/examples/src/main/java/com/amazonaws
Create_ds/aws-dynamodb-encryption-java/examples/src/main/java/com/amazonaws/examples/AwsKmsEncryptedItem.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.examples; 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.datamodeling.encryption.providers.DirectKmsMaterialProvider; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.AWSKMSClientBuilder; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.Set; /** Example showing use of AWS KMS CMP with record encryption functions directly. */ public class AwsKmsEncryptedItem { private static final String STRING_FIELD_NAME = "example"; private static final String BINARY_FIELD_NAME = "and some binary"; private static final String NUMBER_FIELD_NAME = "some numbers"; private static final String IGNORED_FIELD_NAME = "leave me"; public static void main(String[] args) throws GeneralSecurityException { final String tableName = args[0]; final String cmkArn = args[1]; final String region = args[2]; AWSKMS kms = null; try { kms = AWSKMSClientBuilder.standard().withRegion(region).build(); encryptRecord(tableName, cmkArn, kms); } finally { if (kms != null) { kms.shutdown(); } } } public static void encryptRecord( final String tableName, final String cmkArn, final AWSKMS kmsClient) throws GeneralSecurityException { // Sample record to be encrypted final String partitionKeyName = "partition_attribute"; final String sortKeyName = "sort_attribute"; final Map<String, AttributeValue> record = new HashMap<>(); record.put(partitionKeyName, new AttributeValue().withS("is this")); record.put(sortKeyName, new AttributeValue().withN("55")); record.put(STRING_FIELD_NAME, new AttributeValue().withS("data")); record.put(NUMBER_FIELD_NAME, new AttributeValue().withN("99")); record.put( BINARY_FIELD_NAME, new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0x00, 0x01, 0x02}))); record.put( IGNORED_FIELD_NAME, new AttributeValue().withS("alone")); // We want to ignore this attribute // Set up our configuration and clients. All of this is thread-safe and can be reused across // calls. // This example assumes we already have a AWS KMS client `kmsClient` // Provider Configuration final DirectKmsMaterialProvider cmp = new DirectKmsMaterialProvider(kmsClient, cmkArn); // Encryptor creation final DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(cmp); // Information about the context of our data (normally just Table information) final EncryptionContext encryptionContext = new EncryptionContext.Builder() .withTableName(tableName) .withHashKeyName(partitionKeyName) .withRangeKeyName(sortKeyName) .build(); // Describe what actions need to be taken for each attribute final EnumSet<EncryptionFlags> signOnly = EnumSet.of(EncryptionFlags.SIGN); final EnumSet<EncryptionFlags> encryptAndSign = EnumSet.of(EncryptionFlags.ENCRYPT, EncryptionFlags.SIGN); final Map<String, Set<EncryptionFlags>> actions = new HashMap<>(); for (final String attributeName : record.keySet()) { switch (attributeName) { case partitionKeyName: // fall through case sortKeyName: // Partition and sort keys must not be encrypted but should be signed actions.put(attributeName, signOnly); break; case IGNORED_FIELD_NAME: // For this example, we are neither signing nor encrypting this field break; default: // We want to encrypt and sign everything else actions.put(attributeName, encryptAndSign); break; } } // End set-up // Encrypt the plaintext record directly final Map<String, AttributeValue> encrypted_record = encryptor.encryptRecord(record, actions, encryptionContext); // Encrypted record fields change as expected assert encrypted_record.get(STRING_FIELD_NAME).getB() != null; // the encrypted string is stored as bytes assert encrypted_record.get(NUMBER_FIELD_NAME).getB() != null; // the encrypted number is stored as bytes assert !record .get(BINARY_FIELD_NAME) .getB() .equals(encrypted_record.get(BINARY_FIELD_NAME).getB()); // the encrypted bytes have updated assert record .get(IGNORED_FIELD_NAME) .getS() .equals(encrypted_record.get(IGNORED_FIELD_NAME).getS()); // ignored field is left as is // We could now put the encrypted item to DynamoDB just as we would any other item. // We're skipping it to to keep the example simpler. System.out.println("Plaintext Record: " + record); System.out.println("Encrypted Record: " + encrypted_record); // Decryption is identical. We'll pretend that we retrieved the record from DynamoDB. final Map<String, AttributeValue> decrypted_record = encryptor.decryptRecord(encrypted_record, actions, encryptionContext); System.out.println("Decrypted Record: " + decrypted_record); // The decrypted fields match the original fields before encryption assert record .get(STRING_FIELD_NAME) .getS() .equals(decrypted_record.get(STRING_FIELD_NAME).getS()); assert record .get(NUMBER_FIELD_NAME) .getN() .equals(decrypted_record.get(NUMBER_FIELD_NAME).getN()); assert record .get(BINARY_FIELD_NAME) .getB() .equals(decrypted_record.get(BINARY_FIELD_NAME).getB()); } }
4,353
0
Create_ds/aws-dynamodb-encryption-java/examples/src/main/java/com/amazonaws
Create_ds/aws-dynamodb-encryption-java/examples/src/main/java/com/amazonaws/examples/AwsKmsEncryptedObject.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.examples; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.datamodeling.AttributeEncryptor; 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.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.DirectKmsMaterialProvider; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.AWSKMSClientBuilder; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * This demonstrates how to use the {@link DynamoDBMapper} with the {@link AttributeEncryptor} to * encrypt your data. Before you can use this you need to set up a DynamoDB table called * "ExampleTable" to hold the encrypted data. "ExampleTable" should have a partition key named * "partition_attribute" for Strings and a sort (range) key named "sort_attribute" for numbers. */ public class AwsKmsEncryptedObject { public static final String EXAMPLE_TABLE_NAME = "ExampleTable"; public static final String PARTITION_ATTRIBUTE = "partition_attribute"; public static final String SORT_ATTRIBUTE = "sort_attribute"; private static final String STRING_FIELD_NAME = "example"; private static final String BINARY_FIELD_NAME = "and some binary"; private static final String NUMBER_FIELD_NAME = "some numbers"; private static final String IGNORED_FIELD_NAME = "leave me"; public static void main(String[] args) throws GeneralSecurityException { final String cmkArn = args[0]; final String region = args[1]; AmazonDynamoDB ddb = null; AWSKMS kms = null; try { ddb = AmazonDynamoDBClientBuilder.standard().withRegion(region).build(); kms = AWSKMSClientBuilder.standard().withRegion(region).build(); encryptRecord(cmkArn, ddb, kms); } finally { if (ddb != null) { ddb.shutdown(); } if (kms != null) { kms.shutdown(); } } } public static void encryptRecord( final String cmkArn, final AmazonDynamoDB ddbClient, final AWSKMS kmsClient) { // Sample object to be encrypted DataPoJo record = new DataPoJo(); record.setPartitionAttribute("is this"); record.setSortAttribute(55); record.setExample("data"); record.setSomeNumbers(99); record.setSomeBinary(new byte[] {0x00, 0x01, 0x02}); record.setLeaveMe("alone"); // Set up our configuration and clients // This example assumes we already have a DynamoDB client `ddbClient` and AWS KMS client // `kmsClient` final DirectKmsMaterialProvider cmp = new DirectKmsMaterialProvider(kmsClient, cmkArn); // Encryptor creation final DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(cmp); // Mapper Creation // Please note the use of SaveBehavior.PUT (SaveBehavior.CLOBBER works as well). // Omitting this can result in data-corruption. DynamoDBMapperConfig mapperConfig = DynamoDBMapperConfig.builder().withSaveBehavior(SaveBehavior.PUT).build(); DynamoDBMapper mapper = new DynamoDBMapper(ddbClient, mapperConfig, new AttributeEncryptor(encryptor)); System.out.println("Plaintext Record: " + record); // Save the item to the DynamoDB table mapper.save(record); // Retrieve the encrypted item (directly without decrypting) from Dynamo so we can see it in our // example final Map<String, AttributeValue> itemKey = new HashMap<>(); itemKey.put(PARTITION_ATTRIBUTE, new AttributeValue().withS("is this")); itemKey.put(SORT_ATTRIBUTE, new AttributeValue().withN("55")); final Map<String, AttributeValue> encrypted_record = ddbClient.getItem(EXAMPLE_TABLE_NAME, itemKey).getItem(); System.out.println("Encrypted Record: " + encrypted_record); // Encrypted record fields change as expected assert encrypted_record.get(STRING_FIELD_NAME).getB() != null; // the encrypted string is stored as bytes assert encrypted_record.get(NUMBER_FIELD_NAME).getB() != null; // the encrypted number is stored as bytes assert !ByteBuffer.wrap(record.getSomeBinary()) .equals(encrypted_record.get(BINARY_FIELD_NAME).getB()); // the encrypted bytes have updated assert record .getLeaveMe() .equals(encrypted_record.get(IGNORED_FIELD_NAME).getS()); // ignored field is left as is // Retrieve (and decrypt) it from DynamoDB DataPoJo decrypted_record = mapper.load(DataPoJo.class, "is this", 55); System.out.println("Decrypted Record: " + decrypted_record); // The decrypted fields match the original fields before encryption assert record.getExample().equals(decrypted_record.getExample()); assert record.getSomeNumbers() == decrypted_record.getSomeNumbers(); assert Arrays.equals(record.getSomeBinary(), decrypted_record.getSomeBinary()); } @DynamoDBTable(tableName = EXAMPLE_TABLE_NAME) public static final class DataPoJo { private String partitionAttribute; private int sortAttribute; private String example; private long someNumbers; private byte[] someBinary; private String leaveMe; @DynamoDBHashKey(attributeName = PARTITION_ATTRIBUTE) public String getPartitionAttribute() { return partitionAttribute; } public void setPartitionAttribute(String partitionAttribute) { this.partitionAttribute = partitionAttribute; } @DynamoDBRangeKey(attributeName = SORT_ATTRIBUTE) public int getSortAttribute() { return sortAttribute; } public void setSortAttribute(int sortAttribute) { this.sortAttribute = sortAttribute; } @DynamoDBAttribute(attributeName = STRING_FIELD_NAME) public String getExample() { return example; } public void setExample(String example) { this.example = example; } @DynamoDBAttribute(attributeName = NUMBER_FIELD_NAME) public long getSomeNumbers() { return someNumbers; } public void setSomeNumbers(long someNumbers) { this.someNumbers = someNumbers; } @DynamoDBAttribute(attributeName = BINARY_FIELD_NAME) public byte[] getSomeBinary() { return someBinary; } public void setSomeBinary(byte[] someBinary) { this.someBinary = someBinary; } @DynamoDBAttribute(attributeName = IGNORED_FIELD_NAME) @DoNotTouch public String getLeaveMe() { return leaveMe; } public void setLeaveMe(String leaveMe) { this.leaveMe = leaveMe; } @Override public String toString() { return "DataPoJo [partitionAttribute=" + partitionAttribute + ", sortAttribute=" + sortAttribute + ", example=" + example + ", someNumbers=" + someNumbers + ", someBinary=" + Arrays.toString(someBinary) + ", leaveMe=" + leaveMe + "]"; } } }
4,354
0
Create_ds/aws-dynamodb-encryption-java/examples/src/main/java/com/amazonaws
Create_ds/aws-dynamodb-encryption-java/examples/src/main/java/com/amazonaws/examples/SymmetricEncryptedItem.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.examples; 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.datamodeling.encryption.providers.WrappedMaterialsProvider; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.security.SecureRandom; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; /** * Example showing use of an AES key for encryption and an HmacSHA256 key for signing. For ease of * the example, we create new random ones every time. */ public class SymmetricEncryptedItem { private static final String STRING_FIELD_NAME = "example"; private static final String BINARY_FIELD_NAME = "and some binary"; private static final String NUMBER_FIELD_NAME = "some numbers"; private static final String IGNORED_FIELD_NAME = "leave me"; public static void main(String[] args) throws GeneralSecurityException { final String tableName = args[0]; // Both AES and HMAC keys are just random bytes. // You should never use the same keys for encryption and signing/integrity. final SecureRandom secureRandom = new SecureRandom(); byte[] rawAes = new byte[32]; byte[] rawHmac = new byte[32]; secureRandom.nextBytes(rawAes); secureRandom.nextBytes(rawHmac); final SecretKey wrappingKey = new SecretKeySpec(rawAes, "AES"); final SecretKey signingKey = new SecretKeySpec(rawHmac, "HmacSHA256"); encryptRecord(tableName, wrappingKey, signingKey); } public static void encryptRecord(String tableName, SecretKey wrappingKey, SecretKey signingKey) throws GeneralSecurityException { // Sample record to be encrypted final String partitionKeyName = "partition_attribute"; final String sortKeyName = "sort_attribute"; final Map<String, AttributeValue> record = new HashMap<>(); record.put(partitionKeyName, new AttributeValue().withS("is this")); record.put(sortKeyName, new AttributeValue().withN("55")); record.put(STRING_FIELD_NAME, new AttributeValue().withS("data")); record.put(NUMBER_FIELD_NAME, new AttributeValue().withN("99")); record.put( BINARY_FIELD_NAME, new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0x00, 0x01, 0x02}))); record.put( IGNORED_FIELD_NAME, new AttributeValue().withS("alone")); // We want to ignore this attribute // Set up our configuration and clients. All of this is thread-safe and can be reused across // calls. // Provider Configuration final WrappedMaterialsProvider cmp = new WrappedMaterialsProvider(wrappingKey, wrappingKey, signingKey); // While the wrappedMaterialsProvider is better as it uses a unique encryption key per record, // many existing systems use the SymmetricStaticProvider which always uses the same encryption // key. // final SymmetricStaticProvider cmp = new SymmetricStaticProvider(encryptionKey, // signingKey); // Encryptor creation final DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(cmp); // Information about the context of our data (normally just Table information) final EncryptionContext encryptionContext = new EncryptionContext.Builder() .withTableName(tableName) .withHashKeyName(partitionKeyName) .withRangeKeyName(sortKeyName) .build(); // Describe what actions need to be taken for each attribute final EnumSet<EncryptionFlags> signOnly = EnumSet.of(EncryptionFlags.SIGN); final EnumSet<EncryptionFlags> encryptAndSign = EnumSet.of(EncryptionFlags.ENCRYPT, EncryptionFlags.SIGN); final Map<String, Set<EncryptionFlags>> actions = new HashMap<>(); for (final String attributeName : record.keySet()) { switch (attributeName) { case partitionKeyName: // fall through case sortKeyName: // Partition and sort keys must not be encrypted but should be signed actions.put(attributeName, signOnly); break; case IGNORED_FIELD_NAME: // For this example, we are neither signing nor encrypting this field break; default: // We want to encrypt and sign everything else actions.put(attributeName, encryptAndSign); break; } } // End set-up // Encrypt the plaintext record directly final Map<String, AttributeValue> encrypted_record = encryptor.encryptRecord(record, actions, encryptionContext); // Encrypted record fields change as expected assert encrypted_record.get(STRING_FIELD_NAME).getB() != null; // the encrypted string is stored as bytes assert encrypted_record.get(NUMBER_FIELD_NAME).getB() != null; // the encrypted number is stored as bytes assert !record .get(BINARY_FIELD_NAME) .getB() .equals(encrypted_record.get(BINARY_FIELD_NAME).getB()); // the encrypted bytes have updated assert record .get(IGNORED_FIELD_NAME) .getS() .equals(encrypted_record.get(IGNORED_FIELD_NAME).getS()); // ignored field is left as is // We could now put the encrypted item to DynamoDB just as we would any other item. // We're skipping it to to keep the example simpler. System.out.println("Plaintext Record: " + record); System.out.println("Encrypted Record: " + encrypted_record); // Decryption is identical. We'll pretend that we retrieved the record from DynamoDB. final Map<String, AttributeValue> decrypted_record = encryptor.decryptRecord(encrypted_record, actions, encryptionContext); System.out.println("Decrypted Record: " + decrypted_record); // The decrypted fields match the original fields before encryption assert record .get(STRING_FIELD_NAME) .getS() .equals(decrypted_record.get(STRING_FIELD_NAME).getS()); assert record .get(NUMBER_FIELD_NAME) .getN() .equals(decrypted_record.get(NUMBER_FIELD_NAME).getN()); assert record .get(BINARY_FIELD_NAME) .getB() .equals(decrypted_record.get(BINARY_FIELD_NAME).getB()); } }
4,355
0
Create_ds/aws-dynamodb-encryption-java/examples/src/main/java/com/amazonaws
Create_ds/aws-dynamodb-encryption-java/examples/src/main/java/com/amazonaws/examples/AwsKmsMultiRegionKey.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.examples; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.datamodeling.AttributeEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.TableNameOverride; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.DirectKmsMaterialProvider; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.AWSKMSClientBuilder; import java.security.GeneralSecurityException; import java.util.Arrays; /** * Example showing use of AWS KMS CMP with an AWS KMS Multi-Region Key. We encrypt a record with a * key in one region, then decrypt the ciphertext with the same key replicated to another region. * * <p>This example assumes that you have a DDB Global Table replicated to two regions, and an AWS * KMS Multi-Region Key replicated to the same regions. */ public class AwsKmsMultiRegionKey { public static void main(String[] args) throws GeneralSecurityException { final String tableName = args[0]; final String cmkArn1 = args[1]; final String cmkArn2 = args[2]; encryptRecord(tableName, cmkArn1, cmkArn2); } public static void encryptRecord( final String tableName, final String cmkArnEncrypt, final String cmkArnDecrypt) throws GeneralSecurityException { AWSKMS kmsDecrypt = null; AWSKMS kmsEncrypt = null; AmazonDynamoDB ddbEncrypt = null; AmazonDynamoDB ddbDecrypt = null; try { // Sample object to be encrypted AwsKmsEncryptedObject.DataPoJo record = new AwsKmsEncryptedObject.DataPoJo(); record.setPartitionAttribute("is this"); record.setSortAttribute(42); record.setExample("data"); record.setSomeNumbers(99); record.setSomeBinary(new byte[] {0x00, 0x01, 0x02}); record.setLeaveMe("alone"); // Set up clients and configuration in the first region. All of this is thread-safe and can be // reused // across calls final String encryptRegion = cmkArnEncrypt.split(":")[3]; kmsEncrypt = AWSKMSClientBuilder.standard().withRegion(encryptRegion).build(); ddbEncrypt = AmazonDynamoDBClientBuilder.standard().withRegion(encryptRegion).build(); final DirectKmsMaterialProvider cmpEncrypt = new DirectKmsMaterialProvider(kmsEncrypt, cmkArnEncrypt); final DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(cmpEncrypt); // Mapper Creation // Please note the use of SaveBehavior.PUT (SaveBehavior.CLOBBER works as well). // Omitting this can result in data-corruption. DynamoDBMapperConfig mapperConfig = DynamoDBMapperConfig.builder() .withSaveBehavior(DynamoDBMapperConfig.SaveBehavior.PUT) .withTableNameOverride(TableNameOverride.withTableNameReplacement(tableName)) .build(); DynamoDBMapper encryptMapper = new DynamoDBMapper(ddbEncrypt, mapperConfig, new AttributeEncryptor(encryptor)); System.out.println("Plaintext Record: " + record); // Save the item to the DynamoDB table encryptMapper.save(record); // DDB Global Table replication takes some time. Sleep for a moment to give the item a chance // to replicate // to the second region try { Thread.sleep(1000); } catch (InterruptedException e) { } // Set up clients and configuration in the second region final String decryptRegion = cmkArnDecrypt.split(":")[3]; kmsDecrypt = AWSKMSClientBuilder.standard().withRegion(decryptRegion).build(); ddbDecrypt = AmazonDynamoDBClientBuilder.standard().withRegion(decryptRegion).build(); final DirectKmsMaterialProvider cmpDecrypt = new DirectKmsMaterialProvider(kmsDecrypt, cmkArnDecrypt); final DynamoDBEncryptor decryptor = DynamoDBEncryptor.getInstance(cmpDecrypt); DynamoDBMapper decryptMapper = new DynamoDBMapper(ddbDecrypt, mapperConfig, new AttributeEncryptor(decryptor)); // Retrieve (and decrypt) it in the second region. This allows you to avoid a cross-region KMS // call to the // first region if your application is running in the second region AwsKmsEncryptedObject.DataPoJo decryptedRecord = decryptMapper.load(AwsKmsEncryptedObject.DataPoJo.class, "is this", 42); System.out.println("Decrypted Record: " + decryptedRecord); // The decrypted fields match the original fields before encryption assert record.getExample().equals(decryptedRecord.getExample()); assert record.getSomeNumbers() == decryptedRecord.getSomeNumbers(); assert Arrays.equals(record.getSomeBinary(), decryptedRecord.getSomeBinary()); } finally { if (kmsDecrypt != null) { kmsDecrypt.shutdown(); } if (kmsEncrypt != null) { kmsEncrypt.shutdown(); } if (ddbEncrypt != null) { ddbEncrypt.shutdown(); } if (ddbDecrypt != null) { ddbDecrypt.shutdown(); } } } }
4,356
0
Create_ds/aws-dynamodb-encryption-java/examples/src/main/java/com/amazonaws
Create_ds/aws-dynamodb-encryption-java/examples/src/main/java/com/amazonaws/examples/AsymmetricEncryptedItem.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.examples; 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.datamodeling.encryption.providers.WrappedMaterialsProvider; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Example showing use of RSA keys for encryption and signing. For ease of the example, we create * new random ones every time. */ public class AsymmetricEncryptedItem { private static final String STRING_FIELD_NAME = "example"; private static final String BINARY_FIELD_NAME = "and some binary"; private static final String NUMBER_FIELD_NAME = "some numbers"; private static final String IGNORED_FIELD_NAME = "leave me"; public static void main(String[] args) throws GeneralSecurityException { final String tableName = args[0]; final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); // You should never use the same key for encryption and signing final KeyPair wrappingKeys = keyGen.generateKeyPair(); final KeyPair signingKeys = keyGen.generateKeyPair(); encryptRecord(tableName, wrappingKeys, signingKeys); } public static void encryptRecord(String tableName, KeyPair wrappingKeys, KeyPair signingKeys) throws GeneralSecurityException { // Sample record to be encrypted final String partitionKeyName = "partition_attribute"; final String sortKeyName = "sort_attribute"; final Map<String, AttributeValue> record = new HashMap<>(); record.put(partitionKeyName, new AttributeValue().withS("is this")); record.put(sortKeyName, new AttributeValue().withN("55")); record.put(STRING_FIELD_NAME, new AttributeValue().withS("data")); record.put(NUMBER_FIELD_NAME, new AttributeValue().withN("99")); record.put( BINARY_FIELD_NAME, new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0x00, 0x01, 0x02}))); record.put( IGNORED_FIELD_NAME, new AttributeValue().withS("alone")); // We want to ignore this attribute // Set up our configuration and clients. All of this is thread-safe and can be reused across // calls. // Provider Configuration final WrappedMaterialsProvider cmp = new WrappedMaterialsProvider( wrappingKeys.getPublic(), wrappingKeys.getPrivate(), signingKeys); // Encryptor creation final DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(cmp); // Information about the context of our data (normally just Table information) final EncryptionContext encryptionContext = new EncryptionContext.Builder() .withTableName(tableName) .withHashKeyName(partitionKeyName) .withRangeKeyName(sortKeyName) .build(); // Describe what actions need to be taken for each attribute final EnumSet<EncryptionFlags> signOnly = EnumSet.of(EncryptionFlags.SIGN); final EnumSet<EncryptionFlags> encryptAndSign = EnumSet.of(EncryptionFlags.ENCRYPT, EncryptionFlags.SIGN); final Map<String, Set<EncryptionFlags>> actions = new HashMap<>(); for (final String attributeName : record.keySet()) { switch (attributeName) { case partitionKeyName: // fall through case sortKeyName: // Partition and sort keys must not be encrypted but should be signed actions.put(attributeName, signOnly); break; case IGNORED_FIELD_NAME: // For this example, we are neither signing nor encrypting this field break; default: // We want to encrypt and sign everything else actions.put(attributeName, encryptAndSign); break; } } // End set-up // Encrypt the plaintext record directly final Map<String, AttributeValue> encrypted_record = encryptor.encryptRecord(record, actions, encryptionContext); // Encrypted record fields change as expected assert encrypted_record.get(STRING_FIELD_NAME).getB() != null; // the encrypted string is stored as bytes assert encrypted_record.get(NUMBER_FIELD_NAME).getB() != null; // the encrypted number is stored as bytes assert !record .get(BINARY_FIELD_NAME) .getB() .equals(encrypted_record.get(BINARY_FIELD_NAME).getB()); // the encrypted bytes have updated assert record .get(IGNORED_FIELD_NAME) .getS() .equals(encrypted_record.get(IGNORED_FIELD_NAME).getS()); // ignored field is left as is // We could now put the encrypted item to DynamoDB just as we would any other item. // We're skipping it to to keep the example simpler. System.out.println("Plaintext Record: " + record); System.out.println("Encrypted Record: " + encrypted_record); // Decryption is identical. We'll pretend that we retrieved the record from DynamoDB. final Map<String, AttributeValue> decrypted_record = encryptor.decryptRecord(encrypted_record, actions, encryptionContext); System.out.println("Decrypted Record: " + decrypted_record); // The decrypted fields match the original fields before encryption assert record .get(STRING_FIELD_NAME) .getS() .equals(decrypted_record.get(STRING_FIELD_NAME).getS()); assert record .get(NUMBER_FIELD_NAME) .getN() .equals(decrypted_record.get(NUMBER_FIELD_NAME).getN()); assert record .get(BINARY_FIELD_NAME) .getB() .equals(decrypted_record.get(BINARY_FIELD_NAME).getB()); } }
4,357
0
Create_ds/aws-dynamodb-encryption-java/examples/src/main/java/com/amazonaws
Create_ds/aws-dynamodb-encryption-java/examples/src/main/java/com/amazonaws/examples/EncryptionContextOverridesWithDynamoDBMapper.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.examples; import static com.amazonaws.services.dynamodbv2.datamodeling.encryption.utils.EncryptionContextOperators.overrideEncryptionContextTableNameUsingMap; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.datamodeling.AttributeEncryptor; 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.DynamoDBRangeKey; 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.datamodeling.encryption.EncryptionFlags; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.DirectKmsMaterialProvider; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.AWSKMSClientBuilder; import java.security.GeneralSecurityException; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * This demonstrates how to use an operator to override the table name used in the encryption * context. Before you can use this you need to set up a DynamoDB table called * "ExampleTableForEncryptionContextOverrides" to hold the encrypted data. * "ExampleTableForEncryptionContextOverrides" should have a partition key named * "partition_attribute" for Strings and a sort (range) key named "sort_attribute" for numbers. */ public class EncryptionContextOverridesWithDynamoDBMapper { public static final String TABLE_NAME_TO_OVERRIDE = "ExampleTableForEncryptionContextOverrides"; public static final String PARTITION_ATTRIBUTE = "partition_attribute"; public static final String SORT_ATTRIBUTE = "sort_attribute"; private static final String STRING_FIELD_NAME = "example"; private static final String BINARY_FIELD_NAME = "and some binary"; private static final String NUMBER_FIELD_NAME = "some numbers"; private static final String IGNORED_FIELD_NAME = "leave me"; public static void main(String[] args) throws GeneralSecurityException { final String cmkArn = args[0]; final String region = args[1]; final String encryptionContextTableName = args[2]; AmazonDynamoDB ddb = null; AWSKMS kms = null; try { ddb = AmazonDynamoDBClientBuilder.standard().withRegion(region).build(); kms = AWSKMSClientBuilder.standard().withRegion(region).build(); encryptRecord(cmkArn, encryptionContextTableName, ddb, kms); } finally { if (ddb != null) { ddb.shutdown(); } if (kms != null) { kms.shutdown(); } } } public static void encryptRecord( final String cmkArn, final String newEncryptionContextTableName, AmazonDynamoDB ddbClient, AWSKMS kmsClient) throws GeneralSecurityException { // Sample object to be encrypted ExampleItem record = new ExampleItem(); record.setPartitionAttribute("is this"); record.setSortAttribute(55); record.setExample("my data"); // Set up our configuration and clients // This example assumes we already have a DynamoDB client `ddbClient` and AWS KMS client // `kmsClient` final DirectKmsMaterialProvider cmp = new DirectKmsMaterialProvider(kmsClient, cmkArn); final DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(cmp); Map<String, String> tableNameEncryptionContextOverrides = new HashMap<>(); tableNameEncryptionContextOverrides.put(TABLE_NAME_TO_OVERRIDE, newEncryptionContextTableName); tableNameEncryptionContextOverrides.put( "AnotherExampleTableForEncryptionContextOverrides", "this table doesn't exist"); // Supply an operator to override the table name used in the encryption context encryptor.setEncryptionContextOverrideOperator( overrideEncryptionContextTableNameUsingMap(tableNameEncryptionContextOverrides)); // Mapper Creation // Please note the use of SaveBehavior.PUT (SaveBehavior.CLOBBER works as well). // Omitting this can result in data-corruption. DynamoDBMapperConfig mapperConfig = DynamoDBMapperConfig.builder() .withSaveBehavior(DynamoDBMapperConfig.SaveBehavior.PUT) .build(); DynamoDBMapper mapper = new DynamoDBMapper(ddbClient, mapperConfig, new AttributeEncryptor(encryptor)); System.out.println("Plaintext Record: " + record.toString()); // Save the record to the DynamoDB table mapper.save(record); // Retrieve (and decrypt) it from DynamoDB ExampleItem decrypted_record = mapper.load(ExampleItem.class, "is this", 55); System.out.println("Decrypted Record: " + decrypted_record.toString()); // The decrypted field matches the original field before encryption assert record.getExample().equals(decrypted_record.getExample()); // Setup new configuration to decrypt without using an overridden EncryptionContext final Map<String, AttributeValue> itemKey = new HashMap<>(); itemKey.put(PARTITION_ATTRIBUTE, new AttributeValue().withS("is this")); itemKey.put(SORT_ATTRIBUTE, new AttributeValue().withN("55")); final EnumSet<EncryptionFlags> signOnly = EnumSet.of(EncryptionFlags.SIGN); final EnumSet<EncryptionFlags> encryptAndSign = EnumSet.of(EncryptionFlags.ENCRYPT, EncryptionFlags.SIGN); final Map<String, AttributeValue> encryptedItem = ddbClient.getItem(TABLE_NAME_TO_OVERRIDE, itemKey).getItem(); System.out.println("Encrypted Record: " + encryptedItem); Map<String, Set<EncryptionFlags>> encryptionFlags = new HashMap<>(); encryptionFlags.put(PARTITION_ATTRIBUTE, signOnly); encryptionFlags.put(SORT_ATTRIBUTE, signOnly); encryptionFlags.put(STRING_FIELD_NAME, encryptAndSign); final DynamoDBEncryptor encryptorWithoutOverrides = DynamoDBEncryptor.getInstance(cmp); // Decrypt the record without using an overridden EncryptionContext Map<String, AttributeValue> decrypted_without_override_record = encryptorWithoutOverrides.decryptRecord( encryptedItem, encryptionFlags, new EncryptionContext.Builder() .withHashKeyName(PARTITION_ATTRIBUTE) .withRangeKeyName(SORT_ATTRIBUTE) .withTableName(newEncryptionContextTableName) .build()); System.out.printf( "The example item was encrypted using the table name '%s' in the EncryptionContext%n", newEncryptionContextTableName); // The decrypted field matches the original field before encryption assert record .getExample() .equals(decrypted_without_override_record.get(STRING_FIELD_NAME).getS()); } @DynamoDBTable(tableName = TABLE_NAME_TO_OVERRIDE) public static final class ExampleItem { private String partitionAttribute; private int sortAttribute; private String example; @DynamoDBHashKey(attributeName = PARTITION_ATTRIBUTE) public String getPartitionAttribute() { return partitionAttribute; } public void setPartitionAttribute(String partitionAttribute) { this.partitionAttribute = partitionAttribute; } @DynamoDBRangeKey(attributeName = SORT_ATTRIBUTE) public int getSortAttribute() { return sortAttribute; } public void setSortAttribute(int sortAttribute) { this.sortAttribute = sortAttribute; } @DynamoDBAttribute(attributeName = STRING_FIELD_NAME) public String getExample() { return example; } public void setExample(String example) { this.example = example; } public String toString() { return String.format( "{partition_attribute: %s, sort_attribute: %s, example: %s}", partitionAttribute, sortAttribute, example); } } }
4,358
0
Create_ds/Hystrix/hystrix-serialization/src/test/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-serialization/src/test/java/com/netflix/hystrix/serial/SerialHystrixRequestEventsTest.java
/** * Copyright 2016 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.serial; import com.netflix.hystrix.ExecutionResult; import com.netflix.hystrix.HystrixCollapserKey; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandMetrics; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixEventType; import com.netflix.hystrix.HystrixInvokableInfo; import com.netflix.hystrix.HystrixThreadPoolKey; import com.netflix.hystrix.metric.HystrixRequestEvents; import org.junit.Test; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class SerialHystrixRequestEventsTest { private static final HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("GROUP"); private static final HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool"); private static final HystrixCommandKey fooKey = HystrixCommandKey.Factory.asKey("Foo"); private static final HystrixCommandKey barKey = HystrixCommandKey.Factory.asKey("Bar"); private static final HystrixCollapserKey collapserKey = HystrixCollapserKey.Factory.asKey("FooCollapser"); @Test public void testEmpty() throws IOException { HystrixRequestEvents request = new HystrixRequestEvents(new ArrayList<HystrixInvokableInfo<?>>()); String actual = SerialHystrixRequestEvents.toJsonString(request); assertEquals("[]", actual); } @Test public void testSingleSuccess() throws IOException { List<HystrixInvokableInfo<?>> executions = new ArrayList<HystrixInvokableInfo<?>>(); executions.add(new SimpleExecution(fooKey, 100, HystrixEventType.SUCCESS)); HystrixRequestEvents request = new HystrixRequestEvents(executions); String actual = SerialHystrixRequestEvents.toJsonString(request); assertEquals("[{\"name\":\"Foo\",\"events\":[\"SUCCESS\"],\"latencies\":[100]}]", actual); } @Test public void testSingleFailureFallbackMissing() throws IOException { List<HystrixInvokableInfo<?>> executions = new ArrayList<HystrixInvokableInfo<?>>(); executions.add(new SimpleExecution(fooKey, 101, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_MISSING)); HystrixRequestEvents request = new HystrixRequestEvents(executions); String actual = SerialHystrixRequestEvents.toJsonString(request); assertEquals("[{\"name\":\"Foo\",\"events\":[\"FAILURE\",\"FALLBACK_MISSING\"],\"latencies\":[101]}]", actual); } @Test public void testSingleFailureFallbackSuccess() throws IOException { List<HystrixInvokableInfo<?>> executions = new ArrayList<HystrixInvokableInfo<?>>(); executions.add(new SimpleExecution(fooKey, 102, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_SUCCESS)); HystrixRequestEvents request = new HystrixRequestEvents(executions); String actual = SerialHystrixRequestEvents.toJsonString(request); assertEquals("[{\"name\":\"Foo\",\"events\":[\"FAILURE\",\"FALLBACK_SUCCESS\"],\"latencies\":[102]}]", actual); } @Test public void testSingleFailureFallbackRejected() throws IOException { List<HystrixInvokableInfo<?>> executions = new ArrayList<HystrixInvokableInfo<?>>(); executions.add(new SimpleExecution(fooKey, 103, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_REJECTION)); HystrixRequestEvents request = new HystrixRequestEvents(executions); String actual = SerialHystrixRequestEvents.toJsonString(request); assertEquals("[{\"name\":\"Foo\",\"events\":[\"FAILURE\",\"FALLBACK_REJECTION\"],\"latencies\":[103]}]", actual); } @Test public void testSingleFailureFallbackFailure() throws IOException { List<HystrixInvokableInfo<?>> executions = new ArrayList<HystrixInvokableInfo<?>>(); executions.add(new SimpleExecution(fooKey, 104, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_FAILURE)); HystrixRequestEvents request = new HystrixRequestEvents(executions); String actual = SerialHystrixRequestEvents.toJsonString(request); assertEquals("[{\"name\":\"Foo\",\"events\":[\"FAILURE\",\"FALLBACK_FAILURE\"],\"latencies\":[104]}]", actual); } @Test public void testSingleTimeoutFallbackSuccess() throws IOException { List<HystrixInvokableInfo<?>> executions = new ArrayList<HystrixInvokableInfo<?>>(); executions.add(new SimpleExecution(fooKey, 105, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_SUCCESS)); HystrixRequestEvents request = new HystrixRequestEvents(executions); String actual = SerialHystrixRequestEvents.toJsonString(request); assertEquals("[{\"name\":\"Foo\",\"events\":[\"TIMEOUT\",\"FALLBACK_SUCCESS\"],\"latencies\":[105]}]", actual); } @Test public void testSingleSemaphoreRejectedFallbackSuccess() throws IOException { List<HystrixInvokableInfo<?>> executions = new ArrayList<HystrixInvokableInfo<?>>(); executions.add(new SimpleExecution(fooKey, 1, HystrixEventType.SEMAPHORE_REJECTED, HystrixEventType.FALLBACK_SUCCESS)); HystrixRequestEvents request = new HystrixRequestEvents(executions); String actual = SerialHystrixRequestEvents.toJsonString(request); assertEquals("[{\"name\":\"Foo\",\"events\":[\"SEMAPHORE_REJECTED\",\"FALLBACK_SUCCESS\"],\"latencies\":[1]}]", actual); } @Test public void testSingleThreadPoolRejectedFallbackSuccess() throws IOException { List<HystrixInvokableInfo<?>> executions = new ArrayList<HystrixInvokableInfo<?>>(); executions.add(new SimpleExecution(fooKey, 1, HystrixEventType.THREAD_POOL_REJECTED, HystrixEventType.FALLBACK_SUCCESS)); HystrixRequestEvents request = new HystrixRequestEvents(executions); String actual = SerialHystrixRequestEvents.toJsonString(request); assertEquals("[{\"name\":\"Foo\",\"events\":[\"THREAD_POOL_REJECTED\",\"FALLBACK_SUCCESS\"],\"latencies\":[1]}]", actual); } @Test public void testSingleShortCircuitedFallbackSuccess() throws IOException { List<HystrixInvokableInfo<?>> executions = new ArrayList<HystrixInvokableInfo<?>>(); executions.add(new SimpleExecution(fooKey, 1, HystrixEventType.SHORT_CIRCUITED, HystrixEventType.FALLBACK_SUCCESS)); HystrixRequestEvents request = new HystrixRequestEvents(executions); String actual = SerialHystrixRequestEvents.toJsonString(request); assertEquals("[{\"name\":\"Foo\",\"events\":[\"SHORT_CIRCUITED\",\"FALLBACK_SUCCESS\"],\"latencies\":[1]}]", actual); } @Test public void testSingleBadRequest() throws IOException { List<HystrixInvokableInfo<?>> executions = new ArrayList<HystrixInvokableInfo<?>>(); executions.add(new SimpleExecution(fooKey, 50, HystrixEventType.BAD_REQUEST)); HystrixRequestEvents request = new HystrixRequestEvents(executions); String actual = SerialHystrixRequestEvents.toJsonString(request); assertEquals("[{\"name\":\"Foo\",\"events\":[\"BAD_REQUEST\"],\"latencies\":[50]}]", actual); } @Test public void testTwoSuccessesSameKey() throws IOException { List<HystrixInvokableInfo<?>> executions = new ArrayList<HystrixInvokableInfo<?>>(); HystrixInvokableInfo<Integer> foo1 = new SimpleExecution(fooKey, 23, HystrixEventType.SUCCESS); HystrixInvokableInfo<Integer> foo2 = new SimpleExecution(fooKey, 34, HystrixEventType.SUCCESS); executions.add(foo1); executions.add(foo2); HystrixRequestEvents request = new HystrixRequestEvents(executions); String actual = SerialHystrixRequestEvents.toJsonString(request); assertEquals("[{\"name\":\"Foo\",\"events\":[\"SUCCESS\"],\"latencies\":[23,34]}]", actual); } @Test public void testTwoSuccessesDifferentKey() throws IOException { List<HystrixInvokableInfo<?>> executions = new ArrayList<HystrixInvokableInfo<?>>(); HystrixInvokableInfo<Integer> foo1 = new SimpleExecution(fooKey, 23, HystrixEventType.SUCCESS); HystrixInvokableInfo<Integer> bar1 = new SimpleExecution(barKey, 34, HystrixEventType.SUCCESS); executions.add(foo1); executions.add(bar1); HystrixRequestEvents request = new HystrixRequestEvents(executions); String actual = SerialHystrixRequestEvents.toJsonString(request); assertTrue(actual.equals("[{\"name\":\"Foo\",\"events\":[\"SUCCESS\"],\"latencies\":[23]},{\"name\":\"Bar\",\"events\":[\"SUCCESS\"],\"latencies\":[34]}]") || actual.equals("[{\"name\":\"Bar\",\"events\":[\"SUCCESS\"],\"latencies\":[34]},{\"name\":\"Foo\",\"events\":[\"SUCCESS\"],\"latencies\":[23]}]")); } @Test public void testTwoFailuresSameKey() throws IOException { List<HystrixInvokableInfo<?>> executions = new ArrayList<HystrixInvokableInfo<?>>(); HystrixInvokableInfo<Integer> foo1 = new SimpleExecution(fooKey, 56, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_SUCCESS); HystrixInvokableInfo<Integer> foo2 = new SimpleExecution(fooKey, 67, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_SUCCESS); executions.add(foo1); executions.add(foo2); HystrixRequestEvents request = new HystrixRequestEvents(executions); String actual = SerialHystrixRequestEvents.toJsonString(request); assertEquals("[{\"name\":\"Foo\",\"events\":[\"FAILURE\",\"FALLBACK_SUCCESS\"],\"latencies\":[56,67]}]", actual); } @Test public void testTwoSuccessesOneFailureSameKey() throws IOException { List<HystrixInvokableInfo<?>> executions = new ArrayList<HystrixInvokableInfo<?>>(); HystrixInvokableInfo<Integer> foo1 = new SimpleExecution(fooKey, 10, HystrixEventType.SUCCESS); HystrixInvokableInfo<Integer> foo2 = new SimpleExecution(fooKey, 67, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_SUCCESS); HystrixInvokableInfo<Integer> foo3 = new SimpleExecution(fooKey, 11, HystrixEventType.SUCCESS); executions.add(foo1); executions.add(foo2); executions.add(foo3); HystrixRequestEvents request = new HystrixRequestEvents(executions); String actual = SerialHystrixRequestEvents.toJsonString(request); assertTrue(actual.equals("[{\"name\":\"Foo\",\"events\":[\"SUCCESS\"],\"latencies\":[10,11]},{\"name\":\"Foo\",\"events\":[\"FAILURE\",\"FALLBACK_SUCCESS\"],\"latencies\":[67]}]") || actual.equals("[{\"name\":\"Foo\",\"events\":[\"FAILURE\",\"FALLBACK_SUCCESS\"],\"latencies\":[67]},{\"name\":\"Foo\",\"events\":[\"SUCCESS\"],\"latencies\":[10,11]}]")); } @Test public void testSingleResponseFromCache() throws IOException { List<HystrixInvokableInfo<?>> executions = new ArrayList<HystrixInvokableInfo<?>>(); HystrixInvokableInfo<Integer> foo1 = new SimpleExecution(fooKey, 23, "cacheKeyA", HystrixEventType.SUCCESS); HystrixInvokableInfo<Integer> cachedFoo1 = new SimpleExecution(fooKey, "cacheKeyA"); executions.add(foo1); executions.add(cachedFoo1); HystrixRequestEvents request = new HystrixRequestEvents(executions); String actual = SerialHystrixRequestEvents.toJsonString(request); assertEquals("[{\"name\":\"Foo\",\"events\":[\"SUCCESS\"],\"latencies\":[23],\"cached\":1}]", actual); } @Test public void testMultipleResponsesFromCache() throws IOException { List<HystrixInvokableInfo<?>> executions = new ArrayList<HystrixInvokableInfo<?>>(); HystrixInvokableInfo<Integer> foo1 = new SimpleExecution(fooKey, 23, "cacheKeyA", HystrixEventType.SUCCESS); HystrixInvokableInfo<Integer> cachedFoo1 = new SimpleExecution(fooKey, "cacheKeyA"); HystrixInvokableInfo<Integer> anotherCachedFoo1 = new SimpleExecution(fooKey, "cacheKeyA"); executions.add(foo1); executions.add(cachedFoo1); executions.add(anotherCachedFoo1); HystrixRequestEvents request = new HystrixRequestEvents(executions); String actual = SerialHystrixRequestEvents.toJsonString(request); assertEquals("[{\"name\":\"Foo\",\"events\":[\"SUCCESS\"],\"latencies\":[23],\"cached\":2}]", actual); } @Test public void testMultipleCacheKeys() throws IOException { List<HystrixInvokableInfo<?>> executions = new ArrayList<HystrixInvokableInfo<?>>(); HystrixInvokableInfo<Integer> foo1 = new SimpleExecution(fooKey, 23, "cacheKeyA", HystrixEventType.SUCCESS); HystrixInvokableInfo<Integer> cachedFoo1 = new SimpleExecution(fooKey, "cacheKeyA"); HystrixInvokableInfo<Integer> foo2 = new SimpleExecution(fooKey, 67, "cacheKeyB", HystrixEventType.SUCCESS); HystrixInvokableInfo<Integer> cachedFoo2 = new SimpleExecution(fooKey, "cacheKeyB"); executions.add(foo1); executions.add(cachedFoo1); executions.add(foo2); executions.add(cachedFoo2); HystrixRequestEvents request = new HystrixRequestEvents(executions); String actual = SerialHystrixRequestEvents.toJsonString(request); assertTrue(actual.equals("[{\"name\":\"Foo\",\"events\":[\"SUCCESS\"],\"latencies\":[67],\"cached\":1},{\"name\":\"Foo\",\"events\":[\"SUCCESS\"],\"latencies\":[23],\"cached\":1}]") || actual.equals("[{\"name\":\"Foo\",\"events\":[\"SUCCESS\"],\"latencies\":[23],\"cached\":1},{\"name\":\"Foo\",\"events\":[\"SUCCESS\"],\"latencies\":[67],\"cached\":1}]")); } @Test public void testSingleSuccessMultipleEmits() throws IOException { List<HystrixInvokableInfo<?>> executions = new ArrayList<HystrixInvokableInfo<?>>(); executions.add(new SimpleExecution(fooKey, 100, HystrixEventType.EMIT, HystrixEventType.EMIT, HystrixEventType.EMIT, HystrixEventType.SUCCESS)); HystrixRequestEvents request = new HystrixRequestEvents(executions); String actual = SerialHystrixRequestEvents.toJsonString(request); assertEquals("[{\"name\":\"Foo\",\"events\":[{\"name\":\"EMIT\",\"count\":3},\"SUCCESS\"],\"latencies\":[100]}]", actual); } @Test public void testSingleSuccessMultipleEmitsAndFallbackEmits() throws IOException { List<HystrixInvokableInfo<?>> executions = new ArrayList<HystrixInvokableInfo<?>>(); executions.add(new SimpleExecution(fooKey, 100, HystrixEventType.EMIT, HystrixEventType.EMIT, HystrixEventType.EMIT, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS)); HystrixRequestEvents request = new HystrixRequestEvents(executions); String actual = SerialHystrixRequestEvents.toJsonString(request); assertEquals("[{\"name\":\"Foo\",\"events\":[{\"name\":\"EMIT\",\"count\":3},\"FAILURE\",{\"name\":\"FALLBACK_EMIT\",\"count\":2},\"FALLBACK_SUCCESS\"],\"latencies\":[100]}]", actual); } @Test public void testCollapsedBatchOfOne() throws IOException { List<HystrixInvokableInfo<?>> executions = new ArrayList<HystrixInvokableInfo<?>>(); executions.add(new SimpleExecution(fooKey, 53, collapserKey, 1, HystrixEventType.SUCCESS)); HystrixRequestEvents request = new HystrixRequestEvents(executions); String actual = SerialHystrixRequestEvents.toJsonString(request); assertEquals("[{\"name\":\"Foo\",\"events\":[\"SUCCESS\"],\"latencies\":[53],\"collapsed\":{\"name\":\"FooCollapser\",\"count\":1}}]", actual); } @Test public void testCollapsedBatchOfSix() throws IOException { List<HystrixInvokableInfo<?>> executions = new ArrayList<HystrixInvokableInfo<?>>(); executions.add(new SimpleExecution(fooKey, 53, collapserKey, 6, HystrixEventType.SUCCESS)); HystrixRequestEvents request = new HystrixRequestEvents(executions); String actual = SerialHystrixRequestEvents.toJsonString(request); assertEquals("[{\"name\":\"Foo\",\"events\":[\"SUCCESS\"],\"latencies\":[53],\"collapsed\":{\"name\":\"FooCollapser\",\"count\":6}}]", actual); } private class SimpleExecution implements HystrixInvokableInfo<Integer> { private final HystrixCommandKey commandKey; private final ExecutionResult executionResult; private final String cacheKey; private final HystrixCollapserKey collapserKey; public SimpleExecution(HystrixCommandKey commandKey, int latency, HystrixEventType... events) { this.commandKey = commandKey; this.executionResult = ExecutionResult.from(events).setExecutionLatency(latency); this.cacheKey = null; this.collapserKey = null; } public SimpleExecution(HystrixCommandKey commandKey, int latency, String cacheKey, HystrixEventType... events) { this.commandKey = commandKey; this.executionResult = ExecutionResult.from(events).setExecutionLatency(latency); this.cacheKey = cacheKey; this.collapserKey = null; } public SimpleExecution(HystrixCommandKey commandKey, String cacheKey) { this.commandKey = commandKey; this.executionResult = ExecutionResult.from(HystrixEventType.RESPONSE_FROM_CACHE); this.cacheKey = cacheKey; this.collapserKey = null; } public SimpleExecution(HystrixCommandKey commandKey, int latency, HystrixCollapserKey collapserKey, int batchSize, HystrixEventType... events) { this.commandKey = commandKey; ExecutionResult interimResult = ExecutionResult.from(events).setExecutionLatency(latency); for (int i = 0; i < batchSize; i++) { interimResult = interimResult.addEvent(HystrixEventType.COLLAPSED); } this.executionResult = interimResult; this.cacheKey = null; this.collapserKey = collapserKey; } @Override public HystrixCommandGroupKey getCommandGroup() { return groupKey; } @Override public HystrixCommandKey getCommandKey() { return commandKey; } @Override public HystrixThreadPoolKey getThreadPoolKey() { return threadPoolKey; } @Override public String getPublicCacheKey() { return cacheKey; } @Override public HystrixCollapserKey getOriginatingCollapserKey() { return collapserKey; } @Override public HystrixCommandMetrics getMetrics() { return null; } @Override public HystrixCommandProperties getProperties() { return null; } @Override public boolean isCircuitBreakerOpen() { return false; } @Override public boolean isExecutionComplete() { return true; } @Override public boolean isExecutedInThread() { return false; //do i want this? } @Override public boolean isSuccessfulExecution() { return executionResult.getEventCounts().contains(HystrixEventType.SUCCESS); } @Override public boolean isFailedExecution() { return executionResult.getEventCounts().contains(HystrixEventType.FAILURE); } @Override public Throwable getFailedExecutionException() { return null; } @Override public boolean isResponseFromFallback() { return executionResult.getEventCounts().contains(HystrixEventType.FALLBACK_SUCCESS); } @Override public boolean isResponseTimedOut() { return executionResult.getEventCounts().contains(HystrixEventType.TIMEOUT); } @Override public boolean isResponseShortCircuited() { return executionResult.getEventCounts().contains(HystrixEventType.SHORT_CIRCUITED); } @Override public boolean isResponseFromCache() { return executionResult.getEventCounts().contains(HystrixEventType.RESPONSE_FROM_CACHE); } @Override public boolean isResponseRejected() { return executionResult.isResponseRejected(); } @Override public boolean isResponseSemaphoreRejected() { return executionResult.getEventCounts().contains(HystrixEventType.SEMAPHORE_REJECTED); } @Override public boolean isResponseThreadPoolRejected() { return executionResult.getEventCounts().contains(HystrixEventType.THREAD_POOL_REJECTED); } @Override public List<HystrixEventType> getExecutionEvents() { return executionResult.getOrderedList(); } @Override public int getNumberEmissions() { return executionResult.getEventCounts().getCount(HystrixEventType.EMIT); } @Override public int getNumberFallbackEmissions() { return executionResult.getEventCounts().getCount(HystrixEventType.FALLBACK_EMIT); } @Override public int getNumberCollapsed() { return executionResult.getEventCounts().getCount(HystrixEventType.COLLAPSED); } @Override public int getExecutionTimeInMilliseconds() { return executionResult.getExecutionLatency(); } @Override public long getCommandRunStartTimeInNanos() { return System.currentTimeMillis(); } @Override public ExecutionResult.EventCounts getEventCounts() { return executionResult.getEventCounts(); } @Override public String toString() { return "SimpleExecution{" + "commandKey=" + commandKey.name() + ", executionResult=" + executionResult + ", cacheKey='" + cacheKey + '\'' + ", collapserKey=" + collapserKey + '}'; } } }
4,359
0
Create_ds/Hystrix/hystrix-serialization/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-serialization/src/main/java/com/netflix/hystrix/serial/SerialHystrixConfiguration.java
/** * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.serial; import com.fasterxml.jackson.core.JsonGenerator; import com.netflix.hystrix.HystrixCollapserKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixThreadPoolKey; import com.netflix.hystrix.config.HystrixCollapserConfiguration; import com.netflix.hystrix.config.HystrixCommandConfiguration; import com.netflix.hystrix.config.HystrixConfiguration; import com.netflix.hystrix.config.HystrixThreadPoolConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.StringWriter; import java.nio.ByteBuffer; import java.util.Map; public class SerialHystrixConfiguration extends SerialHystrixMetric { private static final Logger logger = LoggerFactory.getLogger(SerialHystrixConfiguration.class); @Deprecated public static byte[] toBytes(HystrixConfiguration config) { throw new UnsupportedOperationException("Not implemented anymore. Will be implemented in a new class shortly"); } public static String toJsonString(HystrixConfiguration config) { StringWriter jsonString = new StringWriter(); try { JsonGenerator json = jsonFactory.createGenerator(jsonString); serializeConfiguration(config, json); } catch (Exception e) { throw new RuntimeException(e); } return jsonString.getBuffer().toString(); } private static void serializeConfiguration(HystrixConfiguration config, JsonGenerator json) { try { json.writeStartObject(); json.writeStringField("type", "HystrixConfig"); json.writeObjectFieldStart("commands"); for (Map.Entry<HystrixCommandKey, HystrixCommandConfiguration> entry: config.getCommandConfig().entrySet()) { final HystrixCommandKey key = entry.getKey(); final HystrixCommandConfiguration commandConfig = entry.getValue(); writeCommandConfigJson(json, key, commandConfig); } json.writeEndObject(); json.writeObjectFieldStart("threadpools"); for (Map.Entry<HystrixThreadPoolKey, HystrixThreadPoolConfiguration> entry: config.getThreadPoolConfig().entrySet()) { final HystrixThreadPoolKey threadPoolKey = entry.getKey(); final HystrixThreadPoolConfiguration threadPoolConfig = entry.getValue(); writeThreadPoolConfigJson(json, threadPoolKey, threadPoolConfig); } json.writeEndObject(); json.writeObjectFieldStart("collapsers"); for (Map.Entry<HystrixCollapserKey, HystrixCollapserConfiguration> entry: config.getCollapserConfig().entrySet()) { final HystrixCollapserKey collapserKey = entry.getKey(); final HystrixCollapserConfiguration collapserConfig = entry.getValue(); writeCollapserConfigJson(json, collapserKey, collapserConfig); } json.writeEndObject(); json.writeEndObject(); json.close(); } catch (Exception e) { throw new RuntimeException(e); } } @Deprecated public static HystrixConfiguration fromByteBuffer(ByteBuffer bb) { throw new UnsupportedOperationException("Not implemented anymore. Will be implemented in a new class shortly"); } private static void writeCommandConfigJson(JsonGenerator json, HystrixCommandKey key, HystrixCommandConfiguration commandConfig) throws IOException { json.writeObjectFieldStart(key.name()); json.writeStringField("threadPoolKey", commandConfig.getThreadPoolKey().name()); json.writeStringField("groupKey", commandConfig.getGroupKey().name()); json.writeObjectFieldStart("execution"); HystrixCommandConfiguration.HystrixCommandExecutionConfig executionConfig = commandConfig.getExecutionConfig(); json.writeStringField("isolationStrategy", executionConfig.getIsolationStrategy().name()); json.writeStringField("threadPoolKeyOverride", executionConfig.getThreadPoolKeyOverride()); json.writeBooleanField("requestCacheEnabled", executionConfig.isRequestCacheEnabled()); json.writeBooleanField("requestLogEnabled", executionConfig.isRequestLogEnabled()); json.writeBooleanField("timeoutEnabled", executionConfig.isTimeoutEnabled()); json.writeBooleanField("fallbackEnabled", executionConfig.isFallbackEnabled()); json.writeNumberField("timeoutInMilliseconds", executionConfig.getTimeoutInMilliseconds()); json.writeNumberField("semaphoreSize", executionConfig.getSemaphoreMaxConcurrentRequests()); json.writeNumberField("fallbackSemaphoreSize", executionConfig.getFallbackMaxConcurrentRequest()); json.writeBooleanField("threadInterruptOnTimeout", executionConfig.isThreadInterruptOnTimeout()); json.writeEndObject(); json.writeObjectFieldStart("metrics"); HystrixCommandConfiguration.HystrixCommandMetricsConfig metricsConfig = commandConfig.getMetricsConfig(); json.writeNumberField("healthBucketSizeInMs", metricsConfig.getHealthIntervalInMilliseconds()); json.writeNumberField("percentileBucketSizeInMilliseconds", metricsConfig.getRollingPercentileBucketSizeInMilliseconds()); json.writeNumberField("percentileBucketCount", metricsConfig.getRollingCounterNumberOfBuckets()); json.writeBooleanField("percentileEnabled", metricsConfig.isRollingPercentileEnabled()); json.writeNumberField("counterBucketSizeInMilliseconds", metricsConfig.getRollingCounterBucketSizeInMilliseconds()); json.writeNumberField("counterBucketCount", metricsConfig.getRollingCounterNumberOfBuckets()); json.writeEndObject(); json.writeObjectFieldStart("circuitBreaker"); HystrixCommandConfiguration.HystrixCommandCircuitBreakerConfig circuitBreakerConfig = commandConfig.getCircuitBreakerConfig(); json.writeBooleanField("enabled", circuitBreakerConfig.isEnabled()); json.writeBooleanField("isForcedOpen", circuitBreakerConfig.isForceOpen()); json.writeBooleanField("isForcedClosed", circuitBreakerConfig.isForceOpen()); json.writeNumberField("requestVolumeThreshold", circuitBreakerConfig.getRequestVolumeThreshold()); json.writeNumberField("errorPercentageThreshold", circuitBreakerConfig.getErrorThresholdPercentage()); json.writeNumberField("sleepInMilliseconds", circuitBreakerConfig.getSleepWindowInMilliseconds()); json.writeEndObject(); json.writeEndObject(); } private static void writeThreadPoolConfigJson(JsonGenerator json, HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolConfiguration threadPoolConfig) throws IOException { json.writeObjectFieldStart(threadPoolKey.name()); json.writeNumberField("coreSize", threadPoolConfig.getCoreSize()); json.writeNumberField("maximumSize", threadPoolConfig.getMaximumSize()); json.writeNumberField("actualMaximumSize", threadPoolConfig.getActualMaximumSize()); json.writeNumberField("maxQueueSize", threadPoolConfig.getMaxQueueSize()); json.writeNumberField("queueRejectionThreshold", threadPoolConfig.getQueueRejectionThreshold()); json.writeNumberField("keepAliveTimeInMinutes", threadPoolConfig.getKeepAliveTimeInMinutes()); json.writeBooleanField("allowMaximumSizeToDivergeFromCoreSize", threadPoolConfig.getAllowMaximumSizeToDivergeFromCoreSize()); json.writeNumberField("counterBucketSizeInMilliseconds", threadPoolConfig.getRollingCounterBucketSizeInMilliseconds()); json.writeNumberField("counterBucketCount", threadPoolConfig.getRollingCounterNumberOfBuckets()); json.writeEndObject(); } private static void writeCollapserConfigJson(JsonGenerator json, HystrixCollapserKey collapserKey, HystrixCollapserConfiguration collapserConfig) throws IOException { json.writeObjectFieldStart(collapserKey.name()); json.writeNumberField("maxRequestsInBatch", collapserConfig.getMaxRequestsInBatch()); json.writeNumberField("timerDelayInMilliseconds", collapserConfig.getTimerDelayInMilliseconds()); json.writeBooleanField("requestCacheEnabled", collapserConfig.isRequestCacheEnabled()); json.writeObjectFieldStart("metrics"); HystrixCollapserConfiguration.CollapserMetricsConfig metricsConfig = collapserConfig.getCollapserMetricsConfig(); json.writeNumberField("percentileBucketSizeInMilliseconds", metricsConfig.getRollingPercentileBucketSizeInMilliseconds()); json.writeNumberField("percentileBucketCount", metricsConfig.getRollingCounterNumberOfBuckets()); json.writeBooleanField("percentileEnabled", metricsConfig.isRollingPercentileEnabled()); json.writeNumberField("counterBucketSizeInMilliseconds", metricsConfig.getRollingCounterBucketSizeInMilliseconds()); json.writeNumberField("counterBucketCount", metricsConfig.getRollingCounterNumberOfBuckets()); json.writeEndObject(); json.writeEndObject(); } }
4,360
0
Create_ds/Hystrix/hystrix-serialization/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-serialization/src/main/java/com/netflix/hystrix/serial/SerialHystrixDashboardData.java
/** * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.serial; import com.fasterxml.jackson.core.JsonGenerator; import com.netflix.hystrix.HystrixCircuitBreaker; import com.netflix.hystrix.HystrixCollapserKey; import com.netflix.hystrix.HystrixCollapserMetrics; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandMetrics; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixEventType; import com.netflix.hystrix.HystrixThreadPoolKey; import com.netflix.hystrix.HystrixThreadPoolMetrics; import com.netflix.hystrix.metric.consumer.HystrixDashboardStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.functions.Func0; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; public class SerialHystrixDashboardData extends SerialHystrixMetric { private static final Logger logger = LoggerFactory.getLogger(SerialHystrixDashboardData.class); @Deprecated public static byte[] toBytes(HystrixDashboardStream.DashboardData dashboardData) { throw new UnsupportedOperationException("Not implemented anymore. Will be implemented in a new class shortly"); } public static String toJsonString(HystrixDashboardStream.DashboardData dashboardData) { StringWriter jsonString = new StringWriter(); try { JsonGenerator json = jsonFactory.createGenerator(jsonString); writeDashboardData(json, dashboardData); } catch (Exception e) { throw new RuntimeException(e); } return jsonString.getBuffer().toString(); } public static List<String> toMultipleJsonStrings(HystrixDashboardStream.DashboardData dashboardData) { List<String> jsonStrings = new ArrayList<String>(); for (HystrixCommandMetrics commandMetrics : dashboardData.getCommandMetrics()) { jsonStrings.add(toJsonString(commandMetrics)); } for (HystrixThreadPoolMetrics threadPoolMetrics : dashboardData.getThreadPoolMetrics()) { jsonStrings.add(toJsonString(threadPoolMetrics)); } for (HystrixCollapserMetrics collapserMetrics : dashboardData.getCollapserMetrics()) { jsonStrings.add(toJsonString(collapserMetrics)); } return jsonStrings; } private static void writeDashboardData(JsonGenerator json, HystrixDashboardStream.DashboardData dashboardData) { try { json.writeStartArray(); for (HystrixCommandMetrics commandMetrics : dashboardData.getCommandMetrics()) { writeCommandMetrics(commandMetrics, json); } for (HystrixThreadPoolMetrics threadPoolMetrics : dashboardData.getThreadPoolMetrics()) { writeThreadPoolMetrics(threadPoolMetrics, json); } for (HystrixCollapserMetrics collapserMetrics : dashboardData.getCollapserMetrics()) { writeCollapserMetrics(collapserMetrics, json); } json.writeEndArray(); json.close(); } catch (Exception e) { throw new RuntimeException(e); } } public static String toJsonString(HystrixCommandMetrics commandMetrics) { StringWriter jsonString = new StringWriter(); try { JsonGenerator json = jsonFactory.createGenerator(jsonString); writeCommandMetrics(commandMetrics, json); json.close(); return jsonString.getBuffer().toString(); } catch (IOException ioe) { throw new RuntimeException(ioe); } } public static String toJsonString(HystrixThreadPoolMetrics threadPoolMetrics) { StringWriter jsonString = new StringWriter(); try { JsonGenerator json = jsonFactory.createGenerator(jsonString); writeThreadPoolMetrics(threadPoolMetrics, json); json.close(); return jsonString.getBuffer().toString(); } catch (IOException ioe) { throw new RuntimeException(ioe); } } public static String toJsonString(HystrixCollapserMetrics collapserMetrics) { StringWriter jsonString = new StringWriter(); try { JsonGenerator json = jsonFactory.createGenerator(jsonString); writeCollapserMetrics(collapserMetrics, json); json.close(); return jsonString.getBuffer().toString(); } catch (IOException ioe) { throw new RuntimeException(ioe); } } private static void writeCommandMetrics(final HystrixCommandMetrics commandMetrics, JsonGenerator json) throws IOException { HystrixCommandKey key = commandMetrics.getCommandKey(); HystrixCircuitBreaker circuitBreaker = HystrixCircuitBreaker.Factory.getInstance(key); json.writeStartObject(); json.writeStringField("type", "HystrixCommand"); json.writeStringField("name", key.name()); json.writeStringField("group", commandMetrics.getCommandGroup().name()); json.writeNumberField("currentTime", System.currentTimeMillis()); // circuit breaker if (circuitBreaker == null) { // circuit breaker is disabled and thus never open json.writeBooleanField("isCircuitBreakerOpen", false); } else { json.writeBooleanField("isCircuitBreakerOpen", circuitBreaker.isOpen()); } HystrixCommandMetrics.HealthCounts healthCounts = commandMetrics.getHealthCounts(); json.writeNumberField("errorPercentage", healthCounts.getErrorPercentage()); json.writeNumberField("errorCount", healthCounts.getErrorCount()); json.writeNumberField("requestCount", healthCounts.getTotalRequests()); // rolling counters safelyWriteNumberField(json, "rollingCountBadRequests", new Func0<Long>() { @Override public Long call() { return commandMetrics.getRollingCount(HystrixEventType.BAD_REQUEST); } }); safelyWriteNumberField(json, "rollingCountCollapsedRequests", new Func0<Long>() { @Override public Long call() { return commandMetrics.getRollingCount(HystrixEventType.COLLAPSED); } }); safelyWriteNumberField(json, "rollingCountEmit", new Func0<Long>() { @Override public Long call() { return commandMetrics.getRollingCount(HystrixEventType.EMIT); } }); safelyWriteNumberField(json, "rollingCountExceptionsThrown", new Func0<Long>() { @Override public Long call() { return commandMetrics.getRollingCount(HystrixEventType.EXCEPTION_THROWN); } }); safelyWriteNumberField(json, "rollingCountFailure", new Func0<Long>() { @Override public Long call() { return commandMetrics.getRollingCount(HystrixEventType.FAILURE); } }); safelyWriteNumberField(json, "rollingCountFallbackEmit", new Func0<Long>() { @Override public Long call() { return commandMetrics.getRollingCount(HystrixEventType.FALLBACK_EMIT); } }); safelyWriteNumberField(json, "rollingCountFallbackFailure", new Func0<Long>() { @Override public Long call() { return commandMetrics.getRollingCount(HystrixEventType.FALLBACK_FAILURE); } }); safelyWriteNumberField(json, "rollingCountFallbackMissing", new Func0<Long>() { @Override public Long call() { return commandMetrics.getRollingCount(HystrixEventType.FALLBACK_MISSING); } }); safelyWriteNumberField(json, "rollingCountFallbackRejection", new Func0<Long>() { @Override public Long call() { return commandMetrics.getRollingCount(HystrixEventType.FALLBACK_REJECTION); } }); safelyWriteNumberField(json, "rollingCountFallbackSuccess", new Func0<Long>() { @Override public Long call() { return commandMetrics.getRollingCount(HystrixEventType.FALLBACK_SUCCESS); } }); safelyWriteNumberField(json, "rollingCountResponsesFromCache", new Func0<Long>() { @Override public Long call() { return commandMetrics.getRollingCount(HystrixEventType.RESPONSE_FROM_CACHE); } }); safelyWriteNumberField(json, "rollingCountSemaphoreRejected", new Func0<Long>() { @Override public Long call() { return commandMetrics.getRollingCount(HystrixEventType.SEMAPHORE_REJECTED); } }); safelyWriteNumberField(json, "rollingCountShortCircuited", new Func0<Long>() { @Override public Long call() { return commandMetrics.getRollingCount(HystrixEventType.SHORT_CIRCUITED); } }); safelyWriteNumberField(json, "rollingCountSuccess", new Func0<Long>() { @Override public Long call() { return commandMetrics.getRollingCount(HystrixEventType.SUCCESS); } }); safelyWriteNumberField(json, "rollingCountThreadPoolRejected", new Func0<Long>() { @Override public Long call() { return commandMetrics.getRollingCount(HystrixEventType.THREAD_POOL_REJECTED); } }); safelyWriteNumberField(json, "rollingCountTimeout", new Func0<Long>() { @Override public Long call() { return commandMetrics.getRollingCount(HystrixEventType.TIMEOUT); } }); json.writeNumberField("currentConcurrentExecutionCount", commandMetrics.getCurrentConcurrentExecutionCount()); json.writeNumberField("rollingMaxConcurrentExecutionCount", commandMetrics.getRollingMaxConcurrentExecutions()); // latency percentiles json.writeNumberField("latencyExecute_mean", commandMetrics.getExecutionTimeMean()); json.writeObjectFieldStart("latencyExecute"); json.writeNumberField("0", commandMetrics.getExecutionTimePercentile(0)); json.writeNumberField("25", commandMetrics.getExecutionTimePercentile(25)); json.writeNumberField("50", commandMetrics.getExecutionTimePercentile(50)); json.writeNumberField("75", commandMetrics.getExecutionTimePercentile(75)); json.writeNumberField("90", commandMetrics.getExecutionTimePercentile(90)); json.writeNumberField("95", commandMetrics.getExecutionTimePercentile(95)); json.writeNumberField("99", commandMetrics.getExecutionTimePercentile(99)); json.writeNumberField("99.5", commandMetrics.getExecutionTimePercentile(99.5)); json.writeNumberField("100", commandMetrics.getExecutionTimePercentile(100)); json.writeEndObject(); // json.writeNumberField("latencyTotal_mean", commandMetrics.getTotalTimeMean()); json.writeObjectFieldStart("latencyTotal"); json.writeNumberField("0", commandMetrics.getTotalTimePercentile(0)); json.writeNumberField("25", commandMetrics.getTotalTimePercentile(25)); json.writeNumberField("50", commandMetrics.getTotalTimePercentile(50)); json.writeNumberField("75", commandMetrics.getTotalTimePercentile(75)); json.writeNumberField("90", commandMetrics.getTotalTimePercentile(90)); json.writeNumberField("95", commandMetrics.getTotalTimePercentile(95)); json.writeNumberField("99", commandMetrics.getTotalTimePercentile(99)); json.writeNumberField("99.5", commandMetrics.getTotalTimePercentile(99.5)); json.writeNumberField("100", commandMetrics.getTotalTimePercentile(100)); json.writeEndObject(); // property values for reporting what is actually seen by the command rather than what was set somewhere HystrixCommandProperties commandProperties = commandMetrics.getProperties(); json.writeNumberField("propertyValue_circuitBreakerRequestVolumeThreshold", commandProperties.circuitBreakerRequestVolumeThreshold().get()); json.writeNumberField("propertyValue_circuitBreakerSleepWindowInMilliseconds", commandProperties.circuitBreakerSleepWindowInMilliseconds().get()); json.writeNumberField("propertyValue_circuitBreakerErrorThresholdPercentage", commandProperties.circuitBreakerErrorThresholdPercentage().get()); json.writeBooleanField("propertyValue_circuitBreakerForceOpen", commandProperties.circuitBreakerForceOpen().get()); json.writeBooleanField("propertyValue_circuitBreakerForceClosed", commandProperties.circuitBreakerForceClosed().get()); json.writeBooleanField("propertyValue_circuitBreakerEnabled", commandProperties.circuitBreakerEnabled().get()); json.writeStringField("propertyValue_executionIsolationStrategy", commandProperties.executionIsolationStrategy().get().name()); json.writeNumberField("propertyValue_executionIsolationThreadTimeoutInMilliseconds", commandProperties.executionTimeoutInMilliseconds().get()); json.writeNumberField("propertyValue_executionTimeoutInMilliseconds", commandProperties.executionTimeoutInMilliseconds().get()); json.writeBooleanField("propertyValue_executionIsolationThreadInterruptOnTimeout", commandProperties.executionIsolationThreadInterruptOnTimeout().get()); json.writeStringField("propertyValue_executionIsolationThreadPoolKeyOverride", commandProperties.executionIsolationThreadPoolKeyOverride().get()); json.writeNumberField("propertyValue_executionIsolationSemaphoreMaxConcurrentRequests", commandProperties.executionIsolationSemaphoreMaxConcurrentRequests().get()); json.writeNumberField("propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests", commandProperties.fallbackIsolationSemaphoreMaxConcurrentRequests().get()); /* * The following are commented out as these rarely change and are verbose for streaming for something people don't change. * We could perhaps allow a property or request argument to include these. */ // json.put("propertyValue_metricsRollingPercentileEnabled", commandProperties.metricsRollingPercentileEnabled().get()); // json.put("propertyValue_metricsRollingPercentileBucketSize", commandProperties.metricsRollingPercentileBucketSize().get()); // json.put("propertyValue_metricsRollingPercentileWindow", commandProperties.metricsRollingPercentileWindowInMilliseconds().get()); // json.put("propertyValue_metricsRollingPercentileWindowBuckets", commandProperties.metricsRollingPercentileWindowBuckets().get()); // json.put("propertyValue_metricsRollingStatisticalWindowBuckets", commandProperties.metricsRollingStatisticalWindowBuckets().get()); json.writeNumberField("propertyValue_metricsRollingStatisticalWindowInMilliseconds", commandProperties.metricsRollingStatisticalWindowInMilliseconds().get()); json.writeBooleanField("propertyValue_requestCacheEnabled", commandProperties.requestCacheEnabled().get()); json.writeBooleanField("propertyValue_requestLogEnabled", commandProperties.requestLogEnabled().get()); json.writeNumberField("reportingHosts", 1); // this will get summed across all instances in a cluster json.writeStringField("threadPool", commandMetrics.getThreadPoolKey().name()); json.writeEndObject(); } private static void writeThreadPoolMetrics(final HystrixThreadPoolMetrics threadPoolMetrics, JsonGenerator json) throws IOException { HystrixThreadPoolKey key = threadPoolMetrics.getThreadPoolKey(); json.writeStartObject(); json.writeStringField("type", "HystrixThreadPool"); json.writeStringField("name", key.name()); json.writeNumberField("currentTime", System.currentTimeMillis()); json.writeNumberField("currentActiveCount", threadPoolMetrics.getCurrentActiveCount().intValue()); json.writeNumberField("currentCompletedTaskCount", threadPoolMetrics.getCurrentCompletedTaskCount().longValue()); json.writeNumberField("currentCorePoolSize", threadPoolMetrics.getCurrentCorePoolSize().intValue()); json.writeNumberField("currentLargestPoolSize", threadPoolMetrics.getCurrentLargestPoolSize().intValue()); json.writeNumberField("currentMaximumPoolSize", threadPoolMetrics.getCurrentMaximumPoolSize().intValue()); json.writeNumberField("currentPoolSize", threadPoolMetrics.getCurrentPoolSize().intValue()); json.writeNumberField("currentQueueSize", threadPoolMetrics.getCurrentQueueSize().intValue()); json.writeNumberField("currentTaskCount", threadPoolMetrics.getCurrentTaskCount().longValue()); safelyWriteNumberField(json, "rollingCountThreadsExecuted", new Func0<Long>() { @Override public Long call() { return threadPoolMetrics.getRollingCount(HystrixEventType.ThreadPool.EXECUTED); } }); json.writeNumberField("rollingMaxActiveThreads", threadPoolMetrics.getRollingMaxActiveThreads()); safelyWriteNumberField(json, "rollingCountCommandRejections", new Func0<Long>() { @Override public Long call() { return threadPoolMetrics.getRollingCount(HystrixEventType.ThreadPool.REJECTED); } }); json.writeNumberField("propertyValue_queueSizeRejectionThreshold", threadPoolMetrics.getProperties().queueSizeRejectionThreshold().get()); json.writeNumberField("propertyValue_metricsRollingStatisticalWindowInMilliseconds", threadPoolMetrics.getProperties().metricsRollingStatisticalWindowInMilliseconds().get()); json.writeNumberField("reportingHosts", 1); // this will get summed across all instances in a cluster json.writeEndObject(); } private static void writeCollapserMetrics(final HystrixCollapserMetrics collapserMetrics, JsonGenerator json) throws IOException { HystrixCollapserKey key = collapserMetrics.getCollapserKey(); json.writeStartObject(); json.writeStringField("type", "HystrixCollapser"); json.writeStringField("name", key.name()); json.writeNumberField("currentTime", System.currentTimeMillis()); safelyWriteNumberField(json, "rollingCountRequestsBatched", new Func0<Long>() { @Override public Long call() { return collapserMetrics.getRollingCount(HystrixEventType.Collapser.ADDED_TO_BATCH); } }); safelyWriteNumberField(json, "rollingCountBatches", new Func0<Long>() { @Override public Long call() { return collapserMetrics.getRollingCount(HystrixEventType.Collapser.BATCH_EXECUTED); } }); safelyWriteNumberField(json, "rollingCountResponsesFromCache", new Func0<Long>() { @Override public Long call() { return collapserMetrics.getRollingCount(HystrixEventType.Collapser.RESPONSE_FROM_CACHE); } }); // batch size percentiles json.writeNumberField("batchSize_mean", collapserMetrics.getBatchSizeMean()); json.writeObjectFieldStart("batchSize"); json.writeNumberField("25", collapserMetrics.getBatchSizePercentile(25)); json.writeNumberField("50", collapserMetrics.getBatchSizePercentile(50)); json.writeNumberField("75", collapserMetrics.getBatchSizePercentile(75)); json.writeNumberField("90", collapserMetrics.getBatchSizePercentile(90)); json.writeNumberField("95", collapserMetrics.getBatchSizePercentile(95)); json.writeNumberField("99", collapserMetrics.getBatchSizePercentile(99)); json.writeNumberField("99.5", collapserMetrics.getBatchSizePercentile(99.5)); json.writeNumberField("100", collapserMetrics.getBatchSizePercentile(100)); json.writeEndObject(); // shard size percentiles (commented-out for now) //json.writeNumberField("shardSize_mean", collapserMetrics.getShardSizeMean()); //json.writeObjectFieldStart("shardSize"); //json.writeNumberField("25", collapserMetrics.getShardSizePercentile(25)); //json.writeNumberField("50", collapserMetrics.getShardSizePercentile(50)); //json.writeNumberField("75", collapserMetrics.getShardSizePercentile(75)); //json.writeNumberField("90", collapserMetrics.getShardSizePercentile(90)); //json.writeNumberField("95", collapserMetrics.getShardSizePercentile(95)); //json.writeNumberField("99", collapserMetrics.getShardSizePercentile(99)); //json.writeNumberField("99.5", collapserMetrics.getShardSizePercentile(99.5)); //json.writeNumberField("100", collapserMetrics.getShardSizePercentile(100)); //json.writeEndObject(); //json.writeNumberField("propertyValue_metricsRollingStatisticalWindowInMilliseconds", collapserMetrics.getProperties().metricsRollingStatisticalWindowInMilliseconds().get()); json.writeBooleanField("propertyValue_requestCacheEnabled", collapserMetrics.getProperties().requestCacheEnabled().get()); json.writeNumberField("propertyValue_maxRequestsInBatch", collapserMetrics.getProperties().maxRequestsInBatch().get()); json.writeNumberField("propertyValue_timerDelayInMilliseconds", collapserMetrics.getProperties().timerDelayInMilliseconds().get()); json.writeNumberField("reportingHosts", 1); // this will get summed across all instances in a cluster json.writeEndObject(); } protected static void safelyWriteNumberField(JsonGenerator json, String name, Func0<Long> metricGenerator) throws IOException { try { json.writeNumberField(name, metricGenerator.call()); } catch (NoSuchFieldError error) { logger.error("While publishing Hystrix metrics stream, error looking up eventType for : " + name + ". Please check that all Hystrix versions are the same!"); json.writeNumberField(name, 0L); } } }
4,361
0
Create_ds/Hystrix/hystrix-serialization/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-serialization/src/main/java/com/netflix/hystrix/serial/SerialHystrixUtilization.java
/** * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.serial; import com.fasterxml.jackson.core.JsonGenerator; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixThreadPoolKey; import com.netflix.hystrix.metric.sample.HystrixCommandUtilization; import com.netflix.hystrix.metric.sample.HystrixThreadPoolUtilization; import com.netflix.hystrix.metric.sample.HystrixUtilization; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.StringWriter; import java.nio.ByteBuffer; import java.util.Map; public class SerialHystrixUtilization extends SerialHystrixMetric { private final static Logger logger = LoggerFactory.getLogger(SerialHystrixUtilization.class); @Deprecated public static byte[] toBytes(HystrixUtilization utilization) { throw new UnsupportedOperationException("Not implemented anymore. Will be implemented in a new class shortly"); } public static String toJsonString(HystrixUtilization utilization) { StringWriter jsonString = new StringWriter(); try { JsonGenerator json = jsonFactory.createGenerator(jsonString); serializeUtilization(utilization, json); } catch (Exception e) { throw new RuntimeException(e); } return jsonString.getBuffer().toString(); } private static void serializeUtilization(HystrixUtilization utilization, JsonGenerator json) { try { json.writeStartObject(); json.writeStringField("type", "HystrixUtilization"); json.writeObjectFieldStart("commands"); for (Map.Entry<HystrixCommandKey, HystrixCommandUtilization> entry: utilization.getCommandUtilizationMap().entrySet()) { final HystrixCommandKey key = entry.getKey(); final HystrixCommandUtilization commandUtilization = entry.getValue(); writeCommandUtilizationJson(json, key, commandUtilization); } json.writeEndObject(); json.writeObjectFieldStart("threadpools"); for (Map.Entry<HystrixThreadPoolKey, HystrixThreadPoolUtilization> entry: utilization.getThreadPoolUtilizationMap().entrySet()) { final HystrixThreadPoolKey threadPoolKey = entry.getKey(); final HystrixThreadPoolUtilization threadPoolUtilization = entry.getValue(); writeThreadPoolUtilizationJson(json, threadPoolKey, threadPoolUtilization); } json.writeEndObject(); json.writeEndObject(); json.close(); } catch (Exception e) { throw new RuntimeException(e); } } @Deprecated public static HystrixUtilization fromByteBuffer(ByteBuffer bb) { throw new UnsupportedOperationException("Not implemented anymore. Will be implemented in a new class shortly"); } private static void writeCommandUtilizationJson(JsonGenerator json, HystrixCommandKey key, HystrixCommandUtilization utilization) throws IOException { json.writeObjectFieldStart(key.name()); json.writeNumberField("activeCount", utilization.getConcurrentCommandCount()); json.writeEndObject(); } private static void writeThreadPoolUtilizationJson(JsonGenerator json, HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolUtilization utilization) throws IOException { json.writeObjectFieldStart(threadPoolKey.name()); json.writeNumberField("activeCount", utilization.getCurrentActiveCount()); json.writeNumberField("queueSize", utilization.getCurrentQueueSize()); json.writeNumberField("corePoolSize", utilization.getCurrentCorePoolSize()); json.writeNumberField("poolSize", utilization.getCurrentPoolSize()); json.writeEndObject(); } }
4,362
0
Create_ds/Hystrix/hystrix-serialization/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-serialization/src/main/java/com/netflix/hystrix/serial/SerialHystrixRequestEvents.java
/** * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.serial; import com.fasterxml.jackson.core.JsonGenerator; import com.netflix.hystrix.ExecutionResult; import com.netflix.hystrix.HystrixEventType; import com.netflix.hystrix.metric.HystrixRequestEvents; import java.io.IOException; import java.io.StringWriter; import java.util.List; import java.util.Map; public class SerialHystrixRequestEvents extends SerialHystrixMetric { @Deprecated public static byte[] toBytes(HystrixRequestEvents requestEvents) { throw new UnsupportedOperationException("Not implemented anymore. Will be implemented in a new class shortly"); } public static String toJsonString(HystrixRequestEvents requestEvents) { StringWriter jsonString = new StringWriter(); try { JsonGenerator json = jsonFactory.createGenerator(jsonString); serializeRequestEvents(requestEvents, json); } catch (Exception e) { throw new RuntimeException(e); } return jsonString.getBuffer().toString(); } private static void serializeRequestEvents(HystrixRequestEvents requestEvents, JsonGenerator json) { try { json.writeStartArray(); for (Map.Entry<HystrixRequestEvents.ExecutionSignature, List<Integer>> entry: requestEvents.getExecutionsMappedToLatencies().entrySet()) { convertExecutionToJson(json, entry.getKey(), entry.getValue()); } json.writeEndArray(); json.close(); } catch (Exception e) { throw new RuntimeException(e); } } private static void convertExecutionToJson(JsonGenerator json, HystrixRequestEvents.ExecutionSignature executionSignature, List<Integer> latencies) throws IOException { json.writeStartObject(); json.writeStringField("name", executionSignature.getCommandName()); json.writeArrayFieldStart("events"); ExecutionResult.EventCounts eventCounts = executionSignature.getEventCounts(); for (HystrixEventType eventType: HystrixEventType.values()) { if (!eventType.equals(HystrixEventType.COLLAPSED)) { if (eventCounts.contains(eventType)) { int eventCount = eventCounts.getCount(eventType); if (eventCount > 1) { json.writeStartObject(); json.writeStringField("name", eventType.name()); json.writeNumberField("count", eventCount); json.writeEndObject(); } else { json.writeString(eventType.name()); } } } } json.writeEndArray(); json.writeArrayFieldStart("latencies"); for (int latency: latencies) { json.writeNumber(latency); } json.writeEndArray(); if (executionSignature.getCachedCount() > 0) { json.writeNumberField("cached", executionSignature.getCachedCount()); } if (executionSignature.getEventCounts().contains(HystrixEventType.COLLAPSED)) { json.writeObjectFieldStart("collapsed"); json.writeStringField("name", executionSignature.getCollapserKey().name()); json.writeNumberField("count", executionSignature.getCollapserBatchSize()); json.writeEndObject(); } json.writeEndObject(); } }
4,363
0
Create_ds/Hystrix/hystrix-serialization/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-serialization/src/main/java/com/netflix/hystrix/serial/SerialHystrixMetric.java
/** * Copyright 2016 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.serial; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; public class SerialHystrixMetric { protected final static JsonFactory jsonFactory = new JsonFactory(); protected final static ObjectMapper mapper = new ObjectMapper(); protected final static Logger logger = LoggerFactory.getLogger(SerialHystrixMetric.class); @Deprecated public static String fromByteBufferToString(ByteBuffer bb) { throw new UnsupportedOperationException("Not implemented anymore. Will be implemented in a new class shortly"); } }
4,364
0
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples/demo/Order.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.examples.demo; import java.net.HttpCookie; /** * POJO */ public class Order { private final int orderId; private UserAccount user; public Order(int orderId) { this.orderId = orderId; /* a contrived example of calling GetUserAccount again */ user = new GetUserAccountCommand(new HttpCookie("mockKey", "mockValueFromHttpRequest")).execute(); } }
4,365
0
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples/demo/PaymentInformation.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.examples.demo; /** * POJO */ public class PaymentInformation { private final UserAccount user; private final String creditCardNumber; private final int expirationMonth; private final int expirationYear; public PaymentInformation(UserAccount user, String creditCardNumber, int expirationMonth, int expirationYear) { this.user = user; this.creditCardNumber = creditCardNumber; this.expirationMonth = expirationMonth; this.expirationYear = expirationYear; } public String getCreditCardNumber() { return creditCardNumber; } public int getExpirationMonth() { return expirationMonth; } public int getExpirationYear() { return expirationYear; } }
4,366
0
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples/demo/GetUserAccountCommand.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.examples.demo; import java.net.HttpCookie; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; /** * Sample HystrixCommand simulating one that would fetch UserAccount objects from a remote service or database. * <p> * This uses request caching and fallback behavior. */ public class GetUserAccountCommand extends HystrixCommand<UserAccount> { private final HttpCookie httpCookie; private final UserCookie userCookie; /** * * @param cookie * @throws IllegalArgumentException * if cookie is invalid meaning the user is not authenticated */ public GetUserAccountCommand(HttpCookie cookie) { super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("User"))); this.httpCookie = cookie; /* parse or throw an IllegalArgumentException */ this.userCookie = UserCookie.parseCookie(httpCookie); } @Override protected UserAccount run() { /* simulate performing network call to retrieve user information */ try { Thread.sleep((int) (Math.random() * 10) + 2); } catch (InterruptedException e) { // do nothing } /* fail 5% of the time to show how fallback works */ if (Math.random() > 0.95) { throw new RuntimeException("random failure processing UserAccount network response"); } /* latency spike 5% of the time so timeouts can be triggered occasionally */ if (Math.random() > 0.95) { // random latency spike try { Thread.sleep((int) (Math.random() * 300) + 25); } catch (InterruptedException e) { // do nothing } } /* success ... create UserAccount with data "from" the remote service response */ return new UserAccount(86975, "John James", 2, true, false, true); } /** * Use the HttpCookie value as the cacheKey so multiple executions * in the same HystrixRequestContext will respond from cache. */ @Override protected String getCacheKey() { return httpCookie.getValue(); } /** * Fallback that will use data from the UserCookie and stubbed defaults * to create a UserAccount if the network call failed. */ @Override protected UserAccount getFallback() { /* * first 3 come from the HttpCookie * next 3 are stubbed defaults */ return new UserAccount(userCookie.userId, userCookie.name, userCookie.accountType, true, true, true); } /** * Represents values containing in the cookie. * <p> * A real version of this could handle decrypting a secure HTTPS cookie. */ private static class UserCookie { /** * Parse an HttpCookie into a UserCookie or IllegalArgumentException if invalid cookie * * @param cookie * @return UserCookie * @throws IllegalArgumentException * if cookie is invalid */ private static UserCookie parseCookie(HttpCookie cookie) { /* real code would parse the cookie here */ if (Math.random() < 0.998) { /* valid cookie */ return new UserCookie(12345, "Henry Peter", 1); } else { /* invalid cookie */ throw new IllegalArgumentException(); } } public UserCookie(int userId, String name, int accountType) { this.userId = userId; this.name = name; this.accountType = accountType; } private final int userId; private final String name; private final int accountType; } }
4,367
0
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples/demo/HystrixCommandDemo.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.examples.demo; import java.math.BigDecimal; import java.net.HttpCookie; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import com.netflix.config.ConfigurationManager; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandMetrics; import com.netflix.hystrix.HystrixCommandMetrics.HealthCounts; import com.netflix.hystrix.HystrixRequestLog; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; /** * Executable client that demonstrates the lifecycle, metrics, request log and behavior of HystrixCommands. */ public class HystrixCommandDemo { public static void main(String args[]) { new HystrixCommandDemo().startDemo(); } public HystrixCommandDemo() { /* * Instead of using injected properties we'll set them via Archaius * so the rest of the code behaves as it would in a real system * where it picks up properties externally provided. */ ConfigurationManager.getConfigInstance().setProperty("hystrix.threadpool.default.coreSize", 8); ConfigurationManager.getConfigInstance().setProperty("hystrix.command.CreditCardCommand.execution.isolation.thread.timeoutInMilliseconds", 3000); ConfigurationManager.getConfigInstance().setProperty("hystrix.command.GetUserAccountCommand.execution.isolation.thread.timeoutInMilliseconds", 50); // set the rolling percentile more granular so we see data change every second rather than every 10 seconds as is the default ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.metrics.rollingPercentile.numBuckets", 60); } /* * Thread-pool to simulate HTTP requests. * * Use CallerRunsPolicy so we can just keep iterating and adding to it and it will block when full. */ private final ThreadPoolExecutor pool = new ThreadPoolExecutor(5, 5, 5, TimeUnit.DAYS, new SynchronousQueue<Runnable>(), new ThreadPoolExecutor.CallerRunsPolicy()); public void startDemo() { startMetricsMonitor(); while (true) { runSimulatedRequestOnThread(); } } public void runSimulatedRequestOnThread() { pool.execute(new Runnable() { @Override public void run() { HystrixRequestContext context = HystrixRequestContext.initializeContext(); try { executeSimulatedUserRequestForOrderConfirmationAndCreditCardPayment(); System.out.println("Request => " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); } catch (Exception e) { e.printStackTrace(); } finally { context.shutdown(); } } }); } public void executeSimulatedUserRequestForOrderConfirmationAndCreditCardPayment() throws InterruptedException, ExecutionException { /* fetch user object with http cookies */ UserAccount user = new GetUserAccountCommand(new HttpCookie("mockKey", "mockValueFromHttpRequest")).execute(); /* fetch the payment information (asynchronously) for the user so the credit card payment can proceed */ Future<PaymentInformation> paymentInformation = new GetPaymentInformationCommand(user).queue(); /* fetch the order we're processing for the user */ int orderIdFromRequestArgument = 13579; Order previouslySavedOrder = new GetOrderCommand(orderIdFromRequestArgument).execute(); CreditCardCommand credit = new CreditCardCommand(previouslySavedOrder, paymentInformation.get(), new BigDecimal(123.45)); credit.execute(); } public void startMetricsMonitor() { Thread t = new Thread(new Runnable() { @Override public void run() { while (true) { /** * Since this is a simple example and we know the exact HystrixCommandKeys we are interested in * we will retrieve the HystrixCommandMetrics objects directly. * * Typically you would instead retrieve metrics from where they are published which is by default * done using Servo: https://github.com/Netflix/Hystrix/wiki/Metrics-and-Monitoring */ // wait 5 seconds on each loop try { Thread.sleep(5000); } catch (Exception e) { // ignore } // we are using default names so can use class.getSimpleName() to derive the keys HystrixCommandMetrics creditCardMetrics = HystrixCommandMetrics.getInstance(HystrixCommandKey.Factory.asKey(CreditCardCommand.class.getSimpleName())); HystrixCommandMetrics orderMetrics = HystrixCommandMetrics.getInstance(HystrixCommandKey.Factory.asKey(GetOrderCommand.class.getSimpleName())); HystrixCommandMetrics userAccountMetrics = HystrixCommandMetrics.getInstance(HystrixCommandKey.Factory.asKey(GetUserAccountCommand.class.getSimpleName())); HystrixCommandMetrics paymentInformationMetrics = HystrixCommandMetrics.getInstance(HystrixCommandKey.Factory.asKey(GetPaymentInformationCommand.class.getSimpleName())); // print out metrics StringBuilder out = new StringBuilder(); out.append("\n"); out.append("#####################################################################################").append("\n"); out.append("# CreditCardCommand: " + getStatsStringFromMetrics(creditCardMetrics)).append("\n"); out.append("# GetOrderCommand: " + getStatsStringFromMetrics(orderMetrics)).append("\n"); out.append("# GetUserAccountCommand: " + getStatsStringFromMetrics(userAccountMetrics)).append("\n"); out.append("# GetPaymentInformationCommand: " + getStatsStringFromMetrics(paymentInformationMetrics)).append("\n"); out.append("#####################################################################################").append("\n"); System.out.println(out.toString()); } } private String getStatsStringFromMetrics(HystrixCommandMetrics metrics) { StringBuilder m = new StringBuilder(); if (metrics != null) { HealthCounts health = metrics.getHealthCounts(); m.append("Requests: ").append(health.getTotalRequests()).append(" "); m.append("Errors: ").append(health.getErrorCount()).append(" (").append(health.getErrorPercentage()).append("%) "); m.append("Mean: ").append(metrics.getExecutionTimePercentile(50)).append(" "); m.append("75th: ").append(metrics.getExecutionTimePercentile(75)).append(" "); m.append("90th: ").append(metrics.getExecutionTimePercentile(90)).append(" "); m.append("99th: ").append(metrics.getExecutionTimePercentile(99)).append(" "); } return m.toString(); } }); t.setDaemon(true); t.start(); } }
4,368
0
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples/demo/GetOrderCommand.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.examples.demo; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; /** * Sample HystrixCommand simulating one that would fetch Order objects from a remote service or database. * <p> * This fails fast with no fallback and does not use request caching. */ public class GetOrderCommand extends HystrixCommand<Order> { private final int orderId; public GetOrderCommand(int orderId) { super(HystrixCommandGroupKey.Factory.asKey("Order")); this.orderId = orderId; } @Override protected Order run() { /* simulate performing network call to retrieve order */ try { Thread.sleep((int) (Math.random() * 200) + 50); } catch (InterruptedException e) { // do nothing } /* fail rarely ... but allow failure as this one has no fallback */ if (Math.random() > 0.9999) { throw new RuntimeException("random failure loading order over network"); } /* latency spike 5% of the time */ if (Math.random() > 0.95) { // random latency spike try { Thread.sleep((int) (Math.random() * 300) + 25); } catch (InterruptedException e) { // do nothing } } /* success ... create Order with data "from" the remote service response */ return new Order(orderId); } }
4,369
0
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples/demo/GetPaymentInformationCommand.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.examples.demo; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; /** * Sample HystrixCommand simulating one that would fetch PaymentInformation objects from a remote service or database. * <p> * This fails fast with no fallback and does not use request caching. */ public class GetPaymentInformationCommand extends HystrixCommand<PaymentInformation> { private final UserAccount user; public GetPaymentInformationCommand(UserAccount user) { super(HystrixCommandGroupKey.Factory.asKey("PaymentInformation")); this.user = user; } @Override protected PaymentInformation run() { /* simulate performing network call to retrieve order */ try { Thread.sleep((int) (Math.random() * 20) + 5); } catch (InterruptedException e) { // do nothing } /* fail rarely ... but allow failure */ if (Math.random() > 0.9999) { throw new RuntimeException("random failure loading payment information over network"); } /* latency spike 2% of the time */ if (Math.random() > 0.98) { // random latency spike try { Thread.sleep((int) (Math.random() * 100) + 25); } catch (InterruptedException e) { // do nothing } } /* success ... create (a very insecure) PaymentInformation with data "from" the remote service response */ return new PaymentInformation(user, "4444888833337777", 12, 15); } }
4,370
0
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples/demo/CreditCardAuthorizationResult.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.examples.demo; /** * POJO for holding the result of a CreditCardAuthorization */ public class CreditCardAuthorizationResult { public static CreditCardAuthorizationResult createSuccessResponse(String transactionID, String authorizationCode) { return new CreditCardAuthorizationResult(true, transactionID, authorizationCode, false); } public static CreditCardAuthorizationResult createDuplicateSuccessResponse(String transactionID, String authorizationCode) { return new CreditCardAuthorizationResult(true, transactionID, authorizationCode, true); } public static CreditCardAuthorizationResult createFailedResponse(String message) { return new CreditCardAuthorizationResult(false, message, null, false); } private final boolean success; private final boolean isDuplicate; private final String authorizationCode; private final String transactionID; private final String errorMessage; /** * Private constructor that normally would be a horrible API as it re-uses different arguments for different state. * * @param success * @param value * @param isResponseDuplicate * boolean whether the response is the result of a duplicate transaction returning a previously submitted transaction result * <p> * This is for handling the idempotent double-posting scenario, such as retries after timeouts. */ private CreditCardAuthorizationResult(boolean success, String value, String value2, boolean isResponseDuplicate) { this.success = success; this.isDuplicate = isResponseDuplicate; if (success) { this.transactionID = value; this.authorizationCode = value2; this.errorMessage = null; } else { this.transactionID = null; this.errorMessage = value; this.authorizationCode = null; } } public boolean isSuccess() { return success; } /** * Whether this result was a duplicate transaction. * * @return boolean */ public boolean isDuplicateTransaction() { return isDuplicate; } /** * If <code>isSuccess() == true</code> this will return the authorization code. * <p> * If <code>isSuccess() == false</code> this will return NULL. * * @return String */ public String getAuthorizationCode() { return authorizationCode; } /** * If <code>isSuccess() == true</code> this will return the transaction ID. * <p> * If <code>isSuccess() == false</code> this will return NULL. * * @return String */ public String getTransactionID() { return transactionID; } /** * If <code>isSuccess() == false</code> this will return the error message. * <p> * If <code>isSuccess() == true</code> this will return NULL. * * @return String */ public String getErrorMessage() { return errorMessage; } }
4,371
0
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples/demo/CreditCardCommand.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.examples.demo; import java.math.BigDecimal; import java.net.HttpCookie; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandProperties; /** * This class was originally taken from a functional example using the Authorize.net API * but was modified for this example to use mock classes so that the real API does not need * to be depended upon and so that a backend account with Authorize.net is not needed. */ // import net.authorize.Environment; // import net.authorize.TransactionType; // import net.authorize.aim.Result; // import net.authorize.aim.Transaction; /** * HystrixCommand for submitting credit card payments. * <p> * No fallback implemented as a credit card failure must result in an error as no logical fallback exists. * <p> * This implementation originated from a functional HystrixCommand wrapper around an Authorize.net API. * <p> * The original used the Authorize.net 'duplicate window' setting to ensure an Order could be submitted multiple times * and it would behave idempotently so that it would not result in duplicate transactions and each would return a successful * response as if it was the first-and-only execution. * <p> * This idempotence (within the duplicate window time frame set to multiple hours) allows for clients that * experience timeouts and failures to confidently retry the credit card transaction without fear of duplicate * credit card charges. * <p> * This in turn allows the HystrixCommand to be configured for reasonable timeouts and isolation rather than * letting it go 10+ seconds hoping for success when latency occurs. * <p> * In this example, the timeout is set to 3,000ms as normal behavior typically saw a credit card transaction taking around 1300ms * and in this case it's better to wait longer and try to succeed as the result is a user error. * <p> * We do not want to wait the 10,000-20,000ms that Authorize.net can default to as that would allow severe resource * saturation under high volume traffic when latency spikes. */ public class CreditCardCommand extends HystrixCommand<CreditCardAuthorizationResult> { private final static AuthorizeNetGateway DEFAULT_GATEWAY = new AuthorizeNetGateway(); private final AuthorizeNetGateway gateway; private final Order order; private final PaymentInformation payment; private final BigDecimal amount; /** * A HystrixCommand implementation accepts arguments into the constructor which are then accessible * to the <code>run()</code> method when it executes. * * @param order * @param payment * @param amount */ public CreditCardCommand(Order order, PaymentInformation payment, BigDecimal amount) { this(DEFAULT_GATEWAY, order, payment, amount); } private CreditCardCommand(AuthorizeNetGateway gateway, Order order, PaymentInformation payment, BigDecimal amount) { super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("CreditCard")) // defaulting to a fairly long timeout value because failing a credit card transaction is a bad user experience and 'costly' to re-attempt .andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(3000))); this.gateway = gateway; this.order = order; this.payment = payment; this.amount = amount; } /** * Actual work of submitting the credit card authorization occurs within this <code>HystrixCommand.run()</code> method. */ @Override protected CreditCardAuthorizationResult run() { // Simulate transitive dependency from CreditCardCommand to GetUserAccountCommand. // UserAccount could be injected into this command as an argument (and that would be more accurate) // but often in large codebase that ends up not happening and each library fetches common data // such as user information directly such as this example. UserAccount user = new GetUserAccountCommand(new HttpCookie("mockKey", "mockValueFromHttpRequest")).execute(); if (user.getAccountType() == 1) { // do something } else { // do something else } // perform credit card transaction Result<Transaction> result = gateway.submit(payment.getCreditCardNumber(), String.valueOf(payment.getExpirationMonth()), String.valueOf(payment.getExpirationYear()), TransactionType.AUTH_CAPTURE, amount, order); if (result.isApproved()) { return CreditCardAuthorizationResult.createSuccessResponse(result.getTarget().getTransactionId(), result.getTarget().getAuthorizationCode()); } else if (result.isDeclined()) { return CreditCardAuthorizationResult.createFailedResponse(result.getReasonResponseCode() + " : " + result.getResponseText()); } else { // check for duplicate transaction if (result.getReasonResponseCode().getResponseReasonCode() == 11) { if (result.getTarget().getAuthorizationCode() != null) { // We will treat this as a success as this is telling us we have a successful authorization code // just that we attempted to re-post it again during the 'duplicateWindow' time period. // This is part of the idempotent behavior we require so that we can safely timeout and/or fail and allow // client applications to re-attempt submitting a credit card transaction for the same order again. // In those cases if the client saw a failure but the transaction actually succeeded, this will capture the // duplicate response and behave to the client as a success. return CreditCardAuthorizationResult.createDuplicateSuccessResponse(result.getTarget().getTransactionId(), result.getTarget().getAuthorizationCode()); } } // handle all other errors return CreditCardAuthorizationResult.createFailedResponse(result.getReasonResponseCode() + " : " + result.getResponseText()); /** * NOTE that in this use case we do not throw an exception for an "error" as this type of error from the service is not a system error, * but a legitimate usage problem successfully delivered back from the service. * * Unexpected errors will be allowed to throw RuntimeExceptions. * * The HystrixBadRequestException could potentially be used here, but with such a complex set of errors and reason codes * it was chosen to stick with the response object approach rather than using an exception. */ } } /* * The following inner classes are all mocks based on the Authorize.net API that this class originally used. * * They are statically mocked in this example to demonstrate how Hystrix might behave when wrapping this type of call. */ public static class AuthorizeNetGateway { public AuthorizeNetGateway() { } public Result<Transaction> submit(String creditCardNumber, String expirationMonth, String expirationYear, TransactionType authCapture, BigDecimal amount, Order order) { /* simulate varying length of time 800-1500ms which is typical for a credit card transaction */ try { Thread.sleep((int) (Math.random() * 700) + 800); } catch (InterruptedException e) { // do nothing } /* and every once in a while we'll cause it to go longer than 3000ms which will cause the command to timeout */ if (Math.random() > 0.99) { try { Thread.sleep(8000); } catch (InterruptedException e) { // do nothing } } if (Math.random() < 0.8) { return new Result<Transaction>(true); } else { return new Result<Transaction>(false); } } } public static class Result<T> { private final boolean approved; public Result(boolean approved) { this.approved = approved; } public boolean isApproved() { return approved; } public ResponseCode getResponseText() { return null; } public Target getTarget() { return new Target(); } public ResponseCode getReasonResponseCode() { return new ResponseCode(); } public boolean isDeclined() { return !approved; } } public static class ResponseCode { public int getResponseReasonCode() { return 0; } } public static class Target { public String getTransactionId() { return "transactionId"; } public String getAuthorizationCode() { return "authorizedCode"; } } public static class Transaction { } public static enum TransactionType { AUTH_CAPTURE } }
4,372
0
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples/demo/UserAccount.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.examples.demo; /** * Simple POJO to represent a user and their metadata. */ public class UserAccount { private final int userId; private final String name; private final int accountType; private final boolean isFeatureXenabled; private final boolean isFeatureYenabled; private final boolean isFeatureZenabled; public UserAccount(int userId, String name, int accountType, boolean x, boolean y, boolean z) { this.userId = userId; this.name = name; this.accountType = accountType; this.isFeatureXenabled = x; this.isFeatureYenabled = y; this.isFeatureZenabled = z; } public int getUserId() { return userId; } public String getName() { return name; } public int getAccountType() { return accountType; } public boolean isFeatureXenabled() { return isFeatureXenabled; } public boolean isFeatureYenabled() { return isFeatureYenabled; } public boolean isFeatureZenabled() { return isFeatureZenabled; } }
4,373
0
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples/demo/HystrixCommandAsyncDemo.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.examples.demo; import java.math.BigDecimal; import java.net.HttpCookie; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import com.netflix.config.ConfigurationManager; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandMetrics; import com.netflix.hystrix.HystrixCommandMetrics.HealthCounts; import com.netflix.hystrix.HystrixRequestLog; import com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; import rx.Observable; import rx.Subscriber; import rx.functions.Action0; import rx.functions.Action1; import rx.functions.Func1; import rx.functions.Func2; import rx.plugins.RxJavaPlugins; import rx.plugins.RxJavaSchedulersHook; /** * Executable client that demonstrates the lifecycle, metrics, request log and behavior of HystrixCommands. */ public class HystrixCommandAsyncDemo { // public static void main(String args[]) { // new HystrixCommandAsyncDemo().startDemo(true); // } static class ContextAwareRxSchedulersHook extends RxJavaSchedulersHook { @Override public Action0 onSchedule(final Action0 initialAction) { final Runnable initialRunnable = new Runnable() { @Override public void run() { initialAction.call(); } }; final Runnable wrappedRunnable = new HystrixContextRunnable(initialRunnable); return new Action0() { @Override public void call() { wrappedRunnable.run(); } }; } } public HystrixCommandAsyncDemo() { /* * Instead of using injected properties we'll set them via Archaius * so the rest of the code behaves as it would in a real system * where it picks up properties externally provided. */ ConfigurationManager.getConfigInstance().setProperty("hystrix.threadpool.default.coreSize", 8); ConfigurationManager.getConfigInstance().setProperty("hystrix.command.CreditCardCommand.execution.isolation.thread.timeoutInMilliseconds", 3000); ConfigurationManager.getConfigInstance().setProperty("hystrix.command.GetUserAccountCommand.execution.isolation.thread.timeoutInMilliseconds", 50); // set the rolling percentile more granular so we see data change every second rather than every 10 seconds as is the default ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.metrics.rollingPercentile.numBuckets", 60); RxJavaPlugins.getInstance().registerSchedulersHook(new ContextAwareRxSchedulersHook()); } public void startDemo(final boolean shouldLog) { startMetricsMonitor(shouldLog); while (true) { final HystrixRequestContext context = HystrixRequestContext.initializeContext(); Observable<CreditCardAuthorizationResult> o = observeSimulatedUserRequestForOrderConfirmationAndCreditCardPayment(); final CountDownLatch latch = new CountDownLatch(1); o.subscribe(new Subscriber<CreditCardAuthorizationResult>() { @Override public void onCompleted() { latch.countDown(); context.shutdown(); } @Override public void onError(Throwable e) { e.printStackTrace(); latch.countDown(); context.shutdown(); } @Override public void onNext(CreditCardAuthorizationResult creditCardAuthorizationResult) { if (shouldLog) { System.out.println("Request => " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); } } }); try { latch.await(5000, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { System.out.println("INTERRUPTED!"); } } } private final static Random r = new Random(); private class Pair<A, B> { private final A a; private final B b; Pair(A a, B b) { this.a = a; this.b = b; } A a() { return this.a; } B b() { return this.b; } } public Observable<CreditCardAuthorizationResult> observeSimulatedUserRequestForOrderConfirmationAndCreditCardPayment() { /* fetch user object with http cookies */ try { Observable<UserAccount> user = new GetUserAccountCommand(new HttpCookie("mockKey", "mockValueFromHttpRequest")).observe(); /* fetch the payment information (asynchronously) for the user so the credit card payment can proceed */ Observable<PaymentInformation> paymentInformation = user.flatMap(new Func1<UserAccount, Observable<PaymentInformation>>() { @Override public Observable<PaymentInformation> call(UserAccount userAccount) { return new GetPaymentInformationCommand(userAccount).observe(); } }); /* fetch the order we're processing for the user */ int orderIdFromRequestArgument = 13579; final Observable<Order> previouslySavedOrder = new GetOrderCommand(orderIdFromRequestArgument).observe(); return Observable.zip(paymentInformation, previouslySavedOrder, new Func2<PaymentInformation, Order, Pair<PaymentInformation, Order>>() { @Override public Pair<PaymentInformation, Order> call(PaymentInformation paymentInformation, Order order) { return new Pair<PaymentInformation, Order>(paymentInformation, order); } }).flatMap(new Func1<Pair<PaymentInformation, Order>, Observable<CreditCardAuthorizationResult>>() { @Override public Observable<CreditCardAuthorizationResult> call(Pair<PaymentInformation, Order> pair) { return new CreditCardCommand(pair.b(), pair.a(), new BigDecimal(123.45)).observe(); } }); } catch (IllegalArgumentException ex) { return Observable.error(ex); } } public void startMetricsMonitor(final boolean shouldLog) { Thread t = new Thread(new Runnable() { @Override public void run() { while (true) { /** * Since this is a simple example and we know the exact HystrixCommandKeys we are interested in * we will retrieve the HystrixCommandMetrics objects directly. * * Typically you would instead retrieve metrics from where they are published which is by default * done using Servo: https://github.com/Netflix/Hystrix/wiki/Metrics-and-Monitoring */ // wait 5 seconds on each loop try { Thread.sleep(5000); } catch (Exception e) { // ignore } // we are using default names so can use class.getSimpleName() to derive the keys HystrixCommandMetrics creditCardMetrics = HystrixCommandMetrics.getInstance(HystrixCommandKey.Factory.asKey(CreditCardCommand.class.getSimpleName())); HystrixCommandMetrics orderMetrics = HystrixCommandMetrics.getInstance(HystrixCommandKey.Factory.asKey(GetOrderCommand.class.getSimpleName())); HystrixCommandMetrics userAccountMetrics = HystrixCommandMetrics.getInstance(HystrixCommandKey.Factory.asKey(GetUserAccountCommand.class.getSimpleName())); HystrixCommandMetrics paymentInformationMetrics = HystrixCommandMetrics.getInstance(HystrixCommandKey.Factory.asKey(GetPaymentInformationCommand.class.getSimpleName())); if (shouldLog) { // print out metrics StringBuilder out = new StringBuilder(); out.append("\n"); out.append("#####################################################################################").append("\n"); out.append("# CreditCardCommand: " + getStatsStringFromMetrics(creditCardMetrics)).append("\n"); out.append("# GetOrderCommand: " + getStatsStringFromMetrics(orderMetrics)).append("\n"); out.append("# GetUserAccountCommand: " + getStatsStringFromMetrics(userAccountMetrics)).append("\n"); out.append("# GetPaymentInformationCommand: " + getStatsStringFromMetrics(paymentInformationMetrics)).append("\n"); out.append("#####################################################################################").append("\n"); System.out.println(out.toString()); } } } private String getStatsStringFromMetrics(HystrixCommandMetrics metrics) { StringBuilder m = new StringBuilder(); if (metrics != null) { HealthCounts health = metrics.getHealthCounts(); m.append("Requests: ").append(health.getTotalRequests()).append(" "); m.append("Errors: ").append(health.getErrorCount()).append(" (").append(health.getErrorPercentage()).append("%) "); m.append("Mean: ").append(metrics.getExecutionTimePercentile(50)).append(" "); m.append("75th: ").append(metrics.getExecutionTimePercentile(75)).append(" "); m.append("90th: ").append(metrics.getExecutionTimePercentile(90)).append(" "); m.append("99th: ").append(metrics.getExecutionTimePercentile(99)).append(" "); } return m.toString(); } }); t.setDaemon(true); t.start(); } }
4,374
0
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples/basic/CommandUsingSemaphoreIsolation.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.examples.basic; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy; /** * Example of {@link HystrixCommand} defaulting to use a semaphore isolation strategy * when its run() method will not perform network traffic. */ public class CommandUsingSemaphoreIsolation extends HystrixCommand<String> { private final int id; public CommandUsingSemaphoreIsolation(int id) { super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup")) // since we're doing work in the run() method that doesn't involve network traffic // and executes very fast with low risk we choose SEMAPHORE isolation .andCommandPropertiesDefaults(HystrixCommandProperties.Setter() .withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE))); this.id = id; } @Override protected String run() { // a real implementation would retrieve data from in memory data structure // or some other similar non-network involved work return "ValueFromHashMap_" + id; } }
4,375
0
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples/basic/CommandThatFailsSilently.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.examples.basic; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.Test; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.exception.HystrixRuntimeException; /** * Sample {@link HystrixCommand} that has a fallback implemented * that will "fail silent" when failures, rejections, short-circuiting etc occur * by returning an empty List. */ public class CommandThatFailsSilently extends HystrixCommand<List<String>> { private final boolean throwException; public CommandThatFailsSilently(boolean throwException) { super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup")); this.throwException = throwException; } @Override protected List<String> run() { if (throwException) { throw new RuntimeException("failure from CommandThatFailsFast"); } else { ArrayList<String> values = new ArrayList<String>(); values.add("success"); return values; } } @Override protected List<String> getFallback() { return Collections.emptyList(); } public static class UnitTest { @Test public void testSuccess() { assertEquals("success", new CommandThatFailsSilently(false).execute().get(0)); } @Test public void testFailure() { try { assertEquals(0, new CommandThatFailsSilently(true).execute().size()); } catch (HystrixRuntimeException e) { fail("we should not get an exception as we fail silently with a fallback"); } } } }
4,376
0
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples/basic/CommandWithStubbedFallback.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.examples.basic; import static org.junit.Assert.*; import org.junit.Test; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.examples.basic.CommandWithStubbedFallback.UserAccount; /** * Sample {@link HystrixCommand} that implements a fallback that returns an object * combining defaults and injected values from elsewhere in the system (such as * HTTP request headers, arguments and cookies or other services previously executed). */ public class CommandWithStubbedFallback extends HystrixCommand<UserAccount> { private final int customerId; private final String countryCodeFromGeoLookup; /** * @param customerId * The customerID to retrieve UserAccount for * @param countryCodeFromGeoLookup * The default country code from the HTTP request geo code lookup used for fallback. */ protected CommandWithStubbedFallback(int customerId, String countryCodeFromGeoLookup) { super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup")); this.customerId = customerId; this.countryCodeFromGeoLookup = countryCodeFromGeoLookup; } @Override protected UserAccount run() { // fetch UserAccount from remote service // return UserAccountClient.getAccount(customerId); throw new RuntimeException("forcing failure for example"); } @Override protected UserAccount getFallback() { /** * Return stubbed fallback with some static defaults, placeholders, * and an injected value 'countryCodeFromGeoLookup' that we'll use * instead of what we would have retrieved from the remote service. */ return new UserAccount(customerId, "Unknown Name", countryCodeFromGeoLookup, true, true, false); } public static class UserAccount { private final int customerId; private final String name; private final String countryCode; private final boolean isFeatureXPermitted; private final boolean isFeatureYPermitted; private final boolean isFeatureZPermitted; UserAccount(int customerId, String name, String countryCode, boolean isFeatureXPermitted, boolean isFeatureYPermitted, boolean isFeatureZPermitted) { this.customerId = customerId; this.name = name; this.countryCode = countryCode; this.isFeatureXPermitted = isFeatureXPermitted; this.isFeatureYPermitted = isFeatureYPermitted; this.isFeatureZPermitted = isFeatureZPermitted; } } public static class UnitTest { @Test public void test() { CommandWithStubbedFallback command = new CommandWithStubbedFallback(1234, "ca"); UserAccount account = command.execute(); assertTrue(command.isFailedExecution()); assertTrue(command.isResponseFromFallback()); assertEquals(1234, account.customerId); assertEquals("ca", account.countryCode); assertEquals(true, account.isFeatureXPermitted); assertEquals(true, account.isFeatureYPermitted); assertEquals(false, account.isFeatureZPermitted); } } }
4,377
0
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples/basic/CommandUsingRequestCacheInvalidation.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.examples.basic; import static org.junit.Assert.*; import org.junit.Test; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixRequestCache; import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; /** * Example {@link HystrixCommand} implementation for handling the get-set-get use case within * a single request context so that the "set" can invalidate the cached "get". */ public class CommandUsingRequestCacheInvalidation { /* represents a remote data store */ private static volatile String prefixStoredOnRemoteDataStore = "ValueBeforeSet_"; public static class GetterCommand extends HystrixCommand<String> { private static final HystrixCommandKey GETTER_KEY = HystrixCommandKey.Factory.asKey("GetterCommand"); private final int id; public GetterCommand(int id) { super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("GetSetGet")) .andCommandKey(GETTER_KEY)); this.id = id; } @Override protected String run() { return prefixStoredOnRemoteDataStore + id; } @Override protected String getCacheKey() { return String.valueOf(id); } /** * Allow the cache to be flushed for this object. * * @param id * argument that would normally be passed to the command */ public static void flushCache(int id) { HystrixRequestCache.getInstance(GETTER_KEY, HystrixConcurrencyStrategyDefault.getInstance()).clear(String.valueOf(id)); } } public static class SetterCommand extends HystrixCommand<Void> { private final int id; private final String prefix; public SetterCommand(int id, String prefix) { super(HystrixCommandGroupKey.Factory.asKey("GetSetGet")); this.id = id; this.prefix = prefix; } @Override protected Void run() { // persist the value against the datastore prefixStoredOnRemoteDataStore = prefix; // flush the cache GetterCommand.flushCache(id); // no return value return null; } } public static class UnitTest { @Test public void getGetSetGet() { HystrixRequestContext context = HystrixRequestContext.initializeContext(); try { assertEquals("ValueBeforeSet_1", new GetterCommand(1).execute()); GetterCommand commandAgainstCache = new GetterCommand(1); assertEquals("ValueBeforeSet_1", commandAgainstCache.execute()); // confirm it executed against cache the second time assertTrue(commandAgainstCache.isResponseFromCache()); // set the new value new SetterCommand(1, "ValueAfterSet_").execute(); // fetch it again GetterCommand commandAfterSet = new GetterCommand(1); // the getter should return with the new prefix, not the value from cache assertFalse(commandAfterSet.isResponseFromCache()); assertEquals("ValueAfterSet_1", commandAfterSet.execute()); } finally { context.shutdown(); } } } }
4,378
0
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples/basic/ObservableCommandNumbersToWords.java
/** * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.examples.basic; import java.util.HashMap; import java.util.List; import java.util.Map; import rx.Observable; import rx.functions.Func1; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixObservableCommand; import com.netflix.hystrix.examples.basic.ObservableCommandNumbersToWords.NumberWord; /** * A simple Hystrix Observable command that translates a number (<code>Integer</code>) into an English text. */ class ObservableCommandNumbersToWords extends HystrixObservableCommand<NumberWord> { private final List<Integer> numbers; // in the real world you'd probably want to replace this very simple code by using ICU or similar static Map<Integer, String> dict = new HashMap<Integer, String>(11); static { dict.put(0, "zero"); dict.put(1, "one"); dict.put(2, "two"); dict.put(3, "three"); dict.put(4, "four"); dict.put(5, "five"); dict.put(6, "six"); dict.put(7, "seven"); dict.put(8, "eight"); dict.put(9, "nine"); dict.put(10, "ten"); } public ObservableCommandNumbersToWords(final List<Integer> numbers) { super(HystrixCommandGroupKey.Factory.asKey(ObservableCommandNumbersToWords.class.getName())); this.numbers = numbers; } @Override protected Observable<NumberWord> construct() { return Observable.from(numbers).map(new Func1<Integer, NumberWord>() { @Override public NumberWord call(final Integer number) { return new NumberWord(number, dict.get(number)); } }); } static class NumberWord { private final Integer number; private final String word; public NumberWord(final Integer number, final String word) { super(); this.number = number; this.word = word; } public Integer getNumber() { return number; } public String getWord() { return word; } } }
4,379
0
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples/basic/CommandThatFailsFast.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.examples.basic; import static org.junit.Assert.*; import org.junit.Test; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.exception.HystrixRuntimeException; /** * Sample {@link HystrixCommand} that does not have a fallback implemented * so will "fail fast" when failures, rejections, short-circuiting etc occur. */ public class CommandThatFailsFast extends HystrixCommand<String> { private final boolean throwException; public CommandThatFailsFast(boolean throwException) { super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup")); this.throwException = throwException; } @Override protected String run() { if (throwException) { throw new RuntimeException("failure from CommandThatFailsFast"); } else { return "success"; } } public static class UnitTest { @Test public void testSuccess() { assertEquals("success", new CommandThatFailsFast(false).execute()); } @Test public void testFailure() { try { new CommandThatFailsFast(true).execute(); fail("we should have thrown an exception"); } catch (HystrixRuntimeException e) { assertEquals("failure from CommandThatFailsFast", e.getCause().getMessage()); e.printStackTrace(); } } } }
4,380
0
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples/basic/ObservableCollapserGetWordForNumber.java
/** * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.examples.basic; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.junit.After; import org.junit.Before; import org.junit.Test; import rx.Observable; import rx.functions.Func0; import rx.functions.Func1; import rx.observers.TestSubscriber; import rx.schedulers.Schedulers; import com.netflix.hystrix.HystrixCollapser.CollapsedRequest; import com.netflix.hystrix.HystrixObservableCollapser; import com.netflix.hystrix.HystrixObservableCommand; import com.netflix.hystrix.HystrixRequestLog; import com.netflix.hystrix.examples.basic.ObservableCommandNumbersToWords.NumberWord; import com.netflix.hystrix.strategy.concurrency.HystrixContextScheduler; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; /** * Example that uses {@link HystrixObservableCollapser} to batch multiple {@link ObservableCommandNumbersToWords} requests. * * @author Patrick Ruhkopf */ public class ObservableCollapserGetWordForNumber extends HystrixObservableCollapser<Integer, NumberWord, String, Integer> { private final Integer number; private final static AtomicInteger counter = new AtomicInteger(); public static void resetCmdCounter() { counter.set(0); } public static int getCmdCount() { return counter.get(); } public ObservableCollapserGetWordForNumber(final Integer number) { this.number = number; } @Override public Integer getRequestArgument() { return number; } @SuppressWarnings("boxing") @Override protected HystrixObservableCommand<NumberWord> createCommand(final Collection<CollapsedRequest<String, Integer>> requests) { final int count = counter.incrementAndGet(); System.out.println("Creating batch for " + requests.size() + " requests. Total invocations so far: " + count); final List<Integer> numbers = new ArrayList<Integer>(); for (final CollapsedRequest<String, Integer> request : requests) { numbers.add(request.getArgument()); } return new ObservableCommandNumbersToWords(numbers); } @Override protected Func1<NumberWord, Integer> getBatchReturnTypeKeySelector() { // Java 8: (final NumberWord nw) -> nw.getNumber(); return new Func1<NumberWord, Integer>() { @Override public Integer call(final NumberWord nw) { return nw.getNumber(); } }; } @Override protected Func1<Integer, Integer> getRequestArgumentKeySelector() { // Java 8: return (final Integer no) -> no; return new Func1<Integer, Integer>() { @Override public Integer call(final Integer no) { return no; } }; } @Override protected Func1<NumberWord, String> getBatchReturnTypeToResponseTypeMapper() { // Java 8: return (final NumberWord nw) -> nw.getWord(); return new Func1<NumberWord, String>() { @Override public String call(final NumberWord nw) { return nw.getWord(); } }; } @Override protected void onMissingResponse(final CollapsedRequest<String, Integer> request) { request.setException(new Exception("No word")); } public static class ObservableCollapserGetWordForNumberTest { private HystrixRequestContext ctx; @Before public void before() { ctx = HystrixRequestContext.initializeContext(); ObservableCollapserGetWordForNumber.resetCmdCounter(); } @After public void after() { System.out.println(HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); ctx.shutdown(); } /** * Example where we subscribe without using a specific scheduler. That means we run the actions on the same thread. */ @Test public void shouldCollapseRequestsSync() { final int noOfRequests = 10; final Map<Integer, TestSubscriber<String>> subscribersByNumber = new HashMap<Integer, TestSubscriber<String>>( noOfRequests); TestSubscriber<String> subscriber; for (int number = 0; number < noOfRequests; number++) { subscriber = new TestSubscriber<String>(); new ObservableCollapserGetWordForNumber(number).toObservable().subscribe(subscriber); subscribersByNumber.put(number, subscriber); // wait a little bit after running half of the requests so that we don't collapse all of them into one batch // TODO this can probably be improved by using a test scheduler if (number == noOfRequests / 2) sleep(1000); } assertThat(subscribersByNumber.size(), is(noOfRequests)); for (final Entry<Integer, TestSubscriber<String>> subscriberByNumber : subscribersByNumber.entrySet()) { subscriber = subscriberByNumber.getValue(); subscriber.awaitTerminalEvent(10, TimeUnit.SECONDS); assertThat(subscriber.getOnErrorEvents().toString(), subscriber.getOnErrorEvents().size(), is(0)); assertThat(subscriber.getOnNextEvents().size(), is(1)); final String word = subscriber.getOnNextEvents().get(0); System.out.println("Translated " + subscriberByNumber.getKey() + " to " + word); assertThat(word, equalTo(numberToWord(subscriberByNumber.getKey()))); } assertTrue(ObservableCollapserGetWordForNumber.getCmdCount() > 1); assertTrue(ObservableCollapserGetWordForNumber.getCmdCount() < noOfRequests); } /** * Example where we subscribe on the computation scheduler. For this we need the {@link HystrixContextScheduler}, that * passes the {@link HystrixRequestContext} to the thread that runs the action. */ @Test public void shouldCollapseRequestsAsync() { final HystrixContextScheduler contextAwareScheduler = new HystrixContextScheduler(Schedulers.computation()); final int noOfRequests = 10; final Map<Integer, TestSubscriber<String>> subscribersByNumber = new HashMap<Integer, TestSubscriber<String>>( noOfRequests); TestSubscriber<String> subscriber; for (int number = 0; number < noOfRequests; number++) { subscriber = new TestSubscriber<String>(); final int finalNumber = number; // defer and subscribe on specific scheduler Observable.defer(new Func0<Observable<String>>() { @Override public Observable<String> call() { return new ObservableCollapserGetWordForNumber(finalNumber).toObservable(); } }).subscribeOn(contextAwareScheduler).subscribe(subscriber); subscribersByNumber.put(number, subscriber); // wait a little bit after running half of the requests so that we don't collapse all of them into one batch // TODO this can probably be improved by using a test scheduler if (number == noOfRequests / 2) sleep(1000); } assertThat(subscribersByNumber.size(), is(noOfRequests)); for (final Entry<Integer, TestSubscriber<String>> subscriberByNumber : subscribersByNumber.entrySet()) { subscriber = subscriberByNumber.getValue(); subscriber.awaitTerminalEvent(10, TimeUnit.SECONDS); assertThat(subscriber.getOnErrorEvents().toString(), subscriber.getOnErrorEvents().size(), is(0)); assertThat(subscriber.getOnNextEvents().size(), is(1)); final String word = subscriber.getOnNextEvents().get(0); System.out.println("Translated " + subscriberByNumber.getKey() + " to " + word); assertThat(word, equalTo(numberToWord(subscriberByNumber.getKey()))); } assertTrue(ObservableCollapserGetWordForNumber.getCmdCount() > 1); assertTrue(ObservableCollapserGetWordForNumber.getCmdCount() < noOfRequests); } @Test public void shouldCollapseSameRequests() { //given final HystrixContextScheduler contextAwareScheduler = new HystrixContextScheduler(Schedulers.computation()); //when TestSubscriber<String> subscriber1 = getWordForNumber(contextAwareScheduler, 0); TestSubscriber<String> subscriber2 = getWordForNumber(contextAwareScheduler, 0); //then subscriberReceived(subscriber1, 0); subscriberReceived(subscriber2, 0); } private TestSubscriber<String> getWordForNumber(HystrixContextScheduler contextAwareScheduler, final int number) { final TestSubscriber<String> subscriber = new TestSubscriber<String>(); Observable.defer(new Func0<Observable<String>>() { @Override public Observable<String> call() { return new ObservableCollapserGetWordForNumber(number).toObservable(); } }).subscribeOn(contextAwareScheduler).subscribe(subscriber); return subscriber; } private void subscriberReceived(TestSubscriber<String> subscriber, int number) { subscriber.awaitTerminalEvent(10, TimeUnit.SECONDS); assertThat(subscriber.getOnErrorEvents().toString(), subscriber.getOnErrorEvents().size(), is(0)); assertThat(subscriber.getOnNextEvents().size(), is(1)); assertThat(subscriber.getOnNextEvents().get(0), equalTo(numberToWord(number))); } private String numberToWord(final int number) { return ObservableCommandNumbersToWords.dict.get(number); } private void sleep(final long ms) { try { Thread.sleep(1000); } catch (final InterruptedException e) { throw new IllegalStateException(e); } } } }
4,381
0
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples/basic/CommandUsingRequestCache.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.examples.basic; import static org.junit.Assert.*; import org.junit.Test; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; /** * Sample {@link HystrixCommand} showing how implementing the {@link #getCacheKey()} method * enables request caching for eliminating duplicate calls within the same request context. */ public class CommandUsingRequestCache extends HystrixCommand<Boolean> { private final int value; protected CommandUsingRequestCache(int value) { super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup")); this.value = value; } @Override protected Boolean run() { return value == 0 || value % 2 == 0; } @Override protected String getCacheKey() { return String.valueOf(value); } public static class UnitTest { @Test public void testWithoutCacheHits() { HystrixRequestContext context = HystrixRequestContext.initializeContext(); try { assertTrue(new CommandUsingRequestCache(2).execute()); assertFalse(new CommandUsingRequestCache(1).execute()); assertTrue(new CommandUsingRequestCache(0).execute()); assertTrue(new CommandUsingRequestCache(58672).execute()); } finally { context.shutdown(); } } @Test public void testWithCacheHits() { HystrixRequestContext context = HystrixRequestContext.initializeContext(); try { CommandUsingRequestCache command2a = new CommandUsingRequestCache(2); CommandUsingRequestCache command2b = new CommandUsingRequestCache(2); assertTrue(command2a.execute()); // this is the first time we've executed this command with the value of "2" so it should not be from cache assertFalse(command2a.isResponseFromCache()); assertTrue(command2b.execute()); // this is the second time we've executed this command with the same value so it should return from cache assertTrue(command2b.isResponseFromCache()); } finally { context.shutdown(); } // start a new request context context = HystrixRequestContext.initializeContext(); try { CommandUsingRequestCache command3b = new CommandUsingRequestCache(2); assertTrue(command3b.execute()); // this is a new request context so this should not come from cache assertFalse(command3b.isResponseFromCache()); } finally { context.shutdown(); } } } }
4,382
0
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples/basic/CommandHelloWorld.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.examples.basic; import static org.junit.Assert.*; import java.util.concurrent.Future; import org.junit.Test; import rx.Observable; import rx.Observer; import rx.functions.Action1; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; /** * The obligatory "Hello World!" showing a simple implementation of a {@link HystrixCommand}. */ public class CommandHelloWorld extends HystrixCommand<String> { private final String name; public CommandHelloWorld(String name) { super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup")); this.name = name; } @Override protected String run() { return "Hello " + name + "!"; } public static class UnitTest { @Test public void testSynchronous() { assertEquals("Hello World!", new CommandHelloWorld("World").execute()); assertEquals("Hello Bob!", new CommandHelloWorld("Bob").execute()); } @Test public void testAsynchronous1() throws Exception { assertEquals("Hello World!", new CommandHelloWorld("World").queue().get()); assertEquals("Hello Bob!", new CommandHelloWorld("Bob").queue().get()); } @Test public void testAsynchronous2() throws Exception { Future<String> fWorld = new CommandHelloWorld("World").queue(); Future<String> fBob = new CommandHelloWorld("Bob").queue(); assertEquals("Hello World!", fWorld.get()); assertEquals("Hello Bob!", fBob.get()); } @Test public void testObservable() throws Exception { Observable<String> fWorld = new CommandHelloWorld("World").observe(); Observable<String> fBob = new CommandHelloWorld("Bob").observe(); // blocking assertEquals("Hello World!", fWorld.toBlocking().single()); assertEquals("Hello Bob!", fBob.toBlocking().single()); // non-blocking // - this is a verbose anonymous inner-class approach and doesn't do assertions fWorld.subscribe(new Observer<String>() { @Override public void onCompleted() { // nothing needed here } @Override public void onError(Throwable e) { e.printStackTrace(); } @Override public void onNext(String v) { System.out.println("onNext: " + v); } }); // non-blocking // - also verbose anonymous inner-class // - ignore errors and onCompleted signal fBob.subscribe(new Action1<String>() { @Override public void call(String v) { System.out.println("onNext: " + v); } }); // non-blocking // - using closures in Java 8 would look like this: // fWorld.subscribe((v) -> { // System.out.println("onNext: " + v); // }) // - or while also including error handling // fWorld.subscribe((v) -> { // System.out.println("onNext: " + v); // }, (exception) -> { // exception.printStackTrace(); // }) // More information about Observable can be found at https://github.com/Netflix/RxJava/wiki/How-To-Use } } }
4,383
0
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples/basic/CommandWithFallbackViaNetwork.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.examples.basic; import static org.junit.Assert.*; import org.junit.Test; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixEventType; import com.netflix.hystrix.HystrixInvokableInfo; import com.netflix.hystrix.HystrixRequestLog; import com.netflix.hystrix.HystrixThreadPoolKey; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; /** * Sample {@link HystrixCommand} that implements fallback logic that requires * network traffic and thus executes another {@link HystrixCommand} from the {@link #getFallback()} method. * <p> * Note also that the fallback command uses a separate thread-pool as well even though * it's in the same command group. * <p> * It needs to be on a separate thread-pool otherwise the first command could saturate it * and the fallback command never have a chance to execute. */ public class CommandWithFallbackViaNetwork extends HystrixCommand<String> { private final int id; protected CommandWithFallbackViaNetwork(int id) { super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceX")) .andCommandKey(HystrixCommandKey.Factory.asKey("GetValueCommand"))); this.id = id; } @Override protected String run() { // RemoteServiceXClient.getValue(id); throw new RuntimeException("force failure for example"); } @Override protected String getFallback() { return new FallbackViaNetwork(id).execute(); } private static class FallbackViaNetwork extends HystrixCommand<String> { private final int id; public FallbackViaNetwork(int id) { super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceX")) .andCommandKey(HystrixCommandKey.Factory.asKey("GetValueFallbackCommand")) // use a different threadpool for the fallback command // so saturating the RemoteServiceX pool won't prevent // fallbacks from executing .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("RemoteServiceXFallback"))); this.id = id; } @Override protected String run() { // MemCacheClient.getValue(id); throw new RuntimeException("the fallback also failed"); } @Override protected String getFallback() { // the fallback also failed // so this fallback-of-a-fallback will // fail silently and return null return null; } } public static class UnitTest { @Test public void test() { HystrixRequestContext context = HystrixRequestContext.initializeContext(); try { assertEquals(null, new CommandWithFallbackViaNetwork(1).execute()); HystrixInvokableInfo<?> command1 = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().toArray(new HystrixInvokableInfo<?>[2])[0]; assertEquals("GetValueCommand", command1.getCommandKey().name()); assertTrue(command1.getExecutionEvents().contains(HystrixEventType.FAILURE)); HystrixInvokableInfo<?> command2 = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().toArray(new HystrixInvokableInfo<?>[2])[1]; assertEquals("GetValueFallbackCommand", command2.getCommandKey().name()); assertTrue(command2.getExecutionEvents().contains(HystrixEventType.FAILURE)); } finally { context.shutdown(); } } } }
4,384
0
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples/basic/CommandFacadeWithPrimarySecondary.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.examples.basic; import static org.junit.Assert.*; import org.junit.Test; import com.netflix.config.ConfigurationManager; import com.netflix.config.DynamicBooleanProperty; import com.netflix.config.DynamicPropertyFactory; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy; import com.netflix.hystrix.HystrixThreadPoolKey; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; /** * Sample {@link HystrixCommand} pattern using a semaphore-isolated command * that conditionally invokes thread-isolated commands. */ public class CommandFacadeWithPrimarySecondary extends HystrixCommand<String> { private final static DynamicBooleanProperty usePrimary = DynamicPropertyFactory.getInstance().getBooleanProperty("primarySecondary.usePrimary", true); private final int id; public CommandFacadeWithPrimarySecondary(int id) { super(Setter .withGroupKey(HystrixCommandGroupKey.Factory.asKey("SystemX")) .andCommandKey(HystrixCommandKey.Factory.asKey("PrimarySecondaryCommand")) .andCommandPropertiesDefaults( // we want to default to semaphore-isolation since this wraps // 2 others commands that are already thread isolated HystrixCommandProperties.Setter() .withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE))); this.id = id; } @Override protected String run() { if (usePrimary.get()) { return new PrimaryCommand(id).execute(); } else { return new SecondaryCommand(id).execute(); } } @Override protected String getFallback() { return "static-fallback-" + id; } @Override protected String getCacheKey() { return String.valueOf(id); } private static class PrimaryCommand extends HystrixCommand<String> { private final int id; private PrimaryCommand(int id) { super(Setter .withGroupKey(HystrixCommandGroupKey.Factory.asKey("SystemX")) .andCommandKey(HystrixCommandKey.Factory.asKey("PrimaryCommand")) .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("PrimaryCommand")) .andCommandPropertiesDefaults( // we default to a 600ms timeout for primary HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(600))); this.id = id; } @Override protected String run() { // perform expensive 'primary' service call return "responseFromPrimary-" + id; } } private static class SecondaryCommand extends HystrixCommand<String> { private final int id; private SecondaryCommand(int id) { super(Setter .withGroupKey(HystrixCommandGroupKey.Factory.asKey("SystemX")) .andCommandKey(HystrixCommandKey.Factory.asKey("SecondaryCommand")) .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("SecondaryCommand")) .andCommandPropertiesDefaults( // we default to a 100ms timeout for secondary HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(100))); this.id = id; } @Override protected String run() { // perform fast 'secondary' service call return "responseFromSecondary-" + id; } } public static class UnitTest { @Test public void testPrimary() { HystrixRequestContext context = HystrixRequestContext.initializeContext(); try { ConfigurationManager.getConfigInstance().setProperty("primarySecondary.usePrimary", true); assertEquals("responseFromPrimary-20", new CommandFacadeWithPrimarySecondary(20).execute()); } finally { context.shutdown(); ConfigurationManager.getConfigInstance().clear(); } } @Test public void testSecondary() { HystrixRequestContext context = HystrixRequestContext.initializeContext(); try { ConfigurationManager.getConfigInstance().setProperty("primarySecondary.usePrimary", false); assertEquals("responseFromSecondary-20", new CommandFacadeWithPrimarySecondary(20).execute()); } finally { context.shutdown(); ConfigurationManager.getConfigInstance().clear(); } } } }
4,385
0
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples/basic/CommandCollapserGetValueForKey.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.examples.basic; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.Future; import org.junit.Test; import com.netflix.hystrix.HystrixCollapser; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixEventType; import com.netflix.hystrix.HystrixInvokableInfo; import com.netflix.hystrix.HystrixRequestLog; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; /** * Sample {@link HystrixCollapser} that automatically batches multiple requests to execute()/queue() * into a single {@link HystrixCommand} execution for all requests within the defined batch (time or size). */ public class CommandCollapserGetValueForKey extends HystrixCollapser<List<String>, String, Integer> { private final Integer key; public CommandCollapserGetValueForKey(Integer key) { this.key = key; } @Override public Integer getRequestArgument() { return key; } @Override protected HystrixCommand<List<String>> createCommand(final Collection<CollapsedRequest<String, Integer>> requests) { return new BatchCommand(requests); } @Override protected void mapResponseToRequests(List<String> batchResponse, Collection<CollapsedRequest<String, Integer>> requests) { int count = 0; for (CollapsedRequest<String, Integer> request : requests) { request.setResponse(batchResponse.get(count++)); } } private static final class BatchCommand extends HystrixCommand<List<String>> { private final Collection<CollapsedRequest<String, Integer>> requests; private BatchCommand(Collection<CollapsedRequest<String, Integer>> requests) { super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup")) .andCommandKey(HystrixCommandKey.Factory.asKey("GetValueForKey"))); this.requests = requests; } @Override protected List<String> run() { ArrayList<String> response = new ArrayList<String>(); for (CollapsedRequest<String, Integer> request : requests) { // artificial response for each argument received in the batch response.add("ValueForKey: " + request.getArgument()); } return response; } } public static class UnitTest { @Test public void testCollapser() throws Exception { HystrixRequestContext context = HystrixRequestContext.initializeContext(); try { Future<String> f1 = new CommandCollapserGetValueForKey(1).queue(); Future<String> f2 = new CommandCollapserGetValueForKey(2).queue(); Future<String> f3 = new CommandCollapserGetValueForKey(3).queue(); Future<String> f4 = new CommandCollapserGetValueForKey(4).queue(); assertEquals("ValueForKey: 1", f1.get()); assertEquals("ValueForKey: 2", f2.get()); assertEquals("ValueForKey: 3", f3.get()); assertEquals("ValueForKey: 4", f4.get()); int numExecuted = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size(); System.err.println("num executed: " + numExecuted); // assert that the batch command 'GetValueForKey' was in fact executed and that it executed only // once or twice (due to non-determinism of scheduler since this example uses the real timer) if (numExecuted > 2) { fail("some of the commands should have been collapsed"); } System.err.println("HystrixRequestLog.getCurrentRequest().getAllExecutedCommands(): " + HystrixRequestLog.getCurrentRequest().getAllExecutedCommands()); int numLogs = 0; for (HystrixInvokableInfo<?> command : HystrixRequestLog.getCurrentRequest().getAllExecutedCommands()) { numLogs++; // assert the command is the one we're expecting assertEquals("GetValueForKey", command.getCommandKey().name()); System.err.println(command.getCommandKey().name() + " => command.getExecutionEvents(): " + command.getExecutionEvents()); // confirm that it was a COLLAPSED command execution assertTrue(command.getExecutionEvents().contains(HystrixEventType.COLLAPSED)); assertTrue(command.getExecutionEvents().contains(HystrixEventType.SUCCESS)); } assertEquals(numExecuted, numLogs); } finally { context.shutdown(); } } } }
4,386
0
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples
Create_ds/Hystrix/hystrix-examples/src/main/java/com/netflix/hystrix/examples/basic/CommandHelloFailure.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.examples.basic; import static org.junit.Assert.*; import java.util.concurrent.Future; import org.junit.Test; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; /** * Sample {@link HystrixCommand} showing a basic fallback implementation. */ public class CommandHelloFailure extends HystrixCommand<String> { private final String name; public CommandHelloFailure(String name) { super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup")); this.name = name; } @Override protected String run() { throw new RuntimeException("this command always fails"); } @Override protected String getFallback() { return "Hello Failure " + name + "!"; } public static class UnitTest { @Test public void testSynchronous() { assertEquals("Hello Failure World!", new CommandHelloFailure("World").execute()); assertEquals("Hello Failure Bob!", new CommandHelloFailure("Bob").execute()); } @Test public void testAsynchronous1() throws Exception { assertEquals("Hello Failure World!", new CommandHelloFailure("World").queue().get()); assertEquals("Hello Failure Bob!", new CommandHelloFailure("Bob").queue().get()); } @Test public void testAsynchronous2() throws Exception { Future<String> fWorld = new CommandHelloFailure("World").queue(); Future<String> fBob = new CommandHelloFailure("Bob").queue(); assertEquals("Hello Failure World!", fWorld.get()); assertEquals("Hello Failure Bob!", fBob.get()); } } }
4,387
0
Create_ds/Hystrix/hystrix-contrib/hystrix-servo-metrics-publisher/src/test/java/com/netflix/hystrix/contrib
Create_ds/Hystrix/hystrix-contrib/hystrix-servo-metrics-publisher/src/test/java/com/netflix/hystrix/contrib/servopublisher/HystrixServoMetricsPublisherCommandTest.java
/** * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.contrib.servopublisher; import com.netflix.hystrix.HystrixCircuitBreaker; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandMetrics; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixEventType; import com.netflix.hystrix.strategy.properties.HystrixPropertiesCommandDefault; import org.junit.Test; import rx.Observable; import rx.observers.TestSubscriber; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class HystrixServoMetricsPublisherCommandTest { private static HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ServoGROUP"); private static HystrixCommandProperties.Setter propertiesSetter = HystrixCommandProperties.Setter() .withCircuitBreakerEnabled(true) .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD) .withExecutionTimeoutInMilliseconds(100) .withMetricsRollingStatisticalWindowInMilliseconds(1000) .withMetricsRollingPercentileWindowInMilliseconds(1000) .withMetricsRollingPercentileWindowBuckets(10); @Test public void testCumulativeCounters() throws Exception { //execute 10 commands/sec (8 SUCCESS, 1 FAILURE, 1 TIMEOUT). //after 5 seconds, cumulative counters should have observed 50 commands (40 SUCCESS, 5 FAILURE, 5 TIMEOUT) HystrixCommandKey key = HystrixCommandKey.Factory.asKey("ServoCOMMAND-A"); HystrixCircuitBreaker circuitBreaker = HystrixCircuitBreaker.Factory.getInstance(key); HystrixCommandProperties properties = new HystrixPropertiesCommandDefault(key, propertiesSetter); HystrixCommandMetrics metrics = HystrixCommandMetrics.getInstance(key, groupKey, properties); HystrixServoMetricsPublisherCommand servoPublisher = new HystrixServoMetricsPublisherCommand(key, groupKey, metrics, circuitBreaker, properties); servoPublisher.initialize(); final int NUM_SECONDS = 5; for (int i = 0; i < NUM_SECONDS; i++) { new SuccessCommand(key).execute(); new SuccessCommand(key).execute(); new SuccessCommand(key).execute(); Thread.sleep(10); new TimeoutCommand(key).execute(); new SuccessCommand(key).execute(); new FailureCommand(key).execute(); new SuccessCommand(key).execute(); new SuccessCommand(key).execute(); new SuccessCommand(key).execute(); Thread.sleep(10); new SuccessCommand(key).execute(); } Thread.sleep(500); assertEquals(40L, servoPublisher.getCumulativeMonitor("success", HystrixEventType.SUCCESS).getValue()); assertEquals(5L, servoPublisher.getCumulativeMonitor("timeout", HystrixEventType.TIMEOUT).getValue()); assertEquals(5L, servoPublisher.getCumulativeMonitor("failure", HystrixEventType.FAILURE).getValue()); assertEquals(10L, servoPublisher.getCumulativeMonitor("fallback_success", HystrixEventType.FALLBACK_SUCCESS).getValue()); } @Test public void testRollingCounters() throws Exception { //execute 10 commands, then sleep for 2000ms to let these age out //execute 10 commands again, these should show up in rolling count HystrixCommandKey key = HystrixCommandKey.Factory.asKey("ServoCOMMAND-B"); HystrixCircuitBreaker circuitBreaker = HystrixCircuitBreaker.Factory.getInstance(key); HystrixCommandProperties properties = new HystrixPropertiesCommandDefault(key, propertiesSetter); HystrixCommandMetrics metrics = HystrixCommandMetrics.getInstance(key, groupKey, properties); HystrixServoMetricsPublisherCommand servoPublisher = new HystrixServoMetricsPublisherCommand(key, groupKey, metrics, circuitBreaker, properties); servoPublisher.initialize(); new SuccessCommand(key).execute(); new SuccessCommand(key).execute(); new SuccessCommand(key).execute(); new TimeoutCommand(key).execute(); new SuccessCommand(key).execute(); new FailureCommand(key).execute(); new SuccessCommand(key).execute(); new SuccessCommand(key).execute(); new SuccessCommand(key).execute(); new SuccessCommand(key).execute(); Thread.sleep(2000); new SuccessCommand(key).execute(); new SuccessCommand(key).execute(); new SuccessCommand(key).execute(); new TimeoutCommand(key).execute(); new SuccessCommand(key).execute(); new FailureCommand(key).execute(); new TimeoutCommand(key).execute(); new TimeoutCommand(key).execute(); new TimeoutCommand(key).execute(); new TimeoutCommand(key).execute(); Thread.sleep(100); //time for 1 bucket roll assertEquals(4L, servoPublisher.getRollingMonitor("success", HystrixEventType.SUCCESS).getValue()); assertEquals(5L, servoPublisher.getRollingMonitor("timeout", HystrixEventType.TIMEOUT).getValue()); assertEquals(1L, servoPublisher.getRollingMonitor("failure", HystrixEventType.FAILURE).getValue()); assertEquals(6L, servoPublisher.getRollingMonitor("falback_success", HystrixEventType.FALLBACK_SUCCESS).getValue()); } @Test public void testRollingLatencies() throws Exception { //execute 10 commands, then sleep for 2000ms to let these age out //execute 10 commands again, these should show up in rolling count HystrixCommandKey key = HystrixCommandKey.Factory.asKey("ServoCOMMAND-C"); HystrixCircuitBreaker circuitBreaker = HystrixCircuitBreaker.Factory.getInstance(key); HystrixCommandProperties properties = new HystrixPropertiesCommandDefault(key, propertiesSetter); HystrixCommandMetrics metrics = HystrixCommandMetrics.getInstance(key, groupKey, properties); HystrixServoMetricsPublisherCommand servoPublisher = new HystrixServoMetricsPublisherCommand(key, groupKey, metrics, circuitBreaker, properties); servoPublisher.initialize(); new SuccessCommand(key, 5).execute(); new SuccessCommand(key, 5).execute(); new SuccessCommand(key, 5).execute(); new TimeoutCommand(key).execute(); new SuccessCommand(key, 5).execute(); new FailureCommand(key, 5).execute(); new SuccessCommand(key, 5).execute(); new SuccessCommand(key, 5).execute(); new SuccessCommand(key, 5).execute(); new SuccessCommand(key, 5).execute(); Thread.sleep(2000); List<Observable<Integer>> os = new ArrayList<Observable<Integer>>(); TestSubscriber<Integer> testSubscriber = new TestSubscriber<Integer>(); os.add(new SuccessCommand(key, 10).observe()); os.add(new SuccessCommand(key, 20).observe()); os.add(new SuccessCommand(key, 10).observe()); os.add(new TimeoutCommand(key).observe()); os.add(new SuccessCommand(key, 15).observe()); os.add(new FailureCommand(key, 10).observe()); os.add(new TimeoutCommand(key).observe()); os.add(new TimeoutCommand(key).observe()); os.add(new TimeoutCommand(key).observe()); os.add(new TimeoutCommand(key).observe()); Observable.merge(os).subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(300, TimeUnit.MILLISECONDS); testSubscriber.assertCompleted(); testSubscriber.assertNoErrors(); Thread.sleep(100); //1 bucket roll int meanExecutionLatency = servoPublisher.getExecutionLatencyMeanMonitor("meanExecutionLatency").getValue().intValue(); int p5ExecutionLatency = servoPublisher.getExecutionLatencyPercentileMonitor("p5ExecutionLatency", 5).getValue().intValue(); int p25ExecutionLatency = servoPublisher.getExecutionLatencyPercentileMonitor("p25ExecutionLatency", 25).getValue().intValue(); int p50ExecutionLatency = servoPublisher.getExecutionLatencyPercentileMonitor("p50ExecutionLatency", 50).getValue().intValue(); int p75ExecutionLatency = servoPublisher.getExecutionLatencyPercentileMonitor("p75ExecutionLatency", 75).getValue().intValue(); int p90ExecutionLatency = servoPublisher.getExecutionLatencyPercentileMonitor("p90ExecutionLatency", 90).getValue().intValue(); int p99ExecutionLatency = servoPublisher.getExecutionLatencyPercentileMonitor("p99ExecutionLatency", 99).getValue().intValue(); int p995ExecutionLatency = servoPublisher.getExecutionLatencyPercentileMonitor("p995ExecutionLatency", 99.5).getValue().intValue(); System.out.println("Execution: Mean : " + meanExecutionLatency + ", p5 : " + p5ExecutionLatency + ", p25 : " + p25ExecutionLatency + ", p50 : " + p50ExecutionLatency + ", p75 : " + p75ExecutionLatency + ", p90 : " + p90ExecutionLatency + ", p99 : " + p99ExecutionLatency + ", p99.5 : " + p995ExecutionLatency); int meanTotalLatency = servoPublisher.getTotalLatencyMeanMonitor("meanTotalLatency").getValue().intValue(); int p5TotalLatency = servoPublisher.getTotalLatencyPercentileMonitor("p5TotalLatency", 5).getValue().intValue(); int p25TotalLatency = servoPublisher.getTotalLatencyPercentileMonitor("p25TotalLatency", 25).getValue().intValue(); int p50TotalLatency = servoPublisher.getTotalLatencyPercentileMonitor("p50TotalLatency", 50).getValue().intValue(); int p75TotalLatency = servoPublisher.getTotalLatencyPercentileMonitor("p75TotalLatency", 75).getValue().intValue(); int p90TotalLatency = servoPublisher.getTotalLatencyPercentileMonitor("p90TotalLatency", 90).getValue().intValue(); int p99TotalLatency = servoPublisher.getTotalLatencyPercentileMonitor("p99TotalLatency", 99).getValue().intValue(); int p995TotalLatency = servoPublisher.getTotalLatencyPercentileMonitor("p995TotalLatency", 99.5).getValue().intValue(); System.out.println("Total: Mean : " + meanTotalLatency + ", p5 : " + p5TotalLatency + ", p25 : " + p25TotalLatency + ", p50 : " + p50TotalLatency + ", p75 : " + p75TotalLatency + ", p90 : " + p90TotalLatency + ", p99 : " + p99TotalLatency + ", p99.5 : " + p995TotalLatency); assertTrue(meanExecutionLatency > 10); assertTrue(p5ExecutionLatency <= p25ExecutionLatency); assertTrue(p25ExecutionLatency <= p50ExecutionLatency); assertTrue(p50ExecutionLatency <= p75ExecutionLatency); assertTrue(p75ExecutionLatency <= p90ExecutionLatency); assertTrue(p90ExecutionLatency <= p99ExecutionLatency); assertTrue(p99ExecutionLatency <= p995ExecutionLatency); assertTrue(meanTotalLatency > 10); assertTrue(p5TotalLatency <= p25TotalLatency); assertTrue(p25TotalLatency <= p50TotalLatency); assertTrue(p50TotalLatency <= p75TotalLatency); assertTrue(p75TotalLatency <= p90TotalLatency); assertTrue(p90TotalLatency <= p99TotalLatency); assertTrue(p99TotalLatency <= p995TotalLatency); assertTrue(meanExecutionLatency <= meanTotalLatency); assertTrue(p5ExecutionLatency <= p5TotalLatency); assertTrue(p25ExecutionLatency <= p25TotalLatency); assertTrue(p50ExecutionLatency <= p50TotalLatency); assertTrue(p75ExecutionLatency <= p75TotalLatency); assertTrue(p90ExecutionLatency <= p90TotalLatency); assertTrue(p99ExecutionLatency <= p99TotalLatency); assertTrue(p995ExecutionLatency <= p995TotalLatency); } static class SampleCommand extends HystrixCommand<Integer> { boolean shouldFail; int latencyToAdd; protected SampleCommand(HystrixCommandKey key, boolean shouldFail, int latencyToAdd) { super(Setter.withGroupKey(groupKey).andCommandKey(key).andCommandPropertiesDefaults(propertiesSetter)); this.shouldFail = shouldFail; this.latencyToAdd = latencyToAdd; } @Override protected Integer run() throws Exception { if (shouldFail) { throw new RuntimeException("command failure"); } else { Thread.sleep(latencyToAdd); return 1; } } @Override protected Integer getFallback() { return 99; } } static class SuccessCommand extends SampleCommand { protected SuccessCommand(HystrixCommandKey key) { super(key, false, 0); } public SuccessCommand(HystrixCommandKey key, int latencyToAdd) { super(key, false, latencyToAdd); } } static class FailureCommand extends SampleCommand { protected FailureCommand(HystrixCommandKey key) { super(key, true, 0); } public FailureCommand(HystrixCommandKey key, int latencyToAdd) { super(key, true, latencyToAdd); } } static class TimeoutCommand extends SampleCommand { protected TimeoutCommand(HystrixCommandKey key) { super(key, false, 400); //exceeds 100ms timeout } } }
4,388
0
Create_ds/Hystrix/hystrix-contrib/hystrix-servo-metrics-publisher/src/main/java/com/netflix/hystrix/contrib
Create_ds/Hystrix/hystrix-contrib/hystrix-servo-metrics-publisher/src/main/java/com/netflix/hystrix/contrib/servopublisher/HystrixServoMetricsPublisherCommand.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.contrib.servopublisher; import com.netflix.hystrix.HystrixCircuitBreaker; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandMetrics; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixEventType; import com.netflix.hystrix.metric.consumer.CumulativeCommandEventCounterStream; import com.netflix.hystrix.metric.consumer.RollingCommandEventCounterStream; import com.netflix.hystrix.metric.consumer.RollingCommandLatencyDistributionStream; import com.netflix.hystrix.metric.consumer.RollingCommandMaxConcurrencyStream; import com.netflix.hystrix.metric.consumer.RollingCommandUserLatencyDistributionStream; import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherCommand; import com.netflix.hystrix.util.HystrixRollingNumberEvent; import com.netflix.servo.DefaultMonitorRegistry; import com.netflix.servo.annotations.DataSourceLevel; import com.netflix.servo.monitor.BasicCompositeMonitor; import com.netflix.servo.monitor.Monitor; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.tag.Tag; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.functions.Func0; import java.util.ArrayList; import java.util.List; /** * Concrete Implementation of {@link HystrixMetricsPublisherCommand} using Servo (https://github.com/Netflix/servo) * * This class should encapsulate all logic around how to pull metrics. This will allow any other custom Servo publisher * to extend. Then, if that class wishes to override {@link #initialize()}, that concrete implementation can choose * by picking the set of semantic metrics and names, rather than providing an implementation of how. */ public class HystrixServoMetricsPublisherCommand extends HystrixServoMetricsPublisherAbstract implements HystrixMetricsPublisherCommand { private static final Logger logger = LoggerFactory.getLogger(HystrixServoMetricsPublisherCommand.class); private final HystrixCommandKey key; private final HystrixCommandGroupKey commandGroupKey; private final HystrixCommandMetrics metrics; private final HystrixCircuitBreaker circuitBreaker; private final HystrixCommandProperties properties; private final Tag servoInstanceTag; private final Tag servoTypeTag; public HystrixServoMetricsPublisherCommand(HystrixCommandKey commandKey, HystrixCommandGroupKey commandGroupKey, HystrixCommandMetrics metrics, HystrixCircuitBreaker circuitBreaker, HystrixCommandProperties properties) { this.key = commandKey; this.commandGroupKey = commandGroupKey; this.metrics = metrics; this.circuitBreaker = circuitBreaker; this.properties = properties; this.servoInstanceTag = new Tag() { @Override public String getKey() { return "instance"; } @Override public String getValue() { return key.name(); } @Override public String tagString() { return key.name(); } }; this.servoTypeTag = new Tag() { @Override public String getKey() { return "type"; } @Override public String getValue() { return "HystrixCommand"; } @Override public String tagString() { return "HystrixCommand"; } }; } @Override public void initialize() { /* list of monitors */ List<Monitor<?>> monitors = getServoMonitors(); // publish metrics together under a single composite (it seems this name is ignored) MonitorConfig commandMetricsConfig = MonitorConfig.builder("HystrixCommand_" + key.name()).build(); BasicCompositeMonitor commandMetricsMonitor = new BasicCompositeMonitor(commandMetricsConfig, monitors); DefaultMonitorRegistry.getInstance().register(commandMetricsMonitor); RollingCommandEventCounterStream.getInstance(key, properties).startCachingStreamValuesIfUnstarted(); CumulativeCommandEventCounterStream.getInstance(key, properties).startCachingStreamValuesIfUnstarted(); RollingCommandLatencyDistributionStream.getInstance(key, properties).startCachingStreamValuesIfUnstarted(); RollingCommandUserLatencyDistributionStream.getInstance(key, properties).startCachingStreamValuesIfUnstarted(); RollingCommandMaxConcurrencyStream.getInstance(key, properties).startCachingStreamValuesIfUnstarted(); } @Override protected Tag getServoTypeTag() { return servoTypeTag; } @Override protected Tag getServoInstanceTag() { return servoInstanceTag; } protected final Func0<Number> currentConcurrentExecutionCountThunk = new Func0<Number>() { @Override public Integer call() { return metrics.getCurrentConcurrentExecutionCount(); } }; protected final Func0<Number> rollingMaxConcurrentExecutionCountThunk = new Func0<Number>() { @Override public Long call() { return metrics.getRollingMaxConcurrentExecutions(); } }; protected final Func0<Number> errorPercentageThunk = new Func0<Number>() { @Override public Integer call() { return metrics.getHealthCounts().getErrorPercentage(); } }; protected final Func0<Number> currentTimeThunk = new Func0<Number>() { @Override public Number call() { return System.currentTimeMillis(); } }; /** * Convert from HystrixEventType to HystrixRollingNumberEvent * @param eventType HystrixEventType * @return HystrixRollingNumberEvent * @deprecated Instead, use {@link HystrixRollingNumberEvent#from(HystrixEventType)} */ @Deprecated protected final HystrixRollingNumberEvent getRollingNumberTypeFromEventType(HystrixEventType eventType) { return HystrixRollingNumberEvent.from(eventType); } protected Monitor<Number> getCumulativeMonitor(final String name, final HystrixEventType event) { return new CounterMetric(MonitorConfig.builder(name).withTag(getServoTypeTag()).withTag(getServoInstanceTag()).build()) { @Override public Long getValue() { return metrics.getCumulativeCount(event); } }; } protected Monitor<Number> safelyGetCumulativeMonitor(final String name, final Func0<HystrixEventType> eventThunk) { return new CounterMetric(MonitorConfig.builder(name).withTag(getServoTypeTag()).withTag(getServoInstanceTag()).build()) { @Override public Long getValue() { try { HystrixEventType eventType = eventThunk.call(); return metrics.getCumulativeCount(HystrixRollingNumberEvent.from(eventType)); } catch (NoSuchFieldError error) { logger.error("While publishing Servo metrics, error looking up eventType for : {}. Please check that all Hystrix versions are the same!", name); return 0L; } } }; } protected Monitor<Number> getRollingMonitor(final String name, final HystrixEventType event) { return new GaugeMetric(MonitorConfig.builder(name).withTag(DataSourceLevel.DEBUG).withTag(getServoTypeTag()).withTag(getServoInstanceTag()).build()) { @Override public Long getValue() { return metrics.getRollingCount(event); } }; } protected Monitor<Number> safelyGetRollingMonitor(final String name, final Func0<HystrixEventType> eventThunk) { return new GaugeMetric(MonitorConfig.builder(name).withTag(DataSourceLevel.DEBUG).withTag(getServoTypeTag()).withTag(getServoInstanceTag()).build()) { @Override public Long getValue() { try { HystrixEventType eventType = eventThunk.call(); return metrics.getRollingCount(HystrixRollingNumberEvent.from(eventType)); } catch (NoSuchFieldError error) { logger.error("While publishing Servo metrics, error looking up eventType for : {}. Please check that all Hystrix versions are the same!", name); return 0L; } } }; } protected Monitor<Number> getExecutionLatencyMeanMonitor(final String name) { return new GaugeMetric(MonitorConfig.builder(name).build()) { @Override public Number getValue() { return metrics.getExecutionTimeMean(); } }; } protected Monitor<Number> getExecutionLatencyPercentileMonitor(final String name, final double percentile) { return new GaugeMetric(MonitorConfig.builder(name).build()) { @Override public Number getValue() { return metrics.getExecutionTimePercentile(percentile); } }; } protected Monitor<Number> getTotalLatencyMeanMonitor(final String name) { return new GaugeMetric(MonitorConfig.builder(name).build()) { @Override public Number getValue() { return metrics.getTotalTimeMean(); } }; } protected Monitor<Number> getTotalLatencyPercentileMonitor(final String name, final double percentile) { return new GaugeMetric(MonitorConfig.builder(name).build()) { @Override public Number getValue() { return metrics.getTotalTimePercentile(percentile); } }; } protected Monitor<Number> getCurrentValueMonitor(final String name, final Func0<Number> metricToEvaluate) { return new GaugeMetric(MonitorConfig.builder(name).build()) { @Override public Number getValue() { return metricToEvaluate.call(); } }; } protected Monitor<Number> getCurrentValueMonitor(final String name, final Func0<Number> metricToEvaluate, final Tag tag) { return new GaugeMetric(MonitorConfig.builder(name).withTag(tag).build()) { @Override public Number getValue() { return metricToEvaluate.call(); } }; } /** * Servo will flatten metric names as: getServoTypeTag()_getServoInstanceTag()_monitorName * * An implementation note. If there's a version mismatch between hystrix-core and hystrix-servo-metric-publisher, * the code below may reference a HystrixEventType that does not exist in hystrix-core. If this happens, * a j.l.NoSuchFieldError occurs. Since this data is not being generated by hystrix-core, it's safe to count it as 0 * and we should log an error to get users to update their dependency set. * */ private List<Monitor<?>> getServoMonitors() { List<Monitor<?>> monitors = new ArrayList<Monitor<?>>(); monitors.add(new InformationalMetric<Boolean>(MonitorConfig.builder("isCircuitBreakerOpen").build()) { @Override public Boolean getValue() { return circuitBreaker.isOpen(); } }); // allow Servo and monitor to know exactly at what point in time these stats are for so they can be plotted accurately monitors.add(getCurrentValueMonitor("currentTime", currentTimeThunk, DataSourceLevel.DEBUG)); // cumulative counts monitors.add(safelyGetCumulativeMonitor("countBadRequests", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.BAD_REQUEST; } })); monitors.add(safelyGetCumulativeMonitor("countCollapsedRequests", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.COLLAPSED; } })); monitors.add(safelyGetCumulativeMonitor("countEmit", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.EMIT; } })); monitors.add(safelyGetCumulativeMonitor("countExceptionsThrown", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.EXCEPTION_THROWN; } })); monitors.add(safelyGetCumulativeMonitor("countFailure", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.FAILURE; } })); monitors.add(safelyGetCumulativeMonitor("countFallbackEmit", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.FALLBACK_EMIT; } })); monitors.add(safelyGetCumulativeMonitor("countFallbackFailure", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.FALLBACK_FAILURE; } })); monitors.add(safelyGetCumulativeMonitor("countFallbackMissing", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.FALLBACK_MISSING; } })); monitors.add(safelyGetCumulativeMonitor("countFallbackRejection", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.FALLBACK_REJECTION; } })); monitors.add(safelyGetCumulativeMonitor("countFallbackSuccess", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.FALLBACK_SUCCESS; } })); monitors.add(safelyGetCumulativeMonitor("countResponsesFromCache", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.RESPONSE_FROM_CACHE; } })); monitors.add(safelyGetCumulativeMonitor("countSemaphoreRejected", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.SEMAPHORE_REJECTED; } })); monitors.add(safelyGetCumulativeMonitor("countShortCircuited", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.SHORT_CIRCUITED; } })); monitors.add(safelyGetCumulativeMonitor("countSuccess", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.SUCCESS; } })); monitors.add(safelyGetCumulativeMonitor("countThreadPoolRejected", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.THREAD_POOL_REJECTED; } })); monitors.add(safelyGetCumulativeMonitor("countTimeout", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.TIMEOUT; } })); // rolling counts monitors.add(safelyGetRollingMonitor("rollingCountBadRequests", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.BAD_REQUEST; } })); monitors.add(safelyGetRollingMonitor("rollingCountCollapsedRequests", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.COLLAPSED; } })); monitors.add(safelyGetRollingMonitor("rollingCountEmit", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.EMIT; } })); monitors.add(safelyGetRollingMonitor("rollingCountExceptionsThrown", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.EXCEPTION_THROWN; } })); monitors.add(safelyGetRollingMonitor("rollingCountFailure", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.FAILURE; } })); monitors.add(safelyGetRollingMonitor("rollingCountFallbackEmit", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.FALLBACK_EMIT; } })); monitors.add(safelyGetRollingMonitor("rollingCountFallbackFailure", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.FALLBACK_FAILURE; } })); monitors.add(safelyGetRollingMonitor("rollingCountFallbackMissing", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.FALLBACK_MISSING; } })); monitors.add(safelyGetRollingMonitor("rollingCountFallbackRejection", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.FALLBACK_REJECTION; } })); monitors.add(safelyGetRollingMonitor("rollingCountFallbackSuccess", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.FALLBACK_SUCCESS; } })); monitors.add(safelyGetRollingMonitor("rollingCountResponsesFromCache", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.RESPONSE_FROM_CACHE; } })); monitors.add(safelyGetRollingMonitor("rollingCountSemaphoreRejected", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.SEMAPHORE_REJECTED; } })); monitors.add(safelyGetRollingMonitor("rollingCountShortCircuited", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.SHORT_CIRCUITED; } })); monitors.add(safelyGetRollingMonitor("rollingCountSuccess", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.SUCCESS; } })); monitors.add(safelyGetRollingMonitor("rollingCountThreadPoolRejected", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.THREAD_POOL_REJECTED; } })); monitors.add(safelyGetRollingMonitor("rollingCountTimeout", new Func0<HystrixEventType>() { @Override public HystrixEventType call() { return HystrixEventType.TIMEOUT; } })); // the number of executionSemaphorePermits in use right now monitors.add(getCurrentValueMonitor("executionSemaphorePermitsInUse", currentConcurrentExecutionCountThunk)); // error percentage derived from current metrics monitors.add(getCurrentValueMonitor("errorPercentage", errorPercentageThunk)); // execution latency metrics monitors.add(getExecutionLatencyMeanMonitor("latencyExecute_mean")); monitors.add(getExecutionLatencyPercentileMonitor("latencyExecute_percentile_5", 5)); monitors.add(getExecutionLatencyPercentileMonitor("latencyExecute_percentile_25", 25)); monitors.add(getExecutionLatencyPercentileMonitor("latencyExecute_percentile_50", 50)); monitors.add(getExecutionLatencyPercentileMonitor("latencyExecute_percentile_75", 75)); monitors.add(getExecutionLatencyPercentileMonitor("latencyExecute_percentile_90", 90)); monitors.add(getExecutionLatencyPercentileMonitor("latencyExecute_percentile_99", 99)); monitors.add(getExecutionLatencyPercentileMonitor("latencyExecute_percentile_995", 99.5)); // total latency metrics monitors.add(getTotalLatencyMeanMonitor("latencyTotal_mean")); monitors.add(getTotalLatencyPercentileMonitor("latencyTotal_percentile_5", 5)); monitors.add(getTotalLatencyPercentileMonitor("latencyTotal_percentile_25", 25)); monitors.add(getTotalLatencyPercentileMonitor("latencyTotal_percentile_50", 50)); monitors.add(getTotalLatencyPercentileMonitor("latencyTotal_percentile_75", 75)); monitors.add(getTotalLatencyPercentileMonitor("latencyTotal_percentile_90", 90)); monitors.add(getTotalLatencyPercentileMonitor("latencyTotal_percentile_99", 99)); monitors.add(getTotalLatencyPercentileMonitor("latencyTotal_percentile_995", 99.5)); // group monitors.add(new InformationalMetric<String>(MonitorConfig.builder("commandGroup").build()) { @Override public String getValue() { return commandGroupKey != null ? commandGroupKey.name() : null; } }); // properties (so the values can be inspected and monitored) monitors.add(new InformationalMetric<Number>(MonitorConfig.builder("propertyValue_rollingStatisticalWindowInMilliseconds").build()) { @Override public Number getValue() { return properties.metricsRollingStatisticalWindowInMilliseconds().get(); } }); monitors.add(new InformationalMetric<Number>(MonitorConfig.builder("propertyValue_circuitBreakerRequestVolumeThreshold").build()) { @Override public Number getValue() { return properties.circuitBreakerRequestVolumeThreshold().get(); } }); monitors.add(new InformationalMetric<Number>(MonitorConfig.builder("propertyValue_circuitBreakerSleepWindowInMilliseconds").build()) { @Override public Number getValue() { return properties.circuitBreakerSleepWindowInMilliseconds().get(); } }); monitors.add(new InformationalMetric<Number>(MonitorConfig.builder("propertyValue_circuitBreakerErrorThresholdPercentage").build()) { @Override public Number getValue() { return properties.circuitBreakerErrorThresholdPercentage().get(); } }); monitors.add(new InformationalMetric<Boolean>(MonitorConfig.builder("propertyValue_circuitBreakerForceOpen").build()) { @Override public Boolean getValue() { return properties.circuitBreakerForceOpen().get(); } }); monitors.add(new InformationalMetric<Boolean>(MonitorConfig.builder("propertyValue_circuitBreakerForceClosed").build()) { @Override public Boolean getValue() { return properties.circuitBreakerForceClosed().get(); } }); monitors.add(new InformationalMetric<Number>(MonitorConfig.builder("propertyValue_executionIsolationThreadTimeoutInMilliseconds").build()) { @Override public Number getValue() { return properties.executionTimeoutInMilliseconds().get(); } }); monitors.add(new InformationalMetric<Number>(MonitorConfig.builder("propertyValue_executionTimeoutInMilliseconds").build()) { @Override public Number getValue() { return properties.executionTimeoutInMilliseconds().get(); } }); monitors.add(new InformationalMetric<String>(MonitorConfig.builder("propertyValue_executionIsolationStrategy").build()) { @Override public String getValue() { return properties.executionIsolationStrategy().get().name(); } }); monitors.add(new InformationalMetric<Boolean>(MonitorConfig.builder("propertyValue_metricsRollingPercentileEnabled").build()) { @Override public Boolean getValue() { return properties.metricsRollingPercentileEnabled().get(); } }); monitors.add(new InformationalMetric<Boolean>(MonitorConfig.builder("propertyValue_requestCacheEnabled").build()) { @Override public Boolean getValue() { return properties.requestCacheEnabled().get(); } }); monitors.add(new InformationalMetric<Boolean>(MonitorConfig.builder("propertyValue_requestLogEnabled").build()) { @Override public Boolean getValue() { return properties.requestLogEnabled().get(); } }); monitors.add(new InformationalMetric<Number>(MonitorConfig.builder("propertyValue_executionIsolationSemaphoreMaxConcurrentRequests").build()) { @Override public Number getValue() { return properties.executionIsolationSemaphoreMaxConcurrentRequests().get(); } }); monitors.add(new InformationalMetric<Number>(MonitorConfig.builder("propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests").build()) { @Override public Number getValue() { return properties.fallbackIsolationSemaphoreMaxConcurrentRequests().get(); } }); return monitors; } }
4,389
0
Create_ds/Hystrix/hystrix-contrib/hystrix-servo-metrics-publisher/src/main/java/com/netflix/hystrix/contrib
Create_ds/Hystrix/hystrix-contrib/hystrix-servo-metrics-publisher/src/main/java/com/netflix/hystrix/contrib/servopublisher/HystrixServoMetricsPublisherThreadPool.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.contrib.servopublisher; import com.netflix.hystrix.HystrixEventType; import com.netflix.hystrix.HystrixThreadPoolKey; import com.netflix.hystrix.HystrixThreadPoolMetrics; import com.netflix.hystrix.HystrixThreadPoolProperties; import com.netflix.hystrix.metric.consumer.CumulativeThreadPoolEventCounterStream; import com.netflix.hystrix.metric.consumer.RollingThreadPoolMaxConcurrencyStream; import com.netflix.hystrix.metric.consumer.RollingThreadPoolEventCounterStream; import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherThreadPool; import com.netflix.servo.DefaultMonitorRegistry; import com.netflix.servo.annotations.DataSourceLevel; import com.netflix.servo.monitor.BasicCompositeMonitor; import com.netflix.servo.monitor.Monitor; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.tag.Tag; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.functions.Func0; import java.util.ArrayList; import java.util.List; /** * Implementation of {@link HystrixMetricsPublisherThreadPool} using Servo (https://github.com/Netflix/servo) */ public class HystrixServoMetricsPublisherThreadPool extends HystrixServoMetricsPublisherAbstract implements HystrixMetricsPublisherThreadPool { private static final Logger logger = LoggerFactory.getLogger(HystrixServoMetricsPublisherThreadPool.class); private final HystrixThreadPoolKey key; private final HystrixThreadPoolMetrics metrics; private final HystrixThreadPoolProperties properties; private final Tag servoInstanceTag; private final Tag servoTypeTag; public HystrixServoMetricsPublisherThreadPool(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolMetrics metrics, HystrixThreadPoolProperties properties) { this.key = threadPoolKey; this.metrics = metrics; this.properties = properties; this.servoInstanceTag = new Tag() { @Override public String getKey() { return "instance"; } @Override public String getValue() { return key.name(); } @Override public String tagString() { return key.name(); } }; this.servoTypeTag = new Tag() { @Override public String getKey() { return "type"; } @Override public String getValue() { return "HystrixThreadPool"; } @Override public String tagString() { return "HystrixThreadPool"; } }; } @Override public void initialize() { /* list of monitors */ List<Monitor<?>> monitors = getServoMonitors(); // publish metrics together under a single composite (it seems this name is ignored) MonitorConfig commandMetricsConfig = MonitorConfig.builder("HystrixThreadPool_" + key.name()).build(); BasicCompositeMonitor commandMetricsMonitor = new BasicCompositeMonitor(commandMetricsConfig, monitors); DefaultMonitorRegistry.getInstance().register(commandMetricsMonitor); RollingThreadPoolEventCounterStream.getInstance(key, properties).startCachingStreamValuesIfUnstarted(); CumulativeThreadPoolEventCounterStream.getInstance(key, properties).startCachingStreamValuesIfUnstarted(); RollingThreadPoolMaxConcurrencyStream.getInstance(key, properties).startCachingStreamValuesIfUnstarted(); } @Override protected Tag getServoTypeTag() { return servoTypeTag; } @Override protected Tag getServoInstanceTag() { return servoInstanceTag; } protected Monitor<Number> safelyGetCumulativeMonitor(final String name, final Func0<HystrixEventType.ThreadPool> eventThunk) { return new CounterMetric(MonitorConfig.builder(name).withTag(getServoTypeTag()).withTag(getServoInstanceTag()).build()) { @Override public Long getValue() { try { return metrics.getCumulativeCount(eventThunk.call()); } catch (NoSuchFieldError error) { logger.error("While publishing Servo metrics, error looking up eventType for : {}. Please check that all Hystrix versions are the same!", name); return 0L; } } }; } protected Monitor<Number> safelyGetRollingMonitor(final String name, final Func0<HystrixEventType.ThreadPool> eventThunk) { return new GaugeMetric(MonitorConfig.builder(name).withTag(DataSourceLevel.DEBUG).withTag(getServoTypeTag()).withTag(getServoInstanceTag()).build()) { @Override public Long getValue() { try { return metrics.getRollingCount(eventThunk.call()); } catch (NoSuchFieldError error) { logger.error("While publishing Servo metrics, error looking up eventType for : {}. Please check that all Hystrix versions are the same!", name); return 0L; } } }; } /** * Servo will flatten metric names as: getServoTypeTag()_getServoInstanceTag()_monitorName * * An implementation note. If there's a version mismatch between hystrix-core and hystrix-servo-metric-publisher, * the code below may reference a HystrixEventType.ThreadPool that does not exist in hystrix-core. If this happens, * a j.l.NoSuchFieldError occurs. Since this data is not being generated by hystrix-core, it's safe to count it as 0 * and we should log an error to get users to update their dependency set. */ private List<Monitor<?>> getServoMonitors() { List<Monitor<?>> monitors = new ArrayList<Monitor<?>>(); monitors.add(new InformationalMetric<String>(MonitorConfig.builder("name").build()) { @Override public String getValue() { return key.name(); } }); // allow Servo and monitor to know exactly at what point in time these stats are for so they can be plotted accurately monitors.add(new GaugeMetric(MonitorConfig.builder("currentTime").withTag(DataSourceLevel.DEBUG).build()) { @Override public Number getValue() { return System.currentTimeMillis(); } }); monitors.add(new GaugeMetric(MonitorConfig.builder("threadActiveCount").build()) { @Override public Number getValue() { return metrics.getCurrentActiveCount(); } }); monitors.add(new GaugeMetric(MonitorConfig.builder("completedTaskCount").build()) { @Override public Number getValue() { return metrics.getCurrentCompletedTaskCount(); } }); monitors.add(new GaugeMetric(MonitorConfig.builder("largestPoolSize").build()) { @Override public Number getValue() { return metrics.getCurrentLargestPoolSize(); } }); monitors.add(new GaugeMetric(MonitorConfig.builder("totalTaskCount").build()) { @Override public Number getValue() { return metrics.getCurrentTaskCount(); } }); monitors.add(new GaugeMetric(MonitorConfig.builder("queueSize").build()) { @Override public Number getValue() { return metrics.getCurrentQueueSize(); } }); monitors.add(new GaugeMetric(MonitorConfig.builder("rollingMaxActiveThreads").withTag(DataSourceLevel.DEBUG).build()) { @Override public Number getValue() { return metrics.getRollingMaxActiveThreads(); } }); //thread pool event monitors monitors.add(safelyGetCumulativeMonitor("countThreadsExecuted", new Func0<HystrixEventType.ThreadPool>() { @Override public HystrixEventType.ThreadPool call() { return HystrixEventType.ThreadPool.EXECUTED; } })); monitors.add(safelyGetCumulativeMonitor("countThreadsRejected", new Func0<HystrixEventType.ThreadPool>() { @Override public HystrixEventType.ThreadPool call() { return HystrixEventType.ThreadPool.REJECTED; } })); monitors.add(safelyGetRollingMonitor("rollingCountThreadsExecuted", new Func0<HystrixEventType.ThreadPool>() { @Override public HystrixEventType.ThreadPool call() { return HystrixEventType.ThreadPool.EXECUTED; } })); monitors.add(safelyGetRollingMonitor("rollingCountCommandsRejected", new Func0<HystrixEventType.ThreadPool>() { @Override public HystrixEventType.ThreadPool call() { return HystrixEventType.ThreadPool.REJECTED; } })); // properties monitors.add(new InformationalMetric<Number>(MonitorConfig.builder("propertyValue_corePoolSize").build()) { @Override public Number getValue() { return properties.coreSize().get(); } }); monitors.add(new InformationalMetric<Number>(MonitorConfig.builder("propertyValue_maximumSize").build()) { @Override public Number getValue() { return properties.maximumSize().get(); } }); monitors.add(new InformationalMetric<Number>(MonitorConfig.builder("propertyValue_actualMaximumSize").build()) { @Override public Number getValue() { return properties.actualMaximumSize(); } }); monitors.add(new InformationalMetric<Number>(MonitorConfig.builder("propertyValue_keepAliveTimeInMinutes").build()) { @Override public Number getValue() { return properties.keepAliveTimeMinutes().get(); } }); monitors.add(new InformationalMetric<Number>(MonitorConfig.builder("propertyValue_queueSizeRejectionThreshold").build()) { @Override public Number getValue() { return properties.queueSizeRejectionThreshold().get(); } }); monitors.add(new InformationalMetric<Number>(MonitorConfig.builder("propertyValue_maxQueueSize").build()) { @Override public Number getValue() { return properties.maxQueueSize().get(); } }); return monitors; } }
4,390
0
Create_ds/Hystrix/hystrix-contrib/hystrix-servo-metrics-publisher/src/main/java/com/netflix/hystrix/contrib
Create_ds/Hystrix/hystrix-contrib/hystrix-servo-metrics-publisher/src/main/java/com/netflix/hystrix/contrib/servopublisher/HystrixServoMetricsPublisherAbstract.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.contrib.servopublisher; import com.netflix.hystrix.HystrixMetrics; import com.netflix.hystrix.util.HystrixRollingNumberEvent; import com.netflix.servo.annotations.DataSourceLevel; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.monitor.AbstractMonitor; import com.netflix.servo.monitor.Counter; import com.netflix.servo.monitor.Gauge; import com.netflix.servo.monitor.Monitor; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.tag.Tag; /** * Utility used for Servo (https://github.com/Netflix/servo) based implementations of metrics publishers. */ /* package */abstract class HystrixServoMetricsPublisherAbstract { protected abstract Tag getServoTypeTag(); protected abstract Tag getServoInstanceTag(); protected abstract class InformationalMetric<K> extends AbstractMonitor<K> { public InformationalMetric(MonitorConfig config) { super(config.withAdditionalTag(DataSourceType.INFORMATIONAL).withAdditionalTag(getServoTypeTag()).withAdditionalTag(getServoInstanceTag())); } @Override public K getValue(int n) { return getValue(); } @Override public abstract K getValue(); } protected abstract class CounterMetric extends AbstractMonitor<Number> implements Counter { public CounterMetric(MonitorConfig config) { super(config.withAdditionalTag(DataSourceType.COUNTER).withAdditionalTag(getServoTypeTag()).withAdditionalTag(getServoInstanceTag())); } @Override public Number getValue(int n) { return getValue(); } @Override public abstract Number getValue(); @Override public void increment() { throw new IllegalStateException("We are wrapping a value instead."); } @Override public void increment(long arg0) { throw new IllegalStateException("We are wrapping a value instead."); } } protected abstract class GaugeMetric extends AbstractMonitor<Number> implements Gauge<Number> { public GaugeMetric(MonitorConfig config) { super(config.withAdditionalTag(DataSourceType.GAUGE).withAdditionalTag(getServoTypeTag()).withAdditionalTag(getServoInstanceTag())); } @Override public Number getValue(int n) { return getValue(); } @Override public abstract Number getValue(); } protected Monitor<?> getCumulativeCountForEvent(String name, final HystrixMetrics metrics, final HystrixRollingNumberEvent event) { return new CounterMetric(MonitorConfig.builder(name).withTag(getServoTypeTag()).withTag(getServoInstanceTag()).build()) { @Override public Long getValue() { return metrics.getCumulativeCount(event); } }; } protected Monitor<?> getRollingCountForEvent(String name, final HystrixMetrics metrics, final HystrixRollingNumberEvent event) { return new GaugeMetric(MonitorConfig.builder(name).withTag(DataSourceLevel.DEBUG).withTag(getServoTypeTag()).withTag(getServoInstanceTag()).build()) { @Override public Number getValue() { return metrics.getRollingCount(event); } }; } }
4,391
0
Create_ds/Hystrix/hystrix-contrib/hystrix-servo-metrics-publisher/src/main/java/com/netflix/hystrix/contrib
Create_ds/Hystrix/hystrix-contrib/hystrix-servo-metrics-publisher/src/main/java/com/netflix/hystrix/contrib/servopublisher/HystrixServoMetricsPublisherCollapser.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.contrib.servopublisher; import com.netflix.hystrix.HystrixCollapserKey; import com.netflix.hystrix.HystrixCollapserMetrics; import com.netflix.hystrix.HystrixCollapserProperties; import com.netflix.hystrix.HystrixEventType; import com.netflix.hystrix.metric.consumer.CumulativeCollapserEventCounterStream; import com.netflix.hystrix.metric.consumer.RollingCollapserBatchSizeDistributionStream; import com.netflix.hystrix.metric.consumer.RollingCollapserEventCounterStream; import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherCollapser; import com.netflix.servo.DefaultMonitorRegistry; import com.netflix.servo.annotations.DataSourceLevel; import com.netflix.servo.monitor.BasicCompositeMonitor; import com.netflix.servo.monitor.Monitor; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.tag.Tag; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.functions.Func0; import java.util.ArrayList; import java.util.List; /** * Implementation of {@link HystrixMetricsPublisherCollapser} using Servo (https://github.com/Netflix/servo) */ public class HystrixServoMetricsPublisherCollapser extends HystrixServoMetricsPublisherAbstract implements HystrixMetricsPublisherCollapser { private static final Logger logger = LoggerFactory.getLogger(HystrixServoMetricsPublisherCollapser.class); private final HystrixCollapserKey key; private final HystrixCollapserMetrics metrics; private final HystrixCollapserProperties properties; private final Tag servoInstanceTag; private final Tag servoTypeTag; public HystrixServoMetricsPublisherCollapser(HystrixCollapserKey threadPoolKey, HystrixCollapserMetrics metrics, HystrixCollapserProperties properties) { this.key = threadPoolKey; this.metrics = metrics; this.properties = properties; this.servoInstanceTag = new Tag() { @Override public String getKey() { return "instance"; } @Override public String getValue() { return key.name(); } @Override public String tagString() { return key.name(); } }; this.servoTypeTag = new Tag() { @Override public String getKey() { return "type"; } @Override public String getValue() { return "HystrixCollapser"; } @Override public String tagString() { return "HystrixCollapser"; } }; } @Override public void initialize() { /* list of monitors */ List<Monitor<?>> monitors = getServoMonitors(); // publish metrics together under a single composite (it seems this name is ignored) MonitorConfig commandMetricsConfig = MonitorConfig.builder("HystrixCollapser_" + key.name()).build(); BasicCompositeMonitor commandMetricsMonitor = new BasicCompositeMonitor(commandMetricsConfig, monitors); DefaultMonitorRegistry.getInstance().register(commandMetricsMonitor); RollingCollapserBatchSizeDistributionStream.getInstance(key, properties).startCachingStreamValuesIfUnstarted(); RollingCollapserEventCounterStream.getInstance(key, properties).startCachingStreamValuesIfUnstarted(); CumulativeCollapserEventCounterStream.getInstance(key, properties).startCachingStreamValuesIfUnstarted(); } @Override protected Tag getServoTypeTag() { return servoTypeTag; } @Override protected Tag getServoInstanceTag() { return servoInstanceTag; } protected Monitor<Number> getCumulativeMonitor(final String name, final HystrixEventType.Collapser event) { return new CounterMetric(MonitorConfig.builder(name).withTag(getServoTypeTag()).withTag(getServoInstanceTag()).build()) { @Override public Long getValue() { return metrics.getCumulativeCount(event); } }; } protected Monitor<Number> safelyGetCumulativeMonitor(final String name, final Func0<HystrixEventType.Collapser> eventThunk) { return new CounterMetric(MonitorConfig.builder(name).withTag(getServoTypeTag()).withTag(getServoInstanceTag()).build()) { @Override public Long getValue() { try { return metrics.getCumulativeCount(eventThunk.call()); } catch (NoSuchFieldError error) { logger.error("While publishing Servo metrics, error looking up eventType for : {}. Please check that all Hystrix versions are the same!", name); return 0L; } } }; } protected Monitor<Number> getRollingMonitor(final String name, final HystrixEventType.Collapser event) { return new GaugeMetric(MonitorConfig.builder(name).withTag(DataSourceLevel.DEBUG).withTag(getServoTypeTag()).withTag(getServoInstanceTag()).build()) { @Override public Long getValue() { return metrics.getRollingCount(event); } }; } protected Monitor<Number> safelyGetRollingMonitor(final String name, final Func0<HystrixEventType.Collapser> eventThunk) { return new GaugeMetric(MonitorConfig.builder(name).withTag(DataSourceLevel.DEBUG).withTag(getServoTypeTag()).withTag(getServoInstanceTag()).build()) { @Override public Long getValue() { try { return metrics.getRollingCount(eventThunk.call()); } catch (NoSuchFieldError error) { logger.error("While publishing Servo metrics, error looking up eventType for : {}. Please check that all Hystrix versions are the same!", name); return 0L; } } }; } protected Monitor<Number> getBatchSizeMeanMonitor(final String name) { return new GaugeMetric(MonitorConfig.builder(name).build()) { @Override public Number getValue() { return metrics.getBatchSizeMean(); } }; } protected Monitor<Number> getBatchSizePercentileMonitor(final String name, final double percentile) { return new GaugeMetric(MonitorConfig.builder(name).build()) { @Override public Number getValue() { return metrics.getBatchSizePercentile(percentile); } }; } protected Monitor<Number> getShardSizeMeanMonitor(final String name) { return new GaugeMetric(MonitorConfig.builder(name).build()) { @Override public Number getValue() { return metrics.getShardSizeMean(); } }; } protected Monitor<Number> getShardSizePercentileMonitor(final String name, final double percentile) { return new GaugeMetric(MonitorConfig.builder(name).build()) { @Override public Number getValue() { return metrics.getShardSizePercentile(percentile); } }; } /** * Servo will flatten metric names as: getServoTypeTag()_getServoInstanceTag()_monitorName * * An implementation note. If there's a version mismatch between hystrix-core and hystrix-servo-metric-publisher, * the code below may reference a HystrixEventType.Collapser that does not exist in hystrix-core. If this happens, * a j.l.NoSuchFieldError occurs. Since this data is not being generated by hystrix-core, it's safe to count it as 0 * and we should log an error to get users to update their dependency set. */ private List<Monitor<?>> getServoMonitors() { List<Monitor<?>> monitors = new ArrayList<Monitor<?>>(); monitors.add(new InformationalMetric<String>(MonitorConfig.builder("name").build()) { @Override public String getValue() { return key.name(); } }); // allow Servo and monitor to know exactly at what point in time these stats are for so they can be plotted accurately monitors.add(new GaugeMetric(MonitorConfig.builder("currentTime").withTag(DataSourceLevel.DEBUG).build()) { @Override public Number getValue() { return System.currentTimeMillis(); } }); //collapser event cumulative metrics monitors.add(safelyGetCumulativeMonitor("countRequestsBatched", new Func0<HystrixEventType.Collapser>() { @Override public HystrixEventType.Collapser call() { return HystrixEventType.Collapser.ADDED_TO_BATCH; } })); monitors.add(safelyGetCumulativeMonitor("countBatches", new Func0<HystrixEventType.Collapser>() { @Override public HystrixEventType.Collapser call() { return HystrixEventType.Collapser.BATCH_EXECUTED; } })); monitors.add(safelyGetCumulativeMonitor("countResponsesFromCache", new Func0<HystrixEventType.Collapser>() { @Override public HystrixEventType.Collapser call() { return HystrixEventType.Collapser.RESPONSE_FROM_CACHE; } })); //batch size distribution metrics monitors.add(getBatchSizeMeanMonitor("batchSize_mean")); monitors.add(getBatchSizePercentileMonitor("batchSize_percentile_25", 25)); monitors.add(getBatchSizePercentileMonitor("batchSize_percentile_50", 50)); monitors.add(getBatchSizePercentileMonitor("batchSize_percentile_75", 75)); monitors.add(getBatchSizePercentileMonitor("batchSize_percentile_95", 95)); monitors.add(getBatchSizePercentileMonitor("batchSize_percentile_99", 99)); monitors.add(getBatchSizePercentileMonitor("batchSize_percentile_99_5", 99.5)); monitors.add(getBatchSizePercentileMonitor("batchSize_percentile_100", 100)); //shard size distribution metrics monitors.add(getShardSizeMeanMonitor("shardSize_mean")); monitors.add(getShardSizePercentileMonitor("shardSize_percentile_25", 25)); monitors.add(getShardSizePercentileMonitor("shardSize_percentile_50", 50)); monitors.add(getShardSizePercentileMonitor("shardSize_percentile_75", 75)); monitors.add(getShardSizePercentileMonitor("shardSize_percentile_95", 95)); monitors.add(getShardSizePercentileMonitor("shardSize_percentile_99", 99)); monitors.add(getShardSizePercentileMonitor("shardSize_percentile_99_5", 99.5)); monitors.add(getShardSizePercentileMonitor("shardSize_percentile_100", 100)); // properties (so the values can be inspected and monitored) monitors.add(new InformationalMetric<Number>(MonitorConfig.builder("propertyValue_rollingStatisticalWindowInMilliseconds").build()) { @Override public Number getValue() { return properties.metricsRollingStatisticalWindowInMilliseconds().get(); } }); monitors.add(new InformationalMetric<Boolean>(MonitorConfig.builder("propertyValue_requestCacheEnabled").build()) { @Override public Boolean getValue() { return properties.requestCacheEnabled().get(); } }); monitors.add(new InformationalMetric<Number>(MonitorConfig.builder("propertyValue_maxRequestsInBatch").build()) { @Override public Number getValue() { return properties.maxRequestsInBatch().get(); } }); monitors.add(new InformationalMetric<Number>(MonitorConfig.builder("propertyValue_timerDelayInMilliseconds").build()) { @Override public Number getValue() { return properties.timerDelayInMilliseconds().get(); } }); return monitors; } }
4,392
0
Create_ds/Hystrix/hystrix-contrib/hystrix-servo-metrics-publisher/src/main/java/com/netflix/hystrix/contrib
Create_ds/Hystrix/hystrix-contrib/hystrix-servo-metrics-publisher/src/main/java/com/netflix/hystrix/contrib/servopublisher/HystrixServoMetricsPublisher.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.contrib.servopublisher; import com.netflix.hystrix.HystrixCircuitBreaker; import com.netflix.hystrix.HystrixCollapserKey; import com.netflix.hystrix.HystrixCollapserMetrics; import com.netflix.hystrix.HystrixCollapserProperties; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandMetrics; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixThreadPoolKey; import com.netflix.hystrix.HystrixThreadPoolMetrics; import com.netflix.hystrix.HystrixThreadPoolProperties; import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisher; import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherCollapser; import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherCommand; import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherThreadPool; /** * Servo implementation of {@link HystrixMetricsPublisher}. * <p> * See <a href="https://github.com/Netflix/Hystrix/wiki/Plugins">Wiki docs</a> about plugins for more information. */ public class HystrixServoMetricsPublisher extends HystrixMetricsPublisher { private static HystrixServoMetricsPublisher INSTANCE = null; public static HystrixServoMetricsPublisher getInstance() { if (INSTANCE == null) { HystrixServoMetricsPublisher temp = createInstance(); INSTANCE = temp; } return INSTANCE; } private static synchronized HystrixServoMetricsPublisher createInstance() { if (INSTANCE == null) { return new HystrixServoMetricsPublisher(); } else { return INSTANCE; } } private HystrixServoMetricsPublisher() { } @Override public HystrixMetricsPublisherCommand getMetricsPublisherForCommand(HystrixCommandKey commandKey, HystrixCommandGroupKey commandGroupKey, HystrixCommandMetrics metrics, HystrixCircuitBreaker circuitBreaker, HystrixCommandProperties properties) { return new HystrixServoMetricsPublisherCommand(commandKey, commandGroupKey, metrics, circuitBreaker, properties); } @Override public HystrixMetricsPublisherThreadPool getMetricsPublisherForThreadPool(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolMetrics metrics, HystrixThreadPoolProperties properties) { return new HystrixServoMetricsPublisherThreadPool(threadPoolKey, metrics, properties); } @Override public HystrixMetricsPublisherCollapser getMetricsPublisherForCollapser(HystrixCollapserKey collapserKey, HystrixCollapserMetrics metrics, HystrixCollapserProperties properties) { return new HystrixServoMetricsPublisherCollapser(collapserKey, metrics, properties); } }
4,393
0
Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica
Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/cache/CacheInvocationParameterTest.java
/** * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.contrib.javanica.cache; import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheKey; import org.junit.Test; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class CacheInvocationParameterTest { @Test public void testCacheInvocationParameterConstructor() throws NoSuchMethodException { // given Class<?> rawType = String.class; Object value = "test"; Method method = CacheInvocationParameterTest.class.getDeclaredMethod("stabMethod", String.class); method.setAccessible(true); Annotation[] annotations = method.getParameterAnnotations()[0]; int position = 0; // when CacheInvocationParameter cacheInvocationParameter = new CacheInvocationParameter(rawType, value, annotations, position); // then assertEquals(rawType, cacheInvocationParameter.getRawType()); assertEquals(value, cacheInvocationParameter.getValue()); assertEquals(annotations[0], cacheInvocationParameter.getCacheKeyAnnotation()); assertTrue(cacheInvocationParameter.hasCacheKeyAnnotation()); assertTrue(cacheInvocationParameter.getAnnotations().contains(annotations[0])); try { cacheInvocationParameter.getAnnotations().clear(); fail(); } catch (Throwable e) { // getAnnotations should return immutable set. } } private static void stabMethod(@CacheKey String val) { } }
4,394
0
Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica
Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/cache/HystrixCacheKeyGeneratorTest.java
/** * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.contrib.javanica.cache; import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheKey; import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult; import com.netflix.hystrix.contrib.javanica.command.MetaHolder; import org.junit.Test; import static org.junit.Assert.assertEquals; public class HystrixCacheKeyGeneratorTest { @Test public void testGenerateCacheKey_givenUser_shouldReturnCorrectCacheKey() throws NoSuchMethodException { // given TestCacheClass testCacheClass = new TestCacheClass(); String id = "1"; User user = new User(); user.setId(id); Profile profile = new Profile("user name"); user.setProfile(profile); String expectedKey = id + user.getProfile().getName(); MetaHolder metaHolder = MetaHolder.builder() .method(TestCacheClass.class.getMethod("cacheResultMethod", String.class, User.class)) .args(new Object[]{id, user}) .obj(testCacheClass).build(); CacheInvocationContext<CacheResult> context = CacheInvocationContextFactory.createCacheResultInvocationContext(metaHolder); HystrixCacheKeyGenerator keyGenerator = HystrixCacheKeyGenerator.getInstance(); // when String actual = keyGenerator.generateCacheKey(context).getCacheKey(); // then assertEquals(expectedKey, actual); } @Test public void testGenerateCacheKey_givenUserWithNullProfile_shouldReturnCorrectCacheKey() throws NoSuchMethodException { // given TestCacheClass testCacheClass = new TestCacheClass(); String id = "1"; User user = new User(); user.setId(id); user.setProfile(null); String expectedKey = id; MetaHolder metaHolder = MetaHolder.builder() .method(TestCacheClass.class.getMethod("cacheResultMethod", String.class, User.class)) .args(new Object[]{id, user}) .obj(testCacheClass).build(); CacheInvocationContext<CacheResult> context = CacheInvocationContextFactory.createCacheResultInvocationContext(metaHolder); HystrixCacheKeyGenerator keyGenerator = HystrixCacheKeyGenerator.getInstance(); // when String actual = keyGenerator.generateCacheKey(context).getCacheKey(); // then assertEquals(expectedKey, actual); } @Test public void testGenerateCacheKey_givenCacheKeyMethodWithNoArguments_shouldReturnEmptyCacheKey() throws NoSuchMethodException { // given TestCacheClass testCacheClass = new TestCacheClass(); MetaHolder metaHolder = MetaHolder.builder() .method(TestCacheClass.class.getMethod("cacheResultMethod")) .args(new Object[]{}) .obj(testCacheClass).build(); CacheInvocationContext<CacheResult> context = CacheInvocationContextFactory.createCacheResultInvocationContext(metaHolder); HystrixCacheKeyGenerator keyGenerator = HystrixCacheKeyGenerator.getInstance(); // when HystrixGeneratedCacheKey actual = keyGenerator.generateCacheKey(context); // then assertEquals(DefaultHystrixGeneratedCacheKey.EMPTY, actual); } public static class TestCacheClass { @CacheResult public Object cacheResultMethod(@CacheKey String id, @CacheKey("profile.name") User user) { return "test"; } @CacheResult public Object cacheResultMethod() { return "test"; } } public static class User { private String id; private Profile profile; public String getId() { return id; } public void setId(String id) { this.id = id; } public Profile getProfile() { return profile; } public void setProfile(Profile profile) { this.profile = profile; } } public static class Profile { private String name; public Profile() { } public Profile(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } }
4,395
0
Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica
Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/cache/CacheInvocationContextFactoryTest.java
/** * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.contrib.javanica.cache; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheKey; import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove; import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult; import com.netflix.hystrix.contrib.javanica.command.MetaHolder; import com.netflix.hystrix.contrib.javanica.exception.HystrixCachingException; import org.junit.Test; import java.lang.annotation.Annotation; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * Unit test for {@link CacheInvocationContextFactory}. * * @author dmgcodevil */ public class CacheInvocationContextFactoryTest { @Test public void testCreateCacheResultInvocationContext_givenMethodAnnotatedWithCacheResult_shouldCreateCorrectCacheKeyInvocationContext() throws NoSuchMethodException { // given TestCacheClass testCacheClass = new TestCacheClass(); String param1 = "val_1"; String param2 = "val_2"; Integer param3 = 3; MetaHolder metaHolder = MetaHolder.builder() .method(TestCacheClass.class.getMethod("cacheResultMethod", String.class, String.class, Integer.class)) .args(new Object[]{param1, param2, param3}) .obj(testCacheClass).build(); // when CacheInvocationContext<CacheResult> context = CacheInvocationContextFactory.createCacheResultInvocationContext(metaHolder); // then assertNotNull(context.getKeyParameters()); assertEquals(2, context.getKeyParameters().size()); assertEquals(String.class, context.getKeyParameters().get(0).getRawType()); assertEquals(0, context.getKeyParameters().get(0).getPosition()); assertEquals(param1, context.getKeyParameters().get(0).getValue()); assertTrue(isAnnotationPresent(context.getKeyParameters().get(0), CacheKey.class)); assertEquals(Integer.class, context.getKeyParameters().get(1).getRawType()); assertEquals(2, context.getKeyParameters().get(1).getPosition()); assertEquals(param3, context.getKeyParameters().get(1).getValue()); assertTrue(isAnnotationPresent(context.getKeyParameters().get(1), CacheKey.class)); } @Test public void testCreateCacheRemoveInvocationContext_givenMethodAnnotatedWithCacheRemove_shouldCreateCorrectCacheKeyInvocationContext() throws NoSuchMethodException { // given TestCacheClass testCacheClass = new TestCacheClass(); String param1 = "val_1"; MetaHolder metaHolder = MetaHolder.builder() .method(TestCacheClass.class.getMethod("cacheRemoveMethod", String.class)) .args(new Object[]{param1}) .obj(testCacheClass).build(); // when CacheInvocationContext<CacheRemove> context = CacheInvocationContextFactory.createCacheRemoveInvocationContext(metaHolder); // then assertNotNull(context.getKeyParameters()); assertEquals(1, context.getKeyParameters().size()); CacheInvocationParameter actual = context.getKeyParameters().get(0); assertEquals(String.class, actual.getRawType()); assertEquals(param1, actual.getValue()); assertEquals(0, actual.getPosition()); } @Test(expected = HystrixCachingException.class) public void testCacheResultMethodWithWrongCacheKeyMethodSignature_givenWrongCacheKeyMethod_shouldThrowException() throws NoSuchMethodException { // given TestCacheClass testCacheClass = new TestCacheClass(); String param1 = "val_1"; MetaHolder metaHolder = MetaHolder.builder() .method(TestCacheClass.class.getMethod("cacheResultMethodWithWrongCacheKeyMethodSignature", String.class)) .args(new Object[]{param1}) .obj(testCacheClass).build(); // when CacheInvocationContext<CacheResult> context = CacheInvocationContextFactory.createCacheResultInvocationContext(metaHolder); // then expected HystrixCachingException } @Test(expected = HystrixCachingException.class) public void testCacheResultMethodWithCacheKeyMethodWithWrongReturnType_givenCacheKeyMethodWithWrongReturnType_shouldThrowException() throws NoSuchMethodException { // given TestCacheClass testCacheClass = new TestCacheClass(); String param1 = "val_1"; MetaHolder metaHolder = MetaHolder.builder() .method(TestCacheClass.class.getMethod("cacheResultMethodWithCacheKeyMethodWithWrongReturnType", String.class, String.class)) .args(new Object[]{param1}) .obj(testCacheClass).build(); // when CacheInvocationContext<CacheResult> context = CacheInvocationContextFactory.createCacheResultInvocationContext(metaHolder); System.out.println(context); // then expected HystrixCachingException } public static class TestCacheClass { @CacheResult public Object cacheResultMethod(@CacheKey String param1, String param2, @CacheKey Integer param3) { return null; } @CacheRemove(commandKey = "test") public Object cacheRemoveMethod(String param1) { return null; } @CacheResult(cacheKeyMethod = "cacheKeyMethodSignature") public Object cacheResultMethodWithWrongCacheKeyMethodSignature(String param2) { return null; } private String cacheKeyMethodSignature(String param1, String param2) { return null; } @CacheResult(cacheKeyMethod = "cacheKeyMethodWithWrongReturnType") public Object cacheResultMethodWithCacheKeyMethodWithWrongReturnType(String param1, String param2) { return null; } private Long cacheKeyMethodWithWrongReturnType(String param1, String param2) { return null; } } private static boolean isAnnotationPresent(CacheInvocationParameter parameter, final Class<?> annotation) { return Iterables.tryFind(parameter.getAnnotations(), new Predicate<Annotation>() { @Override public boolean apply(Annotation input) { return input.annotationType().equals(annotation); } }).isPresent(); } }
4,396
0
Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test
Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/CommonUtils.java
/** * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.contrib.javanica.test.common; import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandMetrics; import com.netflix.hystrix.HystrixInvokableInfo; import com.netflix.hystrix.HystrixRequestLog; import javax.annotation.Nullable; import java.util.Collection; import java.util.List; import static org.junit.Assert.assertTrue; public class CommonUtils { public HystrixCommandMetrics getMetrics(String commandKey) { return HystrixCommandMetrics.getInstance(HystrixCommandKey.Factory.asKey(commandKey)); } public static HystrixInvokableInfo<?> getLastExecutedCommand() { Collection<HystrixInvokableInfo<?>> executedCommands = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands(); return Iterables.getLast(executedCommands); } public static void assertExecutedCommands(String... commands) { Collection<HystrixInvokableInfo<?>> executedCommands = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands(); List<String> executedCommandsKeys = getExecutedCommandsKeys(Lists.newArrayList(executedCommands)); for (String cmd : commands) { assertTrue("command: '" + cmd + "' wasn't executed", executedCommandsKeys.contains(cmd)); } } public static List<String> getExecutedCommandsKeys() { Collection<HystrixInvokableInfo<?>> executedCommands = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands(); return getExecutedCommandsKeys(Lists.newArrayList(executedCommands)); } public static List<String> getExecutedCommandsKeys(List<HystrixInvokableInfo<?>> executedCommands) { return Lists.transform(executedCommands, new Function<HystrixInvokableInfo<?>, String>() { @Nullable @Override public String apply(@Nullable HystrixInvokableInfo<?> input) { return input.getCommandKey().name(); } }); } public static HystrixInvokableInfo getHystrixCommandByKey(String key) { HystrixInvokableInfo hystrixCommand = null; Collection<HystrixInvokableInfo<?>> executedCommands = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands(); for (HystrixInvokableInfo command : executedCommands) { if (command.getCommandKey().name().equals(key)) { hystrixCommand = command; break; } } return hystrixCommand; } }
4,397
0
Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test
Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/BasicHystrixTest.java
/** * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.netflix.hystrix.contrib.javanica.test.common; import com.google.common.base.Throwables; import com.hystrix.junit.HystrixRequestContextRule; import com.netflix.hystrix.HystrixInvokableInfo; import com.netflix.hystrix.HystrixThreadPool; import com.netflix.hystrix.HystrixThreadPoolProperties; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; import org.junit.Rule; import java.lang.reflect.Field; /** * Created by dmgcodevil */ public abstract class BasicHystrixTest { @Rule public HystrixRequestContextRule request = new HystrixRequestContextRule(); protected final HystrixRequestContext getHystrixContext() { return request.context(); } protected void resetContext() { request.reset(); } protected final HystrixThreadPoolProperties getThreadPoolProperties(HystrixInvokableInfo<?> command) { try { Field field = command.getClass().getSuperclass().getSuperclass().getSuperclass().getDeclaredField("threadPool"); field.setAccessible(true); HystrixThreadPool threadPool = (HystrixThreadPool) field.get(command); Field field2 = HystrixThreadPool.HystrixThreadPoolDefault.class.getDeclaredField("properties"); field2.setAccessible(true); return (HystrixThreadPoolProperties) field2.get(threadPool); } catch (NoSuchFieldException e) { throw Throwables.propagate(e); } catch (IllegalAccessException e) { throw Throwables.propagate(e); } } }
4,398
0
Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/configuration
Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/common/configuration/fallback/BasicFallbackDefaultPropertiesTest.java
package com.netflix.hystrix.contrib.javanica.test.common.configuration.fallback; import com.netflix.hystrix.HystrixThreadPoolProperties; import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty; import com.netflix.hystrix.contrib.javanica.test.common.BasicHystrixTest; import org.junit.Before; import org.junit.Test; import static com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS; import static com.netflix.hystrix.contrib.javanica.test.common.CommonUtils.getHystrixCommandByKey; import static org.junit.Assert.assertEquals; public abstract class BasicFallbackDefaultPropertiesTest extends BasicHystrixTest { private Service service; protected abstract Service createService(); @Before public void setUp() throws Exception { service = createService(); } @Test public void testFallbackInheritsDefaultGroupKey() { service.commandWithFallbackInheritsDefaultProperties(); com.netflix.hystrix.HystrixInvokableInfo fallbackCommand = getHystrixCommandByKey("fallbackInheritsDefaultProperties"); assertEquals("DefaultGroupKey", fallbackCommand.getCommandGroup().name()); } @Test public void testFallbackInheritsDefaultThreadPoolKey() { service.commandWithFallbackInheritsDefaultProperties(); com.netflix.hystrix.HystrixInvokableInfo fallbackCommand = getHystrixCommandByKey("fallbackInheritsDefaultProperties"); assertEquals("DefaultThreadPoolKey", fallbackCommand.getThreadPoolKey().name()); } @Test public void testFallbackInheritsDefaultCommandProperties() { service.commandWithFallbackInheritsDefaultProperties(); com.netflix.hystrix.HystrixInvokableInfo fallbackCommand = getHystrixCommandByKey("fallbackInheritsDefaultProperties"); assertEquals(456, fallbackCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); } @Test public void testFallbackInheritsThreadPollProperties() { service.commandWithFallbackInheritsDefaultProperties(); com.netflix.hystrix.HystrixInvokableInfo fallbackCommand = getHystrixCommandByKey("fallbackInheritsDefaultProperties"); HystrixThreadPoolProperties properties = getThreadPoolProperties(fallbackCommand); assertEquals(123, properties.maxQueueSize().get().intValue()); } @Test public void testFallbackOverridesDefaultGroupKey() { service.commandWithFallbackOverridesDefaultProperties(); com.netflix.hystrix.HystrixInvokableInfo fallbackCommand = getHystrixCommandByKey("fallbackOverridesDefaultProperties"); assertEquals("FallbackGroupKey", fallbackCommand.getCommandGroup().name()); } @Test public void testFallbackOverridesDefaultThreadPoolKey() { service.commandWithFallbackOverridesDefaultProperties(); com.netflix.hystrix.HystrixInvokableInfo fallbackCommand = getHystrixCommandByKey("fallbackOverridesDefaultProperties"); assertEquals("FallbackThreadPoolKey", fallbackCommand.getThreadPoolKey().name()); } @Test public void testFallbackOverridesDefaultCommandProperties() { service.commandWithFallbackOverridesDefaultProperties(); com.netflix.hystrix.HystrixInvokableInfo fallbackCommand = getHystrixCommandByKey("fallbackOverridesDefaultProperties"); assertEquals(654, fallbackCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); } @Test public void testFallbackOverridesThreadPollProperties() { service.commandWithFallbackOverridesDefaultProperties(); com.netflix.hystrix.HystrixInvokableInfo fallbackCommand = getHystrixCommandByKey("fallbackOverridesDefaultProperties"); HystrixThreadPoolProperties properties = getThreadPoolProperties(fallbackCommand); assertEquals(321, properties.maxQueueSize().get().intValue()); } @Test public void testCommandOverridesDefaultPropertiesWithFallbackInheritsDefaultProperties(){ service.commandOverridesDefaultPropertiesWithFallbackInheritsDefaultProperties(); com.netflix.hystrix.HystrixInvokableInfo fallbackCommand = getHystrixCommandByKey("fallbackInheritsDefaultProperties"); HystrixThreadPoolProperties properties = getThreadPoolProperties(fallbackCommand); assertEquals("DefaultGroupKey", fallbackCommand.getCommandGroup().name()); assertEquals("DefaultThreadPoolKey", fallbackCommand.getThreadPoolKey().name()); assertEquals(456, fallbackCommand.getProperties().executionTimeoutInMilliseconds().get().intValue()); assertEquals(123, properties.maxQueueSize().get().intValue()); } @DefaultProperties(groupKey = "DefaultGroupKey", threadPoolKey = "DefaultThreadPoolKey", commandProperties = { @HystrixProperty(name = EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS, value = "456") }, threadPoolProperties = { @HystrixProperty(name = "maxQueueSize", value = "123") }) public static class Service { @HystrixCommand(fallbackMethod = "fallbackInheritsDefaultProperties") public Object commandWithFallbackInheritsDefaultProperties() { throw new RuntimeException(); } @HystrixCommand(fallbackMethod = "fallbackOverridesDefaultProperties") public Object commandWithFallbackOverridesDefaultProperties() { throw new RuntimeException(); } @HystrixCommand(groupKey = "CommandGroupKey", threadPoolKey = "CommandThreadPoolKey", commandProperties = { @HystrixProperty(name = EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS, value = "654") }, threadPoolProperties = { @HystrixProperty(name = "maxQueueSize", value = "321") }, fallbackMethod = "fallbackInheritsDefaultProperties") public Object commandOverridesDefaultPropertiesWithFallbackInheritsDefaultProperties() { throw new RuntimeException(); } @HystrixCommand private Object fallbackInheritsDefaultProperties() { return null; } @HystrixCommand(groupKey = "FallbackGroupKey", threadPoolKey = "FallbackThreadPoolKey", commandProperties = { @HystrixProperty(name = EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS, value = "654") }, threadPoolProperties = { @HystrixProperty(name = "maxQueueSize", value = "321") }) private Object fallbackOverridesDefaultProperties() { return null; } } }
4,399