KeyTypeManager { public final <P> P getPrimitive(KeyProtoT key, Class<P> primitiveClass) throws GeneralSecurityException { @SuppressWarnings("unchecked") PrimitiveFactory<P, KeyProtoT> factory = (PrimitiveFactory<P, KeyProtoT>) factories.get(primitiveClass); if (factory == null) { throw new IllegalArgumentException( "Requested primitive class " + primitiveClass.getCanonicalName() + " not supported."); } return factory.getPrimitive(key); } @SafeVarargs // Safe because we do not reference the array (see Effective Java ed. 3, Item 32). protected  KeyTypeManager(Class<KeyProtoT> clazz, PrimitiveFactory<?, KeyProtoT>... factories); final Class<KeyProtoT> getKeyClass(); abstract String getKeyType(); abstract int getVersion(); abstract KeyMaterialType keyMaterialType(); abstract KeyProtoT parseKey(ByteString byteString); abstract void validateKey(KeyProtoT keyProto); final P getPrimitive(KeyProtoT key, Class<P> primitiveClass); final Set<Class<?>> supportedPrimitives(); KeyFactory<?, KeyProtoT> keyFactory();  }
@Test public void getPrimitive_works() throws Exception { KeyTypeManager<AesGcmKey> keyManager = new TestKeyTypeManager( new TestKeyTypeManager.PrimitiveFactory<Primitive1, AesGcmKey>(Primitive1.class) { @Override public Primitive1 getPrimitive(AesGcmKey key) { return new Primitive1(key.getKeyValue()); } }, new TestKeyTypeManager.PrimitiveFactory<Primitive2, AesGcmKey>(Primitive2.class) { @Override public Primitive2 getPrimitive(AesGcmKey key) { return new Primitive2(key.getKeyValue().size()); } }); Primitive1 primitive1 = keyManager.getPrimitive( AesGcmKey.newBuilder().setKeyValue(TEST_BYTESTRING).build(), Primitive1.class); assertThat(primitive1.getKeyValue()).isEqualTo(TEST_BYTESTRING); Primitive2 primitive2 = keyManager.getPrimitive( AesGcmKey.newBuilder().setKeyValue(TEST_BYTESTRING).build(), Primitive2.class); assertThat(primitive2.getSize()).isEqualTo(TEST_BYTESTRING.size()); }
@Test public void getPrimitive_throwsForUnknownPrimitives() throws Exception { KeyTypeManager<AesGcmKey> keyManager = new TestKeyTypeManager(); try { keyManager.getPrimitive(AesGcmKey.getDefaultInstance(), Primitive1.class); fail(); } catch (IllegalArgumentException e) { } }
@Test public void getPrimitive_throwsForVoid() throws Exception { KeyTypeManager<AesGcmKey> keyManager = new TestKeyTypeManager(); try { keyManager.getPrimitive(AesGcmKey.getDefaultInstance(), Void.class); fail(); } catch (IllegalArgumentException e) { } }