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/SimianArmy/src/main/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/chaos/FailS3ChaosType.java
/* * * Copyright 2013 Justin Santa Barbara. * * 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.simianarmy.chaos; import com.netflix.simianarmy.MonkeyConfiguration; /** * Adds entries to /etc/hosts so that S3 API endpoints are unreachable. */ public class FailS3ChaosType extends ScriptChaosType { /** * Constructor. * * @param config * Configuration to use */ public FailS3ChaosType(MonkeyConfiguration config) { super(config, "FailS3"); } }
4,900
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/client/MonkeyRestClient.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.simianarmy.client; import org.apache.commons.lang.Validate; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultServiceUnavailableRetryStrategy; import org.apache.http.impl.client.HttpClientBuilder; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.util.Scanner; /** * A REST client used by monkeys. */ public abstract class MonkeyRestClient { private static final Logger LOGGER = LoggerFactory.getLogger(MonkeyRestClient.class); private final HttpClient httpClient; /** * Constructor. * @param timeout the timeout in milliseconds * @param maxRetries the max number of retries * @param retryInterval the interval in milliseconds between retries */ public MonkeyRestClient(int timeout, int maxRetries, int retryInterval) { Validate.isTrue(timeout >= 0); Validate.isTrue(maxRetries >= 0); Validate.isTrue(retryInterval > 0); RequestConfig config = RequestConfig.custom() .setConnectTimeout(timeout) .build(); httpClient = HttpClientBuilder.create() .setDefaultRequestConfig(config) .setServiceUnavailableRetryStrategy(new DefaultServiceUnavailableRetryStrategy(maxRetries, retryInterval)) .build(); } /** * Gets the response in JSON from a url. * @param url the url * @return the JSON node for the response */ // CHECKSTYLE IGNORE MagicNumberCheck public JsonNode getJsonNodeFromUrl(String url) throws IOException { LOGGER.info(String.format("Getting Json response from url: %s", url)); HttpGet request = new HttpGet(url); request.setHeader("Accept", "application/json"); HttpResponse response = httpClient.execute(request); InputStream is = response.getEntity().getContent(); String jsonContent; if (is != null) { Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A"); jsonContent = s.hasNext() ? s.next() : ""; is.close(); } else { return null; } int code = response.getStatusLine().getStatusCode(); if (code == 404) { return null; } else if (code >= 300 || code < 200) { throw new DataReadException(code, url, jsonContent); } JsonNode result; try { ObjectMapper mapper = new ObjectMapper(); result = mapper.readTree(jsonContent); } catch (Exception e) { throw new RuntimeException(String.format("Error trying to parse json response from url %s, got: %s", url, jsonContent), e); } return result; } /** * Gets the base url of the service for a specific region. * @param region the region * @return the base url in the region */ public abstract String getBaseUrl(String region); public static class DataReadException extends RuntimeException { public DataReadException(int code, String url, String jsonContent) { super(String.format("Response code %d from url %s: %s", code, url, jsonContent)); } } }
4,901
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/client
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/client/vsphere/VSphereClient.java
/* * Copyright 2012 Immobilien Scout GmbH * * 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.simianarmy.client.vsphere; import java.rmi.RemoteException; import java.util.List; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.autoscaling.model.AutoScalingGroup; import com.netflix.simianarmy.client.aws.AWSClient; import com.vmware.vim25.mo.VirtualMachine; /** * This client describes the VSphere folders as AutoScalingGroup's containing the virtual machines that are directly in * that folder. The hierarchy is flattened this way. And it can terminate these VMs with the configured * TerminationStrategy. * * @author ingmar.krusch@immobilienscout24.de */ public class VSphereClient extends AWSClient { // private static final Logger LOGGER = LoggerFactory.getLogger(VSphereClient.class); private final TerminationStrategy terminationStrategy; private final VSphereServiceConnection connection; /** * Create the specific Client from the given strategy and connection. */ public VSphereClient(TerminationStrategy terminationStrategy, VSphereServiceConnection connection) { super("region-" + connection.getUrl()); this.terminationStrategy = terminationStrategy; this.connection = connection; } @Override public List<AutoScalingGroup> describeAutoScalingGroups(String... names) { final VSphereGroups groups = new VSphereGroups(); try { connection.connect(); for (VirtualMachine virtualMachine : connection.describeVirtualMachines()) { String instanceId = virtualMachine.getName(); String groupName = virtualMachine.getParent().getName(); boolean shouldAddNamedGroup = true; if (names != null) { // TODO need to implement this feature!!! throw new RuntimeException("This feature (selecting groups by name) is not implemented yet"); } if (shouldAddNamedGroup) { groups.addInstance(instanceId, groupName); } } } finally { connection.disconnect(); } return groups.asList(); } @Override /** * reinstall the given instance. If it is powered down this will be ignored and the * reinstall occurs the next time the machine is powered up. */ public void terminateInstance(String instanceId) { try { connection.connect(); VirtualMachine virtualMachine = connection.getVirtualMachineById(instanceId); this.terminationStrategy.terminate(virtualMachine); } catch (RemoteException e) { throw new AmazonServiceException("cannot destroy & recreate " + instanceId, e); } finally { connection.disconnect(); } } }
4,902
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/client
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/client/vsphere/VSphereServiceConnection.java
/* * Copyright 2012 Immobilien Scout GmbH * * 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.simianarmy.client.vsphere; import java.net.MalformedURLException; import java.net.URL; import java.rmi.RemoteException; import java.util.Arrays; import com.amazonaws.AmazonServiceException; import com.netflix.simianarmy.MonkeyConfiguration; import com.vmware.vim25.InvalidProperty; import com.vmware.vim25.RuntimeFault; import com.vmware.vim25.mo.InventoryNavigator; import com.vmware.vim25.mo.ManagedEntity; import com.vmware.vim25.mo.ServiceInstance; import com.vmware.vim25.mo.VirtualMachine; /** * Wraps the connection to VSphere and handles the raw service calls. * * The following properties can be overridden in the client.properties * simianarmy.client.vsphere.url = https://YOUR_VSPHERE_SERVER/sdk * simianarmy.client.vsphere.username = YOUR_SERVICE_ACCOUNT_USERNAME * simianarmy.client.vsphere.password = YOUR_SERVICE_ACCOUNT_PASSWORD * * @author ingmar.krusch@immobilienscout24.de */ public class VSphereServiceConnection { /** The type of managedEntity we operate on are virtual machines. */ public static final String VIRTUAL_MACHINE_TYPE_NAME = "VirtualMachine"; /** The username that is used to connect to VSpehere Center. */ private String username = null; /** The password that is used to connect to VSpehere Center. */ private String password = null; /** The url that is used to connect to VSpehere Center. */ private String url = null; /** The ServiceInstance that is used to issue multiple requests to VSpehere Center. */ private ServiceInstance service = null; /** * Constructor. */ public VSphereServiceConnection(MonkeyConfiguration config) { this.url = config.getStr("simianarmy.client.vsphere.url"); this.username = config.getStr("simianarmy.client.vsphere.username"); this.password = config.getStr("simianarmy.client.vsphere.password"); } /** disconnect from the service if not already disconnected. */ public void disconnect() { if (service != null) { service.getServerConnection().logout(); service = null; } } /** connect to the service if not already connected. */ public void connect() throws AmazonServiceException { try { if (service == null) { service = new ServiceInstance(new URL(url), username, password, true); } } catch (RemoteException e) { throw new AmazonServiceException("cannot connect to VSphere", e); } catch (MalformedURLException e) { throw new AmazonServiceException("cannot connect to VSphere", e); } } /** * Gets the named VirtualMachine. */ public VirtualMachine getVirtualMachineById(String instanceId) throws RemoteException { InventoryNavigator inventoryNavigator = getInventoryNavigator(); VirtualMachine virtualMachine = (VirtualMachine) inventoryNavigator.searchManagedEntity( VIRTUAL_MACHINE_TYPE_NAME, instanceId); return virtualMachine; } /** * Return all VirtualMachines from VSpehere Center. * * @throws AmazonServiceException * If there is any communication error or if no VirtualMachine's are found. */ public VirtualMachine[] describeVirtualMachines() throws AmazonServiceException { ManagedEntity[] mes = null; try { mes = getInventoryNavigator().searchManagedEntities(VIRTUAL_MACHINE_TYPE_NAME); } catch (InvalidProperty e) { throw new AmazonServiceException("cannot query VSphere", e); } catch (RuntimeFault e) { throw new AmazonServiceException("cannot query VSphere", e); } catch (RemoteException e) { throw new AmazonServiceException("cannot query VSphere", e); } if (mes == null || mes.length == 0) { throw new AmazonServiceException( "vsphere returned zero entities of type \"" + VIRTUAL_MACHINE_TYPE_NAME + "\"" ); } else { return Arrays.copyOf(mes, mes.length, VirtualMachine[].class); } } protected InventoryNavigator getInventoryNavigator() { return new InventoryNavigator(service.getRootFolder()); } public String getUsername() { return username; } public String getPassword() { return password; } public String getUrl() { return url; } }
4,903
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/client
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/client/vsphere/TerminationStrategy.java
/* * Copyright 2012 Immobilien Scout GmbH * * 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.simianarmy.client.vsphere; import java.rmi.RemoteException; import com.vmware.vim25.mo.VirtualMachine; /** * Abstracts the concrete way a VirtualMachine is terminated. Implement this to fit to your infrastructure. * * @author ingmar.krusch@immobilienscout24.de */ public interface TerminationStrategy { /** * Terminate the given VirtualMachine. */ void terminate(VirtualMachine virtualMachine) throws RemoteException; }
4,904
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/client
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/client/vsphere/VSphereGroups.java
/* * Copyright 2012 Immobilien Scout GmbH * * 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.simianarmy.client.vsphere; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import com.amazonaws.services.autoscaling.model.AutoScalingGroup; import com.amazonaws.services.autoscaling.model.Instance; /** * Wraps the creation and grouping of Instance's in AutoScalingGroup's. * * @author ingmar.krusch@immobilienscout24.de */ class VSphereGroups { private final Map<String, AutoScalingGroup> map = new HashMap<String, AutoScalingGroup>(); /** * Get all AutoScalingGroup's that have been added. */ public List<AutoScalingGroup> asList() { ArrayList<AutoScalingGroup> list = new ArrayList<AutoScalingGroup>(map.values()); Collections.sort(list, new Comparator<AutoScalingGroup>() { @Override public int compare(AutoScalingGroup o1, AutoScalingGroup o2) { return o1.getAutoScalingGroupName().compareTo(o2.getAutoScalingGroupName()); } }); return list; } /** * Add the given instance to the named group. */ public void addInstance(final String instanceId, final String groupName) { if (!map.containsKey(groupName)) { final AutoScalingGroup asg = new AutoScalingGroup(); asg.setAutoScalingGroupName(groupName); map.put(groupName, asg); } final AutoScalingGroup asg = map.get(groupName); Instance instance = new Instance(); instance.setInstanceId(instanceId); asg.getInstances().add(instance); } }
4,905
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/client
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/client/vsphere/PropertyBasedTerminationStrategy.java
/* * Copyright 2012 Immobilien Scout GmbH * * 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.simianarmy.client.vsphere; import java.rmi.RemoteException; import com.netflix.simianarmy.MonkeyConfiguration; import com.vmware.vim25.mo.VirtualMachine; /** * Terminates a VirtualMachine by setting the named property and resetting it. * * The following properties can be overridden in the client.properties * simianarmy.client.vsphere.terminationStrategy.property.name = PROPERTY_NAME * simianarmy.client.vsphere.terminationStrategy.property.value = PROPERTY_VALUE * * @author ingmar.krusch@immobilienscout24.de */ public class PropertyBasedTerminationStrategy implements TerminationStrategy { private final String propertyName; private final String propertyValue; /** * Reads property name <code>simianarmy.client.vsphere.terminationStrategy.property.name</code> * (default: Force Boot) and value <code>simianarmy.client.vsphere.terminationStrategy.property.value</code> * (default: server) from config. */ public PropertyBasedTerminationStrategy(MonkeyConfiguration config) { this.propertyName = config.getStrOrElse( "simianarmy.client.vsphere.terminationStrategy.property.name", "Force Boot"); this.propertyValue = config.getStrOrElse( "simianarmy.client.vsphere.terminationStrategy.property.value", "server"); } @Override public void terminate(VirtualMachine virtualMachine) throws RemoteException { virtualMachine.setCustomValue(getPropertyName(), getPropertyValue()); virtualMachine.resetVM_Task(); } public String getPropertyName() { return propertyName; } public String getPropertyValue() { return propertyValue; } }
4,906
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/client
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/client/vsphere/VSphereContext.java
/* * Copyright 2012 Immobilien Scout GmbH * * 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.simianarmy.client.vsphere; import com.netflix.simianarmy.MonkeyConfiguration; import com.netflix.simianarmy.basic.BasicChaosMonkeyContext; /** * This Context extends the BasicContext in order to provide a different client: the VSphereClient. * * @author ingmar.krusch@immobilienscout24.de */ public class VSphereContext extends BasicChaosMonkeyContext { @Override protected void createClient() { MonkeyConfiguration config = configuration(); final PropertyBasedTerminationStrategy terminationStrategy = new PropertyBasedTerminationStrategy(config); final VSphereServiceConnection connection = new VSphereServiceConnection(config); final VSphereClient client = new VSphereClient(terminationStrategy, connection); setCloudClient(client); } }
4,907
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/client
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/client/aws/AWSClient.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.simianarmy.client.aws; import com.amazonaws.AmazonServiceException; import com.amazonaws.ClientConfiguration; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.AWSSessionCredentials; import com.amazonaws.services.autoscaling.AmazonAutoScalingClient; import com.amazonaws.services.autoscaling.model.*; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.*; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.Tag; import com.amazonaws.services.elasticloadbalancing.AmazonElasticLoadBalancingClient; import com.amazonaws.services.elasticloadbalancing.model.*; import com.amazonaws.services.elasticloadbalancing.model.DescribeLoadBalancersRequest; import com.amazonaws.services.elasticloadbalancing.model.DescribeLoadBalancersResult; import com.amazonaws.services.elasticloadbalancing.model.DescribeTagsRequest; import com.amazonaws.services.elasticloadbalancing.model.DescribeTagsResult; import com.amazonaws.services.elasticloadbalancing.model.TagDescription; import com.amazonaws.services.route53.AmazonRoute53Client; import com.amazonaws.services.route53.model.*; import com.amazonaws.services.simpledb.AmazonSimpleDB; import com.amazonaws.services.simpledb.AmazonSimpleDBClient; import com.google.common.base.Objects; import com.google.common.base.Strings; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import com.google.inject.Module; import com.netflix.simianarmy.CloudClient; import com.netflix.simianarmy.NotFoundException; import org.apache.commons.lang.Validate; import org.jclouds.ContextBuilder; import org.jclouds.aws.domain.SessionCredentials; import org.jclouds.compute.ComputeService; import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.Utils; import org.jclouds.compute.domain.ComputeMetadata; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; import org.jclouds.domain.Credentials; import org.jclouds.domain.LoginCredentials; import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.ssh.SshClient; import org.jclouds.ssh.jsch.config.JschSshClientModule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; /** * The Class AWSClient. Simple Amazon EC2 and Amazon ASG client interface. */ public class AWSClient implements CloudClient { /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(AWSClient.class); /** The region. */ private final String region; /** The plain name for AWS account */ private final String accountName; /** Maximum retry count for Simple DB */ private static final int SIMPLE_DB_MAX_RETRY = 11; private final AWSCredentialsProvider awsCredentialsProvider; private final ClientConfiguration awsClientConfig; private ComputeService jcloudsComputeService; /** * This constructor will let the AWS SDK obtain the credentials, which will * choose such in the following order: * * <ul> * <li>Environment Variables: {@code AWS_ACCESS_KEY_ID} and * {@code AWS_SECRET_KEY}</li> * <li>Java System Properties: {@code aws.accessKeyId} and * {@code aws.secretKey}</li> * <li>Instance Metadata Service, which provides the credentials associated * with the IAM role for the EC2 instance</li> * </ul> * * <p> * If credentials are provided explicitly, use * {@link com.netflix.simianarmy.basic.BasicSimianArmyContext#exportCredentials(String, String)} * which will set them as System properties used by each AWS SDK call. * </p> * * <p> * <b>Note:</b> Avoid storing credentials received dynamically via the * {@link com.amazonaws.auth.InstanceProfileCredentialsProvider} as these will be rotated and * their renewal is handled by its * {@link com.amazonaws.auth.InstanceProfileCredentialsProvider#getCredentials()} method. * </p> * * @param region * the region * @see com.amazonaws.auth.DefaultAWSCredentialsProviderChain * @see com.amazonaws.auth.InstanceProfileCredentialsProvider * @see com.netflix.simianarmy.basic.BasicSimianArmyContext#exportCredentials(String, String) */ public AWSClient(String region) { this.region = region; this.accountName = "Default"; this.awsCredentialsProvider = null; this.awsClientConfig = null; } /** * The constructor allows you to provide your own AWS credentials provider. * @param region * the region * @param awsCredentialsProvider * the AWS credentials provider */ public AWSClient(String region, AWSCredentialsProvider awsCredentialsProvider) { this.region = region; this.accountName = "Default"; this.awsCredentialsProvider = awsCredentialsProvider; this.awsClientConfig = null; } /** * The constructor allows you to provide your own AWS client configuration. * @param region * the region * @param awsClientConfig * the AWS client configuration */ public AWSClient(String region, ClientConfiguration awsClientConfig) { this.region = region; this.accountName = "Default"; this.awsCredentialsProvider = null; this.awsClientConfig = awsClientConfig; } /** * The constructor allows you to provide your own AWS credentials provider and client config. * @param region * the region * @param awsCredentialsProvider * the AWS credentials provider * @param awsClientConfig * the AWS client configuration */ public AWSClient(String region, AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration awsClientConfig) { this.region = region; this.accountName = "Default"; this.awsCredentialsProvider = awsCredentialsProvider; this.awsClientConfig = awsClientConfig; } /** * The Region. * * @return the region the client is configured to communicate with */ public String region() { return region; } /** * The accountName. * * @return the plain name for the aws account easier to identify which account * monkey is running in */ public String accountName() { return accountName; } /** * Amazon EC2 client. Abstracted to aid testing. * * @return the Amazon EC2 client */ protected AmazonEC2 ec2Client() { AmazonEC2 client; if (awsClientConfig == null) { if (awsCredentialsProvider == null) { client = new AmazonEC2Client(); } else { client = new AmazonEC2Client(awsCredentialsProvider); } } else { if (awsCredentialsProvider == null) { client = new AmazonEC2Client(awsClientConfig); } else { client = new AmazonEC2Client(awsCredentialsProvider, awsClientConfig); } } client.setEndpoint("ec2." + region + ".amazonaws.com"); return client; } /** * Amazon ASG client. Abstracted to aid testing. * * @return the Amazon Auto Scaling client */ protected AmazonAutoScalingClient asgClient() { AmazonAutoScalingClient client; if (awsClientConfig == null) { if (awsCredentialsProvider == null) { client = new AmazonAutoScalingClient(); } else { client = new AmazonAutoScalingClient(awsCredentialsProvider); } } else { if (awsCredentialsProvider == null) { client = new AmazonAutoScalingClient(awsClientConfig); } else { client = new AmazonAutoScalingClient(awsCredentialsProvider, awsClientConfig); } } client.setEndpoint("autoscaling." + region + ".amazonaws.com"); return client; } /** * Amazon ELB client. Abstracted to aid testing. * * @return the Amazon ELB client */ protected AmazonElasticLoadBalancingClient elbClient() { AmazonElasticLoadBalancingClient client; if (awsClientConfig == null) { if (awsCredentialsProvider == null) { client = new AmazonElasticLoadBalancingClient(); } else { client = new AmazonElasticLoadBalancingClient(awsCredentialsProvider); } } else { if (awsCredentialsProvider == null) { client = new AmazonElasticLoadBalancingClient(awsClientConfig); } else { client = new AmazonElasticLoadBalancingClient(awsCredentialsProvider, awsClientConfig); } } client.setEndpoint("elasticloadbalancing." + region + ".amazonaws.com"); return client; } /** * Amazon Route53 client. Abstracted to aid testing. * * @return the Amazon Route53 client */ protected AmazonRoute53Client route53Client() { AmazonRoute53Client client; if (awsClientConfig == null) { if (awsCredentialsProvider == null) { client = new AmazonRoute53Client(); } else { client = new AmazonRoute53Client(awsCredentialsProvider); } } else { if (awsCredentialsProvider == null) { client = new AmazonRoute53Client(awsClientConfig); } else { client = new AmazonRoute53Client(awsCredentialsProvider, awsClientConfig); } } client.setEndpoint("route53.amazonaws.com"); return client; } /** * Amazon SimpleDB client. * * @return the Amazon SimpleDB client */ public AmazonSimpleDB sdbClient() { AmazonSimpleDB client; ClientConfiguration cc = awsClientConfig; if (cc == null) { cc = new ClientConfiguration(); cc.setMaxErrorRetry(SIMPLE_DB_MAX_RETRY); } if (awsCredentialsProvider == null) { client = new AmazonSimpleDBClient(cc); } else { client = new AmazonSimpleDBClient(awsCredentialsProvider, cc); } // us-east-1 has special naming // http://docs.amazonwebservices.com/general/latest/gr/rande.html#sdb_region if (region == null || region.equals("us-east-1")) { client.setEndpoint("sdb.amazonaws.com"); } else { client.setEndpoint("sdb." + region + ".amazonaws.com"); } return client; } /** * Describe auto scaling groups. * * @return the list */ public List<AutoScalingGroup> describeAutoScalingGroups() { return describeAutoScalingGroups((String[]) null); } /** * Describe a set of specific auto scaling groups. * * @param names the ASG names * @return the auto scaling groups */ public List<AutoScalingGroup> describeAutoScalingGroups(String... names) { if (names == null || names.length == 0) { LOGGER.info(String.format("Getting all auto-scaling groups in region %s.", region)); } else { LOGGER.info(String.format("Getting auto-scaling groups for %d names in region %s.", names.length, region)); } List<AutoScalingGroup> asgs = new LinkedList<AutoScalingGroup>(); AmazonAutoScalingClient asgClient = asgClient(); DescribeAutoScalingGroupsRequest request = new DescribeAutoScalingGroupsRequest(); if (names != null) { request.setAutoScalingGroupNames(Arrays.asList(names)); } DescribeAutoScalingGroupsResult result = asgClient.describeAutoScalingGroups(request); asgs.addAll(result.getAutoScalingGroups()); while (result.getNextToken() != null) { request.setNextToken(result.getNextToken()); result = asgClient.describeAutoScalingGroups(request); asgs.addAll(result.getAutoScalingGroups()); } LOGGER.info(String.format("Got %d auto-scaling groups in region %s.", asgs.size(), region)); return asgs; } /** * Describe a set of specific ELBs. * * @param names the ELB names * @return the ELBs */ public List<LoadBalancerDescription> describeElasticLoadBalancers(String... names) { if (names == null || names.length == 0) { LOGGER.info(String.format("Getting all ELBs in region %s.", region)); } else { LOGGER.info(String.format("Getting ELBs for %d names in region %s.", names.length, region)); } AmazonElasticLoadBalancingClient elbClient = elbClient(); DescribeLoadBalancersRequest request = new DescribeLoadBalancersRequest().withLoadBalancerNames(names); DescribeLoadBalancersResult result = elbClient.describeLoadBalancers(request); List<LoadBalancerDescription> elbs = result.getLoadBalancerDescriptions(); LOGGER.info(String.format("Got %d ELBs in region %s.", elbs.size(), region)); return elbs; } /** * Describe a specific ELB. * * @param name the ELB names * @return the ELBs */ public LoadBalancerAttributes describeElasticLoadBalancerAttributes(String name) { LOGGER.info(String.format("Getting attributes for ELB with name '%s' in region %s.", name, region)); AmazonElasticLoadBalancingClient elbClient = elbClient(); DescribeLoadBalancerAttributesRequest request = new DescribeLoadBalancerAttributesRequest().withLoadBalancerName(name); DescribeLoadBalancerAttributesResult result = elbClient.describeLoadBalancerAttributes(request); LoadBalancerAttributes attrs = result.getLoadBalancerAttributes(); LOGGER.info(String.format("Got attributes for ELB with name '%s' in region %s.", name, region)); return attrs; } /** * Retreive the tags for a specific ELB. * * @param name the ELB names * @return the ELBs */ public List<TagDescription> describeElasticLoadBalancerTags(String name) { LOGGER.info(String.format("Getting tags for ELB with name '%s' in region %s.", name, region)); AmazonElasticLoadBalancingClient elbClient = elbClient(); DescribeTagsRequest request = new DescribeTagsRequest().withLoadBalancerNames(name); DescribeTagsResult result = elbClient.describeTags(request); LOGGER.info(String.format("Got tags for ELB with name '%s' in region %s.", name, region)); return result.getTagDescriptions(); } /** * Describe a set of specific auto-scaling instances. * * @param instanceIds the instance ids * @return the instances */ public List<AutoScalingInstanceDetails> describeAutoScalingInstances(String... instanceIds) { if (instanceIds == null || instanceIds.length == 0) { LOGGER.info(String.format("Getting all auto-scaling instances in region %s.", region)); } else { LOGGER.info(String.format("Getting auto-scaling instances for %d ids in region %s.", instanceIds.length, region)); } List<AutoScalingInstanceDetails> instances = new LinkedList<AutoScalingInstanceDetails>(); AmazonAutoScalingClient asgClient = asgClient(); DescribeAutoScalingInstancesRequest request = new DescribeAutoScalingInstancesRequest(); if (instanceIds != null) { request.setInstanceIds(Arrays.asList(instanceIds)); } DescribeAutoScalingInstancesResult result = asgClient.describeAutoScalingInstances(request); instances.addAll(result.getAutoScalingInstances()); while (result.getNextToken() != null) { request = request.withNextToken(result.getNextToken()); result = asgClient.describeAutoScalingInstances(request); instances.addAll(result.getAutoScalingInstances()); } LOGGER.info(String.format("Got %d auto-scaling instances.", instances.size())); return instances; } /** * Describe a set of specific instances. * * @param instanceIds the instance ids * @return the instances */ public List<Instance> describeInstances(String... instanceIds) { if (instanceIds == null || instanceIds.length == 0) { LOGGER.info(String.format("Getting all EC2 instances in region %s.", region)); } else { LOGGER.info(String.format("Getting EC2 instances for %d ids in region %s.", instanceIds.length, region)); } List<Instance> instances = new LinkedList<Instance>(); AmazonEC2 ec2Client = ec2Client(); DescribeInstancesRequest request = new DescribeInstancesRequest(); if (instanceIds != null) { request.withInstanceIds(Arrays.asList(instanceIds)); } DescribeInstancesResult result = ec2Client.describeInstances(request); for (Reservation reservation : result.getReservations()) { instances.addAll(reservation.getInstances()); } LOGGER.info(String.format("Got %d EC2 instances in region %s.", instances.size(), region)); return instances; } /** * Describe a set of specific launch configurations. * * @param names the launch configuration names * @return the launch configurations */ public List<LaunchConfiguration> describeLaunchConfigurations(String... names) { if (names == null || names.length == 0) { LOGGER.info(String.format("Getting all launch configurations in region %s.", region)); } else { LOGGER.info(String.format("Getting launch configurations for %d names in region %s.", names.length, region)); } List<LaunchConfiguration> lcs = new LinkedList<LaunchConfiguration>(); AmazonAutoScalingClient asgClient = asgClient(); DescribeLaunchConfigurationsRequest request = new DescribeLaunchConfigurationsRequest() .withLaunchConfigurationNames(names); DescribeLaunchConfigurationsResult result = asgClient.describeLaunchConfigurations(request); lcs.addAll(result.getLaunchConfigurations()); while (result.getNextToken() != null) { request.setNextToken(result.getNextToken()); result = asgClient.describeLaunchConfigurations(request); lcs.addAll(result.getLaunchConfigurations()); } LOGGER.info(String.format("Got %d launch configurations in region %s.", lcs.size(), region)); return lcs; } /** {@inheritDoc} */ @Override public void deleteAutoScalingGroup(String asgName) { Validate.notEmpty(asgName); LOGGER.info(String.format("Deleting auto-scaling group with name %s in region %s.", asgName, region)); AmazonAutoScalingClient asgClient = asgClient(); DeleteAutoScalingGroupRequest request = new DeleteAutoScalingGroupRequest() .withAutoScalingGroupName(asgName).withForceDelete(true); try { asgClient.deleteAutoScalingGroup(request); LOGGER.info(String.format("Deleted auto-scaling group with name %s in region %s.", asgName, region)); }catch(Exception e) { LOGGER.error("Got an exception deleting ASG " + asgName, e); } } /** {@inheritDoc} */ @Override public void deleteLaunchConfiguration(String launchConfigName) { Validate.notEmpty(launchConfigName); LOGGER.info(String.format("Deleting launch configuration with name %s in region %s.", launchConfigName, region)); AmazonAutoScalingClient asgClient = asgClient(); DeleteLaunchConfigurationRequest request = new DeleteLaunchConfigurationRequest() .withLaunchConfigurationName(launchConfigName); asgClient.deleteLaunchConfiguration(request); } /** {@inheritDoc} */ @Override public void deleteImage(String imageId) { Validate.notEmpty(imageId); LOGGER.info(String.format("Deleting image %s in region %s.", imageId, region)); AmazonEC2 ec2Client = ec2Client(); DeregisterImageRequest request = new DeregisterImageRequest(imageId); ec2Client.deregisterImage(request); } /** {@inheritDoc} */ @Override public void deleteVolume(String volumeId) { Validate.notEmpty(volumeId); LOGGER.info(String.format("Deleting volume %s in region %s.", volumeId, region)); AmazonEC2 ec2Client = ec2Client(); DeleteVolumeRequest request = new DeleteVolumeRequest().withVolumeId(volumeId); ec2Client.deleteVolume(request); } /** {@inheritDoc} */ @Override public void deleteSnapshot(String snapshotId) { Validate.notEmpty(snapshotId); LOGGER.info(String.format("Deleting snapshot %s in region %s.", snapshotId, region)); AmazonEC2 ec2Client = ec2Client(); DeleteSnapshotRequest request = new DeleteSnapshotRequest().withSnapshotId(snapshotId); ec2Client.deleteSnapshot(request); } /** {@inheritDoc} */ @Override public void deleteElasticLoadBalancer(String elbId) { Validate.notEmpty(elbId); LOGGER.info(String.format("Deleting ELB %s in region %s.", elbId, region)); AmazonElasticLoadBalancingClient elbClient = elbClient(); DeleteLoadBalancerRequest request = new DeleteLoadBalancerRequest(elbId); elbClient.deleteLoadBalancer(request); } /** {@inheritDoc} */ @Override public void deleteDNSRecord(String dnsName, String dnsType, String hostedZoneID) { Validate.notEmpty(dnsName); Validate.notEmpty(dnsType); if(dnsType.equals("A") || dnsType.equals("AAAA") || dnsType.equals("CNAME")) { LOGGER.info(String.format("Deleting DNS Route 53 record %s", dnsName)); AmazonRoute53Client route53Client = route53Client(); // AWS API requires us to query for the record first ListResourceRecordSetsRequest listRequest = new ListResourceRecordSetsRequest(hostedZoneID); listRequest.setMaxItems("1"); listRequest.setStartRecordType(dnsType); listRequest.setStartRecordName(dnsName); ListResourceRecordSetsResult listResult = route53Client.listResourceRecordSets(listRequest); if (listResult.getResourceRecordSets().size() < 1) { throw new NotFoundException("Could not find Route53 record for " + dnsName + " (" + dnsType + ") in zone " + hostedZoneID); } else { ResourceRecordSet resourceRecord = listResult.getResourceRecordSets().get(0); ArrayList<Change> changeList = new ArrayList<>(); Change recordChange = new Change(ChangeAction.DELETE, resourceRecord); changeList.add(recordChange); ChangeBatch recordChangeBatch = new ChangeBatch(changeList); ChangeResourceRecordSetsRequest request = new ChangeResourceRecordSetsRequest(hostedZoneID, recordChangeBatch); ChangeResourceRecordSetsResult result = route53Client.changeResourceRecordSets(request); } } else { LOGGER.error("dnsType must be one of 'A', 'AAAA', or 'CNAME'"); } } /** {@inheritDoc} */ @Override public void terminateInstance(String instanceId) { Validate.notEmpty(instanceId); LOGGER.info(String.format("Terminating instance %s in region %s.", instanceId, region)); try { ec2Client().terminateInstances(new TerminateInstancesRequest(Arrays.asList(instanceId))); } catch (AmazonServiceException e) { if (e.getErrorCode().equals("InvalidInstanceID.NotFound")) { throw new NotFoundException("AWS instance " + instanceId + " not found", e); } throw e; } } /** {@inheritDoc} */ public void setInstanceSecurityGroups(String instanceId, List<String> groupIds) { Validate.notEmpty(instanceId); LOGGER.info(String.format("Removing all security groups from instance %s in region %s.", instanceId, region)); try { ModifyInstanceAttributeRequest request = new ModifyInstanceAttributeRequest(); request.setInstanceId(instanceId); request.setGroups(groupIds); ec2Client().modifyInstanceAttribute(request); } catch (AmazonServiceException e) { if (e.getErrorCode().equals("InvalidInstanceID.NotFound")) { throw new NotFoundException("AWS instance " + instanceId + " not found", e); } throw e; } } /** * Describe a set of specific EBS volumes. * * @param volumeIds the volume ids * @return the volumes */ public List<Volume> describeVolumes(String... volumeIds) { if (volumeIds == null || volumeIds.length == 0) { LOGGER.info(String.format("Getting all EBS volumes in region %s.", region)); } else { LOGGER.info(String.format("Getting EBS volumes for %d ids in region %s.", volumeIds.length, region)); } AmazonEC2 ec2Client = ec2Client(); DescribeVolumesRequest request = new DescribeVolumesRequest(); if (volumeIds != null) { request.setVolumeIds(Arrays.asList(volumeIds)); } DescribeVolumesResult result = ec2Client.describeVolumes(request); List<Volume> volumes = result.getVolumes(); LOGGER.info(String.format("Got %d EBS volumes in region %s.", volumes.size(), region)); return volumes; } /** * Describe a set of specific EBS snapshots. * * @param snapshotIds the snapshot ids * @return the snapshots */ public List<Snapshot> describeSnapshots(String... snapshotIds) { if (snapshotIds == null || snapshotIds.length == 0) { LOGGER.info(String.format("Getting all EBS snapshots in region %s.", region)); } else { LOGGER.info(String.format("Getting EBS snapshotIds for %d ids in region %s.", snapshotIds.length, region)); } AmazonEC2 ec2Client = ec2Client(); DescribeSnapshotsRequest request = new DescribeSnapshotsRequest(); // Set the owner id to self to avoid getting snapshots from other accounts. request.withOwnerIds(Arrays.<String>asList("self")); if (snapshotIds != null) { request.setSnapshotIds(Arrays.asList(snapshotIds)); } DescribeSnapshotsResult result = ec2Client.describeSnapshots(request); List<Snapshot> snapshots = result.getSnapshots(); LOGGER.info(String.format("Got %d EBS snapshots in region %s.", snapshots.size(), region)); return snapshots; } @Override public void createTagsForResources(Map<String, String> keyValueMap, String... resourceIds) { Validate.notNull(keyValueMap); Validate.notEmpty(keyValueMap); Validate.notNull(resourceIds); Validate.notEmpty(resourceIds); AmazonEC2 ec2Client = ec2Client(); List<Tag> tags = new ArrayList<Tag>(); for (Map.Entry<String, String> entry : keyValueMap.entrySet()) { tags.add(new Tag(entry.getKey(), entry.getValue())); } CreateTagsRequest req = new CreateTagsRequest(Arrays.asList(resourceIds), tags); ec2Client.createTags(req); } /** * Describe a set of specific images. * * @param imageIds the image ids * @return the images */ public List<Image> describeImages(String... imageIds) { if (imageIds == null || imageIds.length == 0) { LOGGER.info(String.format("Getting all AMIs in region %s.", region)); } else { LOGGER.info(String.format("Getting AMIs for %d ids in region %s.", imageIds.length, region)); } AmazonEC2 ec2Client = ec2Client(); DescribeImagesRequest request = new DescribeImagesRequest(); if (imageIds != null) { request.setImageIds(Arrays.asList(imageIds)); } DescribeImagesResult result = ec2Client.describeImages(request); List<Image> images = result.getImages(); LOGGER.info(String.format("Got %d AMIs in region %s.", images.size(), region)); return images; } @Override public void detachVolume(String instanceId, String volumeId, boolean force) { Validate.notEmpty(instanceId); LOGGER.info(String.format("Detach volumes from instance %s in region %s.", instanceId, region)); try { DetachVolumeRequest detachVolumeRequest = new DetachVolumeRequest(); detachVolumeRequest.setForce(force); detachVolumeRequest.setInstanceId(instanceId); detachVolumeRequest.setVolumeId(volumeId); ec2Client().detachVolume(detachVolumeRequest); } catch (AmazonServiceException e) { if (e.getErrorCode().equals("InvalidInstanceID.NotFound")) { throw new NotFoundException("AWS instance " + instanceId + " not found", e); } throw e; } } @Override public List<String> listAttachedVolumes(String instanceId, boolean includeRoot) { Validate.notEmpty(instanceId); LOGGER.info(String.format("Listing volumes attached to instance %s in region %s.", instanceId, region)); try { List<String> volumeIds = new ArrayList<String>(); for (Instance instance : describeInstances(instanceId)) { String rootDeviceName = instance.getRootDeviceName(); for (InstanceBlockDeviceMapping ibdm : instance.getBlockDeviceMappings()) { EbsInstanceBlockDevice ebs = ibdm.getEbs(); if (ebs == null) { continue; } String volumeId = ebs.getVolumeId(); if (Strings.isNullOrEmpty(volumeId)) { continue; } if (!includeRoot && rootDeviceName != null && rootDeviceName.equals(ibdm.getDeviceName())) { continue; } volumeIds.add(volumeId); } } return volumeIds; } catch (AmazonServiceException e) { if (e.getErrorCode().equals("InvalidInstanceID.NotFound")) { throw new NotFoundException("AWS instance " + instanceId + " not found", e); } throw e; } } /** * Describe a set of security groups. * * @param groupNames the names of the groups to find * @return a list of matching groups */ public List<SecurityGroup> describeSecurityGroups(String... groupNames) { AmazonEC2 ec2Client = ec2Client(); DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest(); if (groupNames == null || groupNames.length == 0) { LOGGER.info(String.format("Getting all EC2 security groups in region %s.", region)); } else { LOGGER.info(String.format("Getting EC2 security groups for %d names in region %s.", groupNames.length, region)); request.withGroupNames(groupNames); } DescribeSecurityGroupsResult result; try { result = ec2Client.describeSecurityGroups(request); } catch (AmazonServiceException e) { if (e.getErrorCode().equals("InvalidGroup.NotFound")) { LOGGER.info("Got InvalidGroup.NotFound error for security groups; returning empty list"); return Collections.emptyList(); } throw e; } List<SecurityGroup> securityGroups = result.getSecurityGroups(); LOGGER.info(String.format("Got %d EC2 security groups in region %s.", securityGroups.size(), region)); return securityGroups; } /** {@inheritDoc} */ public String createSecurityGroup(String instanceId, String name, String description) { String vpcId = getVpcId(instanceId); AmazonEC2 ec2Client = ec2Client(); CreateSecurityGroupRequest request = new CreateSecurityGroupRequest(); request.setGroupName(name); request.setDescription(description); request.setVpcId(vpcId); LOGGER.info(String.format("Creating EC2 security group %s.", name)); CreateSecurityGroupResult result = ec2Client.createSecurityGroup(request); return result.getGroupId(); } /** * Convenience wrapper around describeInstances, for a single instance id. * * @param instanceId id of instance to find * @return the instance info, or null if instance not found */ public Instance describeInstance(String instanceId) { Instance instance = null; for (Instance i : describeInstances(instanceId)) { if (instance != null) { throw new IllegalStateException("Duplicate instance: " + instanceId); } instance = i; } return instance; } /** {@inheritDoc} */ @Override public ComputeService getJcloudsComputeService() { if (jcloudsComputeService == null) { synchronized(this) { if (jcloudsComputeService == null) { AWSCredentials awsCredentials = awsCredentialsProvider.getCredentials(); String username = awsCredentials.getAWSAccessKeyId(); String password = awsCredentials.getAWSSecretKey(); Credentials credentials; if (awsCredentials instanceof AWSSessionCredentials) { AWSSessionCredentials awsSessionCredentials = (AWSSessionCredentials) awsCredentials; credentials = SessionCredentials.builder().accessKeyId(username).secretAccessKey(password) .sessionToken(awsSessionCredentials.getSessionToken()).build(); } else { credentials = new Credentials(username, password); } ComputeServiceContext jcloudsContext = ContextBuilder.newBuilder("aws-ec2") .credentialsSupplier(Suppliers.ofInstance(credentials)) .modules(ImmutableSet.<Module>of(new SLF4JLoggingModule(), new JschSshClientModule())) .buildView(ComputeServiceContext.class); this.jcloudsComputeService = jcloudsContext.getComputeService(); } } } return jcloudsComputeService; } /** {@inheritDoc} */ @Override public String getJcloudsId(String instanceId) { return this.region + "/" + instanceId; } @Override public SshClient connectSsh(String instanceId, LoginCredentials credentials) { ComputeService computeService = getJcloudsComputeService(); String jcloudsId = getJcloudsId(instanceId); NodeMetadata node = getJcloudsNode(computeService, jcloudsId); node = NodeMetadataBuilder.fromNodeMetadata(node).credentials(credentials).build(); Utils utils = computeService.getContext().utils(); SshClient ssh = utils.sshForNode().apply(node); ssh.connect(); return ssh; } private NodeMetadata getJcloudsNode(ComputeService computeService, String jcloudsId) { // Work around a jclouds bug / documentation issue... // TODO: Figure out what's broken, and eliminate this function // This should work (?): // Set<NodeMetadata> nodes = computeService.listNodesByIds(Collections.singletonList(jcloudsId)); Set<NodeMetadata> nodes = Sets.newHashSet(); for (ComputeMetadata n : computeService.listNodes()) { if (jcloudsId.equals(n.getId())) { nodes.add((NodeMetadata) n); } } if (nodes.isEmpty()) { LOGGER.warn("Unable to find jclouds node: {}", jcloudsId); for (ComputeMetadata n : computeService.listNodes()) { LOGGER.info("Did find node: {}", n); } throw new IllegalStateException("Unable to find node using jclouds: " + jcloudsId); } NodeMetadata node = Iterables.getOnlyElement(nodes); return node; } /** {@inheritDoc} */ @Override public String findSecurityGroup(String instanceId, String groupName) { String vpcId = getVpcId(instanceId); SecurityGroup found = null; List<SecurityGroup> securityGroups = describeSecurityGroups(vpcId, groupName); for (SecurityGroup sg : securityGroups) { if (Objects.equal(vpcId, sg.getVpcId())) { if (found != null) { throw new IllegalStateException("Duplicate security groups found"); } found = sg; } } if (found == null) { return null; } return found.getGroupId(); } /** * Gets the VPC id for the given instance. * * @param instanceId * instance we're checking * @return vpc id, or null if not a vpc instance */ String getVpcId(String instanceId) { Instance awsInstance = describeInstance(instanceId); String vpcId = awsInstance.getVpcId(); if (Strings.isNullOrEmpty(vpcId)) { return null; } return vpcId; } /** {@inheritDoc} */ @Override public boolean canChangeInstanceSecurityGroups(String instanceId) { return null != getVpcId(instanceId); } }
4,908
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/client/aws
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/client/aws/chaos/TagPredicate.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.simianarmy.client.aws.chaos; import com.amazonaws.services.autoscaling.model.TagDescription; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.netflix.simianarmy.chaos.ChaosCrawler; /** * * The Class TagPredicate. This will apply the tag-key and the tag-value filter on the list of InstanceGroups . */ public class TagPredicate implements Predicate<ChaosCrawler.InstanceGroup> { private final String key, value; public TagPredicate(String key, String value) { this.key = key; this.value = value; } @Override public boolean apply(ChaosCrawler.InstanceGroup instanceGroup) { return Iterables.any(instanceGroup.tags(), new com.google.common.base.Predicate<TagDescription>() { @Override public boolean apply(TagDescription tagDescription) { return tagDescription.getKey().equals(key) && tagDescription.getValue().equals(value); } }); } }
4,909
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/client/aws
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/client/aws/chaos/FilteringChaosCrawler.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.simianarmy.client.aws.chaos; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.netflix.simianarmy.chaos.ChaosCrawler; import java.util.EnumSet; import java.util.List; /** * The Class FilteringChaosCrawler. This will filter the result from ASGChaosCrawler for all available AutoScalingGroups associated with the AWS account based on requested filter. */ public class FilteringChaosCrawler implements ChaosCrawler { private final ChaosCrawler crawler; private final Predicate<? super InstanceGroup> predicate; public FilteringChaosCrawler(ChaosCrawler crawler, Predicate<? super InstanceGroup> predicate) { this.crawler = crawler; this.predicate = predicate; } /** {@inheritDoc} */ @Override public EnumSet<?> groupTypes() { return crawler.groupTypes(); } /** {@inheritDoc} */ @Override public List<InstanceGroup> groups() { return filter(crawler.groups()); } /** {@inheritDoc} */ @Override public List<InstanceGroup> groups(String... names) { return filter(crawler.groups(names)); } /** * Return the filtered list of InstanceGroups using the requested predicate. The filter is applied on the InstanceGroup retrieved from the ASGChaosCrawler class. * @param list list of InstanceGroups result of the chaos crawler * @return The appropriate {@link InstanceGroup} */ protected List<InstanceGroup> filter(List<InstanceGroup> list) { return Lists.newArrayList(Iterables.filter(list, predicate)); } }
4,910
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/client/aws
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/client/aws/chaos/ASGChaosCrawler.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.simianarmy.client.aws.chaos; import java.util.EnumSet; import java.util.LinkedList; import java.util.List; import com.amazonaws.services.autoscaling.model.AutoScalingGroup; import com.amazonaws.services.autoscaling.model.Instance; import com.amazonaws.services.autoscaling.model.TagDescription; import com.netflix.simianarmy.GroupType; import com.netflix.simianarmy.basic.chaos.BasicChaosMonkey; import com.netflix.simianarmy.basic.chaos.BasicInstanceGroup; import com.netflix.simianarmy.chaos.ChaosCrawler; import com.netflix.simianarmy.client.aws.AWSClient; import com.netflix.simianarmy.tunable.TunableInstanceGroup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The Class ASGChaosCrawler. This will crawl for all available AutoScalingGroups associated with the AWS account. */ public class ASGChaosCrawler implements ChaosCrawler { /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(ASGChaosCrawler.class); /** * The key of the tag that set the aggression coefficient */ private static final String CHAOS_MONKEY_AGGRESSION_COEFFICIENT_KEY = "chaosMonkey.aggressionCoefficient"; /** * The group types Types. */ public enum Types implements GroupType { /** only crawls AutoScalingGroups. */ ASG; } /** The aws client. */ private final AWSClient awsClient; /** * Instantiates a new basic chaos crawler. * * @param awsClient * the aws client */ public ASGChaosCrawler(AWSClient awsClient) { this.awsClient = awsClient; } /** {@inheritDoc} */ @Override public EnumSet<?> groupTypes() { return EnumSet.allOf(Types.class); } /** {@inheritDoc} */ @Override public List<InstanceGroup> groups() { return groups((String[]) null); } @Override public List<InstanceGroup> groups(String... names) { List<InstanceGroup> list = new LinkedList<InstanceGroup>(); for (AutoScalingGroup asg : awsClient.describeAutoScalingGroups(names)) { InstanceGroup ig = getInstanceGroup(asg, findAggressionCoefficient(asg)); for (Instance inst : asg.getInstances()) { ig.addInstance(inst.getInstanceId()); } list.add(ig); } return list; } /** * Returns the desired InstanceGroup. If there is no set aggression coefficient, then it * returns the basic impl, otherwise it returns the tunable impl. * @param asg The autoscaling group * @return The appropriate {@link InstanceGroup} */ protected InstanceGroup getInstanceGroup(AutoScalingGroup asg, double aggressionCoefficient) { InstanceGroup instanceGroup; // if coefficient is 1 then the BasicInstanceGroup is fine, otherwise use Tunable if (aggressionCoefficient == 1.0) { instanceGroup = new BasicInstanceGroup(asg.getAutoScalingGroupName(), Types.ASG, awsClient.region(), asg.getTags()); } else { TunableInstanceGroup tunable = new TunableInstanceGroup(asg.getAutoScalingGroupName(), Types.ASG, awsClient.region(), asg.getTags()); tunable.setAggressionCoefficient(aggressionCoefficient); instanceGroup = tunable; } return instanceGroup; } /** * Reads tags on AutoScalingGroup looking for the tag for the aggression coefficient * and determines the coefficient value. The default value is 1 if there no tag or * if the value in the tag is not a parsable number. * * @param asg The AutoScalingGroup that might have an aggression coefficient tag * @return The set or default aggression coefficient. */ protected double findAggressionCoefficient(AutoScalingGroup asg) { List<TagDescription> tagDescriptions = asg.getTags(); double aggression = 1.0; for (TagDescription tagDescription : tagDescriptions) { if ( CHAOS_MONKEY_AGGRESSION_COEFFICIENT_KEY.equalsIgnoreCase(tagDescription.getKey()) ) { String value = tagDescription.getValue(); // prevent NPE on parseDouble if (value == null) { break; } try { aggression = Double.parseDouble(value); LOGGER.info("Aggression coefficient of {} found for ASG {}", value, asg.getAutoScalingGroupName()); } catch (NumberFormatException e) { LOGGER.warn("Unparsable value of {} found in tag {} for ASG {}", value, CHAOS_MONKEY_AGGRESSION_COEFFICIENT_KEY, asg.getAutoScalingGroupName()); aggression = 1.0; } // stop looking break; } } return aggression; } }
4,911
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/client
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/client/edda/EddaClient.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.simianarmy.client.edda; import com.netflix.simianarmy.MonkeyConfiguration; import com.netflix.simianarmy.client.MonkeyRestClient; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The REST client to access Edda to get the history of a cloud resource. */ public class EddaClient extends MonkeyRestClient { private static final Logger LOGGER = LoggerFactory.getLogger(EddaClient.class); private final MonkeyConfiguration config; /** * Constructor. * @param timeout the timeout in milliseconds * @param maxRetries the max number of retries * @param retryInterval the interval in milliseconds between retries * @param config the monkey configuration */ public EddaClient(int timeout, int maxRetries, int retryInterval, MonkeyConfiguration config) { super(timeout, maxRetries, retryInterval); this.config = config; } @Override public String getBaseUrl(String region) { Validate.notEmpty(region); String baseUrl = config.getStr("simianarmy.janitor.edda.endpoint." + region); if (StringUtils.isBlank(baseUrl)) { LOGGER.error(String.format("No endpoint of Edda is found for region %s.", region)); } return baseUrl; } }
4,912
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/tunable/TunableInstanceGroup.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.simianarmy.tunable; import com.amazonaws.services.autoscaling.model.TagDescription; import com.netflix.simianarmy.GroupType; import com.netflix.simianarmy.basic.chaos.BasicInstanceGroup; import java.util.List; /** * Allows for individual InstanceGroups to alter the aggressiveness * of ChaosMonkey. * * @author jeffggardner * */ public class TunableInstanceGroup extends BasicInstanceGroup { public TunableInstanceGroup(String name, GroupType type, String region, List<TagDescription> tags) { super(name, type, region, tags); } private double aggressionCoefficient = 1.0; /** * @return the aggressionCoefficient */ public final double getAggressionCoefficient() { return aggressionCoefficient; } /** * @param aggressionCoefficient the aggressionCoefficient to set */ public final void setAggressionCoefficient(double aggressionCoefficient) { this.aggressionCoefficient = aggressionCoefficient; } }
4,913
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/tunable/TunablyAggressiveChaosMonkey.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.simianarmy.tunable; import com.netflix.simianarmy.basic.chaos.BasicChaosMonkey; import com.netflix.simianarmy.chaos.ChaosCrawler.InstanceGroup; /** * This class modifies the probability by multiplying the configured * probability by the aggression coefficient tag on the instance group. * * @author jeffggardner */ public class TunablyAggressiveChaosMonkey extends BasicChaosMonkey { public TunablyAggressiveChaosMonkey(Context ctx) { super(ctx); } /** * Gets the tuned probability value, returns 0 if the group is not * enabled. Calls getEffectiveProbability and modifies that value if * the instance group is a TunableInstanceGroup. * * @param group The instance group * @return the effective probability value for the instance group */ @Override protected double getEffectiveProbability(InstanceGroup group) { if (!isGroupEnabled(group)) { return 0; } double probability = getEffectiveProbabilityFromCfg(group); // if this instance group is tunable, then factor in the aggression coefficient if (group instanceof TunableInstanceGroup ) { TunableInstanceGroup tunable = (TunableInstanceGroup) group; probability *= tunable.getAggressionCoefficient(); } return probability; } }
4,914
0
Create_ds/dgs-codegen/graphql-dgs-codegen-shared-core/src/test/java/com/netflix/graphql/dgs/client
Create_ds/dgs-codegen/graphql-dgs-codegen-shared-core/src/test/java/com/netflix/graphql/dgs/client/codegen/MovieInput.java
/* * * Copyright 2020 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.graphql.dgs.client.codegen; import java.util.List; public class MovieInput { private int movieId; private String title; private Genre genre; private Director director; private List<Actor> actor; private DateRange releaseWindow; public MovieInput(int movieId, String title, Genre genre, Director director, List<Actor> actor, DateRange releaseWindow) { this.movieId = movieId; this.title = title; this.genre = genre; this.director = director; this.actor = actor; this.releaseWindow = releaseWindow; } public MovieInput(int movieId) { this.movieId = movieId; } public enum Genre { ACTION,DRAMA } public static class Director { private String name; Director(String name) { this.name = name; } } public static class Actor { private String name; private String roleName; Actor(String name, String roleName) { this.name = name; this.roleName = roleName; } } }
4,915
0
Create_ds/dgs-codegen/graphql-dgs-codegen-shared-core/src/test/java/com/netflix/graphql/dgs/client/codegen
Create_ds/dgs-codegen/graphql-dgs-codegen-shared-core/src/test/java/com/netflix/graphql/dgs/client/codegen/exampleprojection/ShowsProjectionRoot.java
/* * Copyright 2021 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.graphql.dgs.client.codegen.exampleprojection; import com.netflix.graphql.dgs.client.codegen.BaseProjectionNode; import com.netflix.graphql.dgs.client.codegen.BaseSubProjectionNode; import java.time.OffsetDateTime; import java.util.ArrayList; public class ShowsProjectionRoot extends BaseProjectionNode { public Shows_ReviewsProjection reviews() { Shows_ReviewsProjection projection = new Shows_ReviewsProjection(this, this); getFields().put("reviews", projection); return projection; } public Shows_ReviewsProjection reviews(Integer minScore, OffsetDateTime since) { Shows_ReviewsProjection projection = new Shows_ReviewsProjection(this, this); getFields().put("reviews", projection); getInputArguments().computeIfAbsent("reviews", k -> new ArrayList<>()); InputArgument minScoreArg = new InputArgument("minScore", minScore); getInputArguments().get("reviews").add(minScoreArg); InputArgument sinceArg = new InputArgument("since", since); getInputArguments().get("reviews").add(sinceArg); return projection; } public ShowsProjectionRoot id() { getFields().put("id", null); return this; } public ShowsProjectionRoot title() { getFields().put("title", null); return this; } public ShowsProjectionRoot releaseYear() { getFields().put("releaseYear", null); return this; } public static class Shows_ReviewsProjection extends BaseSubProjectionNode<ShowsProjectionRoot, ShowsProjectionRoot> { public Shows_ReviewsProjection(ShowsProjectionRoot parent, ShowsProjectionRoot root) { super(parent, root); } public Shows_ReviewsProjection username() { getFields().put("username", null); return this; } public Shows_ReviewsProjection starScore() { getFields().put("starScore", null); return this; } public Shows_ReviewsProjection submittedDate() { getFields().put("submittedDate", null); return this; } } }
4,916
0
Create_ds/dgs-codegen/graphql-dgs-codegen-gradle/src/test/resources/test-project-no-schema-files/src.main/java/com/netflix
Create_ds/dgs-codegen/graphql-dgs-codegen-gradle/src/test/resources/test-project-no-schema-files/src.main/java/com/netflix/testproject/Foo.java
package com.netflix.testproject; public class Foo { public static void main(String[] args) { System.out.println("Hello, world!"); } }
4,917
0
Create_ds/dgs-codegen/graphql-dgs-codegen-gradle/src/test/resources/test-project/src/main/java/com/netflix
Create_ds/dgs-codegen/graphql-dgs-codegen-gradle/src/test/resources/test-project/src/main/java/com/netflix/testproject/Foo.java
package com.netflix.testproject; public class Foo { public static void main(String[] args) { System.out.println("Hello, world!"); } }
4,918
0
Create_ds/dgs-codegen/graphql-dgs-codegen-gradle/src/main/java/com/netflix/graphql/dgs/codegen
Create_ds/dgs-codegen/graphql-dgs-codegen-gradle/src/main/java/com/netflix/graphql/dgs/codegen/gradle/CodegenPluginExtension.java
/* * * Copyright 2020 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.graphql.dgs.codegen.gradle; import org.gradle.api.provider.Property; public abstract class CodegenPluginExtension { public CodegenPluginExtension() { getClientCoreConventionsEnabled().convention(true); } public abstract Property<Boolean> getClientCoreConventionsEnabled(); public abstract Property<String> getClientCoreVersion(); /** * Describes the configuration/scope that the client-core library is going to be added to. * It defaults to {@link ClientUtilsConventions#GRADLE_CLASSPATH_CONFIGURATION} */ public abstract Property<String> getClientCoreScope(); }
4,919
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/TestUtils.java
package software.amazon.cryptography.dbencryptionsdk.dynamodb; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionFlags; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.DirectKmsMaterialProvider; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.AWSKMSClientBuilder; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.*; import software.amazon.cryptography.keystore.KeyStore; import software.amazon.cryptography.keystore.model.KMSConfiguration; import software.amazon.cryptography.keystore.model.KeyStoreConfig; import software.amazon.cryptography.materialproviders.IBranchKeyIdSupplier; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.MaterialProviders; import software.amazon.cryptography.materialproviders.model.*; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import java.nio.ByteBuffer; import java.util.*; public class TestUtils { // Many of these constants are copied from submodules/MaterialProviders/AwsCryptographicMaterialProviders/dafny/AwsCryptographyKeyStore/test/Fixtures.dfy public static final String TEST_TABLE_NAME = "DynamoDbEncryptionInterceptorTestTable"; public static final String TEST_PARTITION_NAME = "partition_key"; public static final String TEST_SORT_NAME = "sort_key"; public static final String TEST_ATTR_NAME = "attr1"; public static final String TEST_ATTR2_NAME = "attr2"; public static final String TEST_KEY_STORE_NAME = "KeyStoreDdbTable"; public static final String TEST_KEY_STORE_KMS_KEY = "arn:aws:kms:us-west-2:370957321024:key/9d989aa2-2f9c-438c-a745-cc57d3ad0126"; public static final String BRANCH_KEY_ID = "75789115-1deb-4fe3-a2ec-be9e885d1945"; public static final String ALTERNATE_BRANCH_KEY_ID = "4bb57643-07c1-419e-92ad-0df0df149d7c"; public static final String KMS_TEST_KEY_ID = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; public static KeyStore createKeyStore() { return KeyStore.builder().KeyStoreConfig( KeyStoreConfig.builder() .ddbClient(DynamoDbClient.create()) .ddbTableName(TEST_KEY_STORE_NAME) .logicalKeyStoreName(TEST_KEY_STORE_NAME) .kmsClient(KmsClient.create()) .kmsConfiguration( KMSConfiguration.builder() .kmsKeyArn(TEST_KEY_STORE_KMS_KEY) .build() ) .build() ).build(); } public static IKeyring createStaticKeyring() { ByteBuffer key = ByteBuffer.wrap(new byte[32]); return createStaticKeyring(key); } public static IKeyring createStaticKeyring(ByteBuffer aesKey) { MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); CreateRawAesKeyringInput keyringInput = CreateRawAesKeyringInput.builder() .keyName("name") .keyNamespace("namespace") .wrappingAlg(AesWrappingAlg.ALG_AES256_GCM_IV12_TAG16) .wrappingKey(aesKey) .build(); return matProv.CreateRawAesKeyring(keyringInput); } public static IKeyring createKmsKeyring(String kmsKeyId) { MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); CreateAwsKmsKeyringInput keyringInput = CreateAwsKmsKeyringInput.builder() .kmsKeyId(kmsKeyId) .kmsClient(KmsClient.create()) .build(); return matProv.CreateAwsKmsKeyring(keyringInput); } public static IKeyring createKmsKeyring() { return createKmsKeyring(KMS_TEST_KEY_ID); } public static IKeyring createHierarchicalKeyring(KeyStore keystore, String branchKeyId) { return createHierarchicalKeyring(keystore, branchKeyId, null); } public static IKeyring createHierarchicalKeyring(KeyStore keystore, IBranchKeyIdSupplier supplier) { return createHierarchicalKeyring(keystore, null, supplier); } public static IKeyring createHierarchicalKeyring(KeyStore keystore, String branchKeyId, IBranchKeyIdSupplier keyIdSupplier) { MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); CreateAwsKmsHierarchicalKeyringInput.Builder keyringInputBuilder = CreateAwsKmsHierarchicalKeyringInput.builder() .keyStore(keystore) .ttlSeconds(600); if (branchKeyId != null) { keyringInputBuilder = keyringInputBuilder.branchKeyId(branchKeyId); } if (keyIdSupplier != null) { keyringInputBuilder = keyringInputBuilder.branchKeyIdSupplier(keyIdSupplier); } return matProv.CreateAwsKmsHierarchicalKeyring(keyringInputBuilder.build()); } public static DynamoDbEncryptionInterceptor createInterceptor( Map<String, CryptoAction> actions, List<String> allowedUnauth, IKeyring keyring, LegacyPolicy legacyPolicy, PlaintextOverride ptPolicy) { Map<String, DynamoDbTableEncryptionConfig> tableConfigs = new HashMap<>(); DynamoDbTableEncryptionConfig.Builder builder = DynamoDbTableEncryptionConfig.builder() .logicalTableName(TEST_TABLE_NAME) .partitionKeyName(TEST_PARTITION_NAME) .sortKeyName(TEST_SORT_NAME) .attributeActionsOnEncrypt(actions) .algorithmSuiteId(DBEAlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_SYMSIG_HMAC_SHA384) .keyring(keyring); if (!allowedUnauth.isEmpty()) { builder = builder.allowedUnsignedAttributes(allowedUnauth); } if (null != legacyPolicy) { builder = builder.legacyOverride(createLegacyOverride(legacyPolicy)); } if (null != ptPolicy) { builder = builder.plaintextOverride(ptPolicy); } tableConfigs.put(TEST_TABLE_NAME, builder.build()); return DynamoDbEncryptionInterceptor.builder() .config(DynamoDbTablesEncryptionConfig.builder() .tableEncryptionConfigs(tableConfigs) .build()) .build(); } public static DynamoDbEncryptionInterceptor createInterceptor(IKeyring keyring, LegacyPolicy legacyPolicy, PlaintextOverride ptPolicy) { Map<String, CryptoAction> actions = new HashMap<>(); actions.put(TEST_PARTITION_NAME, CryptoAction.SIGN_ONLY); actions.put(TEST_SORT_NAME, CryptoAction.SIGN_ONLY); actions.put(TEST_ATTR_NAME, CryptoAction.ENCRYPT_AND_SIGN); actions.put(TEST_ATTR2_NAME, CryptoAction.DO_NOTHING); List<String> allowedUnauth = Arrays.asList(TEST_ATTR2_NAME); return createInterceptor(actions, allowedUnauth, keyring, legacyPolicy, ptPolicy); } public static Map<String, AttributeValue> createTestItem(String partition, String sort, String attr1, String attr2) { HashMap<String, AttributeValue> item = new HashMap<>(); item.put(TEST_PARTITION_NAME, AttributeValue.builder().s(partition).build()); item.put(TEST_SORT_NAME, AttributeValue.builder().n(sort).build()); item.put(TEST_ATTR_NAME, AttributeValue.builder().s(attr1).build()); item.put(TEST_ATTR2_NAME, AttributeValue.builder().s(attr2).build()); return item; } public static Map<String, com.amazonaws.services.dynamodbv2.model.AttributeValue> createLegacyTestItem( String partition, String sort, String attr1, String attr2) { HashMap<String, com.amazonaws.services.dynamodbv2.model.AttributeValue> item = new HashMap<>(); item.put(TEST_PARTITION_NAME, new com.amazonaws.services.dynamodbv2.model.AttributeValue().withS(partition)); item.put(TEST_SORT_NAME, new com.amazonaws.services.dynamodbv2.model.AttributeValue().withN(sort)); item.put(TEST_ATTR_NAME, new com.amazonaws.services.dynamodbv2.model.AttributeValue().withS(attr1)); item.put(TEST_ATTR2_NAME, new com.amazonaws.services.dynamodbv2.model.AttributeValue().withS(attr2)); return item; } public static Map<String, AttributeValue> createTestKey(String partition, String sort) { HashMap<String, AttributeValue> key = new HashMap<>(); key.put(TEST_PARTITION_NAME, AttributeValue.builder().s(partition).build()); key.put(TEST_SORT_NAME, AttributeValue.builder().n(sort).build()); return key; } public static LegacyOverride createLegacyOverride(LegacyPolicy policy) { DynamoDBEncryptor legacyEncryptor = createLegacyEncryptor(); // These do not have to match the schema for non-Legacy items, // but MUST match what createLegacyEncryptor returns for testing Map<String, CryptoAction> legacyActions = new HashMap<>(); legacyActions.put(TEST_PARTITION_NAME, CryptoAction.SIGN_ONLY); legacyActions.put(TEST_SORT_NAME, CryptoAction.SIGN_ONLY); legacyActions.put(TEST_ATTR_NAME, CryptoAction.ENCRYPT_AND_SIGN); legacyActions.put(TEST_ATTR2_NAME, CryptoAction.DO_NOTHING); return LegacyOverride .builder() .encryptor(legacyEncryptor) .policy(policy) .attributeActionsOnEncrypt(legacyActions) .build(); } public static DynamoDBEncryptor createLegacyEncryptor() { AWSKMS kms = AWSKMSClientBuilder.standard().build(); DirectKmsMaterialProvider cmp = new DirectKmsMaterialProvider(kms, KMS_TEST_KEY_ID); return DynamoDBEncryptor.getInstance(cmp); } public static Map<String, Set<EncryptionFlags>> createLegacyAttributeFlags() { // test item values don't matter, we just need the right keys Map<String, AttributeValue> item = createTestItem("foo", "fi","fo", "fum"); EnumSet<EncryptionFlags> signOnly = EnumSet.of(EncryptionFlags.SIGN); EnumSet<EncryptionFlags> encryptAndSign = EnumSet.of(EncryptionFlags.ENCRYPT, EncryptionFlags.SIGN); Map<String, Set<EncryptionFlags>> actions = new HashMap<>(); for (final String attributeName : item.keySet()) { switch (attributeName) { case TEST_PARTITION_NAME: // fall through case TEST_SORT_NAME: actions.put(attributeName, signOnly); break; case TEST_ATTR2_NAME: break; default: actions.put(attributeName, encryptAndSign); break; } } return actions; } }
4,920
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/DynamoDbEncryptionInterceptorTest.java
package software.amazon.cryptography.dbencryptionsdk.dynamodb; import org.testng.annotations.BeforeTest; import software.amazon.awssdk.core.ClientType; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.interceptor.*; import software.amazon.awssdk.core.util.DefaultSdkAutoConstructMap; import software.amazon.awssdk.services.dynamodb.model.*; import java.util.*; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.DynamoDbItemEncryptorException; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbEncryptionException; import software.amazon.cryptography.dbencryptionsdk.dynamodb.transforms.model.DynamoDbEncryptionTransformsException; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import static org.testng.Assert.*; import static software.amazon.cryptography.dbencryptionsdk.dynamodb.TestUtils.*; import org.testng.annotations.Test; public class DynamoDbEncryptionInterceptorTest { static DynamoDbEncryptionInterceptor interceptor; static ExecutionAttributes validAttributes; @BeforeTest public static void setup() { interceptor = createInterceptor(createKmsKeyring(), null, null); validAttributes = ExecutionAttributes.builder() .put(SdkExecutionAttribute.SERVICE_NAME, "DynamoDb") .put(SdkExecutionAttribute.CLIENT_TYPE, ClientType.SYNC) .build(); } @Test public void TestPutItemEncryptsAccordingToAttributeActions() { String partitionValue = "foo"; String sortValue = "42"; String attrValue = "encrypt"; String attrValue2 = "do nothing"; Map<String, AttributeValue> item = createTestItem(partitionValue, sortValue, attrValue, attrValue2); PutItemRequest oldRequest = PutItemRequest.builder() .tableName(TEST_TABLE_NAME) .item(item) .conditionExpression(TEST_ATTR2_NAME + " < :a") .build(); Context.ModifyRequest context = InterceptorContext.builder() .request(oldRequest) .build(); ExecutionAttributes attributes = validAttributes.toBuilder() .put(SdkExecutionAttribute.OPERATION_NAME, "PutItem") .build(); SdkRequest newRequest = interceptor.modifyRequest(context, attributes); assertTrue(newRequest instanceof PutItemRequest); // ENCRYPT_AND_SIGN results in changed attribute assertNotEquals(oldRequest.item().get(TEST_ATTR_NAME), ((PutItemRequest) newRequest).item().get(TEST_ATTR_NAME)); // SIGN_ONLY and DO_NOTHING does not modify any attribute values assertEquals(oldRequest.item().get(TEST_ATTR2_NAME), ((PutItemRequest) newRequest).item().get(TEST_ATTR2_NAME)); assertEquals(oldRequest.item().get(TEST_PARTITION_NAME), ((PutItemRequest) newRequest).item().get(TEST_PARTITION_NAME)); assertEquals(oldRequest.item().get(TEST_SORT_NAME), ((PutItemRequest) newRequest).item().get(TEST_SORT_NAME)); } @Test( expectedExceptions = DynamoDbEncryptionTransformsException.class, expectedExceptionsMessageRegExp = "^Condition Expressions forbidden on encrypted attributes : attr1$" ) public void TestPutItemGetItemWithConditionExpressionBad() { PutItemRequest oldRequest = PutItemRequest.builder() .tableName(TEST_TABLE_NAME) .conditionExpression(TEST_ATTR_NAME + " < :a") .build(); Context.ModifyRequest context = InterceptorContext.builder() .request(oldRequest) .build(); ExecutionAttributes attributes = validAttributes.toBuilder() .put(SdkExecutionAttribute.OPERATION_NAME, "PutItem") .build(); interceptor.modifyRequest(context, attributes); } @Test public void TestUpdateItemOnEncryptedTableGood() { UpdateItemRequest oldRequest = UpdateItemRequest.builder() .tableName(TEST_TABLE_NAME) .key(Collections.EMPTY_MAP) .updateExpression("SET " + TEST_ATTR2_NAME + " = :p") .build(); Context.ModifyRequest context = InterceptorContext.builder() .request(oldRequest) .build(); ExecutionAttributes attributes = validAttributes.toBuilder() .put(SdkExecutionAttribute.OPERATION_NAME, "UpdateItem") .build(); SdkRequest newRequest = interceptor.modifyRequest(context, attributes); assertEquals(oldRequest, newRequest); } @Test( expectedExceptions = DynamoDbEncryptionTransformsException.class, expectedExceptionsMessageRegExp = "Update Expressions forbidden on signed attributes : " + TEST_ATTR_NAME ) public void TestUpdateItemOnEncryptedTableBad() throws Exception { UpdateItemRequest oldRequest = UpdateItemRequest.builder() .tableName(TEST_TABLE_NAME) .key(Collections.EMPTY_MAP) .updateExpression("SET " + TEST_ATTR_NAME + " = :p") .build(); Context.ModifyRequest context = InterceptorContext.builder() .request(oldRequest) .build(); ExecutionAttributes attributes = validAttributes.toBuilder() .put(SdkExecutionAttribute.OPERATION_NAME, "UpdateItem") .build(); interceptor.modifyRequest(context, attributes); } @Test public void TestUpdateItemOnNonEncryptedTable() { UpdateItemRequest oldRequest = UpdateItemRequest.builder() .tableName("otherTable") .key(Collections.EMPTY_MAP) .build(); Context.ModifyRequest context = InterceptorContext.builder() .request(oldRequest) .build(); ExecutionAttributes attributes = validAttributes.toBuilder() .put(SdkExecutionAttribute.OPERATION_NAME, "UpdateItem") .build(); SdkRequest newRequest = interceptor.modifyRequest(context, attributes); assertEquals(oldRequest, newRequest); } @Test( expectedExceptions = DynamoDbEncryptionTransformsException.class, expectedExceptionsMessageRegExp = "Condition Expressions forbidden on encrypted attributes : attr1" ) public void TestTransactWriteItemsWithConditionCheck() { TransactWriteItemsRequest oldRequest = TransactWriteItemsRequest.builder() .transactItems( TransactWriteItem.builder() .put(Put.builder() .tableName(TEST_TABLE_NAME) .build()) .conditionCheck(ConditionCheck.builder() .tableName(TEST_TABLE_NAME) .conditionExpression(TEST_ATTR_NAME + " < :a") .build()) .build()) .build(); Context.ModifyRequest context = InterceptorContext.builder() .request(oldRequest) .build(); ExecutionAttributes attributes = validAttributes.toBuilder() .put(SdkExecutionAttribute.OPERATION_NAME, "TransactWriteItems") .build(); interceptor.modifyRequest(context, attributes); } @Test( expectedExceptions = DynamoDbEncryptionTransformsException.class, expectedExceptionsMessageRegExp = "Condition Expressions forbidden on encrypted attributes : attr1" ) public void TestTransactWriteItemsWithPutConditionExpression() { TransactWriteItemsRequest oldRequest = TransactWriteItemsRequest.builder() .transactItems( TransactWriteItem.builder() .put(Put.builder() .tableName(TEST_TABLE_NAME) .conditionExpression(TEST_ATTR_NAME + " < :a") .build()) .build()) .build(); Context.ModifyRequest context = InterceptorContext.builder() .request(oldRequest) .build(); ExecutionAttributes attributes = validAttributes.toBuilder() .put(SdkExecutionAttribute.OPERATION_NAME, "TransactWriteItems") .build(); interceptor.modifyRequest(context, attributes); } @Test( expectedExceptions = DynamoDbEncryptionTransformsException.class, expectedExceptionsMessageRegExp = "Condition Expressions forbidden on encrypted attributes : attr1" ) public void TestTransactWriteItemsWithDeleteConditionExpression() { TransactWriteItemsRequest oldRequest = TransactWriteItemsRequest.builder() .transactItems( TransactWriteItem.builder() .delete(Delete.builder() .tableName(TEST_TABLE_NAME) .conditionExpression(TEST_ATTR_NAME + " < :a") .build()) .build()) .build(); Context.ModifyRequest context = InterceptorContext.builder() .request(oldRequest) .build(); ExecutionAttributes attributes = validAttributes.toBuilder() .put(SdkExecutionAttribute.OPERATION_NAME, "TransactWriteItems") .build(); interceptor.modifyRequest(context, attributes); } @Test public void TestTransactWriteItemsWithUpdateOnEncryptedTableGood() { TransactWriteItemsRequest oldRequest = TransactWriteItemsRequest.builder() .transactItems( TransactWriteItem.builder() .update(Update.builder() .tableName(TEST_TABLE_NAME) .key(Collections.EMPTY_MAP) .updateExpression("SET " + TEST_ATTR2_NAME + " = :p") .build()) .build()) .build(); Context.ModifyRequest context = InterceptorContext.builder() .request(oldRequest) .build(); ExecutionAttributes attributes = validAttributes.toBuilder() .put(SdkExecutionAttribute.OPERATION_NAME, "TransactWriteItems") .build(); SdkRequest newRequest = interceptor.modifyRequest(context, attributes); assertEquals(oldRequest, newRequest); } @Test( expectedExceptions = DynamoDbEncryptionTransformsException.class, expectedExceptionsMessageRegExp = "Update Expressions forbidden on signed attributes : " + TEST_ATTR_NAME ) public void TestTransactWriteItemsWithUpdateOnEncryptedTableBad() { TransactWriteItemsRequest oldRequest = TransactWriteItemsRequest.builder() .transactItems( TransactWriteItem.builder() .update(Update.builder() .tableName(TEST_TABLE_NAME) .key(Collections.EMPTY_MAP) .updateExpression("SET " + TEST_ATTR_NAME + " = :p") .build()) .build()) .build(); Context.ModifyRequest context = InterceptorContext.builder() .request(oldRequest) .build(); ExecutionAttributes attributes = validAttributes.toBuilder() .put(SdkExecutionAttribute.OPERATION_NAME, "TransactWriteItems") .build(); interceptor.modifyRequest(context, attributes); } @Test( expectedExceptions = DynamoDbEncryptionTransformsException.class, expectedExceptionsMessageRegExp = "Condition Expressions forbidden on encrypted attributes : attr1" ) public void TestDeleteItemWithConditionExpression() { DeleteItemRequest oldRequest = DeleteItemRequest.builder() .tableName(TEST_TABLE_NAME) .conditionExpression(TEST_ATTR_NAME + " < :a") .build(); Context.ModifyRequest context = InterceptorContext.builder() .request(oldRequest) .build(); ExecutionAttributes attributes = validAttributes.toBuilder() .put(SdkExecutionAttribute.OPERATION_NAME, "DeleteItem") .build(); interceptor.modifyRequest(context, attributes); } @Test public void TestDeleteItemWithConditionExpressionNonEncryptedTable() { DeleteItemRequest oldRequest = DeleteItemRequest.builder() .tableName("otherTable") .key(Collections.EMPTY_MAP) .conditionExpression("foo") .build(); Context.ModifyRequest context = InterceptorContext.builder() .request(oldRequest) .build(); ExecutionAttributes attributes = validAttributes.toBuilder() .put(SdkExecutionAttribute.OPERATION_NAME, "DeleteItem") .build(); SdkRequest newRequest = interceptor.modifyRequest(context, attributes); assertEquals(oldRequest, newRequest); } @Test public void TestExecuteStatementOnEncryptedTable() { List<String> statementsWithEncryptedTable = Arrays.asList( String.format("EXISTS( SELECT * FROM \"%s\" WHERE \"Artist\" = 'Acme Band' AND \"SongTitle\" = 'PartiQL Rocks')", TEST_TABLE_NAME), String.format("INSERT INTO \"%s\" value {'Artist' : 'Acme Band','SongTitle' : 'PartiQL Rocks'}", TEST_TABLE_NAME), String.format("DELETE FROM \"%s\" WHERE \"Artist\" = 'Acme Band' AND \"SongTitle\" = 'PartiQL Rocks' RETURNING ALL OLD *", TEST_TABLE_NAME), String.format("SELECT OrderID, Total FROM \"%s\" WHERE OrderID IN [1, 2, 3] ORDER BY OrderID DESC", TEST_TABLE_NAME), String.format("SELECT Devices.FireStick.DateWatched[0] FROM %s WHERE CustomerID= 'C1' AND MovieID= 'M1'", TEST_TABLE_NAME), String.format("UPDATE \"%s\" SET AwardsWon=1 SET AwardDetail={'Grammys':[2020, 2018]} WHERE Artist='Acme Band' AND SongTitle='PartiQL Rocks", TEST_TABLE_NAME) ); for (String statement : statementsWithEncryptedTable) { ExecuteStatementRequest oldRequest = ExecuteStatementRequest.builder() .statement(statement) .build(); Context.ModifyRequest context = InterceptorContext.builder() .request(oldRequest) .build(); ExecutionAttributes attributes = validAttributes.toBuilder() .put(SdkExecutionAttribute.OPERATION_NAME, "ExecuteStatement") .build(); try { interceptor.modifyRequest(context, attributes); } catch (DynamoDbEncryptionTransformsException e) { assertTrue(e.getMessage().contains("ExecuteStatement not Supported on encrypted tables.")); } } } @Test public void TestExecuteStatementOnNonEncryptedTable() { ExecuteStatementRequest oldRequest = ExecuteStatementRequest.builder() .statement("SELECT * FROM otherTable") .build(); Context.ModifyRequest context = InterceptorContext.builder() .request(oldRequest) .build(); ExecutionAttributes attributes = validAttributes.toBuilder() .put(SdkExecutionAttribute.OPERATION_NAME, "ExecuteStatement") .build(); SdkRequest newRequest = interceptor.modifyRequest(context, attributes); assertEquals(oldRequest, newRequest); } @Test( expectedExceptions = DynamoDbEncryptionTransformsException.class, expectedExceptionsMessageRegExp = "DynamoDbEncryptionInterceptor does not support use with unrecognized operation: UnknownOperation" ) public void TestUnknownOperationRequest() { Context.ModifyRequest context = InterceptorContext.builder() .request(PutItemRequest.builder().build()) .build(); ExecutionAttributes badAttributes = validAttributes.toBuilder() .put(SdkExecutionAttribute.OPERATION_NAME, "UnknownOperation") .build(); interceptor.modifyRequest(context, badAttributes); } @Test( expectedExceptions = DynamoDbEncryptionTransformsException.class, expectedExceptionsMessageRegExp = "DynamoDbEncryptionInterceptor does not support use with the Async client." ) public void TestNonSyncClientRequest() { Context.ModifyRequest context = InterceptorContext.builder() .request(PutItemRequest.builder().build()) .build(); ExecutionAttributes badAttributes = validAttributes.toBuilder() .put(SdkExecutionAttribute.CLIENT_TYPE, ClientType.ASYNC) .put(SdkExecutionAttribute.OPERATION_NAME, "PutItem") // use something valid for operation name .build(); interceptor.modifyRequest(context, badAttributes); } @Test( expectedExceptions = DynamoDbEncryptionTransformsException.class, expectedExceptionsMessageRegExp = "DynamoDbEncryptionInterceptor does not support use with services other than DynamoDb." ) public void TestNonDDBServiceRequest() { Context.ModifyRequest context = InterceptorContext.builder() .request(PutItemRequest.builder().build()) .build(); ExecutionAttributes badAttributes = validAttributes.toBuilder() .put(SdkExecutionAttribute.SERVICE_NAME, "OtherService") .build(); interceptor.modifyRequest(context, badAttributes); } @Test( expectedExceptions = DynamoDbEncryptionTransformsException.class, expectedExceptionsMessageRegExp = "Missing value for required field `config`" ) public void TestEmptyInterceptorBuild() { DynamoDbEncryptionInterceptor.builder().build(); } @Test( expectedExceptions = DynamoDbItemEncryptorException.class, expectedExceptionsMessageRegExp = "^Partition key attribute action MUST be SIGN_ONLY$" ) public void TestBadCryptoActionOnPartitionKey() { Map<String, CryptoAction> actions = new HashMap<>(); actions.put(TEST_PARTITION_NAME, CryptoAction.ENCRYPT_AND_SIGN); actions.put(TEST_SORT_NAME, CryptoAction.SIGN_ONLY); actions.put(TEST_ATTR_NAME, CryptoAction.DO_NOTHING); List<String> allowedUnauth = Arrays.asList(TEST_ATTR_NAME); createInterceptor(actions, allowedUnauth, createKmsKeyring(), null, null); } @Test( expectedExceptions = DynamoDbItemEncryptorException.class, expectedExceptionsMessageRegExp = "^Sort key attribute action MUST be SIGN_ONLY$" ) public void TestBadCryptoActionOnSortKey() { Map<String, CryptoAction> actions = new HashMap<>(); actions.put(TEST_PARTITION_NAME, CryptoAction.SIGN_ONLY); actions.put(TEST_SORT_NAME, CryptoAction.ENCRYPT_AND_SIGN); actions.put(TEST_ATTR_NAME, CryptoAction.DO_NOTHING); List<String> allowedUnauth = Arrays.asList(TEST_ATTR_NAME); createInterceptor(actions, allowedUnauth, createKmsKeyring(), null, null); } @Test( expectedExceptions = DynamoDbItemEncryptorException.class, expectedExceptionsMessageRegExp = "Attribute " + TEST_ATTR_NAME + " is configured as DO_NOTHING but it must also be in unauthenticatedAttributes or begin with the unauthenticatedPrefix." ) public void TestSignatureScopeMissingAttr() { Map<String, CryptoAction> actions = new HashMap<>(); actions.put(TEST_PARTITION_NAME, CryptoAction.SIGN_ONLY); actions.put(TEST_SORT_NAME, CryptoAction.SIGN_ONLY); actions.put(TEST_ATTR_NAME, CryptoAction.DO_NOTHING); List<String> allowedUnauth = Arrays.asList(); createInterceptor(actions, allowedUnauth, createKmsKeyring(), null, null); } @Test( expectedExceptions = DynamoDbItemEncryptorException.class, expectedExceptionsMessageRegExp = "Attribute " + TEST_SORT_NAME + " is configured as SIGN_ONLY but it is also in unauthenticatedAttributes." ) public void TestSignatureScopeExtraAttr() { Map<String, CryptoAction> actions = new HashMap<>(); actions.put(TEST_PARTITION_NAME, CryptoAction.SIGN_ONLY); actions.put(TEST_SORT_NAME, CryptoAction.SIGN_ONLY); actions.put(TEST_ATTR_NAME, CryptoAction.DO_NOTHING); List<String> allowedUnauth = Arrays.asList(TEST_ATTR_NAME, TEST_SORT_NAME); createInterceptor(actions, allowedUnauth, createKmsKeyring(), null, null); } @Test( expectedExceptions = DynamoDbEncryptionException.class, expectedExceptionsMessageRegExp = "No Crypto Action configured for attribute attr3" ) public void TestPutWithInvalidCryptoAction() { Map<String, AttributeValue> item = createTestItem("foo", "10", "bar", "awol"); // Add an attribute not modelled in the crypto schema item.put("attr3", AttributeValue.fromS("attr3")); PutItemRequest oldRequest = PutItemRequest.builder() .item(item) .tableName(TEST_TABLE_NAME) .build(); Context.ModifyRequest context = InterceptorContext.builder() .request(oldRequest) .build(); ExecutionAttributes attributes = validAttributes.toBuilder() .put(SdkExecutionAttribute.OPERATION_NAME, "PutItem") .build(); interceptor.modifyRequest(context, attributes); } @Test( expectedExceptions = DynamoDbItemEncryptorException.class, expectedExceptionsMessageRegExp = "On Encrypt : Partition key 'partition_key' does not exist in item. Item contains these attributes : attr1 attr2 sort_key." ) public void TestPutMissingPartition() { Map<String, AttributeValue> item = createTestItem("foo", "10", "bar", "awol"); // Remove partition key from item item.remove(TEST_PARTITION_NAME); PutItemRequest oldRequest = PutItemRequest.builder() .item(item) .tableName(TEST_TABLE_NAME) .build(); Context.ModifyRequest context = InterceptorContext.builder() .request(oldRequest) .build(); ExecutionAttributes attributes = validAttributes.toBuilder() .put(SdkExecutionAttribute.OPERATION_NAME, "PutItem") .build(); interceptor.modifyRequest(context, attributes); } @Test( expectedExceptions = DynamoDbItemEncryptorException.class, expectedExceptionsMessageRegExp = "On Encrypt : Sort key 'sort_key' does not exist in item. Item contains these attributes : attr1 attr2 partition_key." ) public void TestPutMissingSort() { Map<String, AttributeValue> item = createTestItem("foo", "10", "bar", "awol"); // Remove partition key from item item.remove(TEST_SORT_NAME); PutItemRequest oldRequest = PutItemRequest.builder() .item(item) .tableName(TEST_TABLE_NAME) .build(); Context.ModifyRequest context = InterceptorContext.builder() .request(oldRequest) .build(); ExecutionAttributes attributes = validAttributes.toBuilder() .put(SdkExecutionAttribute.OPERATION_NAME, "PutItem") .build(); interceptor.modifyRequest(context, attributes); } @Test public void TestQueryPreservesEmptyExclusiveStartKey() { QueryRequest oldRequest = QueryRequest.builder() .tableName(TEST_TABLE_NAME) .exclusiveStartKey(new HashMap<>()) .build(); Context.ModifyRequest context = InterceptorContext.builder() .request(oldRequest) .build(); ExecutionAttributes attributes = validAttributes.toBuilder() .put(SdkExecutionAttribute.OPERATION_NAME, "Query") .build(); SdkRequest newRequest = interceptor.modifyRequest(context, attributes); assertTrue(newRequest instanceof QueryRequest); assertFalse(((QueryRequest) newRequest).exclusiveStartKey() instanceof DefaultSdkAutoConstructMap); assertEquals(((QueryRequest) newRequest).exclusiveStartKey().size(), 0); } @Test public void TestScanPreservesEmptyExclusiveStartKey() { ScanRequest oldRequest = ScanRequest.builder() .tableName(TEST_TABLE_NAME) .exclusiveStartKey(new HashMap<>()) .build(); Context.ModifyRequest context = InterceptorContext.builder() .request(oldRequest) .build(); ExecutionAttributes attributes = validAttributes.toBuilder() .put(SdkExecutionAttribute.OPERATION_NAME, "Scan") .build(); SdkRequest newRequest = interceptor.modifyRequest(context, attributes); assertTrue(newRequest instanceof ScanRequest); assertFalse(((ScanRequest) newRequest).exclusiveStartKey() instanceof DefaultSdkAutoConstructMap); assertEquals(((ScanRequest) newRequest).exclusiveStartKey().size(), 0); } }
4,921
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/DynamoDbEncryptionInterceptorIntegrationTests.java
package software.amazon.cryptography.dbencryptionsdk.dynamodb; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.Keyring; 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 software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; import software.amazon.awssdk.services.dynamodb.model.*; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import org.testng.annotations.Test; import org.testng.annotations.BeforeTest; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.*; import software.amazon.cryptography.dbencryptionsdk.dynamodb.transforms.model.DynamoDbEncryptionTransformsException; import software.amazon.cryptography.materialproviders.model.CollectionOfErrors; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static software.amazon.cryptography.dbencryptionsdk.dynamodb.TestUtils.*; /* Tests require access to a DynamoDb table in the default region with: - tableName of "DynamoDbEncryptionInterceptorTestTable" - partition key of type 'S' with name "partition_key" - sort key off type 'N' with name "sort_key" */ public class DynamoDbEncryptionInterceptorIntegrationTests { static DynamoDbEncryptionInterceptor kmsInterceptor; static DynamoDbClient ddbKmsKeyring; @BeforeTest public static void setup() { kmsInterceptor = createInterceptor(createKmsKeyring(), null, null); ddbKmsKeyring = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(kmsInterceptor) .build()) .build(); } @Test public void TestPutItemGetItem() { // Put item into table String partitionValue = "get"; String sortValue = "42"; String attrValue = "bar"; String attrValue2 = "hello world"; Map<String, AttributeValue> item = createTestItem(partitionValue, sortValue, attrValue, attrValue2); PutItemRequest putRequest = PutItemRequest.builder() .tableName(TEST_TABLE_NAME) .item(item) .build(); PutItemResponse putResponse = ddbKmsKeyring.putItem(putRequest); assertEquals(200, putResponse.sdkHttpResponse().statusCode()); // Get Item back from table Map<String, AttributeValue> keyToGet = createTestKey(partitionValue, sortValue); GetItemRequest getRequest = GetItemRequest.builder() .key(keyToGet) .tableName(TEST_TABLE_NAME) .build(); GetItemResponse getResponse = ddbKmsKeyring.getItem(getRequest); assertEquals(200, getResponse.sdkHttpResponse().statusCode()); Map<String, AttributeValue> returnedItem = getResponse.item(); assertNotNull(returnedItem); assertEquals(partitionValue, returnedItem.get(TEST_PARTITION_NAME).s()); assertEquals(sortValue, returnedItem.get(TEST_SORT_NAME).n()); assertEquals(attrValue, returnedItem.get(TEST_ATTR_NAME).s()); } @Test public void TestBatchWriteBatchGet() { // Batch write items to table Map<String, List<WriteRequest>> writeRequestItems = new HashMap<>(); String partitionValue = "batch"; String sortValue1 = "1"; String sortValue2 = "2"; String attrValue = "lorem ipsum"; String attrValue2 = "hello world"; Map<String,AttributeValue> item1 = createTestItem(partitionValue, sortValue1, attrValue, attrValue2); Map<String,AttributeValue> item2 = createTestItem(partitionValue, sortValue2, attrValue, attrValue2); List<WriteRequest> tableRequests = new ArrayList<>(); tableRequests.add(WriteRequest.builder().putRequest(PutRequest.builder().item(item1).build()).build()); tableRequests.add(WriteRequest.builder().putRequest(PutRequest.builder().item(item2).build()).build()); writeRequestItems.put(TEST_TABLE_NAME, tableRequests); BatchWriteItemRequest writeRequest = BatchWriteItemRequest.builder() .requestItems(writeRequestItems) .build(); BatchWriteItemResponse writeResponse = ddbKmsKeyring.batchWriteItem(writeRequest); assertEquals(200, writeResponse.sdkHttpResponse().statusCode()); // Technically DDB does not have to process every item, // however given we are working with a small set of data // this should almost never happen assertEquals(0, writeResponse.unprocessedItems().size()); // Batch get items back from table Map<String, KeysAndAttributes> getRequestItems = new HashMap<>(); Map<String,AttributeValue> key1 = createTestKey(partitionValue, sortValue1); Map<String,AttributeValue> key2 = createTestKey(partitionValue, sortValue2); List<Map<String,AttributeValue>> tableGetRequests = new ArrayList<>(); tableGetRequests.add(key1); tableGetRequests.add(key2); getRequestItems.put(TEST_TABLE_NAME, KeysAndAttributes.builder().keys(tableGetRequests).build()); BatchGetItemRequest getRequest = BatchGetItemRequest.builder() .requestItems(getRequestItems) .build(); BatchGetItemResponse getResponse = ddbKmsKeyring.batchGetItem(getRequest); assertEquals(200, getResponse.sdkHttpResponse().statusCode()); // Technically DDB does not have to process every item, // however given we are working with a small set of data // this should almost never happen assertEquals(0, getResponse.unprocessedKeys().size()); List<Map<String, AttributeValue>> returnedItems = getResponse.responses().get(TEST_TABLE_NAME); assertEquals(2, returnedItems.size()); Map<String, AttributeValue> returnedItem = returnedItems.get(0); assertEquals(partitionValue, returnedItem.get(TEST_PARTITION_NAME).s()); assertEquals(attrValue, returnedItem.get(TEST_ATTR_NAME).s()); } @Test public void TestTransactWriteAndGet() { // Put Item into table via transactions HashMap<String, AttributeValue> item = new HashMap<>(); String partitionValue = "transact"; String sortValue1 = "1"; String sortValue2 = "2"; String attrValue = "lorem ipsum"; String attrValue2 = "hello world"; Map<String,AttributeValue> item1 = createTestItem(partitionValue, sortValue1, attrValue, attrValue2); Map<String,AttributeValue> item2 = createTestItem(partitionValue, sortValue2, attrValue, attrValue2); TransactWriteItemsRequest writeRequest = TransactWriteItemsRequest.builder() .transactItems( TransactWriteItem.builder() .put(Put.builder() .item(item1) .tableName(TEST_TABLE_NAME) .build()) .build(), TransactWriteItem.builder() .put(Put.builder() .item(item2) .tableName(TEST_TABLE_NAME) .build()) .build()) .build(); TransactWriteItemsResponse putResponse = ddbKmsKeyring.transactWriteItems(writeRequest); assertEquals(200, putResponse.sdkHttpResponse().statusCode()); // Get Item back from table via transactions Map<String,AttributeValue> key1 = createTestKey(partitionValue, sortValue1); Map<String,AttributeValue> key2 = createTestKey(partitionValue, sortValue2); TransactGetItemsRequest getRequest = TransactGetItemsRequest.builder() .transactItems( TransactGetItem.builder() .get(Get.builder() .key(key1) .tableName(TEST_TABLE_NAME) .build()) .build(), TransactGetItem.builder() .get(Get.builder() .key(key2) .tableName(TEST_TABLE_NAME) .build()) .build() ) .build(); TransactGetItemsResponse getResponse = ddbKmsKeyring.transactGetItems(getRequest); assertEquals(200, getResponse.sdkHttpResponse().statusCode()); List<ItemResponse> responses = getResponse.responses(); assertEquals(2, responses.size()); ItemResponse response = responses.get(0); assertEquals(partitionValue, response.item().get(TEST_PARTITION_NAME).s()); assertEquals(attrValue, response.item().get(TEST_ATTR_NAME).s()); } @Test public void TestScan() { // Ensure table is populated with expected items String partitionValue = "scan"; String sortValue1 = "1"; String sortValue2 = "2"; String attrValue = "lorem ipsum"; String attrValue2 = "hello world"; Map<String,AttributeValue> item1 = createTestItem(partitionValue, sortValue1, attrValue, attrValue2); Map<String,AttributeValue> item2 = createTestItem(partitionValue, sortValue2, attrValue, attrValue2); List<WriteRequest> tableRequests = new ArrayList<>(); tableRequests.add(WriteRequest.builder().putRequest(PutRequest.builder().item(item1).build()).build()); tableRequests.add(WriteRequest.builder().putRequest(PutRequest.builder().item(item2).build()).build()); Map<String, List<WriteRequest>> writeRequestItems = new HashMap<>(); writeRequestItems.put(TEST_TABLE_NAME, tableRequests); BatchWriteItemRequest writeRequest = BatchWriteItemRequest.builder() .requestItems(writeRequestItems) .build(); BatchWriteItemResponse writeResponse = ddbKmsKeyring.batchWriteItem(writeRequest); assertEquals(200, writeResponse.sdkHttpResponse().statusCode()); assertEquals(0, writeResponse.unprocessedItems().size()); // Scan and filter for items with "scan" Map<String, AttributeValue> attrValues = new HashMap(); attrValues.put(":val", AttributeValue.builder().s(partitionValue).build()); ScanRequest scanRequest = ScanRequest.builder() .tableName(TEST_TABLE_NAME) .filterExpression("partition_key = :val") .expressionAttributeValues(attrValues) .build(); ScanResponse scanResponse = ddbKmsKeyring.scan(scanRequest); assertEquals(200, scanResponse.sdkHttpResponse().statusCode()); assertEquals(2, (double) scanResponse.count()); Map<String, AttributeValue> item = scanResponse.items().get(0); assertEquals(partitionValue, item.get(TEST_PARTITION_NAME).s()); assertEquals(attrValue, item.get(TEST_ATTR_NAME).s()); } @Test public void TestQuery() { // Ensure table is populated with expected items String partitionValue = "query"; String sortValue1 = "1"; String sortValue2 = "2"; String attrValue = "lorem ipsum"; String attrValue2 = "hello world"; Map<String,AttributeValue> item1 = createTestItem(partitionValue, sortValue1, attrValue, attrValue2); Map<String,AttributeValue> item2 = createTestItem(partitionValue, sortValue2, attrValue, attrValue2); List<WriteRequest> tableRequests = new ArrayList<>(); tableRequests.add(WriteRequest.builder().putRequest(PutRequest.builder().item(item1).build()).build()); tableRequests.add(WriteRequest.builder().putRequest(PutRequest.builder().item(item2).build()).build()); Map<String, List<WriteRequest>> writeRequestItems = new HashMap<>(); writeRequestItems.put(TEST_TABLE_NAME, tableRequests); BatchWriteItemRequest writeRequest = BatchWriteItemRequest.builder() .requestItems(writeRequestItems) .build(); BatchWriteItemResponse writeResponse = ddbKmsKeyring.batchWriteItem(writeRequest); assertEquals(200, writeResponse.sdkHttpResponse().statusCode()); assertEquals(0, writeResponse.unprocessedItems().size()); // Query such that we get one "query" item back, but not the other Map<String, AttributeValue> attrValues = new HashMap(); attrValues.put(":v1", AttributeValue.builder().s(partitionValue).build()); attrValues.put(":v2", AttributeValue.builder().n(sortValue1).build()); QueryRequest queryRequest = QueryRequest.builder() .tableName(TEST_TABLE_NAME) .keyConditionExpression("partition_key = :v1 AND sort_key > :v2") .expressionAttributeValues(attrValues) .build(); QueryResponse queryResponse = ddbKmsKeyring.query(queryRequest); assertEquals(200, queryResponse.sdkHttpResponse().statusCode()); assertEquals(1, (double) queryResponse.count()); Map<String, AttributeValue> item = queryResponse.items().get(0); assertEquals(partitionValue, item.get(TEST_PARTITION_NAME).s()); assertEquals(sortValue2, item.get(TEST_SORT_NAME).n()); assertEquals(attrValue, item.get(TEST_ATTR_NAME).s()); } @Test public void TestReadLegacyItem() throws GeneralSecurityException { String partitionValue = "legacyRead"; String sortValue = "42"; String attrValue = "bar"; String attrValue2 = "hello world"; Map<String, com.amazonaws.services.dynamodbv2.model.AttributeValue> legacyItem = createLegacyTestItem(partitionValue, sortValue, attrValue, attrValue2); // Set up Legacy DDBEC Encryptor DynamoDBEncryptor legacyEncryptor = createLegacyEncryptor(); EncryptionContext encryptionContext = new EncryptionContext.Builder() .withTableName(TEST_TABLE_NAME) .withHashKeyName(TEST_PARTITION_NAME) .withRangeKeyName(TEST_SORT_NAME) .build(); Map<String, Set<EncryptionFlags>> actions = createLegacyAttributeFlags(); // Encrypt the plaintext record directly final Map<String, com.amazonaws.services.dynamodbv2.model.AttributeValue> encrypted_record = legacyEncryptor.encryptRecord(legacyItem, actions, encryptionContext); // Put record into ddb directly using SDKv1 Java client AmazonDynamoDB legacyDDB = AmazonDynamoDBClientBuilder.standard().build(); legacyDDB.putItem(new com.amazonaws.services.dynamodbv2.model.PutItemRequest(TEST_TABLE_NAME, encrypted_record)); DynamoDbEncryptionInterceptor interceptor = createInterceptor(createKmsKeyring(), LegacyPolicy.FORCE_LEGACY_ENCRYPT_ALLOW_LEGACY_DECRYPT, null); DynamoDbClient ddbWithLegacy = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(interceptor) .build()) .build(); // Read item written by legacy encryptor Map<String, AttributeValue> keyToGet = createTestKey(partitionValue, sortValue); GetItemRequest getRequest = GetItemRequest.builder() .key(keyToGet) .tableName(TEST_TABLE_NAME) .build(); GetItemResponse getResponse = ddbWithLegacy.getItem(getRequest); assertEquals(200, getResponse.sdkHttpResponse().statusCode()); Map<String, AttributeValue> returnedItem = getResponse.item(); assertNotNull(returnedItem); assertEquals(partitionValue, returnedItem.get(TEST_PARTITION_NAME).s()); assertEquals(sortValue, returnedItem.get(TEST_SORT_NAME).n()); assertEquals(attrValue, returnedItem.get(TEST_ATTR_NAME).s()); } @Test public void TestWriteLegacyItem() throws GeneralSecurityException { // Put item into table String partitionValue = "legacyWrite"; String sortValue = "42"; String attrValue = "bar"; String attrValue2 = "hello world"; Map<String, AttributeValue> item = createTestItem(partitionValue, sortValue, attrValue, attrValue2); // Set up Legacy DDBEC Encryptor DynamoDBEncryptor legacyEncryptor = createLegacyEncryptor(); EncryptionContext encryptionContext = new EncryptionContext.Builder() .withTableName(TEST_TABLE_NAME) .withHashKeyName(TEST_PARTITION_NAME) .withRangeKeyName(TEST_SORT_NAME) .build(); Map<String, Set<EncryptionFlags>> actions = createLegacyAttributeFlags(); // Configure interceptor with legacy behavior DynamoDbEncryptionInterceptor interceptor = createInterceptor(createKmsKeyring(), LegacyPolicy.FORCE_LEGACY_ENCRYPT_ALLOW_LEGACY_DECRYPT, null); DynamoDbClient ddbWithLegacy = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(interceptor) .build()) .build(); // Put Item using legacy behavior PutItemRequest putRequest = PutItemRequest.builder() .tableName(TEST_TABLE_NAME) .item(item) .build(); PutItemResponse putResponse = ddbWithLegacy.putItem(putRequest); assertEquals(200, putResponse.sdkHttpResponse().statusCode()); // Get record from ddb directly using SDKv1 Java client final Map<String, com.amazonaws.services.dynamodbv2.model.AttributeValue> itemKey = new HashMap<>(); itemKey.put(TEST_PARTITION_NAME, new com.amazonaws.services.dynamodbv2.model.AttributeValue().withS(partitionValue)); itemKey.put(TEST_SORT_NAME, new com.amazonaws.services.dynamodbv2.model.AttributeValue().withN(sortValue)); AmazonDynamoDB legacyDDB = AmazonDynamoDBClientBuilder.standard().build(); com.amazonaws.services.dynamodbv2.model.GetItemResult getItemResponse = legacyDDB.getItem( new com.amazonaws.services.dynamodbv2.model.GetItemRequest(TEST_TABLE_NAME, itemKey) ); // Decrypt the plaintext record directly final Map<String, com.amazonaws.services.dynamodbv2.model.AttributeValue> decryptedRecord = legacyEncryptor.decryptRecord(getItemResponse.getItem(), actions, encryptionContext); assertNotNull(decryptedRecord); assertEquals(partitionValue, decryptedRecord.get(TEST_PARTITION_NAME).getS()); assertEquals(sortValue, decryptedRecord.get(TEST_SORT_NAME).getN()); assertEquals(attrValue, decryptedRecord.get(TEST_ATTR_NAME).getS()); } @Test public void TestPlaintextRead() { // Put plaintext item into table String partitionValue = "plaintextRead"; String sortValue = "42"; String attrValue = "bar"; String attrValue2 = "hello world"; Map<String, AttributeValue> item = createTestItem(partitionValue, sortValue, attrValue, attrValue2); DynamoDbClient regularClient = DynamoDbClient.builder().build(); PutItemRequest putRequest = PutItemRequest.builder() .tableName(TEST_TABLE_NAME) .item(item) .build(); PutItemResponse putResponse = regularClient.putItem(putRequest); assertEquals(200, putResponse.sdkHttpResponse().statusCode()); // Get Item back from table, using *ALLOW_READ Plaintext policy DynamoDbEncryptionInterceptor interceptor = createInterceptor( createKmsKeyring(), // Just need to configure some valid keyring null, PlaintextOverride.FORCE_PLAINTEXT_WRITE_ALLOW_PLAINTEXT_READ); DynamoDbClient clientWithPolicy = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(interceptor) .build()) .build(); Map<String, AttributeValue> keyToGet = createTestKey(partitionValue, sortValue); GetItemRequest getRequest = GetItemRequest.builder() .key(keyToGet) .tableName(TEST_TABLE_NAME) .build(); GetItemResponse getResponse = clientWithPolicy.getItem(getRequest); assertEquals(200, getResponse.sdkHttpResponse().statusCode()); Map<String, AttributeValue> returnedItem = getResponse.item(); assertNotNull(returnedItem); assertEquals(partitionValue, returnedItem.get(TEST_PARTITION_NAME).s()); assertEquals(sortValue, returnedItem.get(TEST_SORT_NAME).n()); assertEquals(attrValue, returnedItem.get(TEST_ATTR_NAME).s()); } @Test public void TestPlaintextWrite() { // Put plaintext item into table using client with REQUIRE_WRITE* policy String partitionValue = "plaintextWrite"; String sortValue = "42"; String attrValue = "bar"; String attrValue2 = "hello world"; Map<String, AttributeValue> item = createTestItem(partitionValue, sortValue, attrValue, attrValue2); DynamoDbEncryptionInterceptor interceptor = createInterceptor( createKmsKeyring(), // Just need to configure some valid keyring null, PlaintextOverride.FORCE_PLAINTEXT_WRITE_ALLOW_PLAINTEXT_READ); DynamoDbClient clientWithPolicy = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(interceptor) .build()) .build(); PutItemRequest putRequest = PutItemRequest.builder() .tableName(TEST_TABLE_NAME) .item(item) .build(); PutItemResponse putResponse = clientWithPolicy.putItem(putRequest); assertEquals(200, putResponse.sdkHttpResponse().statusCode()); // Get Item back from table, using regular client policy DynamoDbClient regularClient = DynamoDbClient.builder().build(); Map<String, AttributeValue> keyToGet = createTestKey(partitionValue, sortValue); GetItemRequest getRequest = GetItemRequest.builder() .key(keyToGet) .tableName(TEST_TABLE_NAME) .build(); GetItemResponse getResponse = regularClient.getItem(getRequest); assertEquals(200, getResponse.sdkHttpResponse().statusCode()); Map<String, AttributeValue> returnedItem = getResponse.item(); assertNotNull(returnedItem); assertEquals(partitionValue, returnedItem.get(TEST_PARTITION_NAME).s()); assertEquals(sortValue, returnedItem.get(TEST_SORT_NAME).n()); assertEquals(attrValue, returnedItem.get(TEST_ATTR_NAME).s()); } @Test( expectedExceptions = DynamoDbEncryptionTransformsException.class, expectedExceptionsMessageRegExp = "DynamoDbEncryptionInterceptor does not support use with services other than DynamoDb." ) public void TestFailsNonDDBClient() { KmsClient wrongClient = KmsClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(kmsInterceptor) .build()) .build(); wrongClient.createKey(); } @Test( expectedExceptions = ExecutionException.class, expectedExceptionsMessageRegExp = ".*DynamoDbEncryptionInterceptor does not support use with the Async client." ) public void TestFailsNonSyncClient() throws Throwable { DynamoDbAsyncClient asyncClient = DynamoDbAsyncClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(kmsInterceptor) .build()) .build(); Map<String, AttributeValue> item = createTestItem("expect", "7415", "to", "fail"); CompletableFuture<PutItemResponse> response = asyncClient.putItem( PutItemRequest.builder().tableName(TEST_TABLE_NAME).item(item).build()); response.get(); } @Test( expectedExceptions = CollectionOfErrors.class, expectedExceptionsMessageRegExp = "Raw AES Keyring was unable to decrypt any encrypted data key. The list of encountered Exceptions is avaible via `list`." ) public void TestOnDecryptKeyringFailure() throws Throwable { String partitionValue = "expectedOnDecryptKeyringFailure"; String sortValue = "42"; String attrValue = "bar"; String attrValue2 = "hello world"; Map<String, AttributeValue> item = createTestItem(partitionValue, sortValue, attrValue, attrValue2); // Create two distinct dummy "keys" ByteBuffer keyA = ByteBuffer.allocate(32); ByteBuffer keyB = ByteBuffer.allocate(32); keyB = keyB.putInt(1); // Create two keyrings with the same name/namespace, but different keys IKeyring aesKeyringA = createStaticKeyring(keyA); IKeyring aesKeyringB = createStaticKeyring(keyB); DynamoDbEncryptionInterceptor interceptorA = createInterceptor(aesKeyringA, null, null); DynamoDbClient ddbA = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(interceptorA) .build()) .build(); DynamoDbEncryptionInterceptor interceptorB = createInterceptor(aesKeyringB, null, null); DynamoDbClient ddbB = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(interceptorB) .build()) .build(); // Write item with key material A PutItemRequest putRequest = PutItemRequest.builder() .tableName(TEST_TABLE_NAME) .item(item) .build(); PutItemResponse putResponse = ddbA.putItem(putRequest); assertEquals(200, putResponse.sdkHttpResponse().statusCode()); // Read item with key material B Map<String, AttributeValue> keyToGet = createTestKey(partitionValue, sortValue); GetItemRequest getRequest = GetItemRequest.builder() .key(keyToGet) .tableName(TEST_TABLE_NAME) .build(); try { ddbB.getItem(getRequest); } catch(SdkClientException e) { throw e.getCause(); } } }
4,922
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/DynamoDbItemConversionIntegrationTests.java
package software.amazon.cryptography.dbencryptionsdk.dynamodb; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.*; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import java.util.*; import java.util.stream.Collectors; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNotNull; import static software.amazon.cryptography.dbencryptionsdk.dynamodb.TestUtils.*; import org.testng.annotations.Test; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; public class DynamoDbItemConversionIntegrationTests { @Test public void TestPutItemGetRichItem() { Map<String, CryptoAction> actions = new HashMap<>(); actions.put(TEST_PARTITION_NAME, CryptoAction.SIGN_ONLY); actions.put(TEST_SORT_NAME, CryptoAction.SIGN_ONLY); actions.put(TEST_ATTR_NAME, CryptoAction.SIGN_ONLY); actions.put(TEST_ATTR2_NAME, CryptoAction.DO_NOTHING); actions.put("Sattr", CryptoAction.ENCRYPT_AND_SIGN); actions.put("Nattr", CryptoAction.ENCRYPT_AND_SIGN); actions.put("Battr", CryptoAction.ENCRYPT_AND_SIGN); actions.put("SSattr", CryptoAction.ENCRYPT_AND_SIGN); actions.put("NSattr", CryptoAction.ENCRYPT_AND_SIGN); actions.put("BSattr", CryptoAction.ENCRYPT_AND_SIGN); actions.put("Lattr", CryptoAction.ENCRYPT_AND_SIGN); actions.put("Lattr-empty", CryptoAction.ENCRYPT_AND_SIGN); actions.put("Mattr", CryptoAction.ENCRYPT_AND_SIGN); actions.put("Mattr-empty", CryptoAction.ENCRYPT_AND_SIGN); actions.put("BOOLattr-true", CryptoAction.ENCRYPT_AND_SIGN); actions.put("BOOLattr-false", CryptoAction.ENCRYPT_AND_SIGN); actions.put("NULattr", CryptoAction.ENCRYPT_AND_SIGN); String sValue = "Sattr"; String sValue2 = ""; String nValue = "0"; String nValue2 = "1E-130"; // positive minimum String nValue3 = "9.9999999999999999999999999999999999999E+125"; // positive maximum String nValue4 = "-9.9999999999999999999999999999999999999E+125"; // negative minimum String nValue5 = "-1E-130"; // negative maximum SdkBytes bValue = SdkBytes.fromByteArray(new byte[0]); SdkBytes bValue2 = SdkBytes.fromByteArray(Base64.getEncoder().encode("hello World".getBytes())); List<AttributeValue> lValue = new ArrayList(); lValue.add(AttributeValue.fromB(bValue)); lValue.add(AttributeValue.fromS(sValue)); lValue.add(AttributeValue.fromN(nValue)); Map<String, AttributeValue> mValue = new HashMap<>(); mValue.put("M:Nattr", AttributeValue.fromN(nValue2)); mValue.put("M:Sattr", AttributeValue.fromS(sValue2)); mValue.put("M:Battr", AttributeValue.fromB(bValue2)); Map<String, AttributeValue> item = createTestItem("foo", "42", "bar", "awol"); item.put("Sattr", AttributeValue.fromS(sValue)); item.put("Nattr", AttributeValue.fromN(nValue)); item.put("Battr", AttributeValue.fromB(bValue)); item.put("BOOLattr-true", AttributeValue.fromBool(true)); item.put("BOOLattr-false", AttributeValue.fromBool(false)); item.put("NULattr", AttributeValue.fromNul(true)); item.put("SSattr", AttributeValue.builder().ss(sValue, sValue2).build()); item.put("NSattr", AttributeValue.builder().ns(nValue, nValue2, nValue3, nValue4, nValue5).build()); item.put("BSattr", AttributeValue.builder().bs(bValue, bValue2).build()); item.put("Lattr", AttributeValue.fromL(lValue)); item.put("Lattr-empty", AttributeValue.fromL(Collections.EMPTY_LIST)); item.put("Mattr", AttributeValue.fromM(mValue)); item.put("Mattr-empty", AttributeValue.fromM(Collections.EMPTY_MAP)); DynamoDbEncryptionInterceptor interceptor = createInterceptor(actions, Arrays.asList(TEST_ATTR2_NAME), createKmsKeyring(), null, null); DynamoDbClient ddb = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(interceptor) .build()) .build(); String partitionValue = "foo"; String sortValue = "42"; String attrValue = "bar"; PutItemRequest putRequest = PutItemRequest.builder() .tableName(TEST_TABLE_NAME) .item(item) .build(); PutItemResponse putResponse = ddb.putItem(putRequest); assertEquals(200, putResponse.sdkHttpResponse().statusCode()); // Using a client with the DDBEncryptionInterceptor, ensure that attributes have been "encrypted" DynamoDbClient ddbWithoutDecryption = DynamoDbClient.create(); Map<String, AttributeValue> keyToGet = createTestKey(partitionValue, sortValue); GetItemRequest getRequest = GetItemRequest.builder() .key(keyToGet) .tableName(TEST_TABLE_NAME) .build(); GetItemResponse encryptedGetResponse = ddbWithoutDecryption.getItem(getRequest); Map<String, AttributeValue> encryptedItem = encryptedGetResponse.item(); assertNotNull(encryptedItem); assertEquals(partitionValue, encryptedItem.get(TEST_PARTITION_NAME).s()); assertEquals(sortValue, encryptedItem.get(TEST_SORT_NAME).n()); assertEquals(attrValue, encryptedItem.get(TEST_ATTR_NAME).s()); // Check Simple Types assertNull(encryptedItem.get("Sattr").s()); assertNotNull(encryptedItem.get("Sattr").b()); assertNotEquals(sValue, encryptedItem.get("Sattr").b()); assertNull(encryptedItem.get("Nattr").n()); assertNotNull(encryptedItem.get("Nattr").b()); assertNotEquals(nValue, encryptedItem.get("Nattr").b()); assertNotNull(encryptedItem.get("Battr").b()); assertNotEquals(bValue, encryptedItem.get("Battr").b()); assertNull(encryptedItem.get("BOOLattr-true").bool()); assertNotNull(encryptedItem.get("BOOLattr-true").b()); assertNull(encryptedItem.get("BOOLattr-false").bool()); assertNotNull(encryptedItem.get("BOOLattr-false").b()); assertNull(encryptedItem.get("NULattr").nul()); assertNotNull(encryptedItem.get("NULattr").b()); // Check Sets assertEquals(0, encryptedItem.get("SSattr").ss().size()); assertNotNull(encryptedItem.get("SSattr").b()); assertEquals(0, encryptedItem.get("NSattr").ss().size()); assertNotNull(encryptedItem.get("NSattr").b()); assertEquals(0, encryptedItem.get("BSattr").ss().size()); assertNotNull(encryptedItem.get("BSattr").b()); // Check List assertEquals(0, encryptedItem.get("Lattr").l().size()); assertNotNull(encryptedItem.get("Lattr").b()); assertEquals(0, encryptedItem.get("Lattr-empty").l().size()); assertNotNull(encryptedItem.get("Lattr-empty").b()); // Check Map assertEquals(0, encryptedItem.get("Mattr").m().size()); assertNotNull(encryptedItem.get("Mattr").b()); assertEquals(0, encryptedItem.get("Mattr-empty").m().size()); assertNotNull(encryptedItem.get("Mattr-empty").b()); // Get Item back from table using Interceptor GetItemResponse getResponse = ddb.getItem(getRequest); assertEquals(200, getResponse.sdkHttpResponse().statusCode()); Map<String, AttributeValue> newItem = getResponse.item(); assertNotNull(newItem); assertEquals(partitionValue, newItem.get(TEST_PARTITION_NAME).s()); assertEquals(sortValue, newItem.get(TEST_SORT_NAME).n()); assertEquals(attrValue, newItem.get(TEST_ATTR_NAME).s()); // Check Simple Types assertEquals(sValue, newItem.get("Sattr").s()); assertEquals(nValue, newItem.get("Nattr").n()); assertEquals(bValue, newItem.get("Battr").b()); assertTrue(newItem.get("BOOLattr-true").bool()); assertFalse(newItem.get("BOOLattr-false").bool()); assertTrue(newItem.get("NULattr").nul()); // Check Sets List<String> ss = newItem.get("SSattr").ss(); assertTrue(ss.containsAll(Arrays.asList(sValue, sValue2))); List<String> ns = newItem.get("NSattr").ns(); assertTrue(ns.size() > 0); List<Double> nsConverted = ns.stream().map(val -> Double.parseDouble(val)).collect(Collectors.toList()); assertTrue(nsConverted.contains(Double.parseDouble(nValue2))); assertTrue(nsConverted.contains(Double.parseDouble(nValue3))); assertTrue(nsConverted.contains(Double.parseDouble(nValue4))); assertTrue(nsConverted.contains(Double.parseDouble(nValue5))); List<SdkBytes> bs = newItem.get("BSattr").bs(); assertTrue(bs.size() > 0); assertTrue(bs.containsAll(Arrays.asList(bValue, bValue2))); // Check List List<AttributeValue> l = newItem.get("Lattr").l(); assertEquals(3, l.size()); assertEquals(bValue, l.get(0).b()); assertEquals(sValue, l.get(1).s()); assertEquals(nValue, l.get(2).n()); // Check Map Map<String, AttributeValue> m = newItem.get("Mattr").m(); assertEquals(3, m.size()); assertEquals(sValue2, m.get("M:Sattr").s()); assertEquals(Double.parseDouble(nValue2), Double.parseDouble(m.get("M:Nattr").n())); assertEquals(bValue2, m.get("M:Battr").b()); // Check empty structures assertEquals(0, newItem.get("Lattr-empty").l().size()); assertEquals(0, newItem.get("Mattr-empty").m().size()); } }
4,923
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/HierarchicalKeyringBranchKeyIdSupplierTests.java
package software.amazon.cryptography.dbencryptionsdk.dynamodb; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.*; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryption; import software.amazon.cryptography.dbencryptionsdk.dynamodb.IDynamoDbKeyBranchKeyIdSupplier; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.DynamoDbItemEncryptor; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.*; import software.amazon.cryptography.keystore.KeyStore; import software.amazon.cryptography.materialproviders.IBranchKeyIdSupplier; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.DynamoDbItemEncryptorConfig; import software.amazon.cryptography.materialproviders.model.*; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import java.util.HashMap; import java.util.Map; import static org.testng.Assert.*; import static software.amazon.cryptography.dbencryptionsdk.dynamodb.TestUtils.*; import org.testng.annotations.Test; public class HierarchicalKeyringBranchKeyIdSupplierTests { @Test public void TestHierarchyKeyringWithSupplier() { // Create client with keyring that uses branch key supplier for key A and key B KeyStore keystore = createKeyStore(); DynamoDbEncryption ddbEnc = DynamoDbEncryption.builder() .DynamoDbEncryptionConfig(DynamoDbEncryptionConfig.builder().build()) .build(); IBranchKeyIdSupplier branchKeyIdSupplier = ddbEnc.CreateDynamoDbEncryptionBranchKeyIdSupplier( CreateDynamoDbEncryptionBranchKeyIdSupplierInput.builder() .ddbKeyBranchKeyIdSupplier(new TestSupplier()) .build()) .branchKeyIdSupplier(); IKeyring keyring = createHierarchicalKeyring(keystore, branchKeyIdSupplier); assertNotNull(keyring); DynamoDbEncryptionInterceptor interceptor = TestUtils.createInterceptor(keyring, null, null); DynamoDbClient ddbAB = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(interceptor) .build()) .build(); // Create client with keyring only configured with key A IKeyring keyringA = createHierarchicalKeyring(keystore, BRANCH_KEY_ID); assertNotNull(keyringA); DynamoDbEncryptionInterceptor interceptorA = TestUtils.createInterceptor(keyringA, null, null); DynamoDbClient ddbA = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(interceptorA) .build()) .build(); // Put CaseA item into table with Hierarchy keyring with supplier // Put item into table String partitionValue = "caseA"; String sortValue = "42"; String attrValue = "bar"; String attrValue2 = "hello world"; Map<String, AttributeValue> item = createTestItem(partitionValue, sortValue, attrValue, attrValue2); PutItemRequest putRequestA = PutItemRequest.builder() .tableName(TEST_TABLE_NAME) .item(item) .build(); PutItemResponse putResponseA = ddbAB.putItem(putRequestA); assertEquals(200, putResponseA.sdkHttpResponse().statusCode()); // Get Item back from table Map<String, AttributeValue> keyToGetA = createTestKey(partitionValue, sortValue); GetItemRequest getRequestA = GetItemRequest.builder() .key(keyToGetA) .tableName(TEST_TABLE_NAME) .build(); GetItemResponse getResponseA = ddbAB.getItem(getRequestA); assertEquals(200, getResponseA.sdkHttpResponse().statusCode()); Map<String, AttributeValue> returnedItemA = getResponseA.item(); assertNotNull(returnedItemA); assertEquals(partitionValue, returnedItemA.get(TEST_PARTITION_NAME).s()); assertEquals(sortValue, returnedItemA.get(TEST_SORT_NAME).n()); assertEquals(attrValue, returnedItemA.get(TEST_ATTR_NAME).s()); // Assert we can retrieve this item with a Hierarchical keyring configured only with key A getResponseA = ddbA.getItem(getRequestA); assertEquals(200, getResponseA.sdkHttpResponse().statusCode()); returnedItemA = getResponseA.item(); assertNotNull(returnedItemA); assertEquals(partitionValue, returnedItemA.get(TEST_PARTITION_NAME).s()); assertEquals(sortValue, returnedItemA.get(TEST_SORT_NAME).n()); assertEquals(attrValue, returnedItemA.get(TEST_ATTR_NAME).s()); // Put CaseB item // Put item into table partitionValue = "caseB"; sortValue = "42"; attrValue = "bar"; attrValue2 = "hello world"; Map<String, AttributeValue> itemB = createTestItem(partitionValue, sortValue, attrValue, attrValue2); PutItemRequest putRequest2 = PutItemRequest.builder() .tableName(TEST_TABLE_NAME) .item(itemB) .build(); PutItemResponse putResponse2 = ddbAB.putItem(putRequest2); assertEquals(200, putResponse2.sdkHttpResponse().statusCode()); // Get Item back from table Map<String, AttributeValue> keyToGetB = createTestKey(partitionValue, sortValue); GetItemRequest getRequestB = GetItemRequest.builder() .key(keyToGetB) .tableName(TEST_TABLE_NAME) .build(); GetItemResponse getResponseB = ddbAB.getItem(getRequestB); assertEquals(200, getResponseB.sdkHttpResponse().statusCode()); Map<String, AttributeValue> returnedItemB = getResponseB.item(); assertNotNull(returnedItemB); assertEquals(partitionValue, returnedItemB.get(TEST_PARTITION_NAME).s()); assertEquals(sortValue, returnedItemB.get(TEST_SORT_NAME).n()); assertEquals(attrValue, returnedItemB.get(TEST_ATTR_NAME).s()); } @Test( expectedExceptions = software.amazon.cryptography.materialproviders.model.OpaqueError.class, expectedExceptionsMessageRegExp = "Item invalid, does not contain expected attributes." ) public void TestHierarchyKeyringWithSupplierReturnsExpectedError() { // Create client with keyring that uses branch key supplier that errors on "caseC" KeyStore keystore = createKeyStore(); DynamoDbEncryption ddbEnc = DynamoDbEncryption.builder() .DynamoDbEncryptionConfig(DynamoDbEncryptionConfig.builder().build()) .build(); IBranchKeyIdSupplier branchKeyIdSupplier = ddbEnc.CreateDynamoDbEncryptionBranchKeyIdSupplier( CreateDynamoDbEncryptionBranchKeyIdSupplierInput.builder() .ddbKeyBranchKeyIdSupplier(new TestSupplier()) .build()) .branchKeyIdSupplier(); IKeyring keyring = createHierarchicalKeyring(keystore, branchKeyIdSupplier); assertNotNull(keyring); DynamoDbEncryptionInterceptor interceptor = TestUtils.createInterceptor(keyring, null, null); DynamoDbClient ddbAB = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(interceptor) .build()) .build(); // Put CaseA item into table with Hierarchy keyring with supplier String partitionValue = "caseC"; String sortValue = "42"; String attrValue = "bar"; String attrValue2 = "hello world"; Map<String, AttributeValue> item = createTestItem(partitionValue, sortValue, attrValue, attrValue2); PutItemRequest putRequestA = PutItemRequest.builder() .tableName(TEST_TABLE_NAME) .item(item) .build(); ddbAB.putItem(putRequestA); } // DynamoDbKeyBranchKeyIdSupplier to be used with test items produced from TestUtils.java class TestSupplier implements IDynamoDbKeyBranchKeyIdSupplier { public GetBranchKeyIdFromDdbKeyOutput GetBranchKeyIdFromDdbKey(GetBranchKeyIdFromDdbKeyInput getBranchKeyIdFromDdbKeyInput) { Map<String, AttributeValue> key = getBranchKeyIdFromDdbKeyInput.ddbKey(); // Ensure that key only contains the expected attributes assertTrue(key.containsKey(TEST_PARTITION_NAME)); assertTrue(key.containsKey(TEST_SORT_NAME)); assertFalse(key.containsKey(TEST_ATTR_NAME)); assertFalse(key.containsKey(TEST_ATTR2_NAME)); String branchKeyId; if (key.containsKey(TEST_PARTITION_NAME) && key.get(TEST_PARTITION_NAME).s().equals("caseA")) { branchKeyId = BRANCH_KEY_ID; } else if (key.containsKey(TEST_PARTITION_NAME) && key.get(TEST_PARTITION_NAME).s().equals("caseB")) { branchKeyId = ALTERNATE_BRANCH_KEY_ID; } else { throw new IllegalArgumentException("Item invalid, does not contain expected attributes."); } return GetBranchKeyIdFromDdbKeyOutput.builder().branchKeyId(branchKeyId).build(); } } }
4,924
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient/DynamoDbEncryptionEnhancedClientIntegrationTests.java
package software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient; 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.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.DirectKmsMaterialProvider; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.AWSKMSClientBuilder; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import software.amazon.awssdk.services.kms.model.KmsException; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.validdatamodels.*; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.LegacyOverride; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.LegacyPolicy; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; import software.amazon.cryptography.materialproviders.IKeyring; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.testng.Assert.assertEquals; import static software.amazon.cryptography.dbencryptionsdk.dynamodb.TestUtils.*; import org.testng.annotations.Test; import javax.annotation.Nullable; public class DynamoDbEncryptionEnhancedClientIntegrationTests { private static <T> DynamoDbEnhancedClient initEnhancedClientWithInterceptor( final TableSchema<T> schemaOnEncrypt, final List<String> allowedUnsignedAttributes, @Nullable String kmsKeyId, @Nullable String tableName ) { Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); IKeyring kmsKeyring = kmsKeyId == null ? createKmsKeyring() : createKmsKeyring(kmsKeyId); String testTableName = tableName == null ? TEST_TABLE_NAME : tableName; tableConfigs.put(testTableName, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(testTableName) .keyring(kmsKeyring) .allowedUnsignedAttributes(allowedUnsignedAttributes) .schemaOnEncrypt(schemaOnEncrypt) .build()); DynamoDbEncryptionInterceptor interceptor = DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build() ); DynamoDbClient ddb = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(interceptor) .build()) .build(); return DynamoDbEnhancedClient.builder() .dynamoDbClient(ddb) .build(); } @Test public void TestPutAndGet() { TableSchema<SimpleClass> schemaOnEncrypt = TableSchema.fromBean(SimpleClass.class); List<String> allowedUnsignedAttributes = Collections.singletonList("doNothing"); DynamoDbEnhancedClient enhancedClient = initEnhancedClientWithInterceptor(schemaOnEncrypt, allowedUnsignedAttributes, null, null); DynamoDbTable<SimpleClass> table = enhancedClient.table(TEST_TABLE_NAME, schemaOnEncrypt); SimpleClass record = new SimpleClass(); record.setPartitionKey("SimpleEnhanced"); record.setSortKey(777); record.setEncryptAndSign("lorem"); record.setSignOnly("ipsum"); record.setDoNothing("fizzbuzz"); // Put an item into an Amazon DynamoDB table. table.putItem(record); // Get the item back from the table Key key = Key.builder() .partitionValue("SimpleEnhanced").sortValue(777) .build(); // Get the item by using the key. SimpleClass result = table.getItem( (GetItemEnhancedRequest.Builder requestBuilder) -> requestBuilder.key(key)); assertEquals(result.getPartitionKey(), "SimpleEnhanced"); assertEquals(result.getSortKey(), 777); assertEquals(result.getEncryptAndSign(), "lorem"); assertEquals(result.getSignOnly(), "ipsum"); assertEquals(result.getDoNothing(), "fizzbuzz"); } @Test public void TestPutAndGetAnnotatedFlattenedBean() { final String PARTITION = "AnnotatedFlattenedBean"; final int SORT = 20230713; TableSchema<AnnotatedFlattenedBean> schemaOnEncrypt = TableSchema.fromBean(AnnotatedFlattenedBean.class); List<String> allowedUnsignedAttributes = Collections.singletonList("lastName"); DynamoDbEnhancedClient enhancedClient = initEnhancedClientWithInterceptor(schemaOnEncrypt, allowedUnsignedAttributes, null, null); DynamoDbTable<AnnotatedFlattenedBean> table = enhancedClient.table(TEST_TABLE_NAME, schemaOnEncrypt); AnnotatedFlattenedBean record = new AnnotatedFlattenedBean(); record.setPartitionKey(PARTITION); record.setSortKey(SORT); AnnotatedFlattenedBean.FlattenedNestedBean nestedBean = new AnnotatedFlattenedBean.FlattenedNestedBean( "9305B367-C477-4A58-9E6C-BF7D59D17C8A", "James", "Bond" ); record.setNestedBeanClass(nestedBean); // Put an item into an Amazon DynamoDB table. table.putItem(record); // Get the item back from the table Key key = Key.builder() .partitionValue(PARTITION).sortValue(SORT) .build(); // Get the item by using the key. AnnotatedFlattenedBean result = table.getItem( (GetItemEnhancedRequest.Builder requestBuilder) -> requestBuilder.key(key)); assertEquals(result.getPartitionKey(), record.getPartitionKey()); assertEquals(result.getSortKey(), record.getSortKey()); assertEquals(result.getNestedBeanClass(), record.getNestedBeanClass()); } @Test public void TestPutAndGetAnnotatedConvertedBy() { final String PARTITION = "AnnotatedConvertedBy"; final int SORT = 20230713; TableSchema<AnnotatedConvertedBy> schemaOnEncrypt = TableSchema.fromBean(AnnotatedConvertedBy.class); List<String> allowedUnsignedAttributes = Collections.singletonList("nestedIgnored"); DynamoDbEnhancedClient enhancedClient = initEnhancedClientWithInterceptor(schemaOnEncrypt, allowedUnsignedAttributes, null, null); DynamoDbTable<AnnotatedConvertedBy> table = enhancedClient.table(TEST_TABLE_NAME, schemaOnEncrypt); AnnotatedConvertedBy record = new AnnotatedConvertedBy(); record.setPartitionKey(PARTITION); record.setSortKey(SORT); AnnotatedConvertedBy.ConvertedByNestedBean nestedBean = new AnnotatedConvertedBy.ConvertedByNestedBean( "9305B367-C477-4A58-9E6C-BF7D59D17C8A", "Winnie", "the-Pooh" ); record.setNestedEncrypted(nestedBean); record.setNestedIgnored(nestedBean); record.setNestedSigned(nestedBean); // Put an item into an Amazon DynamoDB table. table.putItem(record); // Get the item back from the table Key key = Key.builder() .partitionValue(PARTITION).sortValue(SORT) .build(); // Get the item by using the key. AnnotatedConvertedBy result = table.getItem( (GetItemEnhancedRequest.Builder requestBuilder) -> requestBuilder.key(key)); assertEquals(result.getPartitionKey(), record.getPartitionKey()); assertEquals(result.getSortKey(), record.getSortKey()); assertEquals(result.getNestedIgnored(), record.getNestedIgnored()); assertEquals(result.getNestedEncrypted(), record.getNestedEncrypted()); assertEquals(result.getNestedSigned(), record.getNestedSigned()); } @Test public void TestPutAndGetSignOnly() { TableSchema<SignOnlyClass> schemaOnEncrypt = TableSchema.fromBean(SignOnlyClass.class); List<String> allowedUnsignedAttributes = Collections.singletonList("doNothing"); DynamoDbEnhancedClient enhancedClient = initEnhancedClientWithInterceptor(schemaOnEncrypt, allowedUnsignedAttributes, null, null); DynamoDbTable<SignOnlyClass> table = enhancedClient.table(TEST_TABLE_NAME, schemaOnEncrypt); SignOnlyClass record = new SignOnlyClass(); record.setPartitionKey("SignOnlyEnhanced"); record.setSortKey(777); record.setAttr1("lorem"); record.setAttr2("ipsum"); // Put an item into an Amazon DynamoDB table. table.putItem(record); // Get the item back from the table Key key = Key.builder() .partitionValue("SignOnlyEnhanced").sortValue(777) .build(); // Get the item by using the key. SignOnlyClass result = table.getItem( (GetItemEnhancedRequest.Builder requestBuilder) -> requestBuilder.key(key)); assertEquals(result.getPartitionKey(), "SignOnlyEnhanced"); assertEquals(result.getSortKey(), 777); assertEquals(result.getAttr1(), "lorem"); assertEquals(result.getAttr2(), "ipsum"); } @Test public void TestGetLegacyItem() { // Put item using legacy DDBMapper AWSKMS kmsClient = AWSKMSClientBuilder.standard().build(); final DirectKmsMaterialProvider cmp = new DirectKmsMaterialProvider(kmsClient, KMS_TEST_KEY_ID); final DynamoDBEncryptor oldEncryptor = DynamoDBEncryptor.getInstance(cmp); final AmazonDynamoDB ddbv1 = AmazonDynamoDBClientBuilder.standard().build(); DynamoDBMapperConfig mapperConfig = DynamoDBMapperConfig.builder().withSaveBehavior(DynamoDBMapperConfig.SaveBehavior.PUT).build(); DynamoDBMapper mapper = new DynamoDBMapper(ddbv1, mapperConfig, new AttributeEncryptor(oldEncryptor)); LegacyClass record = new LegacyClass(); record.setPartitionKey("ddbMapperItem"); record.setSortKey(777); record.setEncryptAndSign("lorem"); record.setSignOnly("ipsum"); record.setDoNothing("fizzbuzz"); mapper.save(record); // Configure EnhancedClient with Legacy behavior Map<String, CryptoAction> legacyActions = new HashMap<>(); legacyActions.put("partition_key", CryptoAction.SIGN_ONLY); legacyActions.put("sort_key", CryptoAction.SIGN_ONLY); legacyActions.put("encryptAndSign", CryptoAction.ENCRYPT_AND_SIGN); legacyActions.put("signOnly", CryptoAction.SIGN_ONLY); legacyActions.put("doNothing", CryptoAction.DO_NOTHING); LegacyOverride legacyOverride = LegacyOverride .builder() .encryptor(oldEncryptor) .policy(LegacyPolicy.FORCE_LEGACY_ENCRYPT_ALLOW_LEGACY_DECRYPT) .attributeActionsOnEncrypt(legacyActions) .build(); TableSchema<LegacyClass> schemaOnEncrypt = TableSchema.fromBean(LegacyClass.class); DynamoDbEnhancedClient enhancedClient = createEnhancedClientForLegacyClass(oldEncryptor, schemaOnEncrypt); DynamoDbTable<LegacyClass> table = enhancedClient.table(TEST_TABLE_NAME, schemaOnEncrypt); // Get the item back from the table Key key = Key.builder() .partitionValue("ddbMapperItem").sortValue(777) .build(); LegacyClass result = table.getItem( (GetItemEnhancedRequest.Builder requestBuilder) -> requestBuilder.key(key)); assertEquals("ddbMapperItem", result.getPartitionKey()); assertEquals(777, result.getSortKey()); assertEquals("lorem", result.getEncryptAndSign()); assertEquals("ipsum", result.getSignOnly()); assertEquals("fizzbuzz", result.getDoNothing()); } @Test public void TestWriteLegacyItem() { // Configure EnhancedClient with Legacy behavior AWSKMS kmsClient = AWSKMSClientBuilder.standard().build(); final DirectKmsMaterialProvider cmp = new DirectKmsMaterialProvider(kmsClient, KMS_TEST_KEY_ID); final DynamoDBEncryptor oldEncryptor = DynamoDBEncryptor.getInstance(cmp); TableSchema<LegacyClass> schemaOnEncrypt = TableSchema.fromBean(LegacyClass.class); DynamoDbEnhancedClient enhancedClient = createEnhancedClientForLegacyClass(oldEncryptor, schemaOnEncrypt); LegacyClass record = new LegacyClass(); record.setPartitionKey("legacyItem"); record.setSortKey(777); record.setEncryptAndSign("lorem"); record.setSignOnly("ipsum"); record.setDoNothing("fizzbuzz"); DynamoDbTable<LegacyClass> table = enhancedClient.table(TEST_TABLE_NAME, schemaOnEncrypt); table.putItem(record); // Get item using legacy DDBMapper final AmazonDynamoDB ddbv1 = AmazonDynamoDBClientBuilder.standard().build(); DynamoDBMapperConfig mapperConfig = DynamoDBMapperConfig.builder().withSaveBehavior(DynamoDBMapperConfig.SaveBehavior.PUT).build(); DynamoDBMapper mapper = new DynamoDBMapper(ddbv1, mapperConfig, new AttributeEncryptor(oldEncryptor)); LegacyClass result = mapper.load(LegacyClass.class, "legacyItem", 777); assertEquals("legacyItem", result.getPartitionKey()); assertEquals(777, result.getSortKey()); assertEquals("lorem", result.getEncryptAndSign()); assertEquals("ipsum", result.getSignOnly()); assertEquals("fizzbuzz", result.getDoNothing()); } private static DynamoDbEnhancedClient createEnhancedClientForLegacyClass(DynamoDBEncryptor oldEncryptor, TableSchema schemaOnEncrypt) { Map<String, CryptoAction> legacyActions = new HashMap<>(); legacyActions.put("partition_key", CryptoAction.SIGN_ONLY); legacyActions.put("sort_key", CryptoAction.SIGN_ONLY); legacyActions.put("encryptAndSign", CryptoAction.ENCRYPT_AND_SIGN); legacyActions.put("signOnly", CryptoAction.SIGN_ONLY); legacyActions.put("doNothing", CryptoAction.DO_NOTHING); LegacyOverride legacyOverride = LegacyOverride .builder() .encryptor(oldEncryptor) .policy(LegacyPolicy.FORCE_LEGACY_ENCRYPT_ALLOW_LEGACY_DECRYPT) .attributeActionsOnEncrypt(legacyActions) .build(); Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(TEST_TABLE_NAME, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(TEST_TABLE_NAME) .keyring(createKmsKeyring()) .allowedUnsignedAttributes(Arrays.asList("doNothing")) .schemaOnEncrypt(schemaOnEncrypt) .legacyOverride(legacyOverride) .build()); DynamoDbEncryptionInterceptor interceptor = DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build() ); DynamoDbClient ddb = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(interceptor) .build()) .build(); return DynamoDbEnhancedClient.builder() .dynamoDbClient(ddb) .build(); } @Test( expectedExceptions = KmsException.class, expectedExceptionsMessageRegExp = ".*" ) public void TestKmsError() { // Use an KMS Key that does not exist String invalidKey = "arn:aws:kms:us-west-2:658956600833:key/ffffffff-ffff-ffff-ffff-ffffffffffff"; TableSchema<SimpleClass> schemaOnEncrypt = TableSchema.fromBean(SimpleClass.class); List<String> allowedUnsignedAttributes = Collections.singletonList("doNothing"); DynamoDbEnhancedClient enhancedClient = initEnhancedClientWithInterceptor(schemaOnEncrypt, allowedUnsignedAttributes, invalidKey, null); DynamoDbTable<SimpleClass> table = enhancedClient.table(TEST_TABLE_NAME, schemaOnEncrypt); SimpleClass record = new SimpleClass(); record.setPartitionKey("foo"); record.setSortKey(777); record.setEncryptAndSign("lorem"); record.setSignOnly("ipsum"); record.setDoNothing("fizzbuzz"); // Put an item into an Amazon DynamoDB table. table.putItem(record); } @Test( expectedExceptions = DynamoDbException.class, expectedExceptionsMessageRegExp = ".*Status Code: 400.*" ) public void TestDdbError() { // Use a DynamoDB Table that does not exist String badTableName = "tableDoesNotExist"; TableSchema<SimpleClass> schemaOnEncrypt = TableSchema.fromBean(SimpleClass.class); List<String> allowedUnsignedAttributes = Collections.singletonList("doNothing"); DynamoDbEnhancedClient enhancedClient = initEnhancedClientWithInterceptor(schemaOnEncrypt, allowedUnsignedAttributes, null, badTableName); DynamoDbTable<SimpleClass> table = enhancedClient.table(badTableName, schemaOnEncrypt); SimpleClass record = new SimpleClass(); record.setPartitionKey("foo"); record.setSortKey(777); record.setEncryptAndSign("lorem"); record.setSignOnly("ipsum"); record.setDoNothing("fizzbuzz"); // Put an item into an Amazon DynamoDB table. table.putItem(record); } }
4,925
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient/DynamoDbEnhancedClientEncryptionTest.java
package software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient; 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 software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.invaliddatamodels.*; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.validdatamodels.*; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.DynamoDbItemEncryptorException; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.LegacyOverride; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.LegacyPolicy; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbEncryptionException; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTableEncryptionConfig; import software.amazon.cryptography.materialproviders.model.DBEAlgorithmSuiteId; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.testng.Assert.*; import static software.amazon.cryptography.dbencryptionsdk.dynamodb.TestUtils.*; import org.testng.annotations.Test; public class DynamoDbEnhancedClientEncryptionTest { @Test public void TestMultipleTables() { TableSchema<SimpleClass> simpleSchema = TableSchema.fromBean(SimpleClass.class); TableSchema<SignOnlyClass> signOnlySchema = TableSchema.fromBean(SignOnlyClass.class); Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put("SimpleClassTestTable", DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName("SimpleClassTestTable") .keyring(createKmsKeyring()) .allowedUnsignedAttributes(Arrays.asList("doNothing")) .schemaOnEncrypt(simpleSchema) .build()); tableConfigs.put("SignOnlyClassTestTable", DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName("SignOnlyClassTestTable") .keyring(createKmsKeyring()) .schemaOnEncrypt(signOnlySchema) .build()); DynamoDbEncryptionInterceptor interceptor = DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build() ); assertEquals(2, interceptor.config().tableEncryptionConfigs().size()); DynamoDbTableEncryptionConfig simpleConfig = interceptor.config().tableEncryptionConfigs().get("SimpleClassTestTable"); assertEquals(CryptoAction.DO_NOTHING, simpleConfig.attributeActionsOnEncrypt().get("doNothing")); assertEquals(CryptoAction.SIGN_ONLY, simpleConfig.attributeActionsOnEncrypt().get("signOnly")); assertEquals(CryptoAction.SIGN_ONLY, simpleConfig.attributeActionsOnEncrypt().get("partition_key")); assertEquals(CryptoAction.SIGN_ONLY, simpleConfig.attributeActionsOnEncrypt().get("sort_key")); assertEquals(CryptoAction.ENCRYPT_AND_SIGN, simpleConfig.attributeActionsOnEncrypt().get("encryptAndSign")); DynamoDbTableEncryptionConfig signOnlyConfig = interceptor.config().tableEncryptionConfigs().get("SignOnlyClassTestTable"); assertEquals(CryptoAction.SIGN_ONLY, signOnlyConfig.attributeActionsOnEncrypt().get("partition_key")); assertEquals(CryptoAction.SIGN_ONLY, signOnlyConfig.attributeActionsOnEncrypt().get("sort_key")); assertEquals(CryptoAction.SIGN_ONLY, signOnlyConfig.attributeActionsOnEncrypt().get("attr1")); assertEquals(CryptoAction.SIGN_ONLY, signOnlyConfig.attributeActionsOnEncrypt().get("attr2")); } @Test public void TestEnhancedCreateWithLegacyPolicy() { // Encryptor creation AWSKMS kmsClient = AWSKMSClientBuilder.standard().build(); final DirectKmsMaterialProvider cmp = new DirectKmsMaterialProvider(kmsClient, "kmsKeyARN"); final DynamoDBEncryptor oldEncryptor = DynamoDBEncryptor.getInstance(cmp); final Map<String, CryptoAction> oldActions = new HashMap<>(); TableSchema<SimpleClass> simpleSchema = TableSchema.fromBean(SimpleClass.class); Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(TEST_TABLE_NAME, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(TEST_TABLE_NAME) .keyring(createKmsKeyring()) .allowedUnsignedAttributes(Arrays.asList("doNothing")) .schemaOnEncrypt(simpleSchema) .legacyOverride( LegacyOverride.builder() .encryptor(oldEncryptor) .policy(LegacyPolicy.FORCE_LEGACY_ENCRYPT_ALLOW_LEGACY_DECRYPT) .attributeActionsOnEncrypt(oldActions) .build()) .build()); DynamoDbEncryptionInterceptor interceptor = DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build() ); assertNotNull(interceptor); } @Test public void TestEnhancedCreateWithAlgorithmSuite() { // Encryptor creation AWSKMS kmsClient = AWSKMSClientBuilder.standard().build(); final DirectKmsMaterialProvider cmp = new DirectKmsMaterialProvider(kmsClient, "kmsKeyARN"); TableSchema<SimpleClass> simpleSchema = TableSchema.fromBean(SimpleClass.class); Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(TEST_TABLE_NAME, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(TEST_TABLE_NAME) .keyring(createKmsKeyring()) .allowedUnsignedAttributes(Arrays.asList("doNothing")) .schemaOnEncrypt(simpleSchema) .algorithmSuiteId(DBEAlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_SYMSIG_HMAC_SHA384) .build()); DynamoDbEncryptionInterceptor interceptor = DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build() ); assertNotNull(interceptor); } @Test( expectedExceptions = DynamoDbEncryptionException.class, expectedExceptionsMessageRegExp = "Cannot use @DynamoDbEncryptionDoNothing on primary key attributes. Found on Table Name: DynamoDbEncryptionInterceptorTestTable" ) public void TestDoNothingOnPartitionAttribute() { TableSchema<InvalidAnnotatedPartitionClass> schemaOnEncrypt = TableSchema.fromBean(InvalidAnnotatedPartitionClass.class); Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(TEST_TABLE_NAME, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(TEST_TABLE_NAME) .keyring(createKmsKeyring()) .schemaOnEncrypt(schemaOnEncrypt) .build()); DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build()); } @Test( expectedExceptions = DynamoDbItemEncryptorException.class, expectedExceptionsMessageRegExp = "Attribute doNothing is configured as DO_NOTHING but it must also be in unauthenticatedAttributes or begin with the unauthenticatedPrefix." ) public void TestInconsistentSignatureScopeMissing() { TableSchema<SimpleClass> schemaOnEncrypt = TableSchema.fromBean(SimpleClass.class); // Do not specify Unauthenticated attributes when you should Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(TEST_TABLE_NAME, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(TEST_TABLE_NAME) .keyring(createKmsKeyring()) .schemaOnEncrypt(schemaOnEncrypt) .build()); DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build()); } @Test( expectedExceptions = DynamoDbItemEncryptorException.class, expectedExceptionsMessageRegExp = "Attribute partition_key is configured as SIGN_ONLY but it is also in unauthenticatedAttributes." ) public void TestInconsistentSignatureScopeIncorrect() { TableSchema<SimpleClass> schemaOnEncrypt = TableSchema.fromBean(SimpleClass.class); // Specify Unauthenticated attributes when you should not Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(TEST_TABLE_NAME, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(TEST_TABLE_NAME) .keyring(createKmsKeyring()) .allowedUnsignedAttributes(Arrays.asList("doNothing", "partition_key")) .schemaOnEncrypt(schemaOnEncrypt) .build()); DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build()); } @Test( expectedExceptions = DynamoDbEncryptionException.class, expectedExceptionsMessageRegExp = "Cannot use @DynamoDbEncryptionDoNothing on primary key attributes. Found on Table Name: DynamoDbEncryptionInterceptorTestTable" ) public void TestDoNothingOnSortAttribute() { TableSchema<InvalidAnnotatedSortClass> schemaOnEncrypt = TableSchema.fromBean(InvalidAnnotatedSortClass.class); Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(TEST_TABLE_NAME, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(TEST_TABLE_NAME) .keyring(createKmsKeyring()) .schemaOnEncrypt(schemaOnEncrypt) .build()); DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build()); } @Test( expectedExceptions = DynamoDbEncryptionException.class, expectedExceptionsMessageRegExp = "Cannot use @DynamoDbEncryptionDoNothing and @DynamoDbEncryptionSignOnly on same attribute. Found on Table Name: DynamoDbEncryptionInterceptorTestTable" ) public void TestDoubleAnnotationOnAttribute() { TableSchema<InvalidDoubleAnnotationClass> schemaOnEncrypt = TableSchema.fromBean(InvalidDoubleAnnotationClass.class); Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(TEST_TABLE_NAME, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(TEST_TABLE_NAME) .keyring(createKmsKeyring()) .schemaOnEncrypt(schemaOnEncrypt) .build()); DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build()); } @Test( expectedExceptions = DynamoDbItemEncryptorException.class, expectedExceptionsMessageRegExp = "Attribute lastName is configured as DO_NOTHING but it must also be in unauthenticatedAttributes or begin with the unauthenticatedPrefix." ) public void TestFlattenedNestedBeanAnnotationMissingUnauthenticatedAttributes() { TableSchema<AnnotatedFlattenedBean> schemaOnEncrypt = TableSchema.fromBean(AnnotatedFlattenedBean.class); Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(TEST_TABLE_NAME, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(TEST_TABLE_NAME) .keyring(createKmsKeyring()) .schemaOnEncrypt(schemaOnEncrypt) .build()); DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build()); } @Test public void TestFlattenedNestedBeanAnnotation() { TableSchema<AnnotatedFlattenedBean> schemaOnEncrypt = TableSchema.fromBean(AnnotatedFlattenedBean.class); Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(TEST_TABLE_NAME, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(TEST_TABLE_NAME) .keyring(createKmsKeyring()) .schemaOnEncrypt(schemaOnEncrypt) .allowedUnsignedAttributes(Collections.singletonList("lastName")) .build()); DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build()); } @Test public void TestAnnotatedConvertedBy() { TableSchema<AnnotatedConvertedBy> schemaOnEncrypt = TableSchema.fromBean(AnnotatedConvertedBy.class); Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(TEST_TABLE_NAME, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(TEST_TABLE_NAME) .keyring(createKmsKeyring()) .schemaOnEncrypt(schemaOnEncrypt) .allowedUnsignedAttributes(Collections.singletonList("nestedIgnored")) .build()); DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build()); } @Test( expectedExceptions = DynamoDbEncryptionException.class ) public void TestInvalidNestedBeanAnnotation() { TableSchema<InvalidAnnotatedNestedBean> schemaOnEncrypt = TableSchema.fromBean(InvalidAnnotatedNestedBean.class); Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(TEST_TABLE_NAME, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(TEST_TABLE_NAME) .keyring(createKmsKeyring()) .schemaOnEncrypt(schemaOnEncrypt) .build()); DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build()); } @Test( expectedExceptions = DynamoDbEncryptionException.class ) public void TestConflictingAnnotatedNestedBean() { TableSchema<ConflictingAnnotatedNestedBean> schemaOnEncrypt = TableSchema.fromBean(ConflictingAnnotatedNestedBean.class); Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(TEST_TABLE_NAME, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(TEST_TABLE_NAME) .keyring(createKmsKeyring()) .schemaOnEncrypt(schemaOnEncrypt) .allowedUnsignedAttributes(Collections.singletonList("nestedIgnored")) .build()); DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build()); } @Test( expectedExceptions = DynamoDbEncryptionException.class, expectedExceptionsMessageRegExp = "Detected DynamoDbEncryption Tag DynamoDbEncryption:SortOnly on a nested attribute with Path DynamoDbEncryptionInterceptorTestTable.nestedObject.secondNest.secondNestedId. This is NOT Supported at this time!" ) public void TestInvalidDeepNested() { TableSchema<InvalidDeepNested> schemaOnEncrypt = TableSchema.fromBean(InvalidDeepNested.class); Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(TEST_TABLE_NAME, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(TEST_TABLE_NAME) .keyring(createKmsKeyring()) .schemaOnEncrypt(schemaOnEncrypt) .allowedUnsignedAttributePrefix(":") .build()); DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build()); } @Test( expectedExceptions = DynamoDbEncryptionException.class, expectedExceptionsMessageRegExp = "Detected DynamoDbEncryption Tag DynamoDbEncryption:SortOnly on a nested attribute with Path DynamoDbEncryptionInterceptorTestTable.nestedObject.secondNestedId. This is NOT Supported at this time!" ) public void TestInvalidDeepFlatten() { TableSchema<InvalidDeepFlatten> schemaOnEncrypt = TableSchema.fromBean(InvalidDeepFlatten.class); Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(TEST_TABLE_NAME, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(TEST_TABLE_NAME) .keyring(createKmsKeyring()) .schemaOnEncrypt(schemaOnEncrypt) .allowedUnsignedAttributePrefix(":") .build()); DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build()); } @Test( // We skip this Test. enabled = false, // The DB-ESDK-DynamoDB for Java SHOULD detect ALL DynamoDBEncryption // Tags & Attributes that are IGNORED and throw an Exception. // However, detecting IGNORED DynamoDBEncryption Tags & Attributes // when a nested class is Flattened has NOT been implemented. // See GitHub Issue #259: // https://github.com/aws/aws-database-encryption-sdk-dynamodb-java/issues/259 expectedExceptions = DynamoDbEncryptionException.class ) public void TestConflictingFlattenedBean() { TableSchema<ConflictingFlattenedBean> schemaOnEncrypt = TableSchema.fromBean(ConflictingFlattenedBean.class); Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); List<String> allowedUnsignedAttributes = Arrays.asList( "lastName", "anotherLastName", "finalLastName"); tableConfigs.put(TEST_TABLE_NAME, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(TEST_TABLE_NAME) .keyring(createKmsKeyring()) .schemaOnEncrypt(schemaOnEncrypt) .allowedUnsignedAttributes(allowedUnsignedAttributes) .build()); DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build()); } }
4,926
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient/invaliddatamodels/InvalidDeepNested.java
package software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.invaliddatamodels; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionSignOnly; /** * This is an INVALID use of DynamoDbEncryption annotations on nested attributes. * The DynamoDbEncryption annotations are placed on elements that are NOT * DynamoDB Attributes but that will be mapped together into one DynamoDB * Attribute that is a Map.<p> */ @NoArgsConstructor @DynamoDbBean public class InvalidDeepNested { @Setter @Getter(onMethod_= {@DynamoDbPartitionKey, @DynamoDbAttribute(value = "partition_key")}) String partitionKey; @Setter @Getter(onMethod_= {@DynamoDbSortKey, @DynamoDbAttribute(value = "sort_key")}) int sortKey; @Setter @Getter(onMethod_= {@DynamoDbAttribute(value = "nestedObject")}) FirstNest firstNest; @NoArgsConstructor @DynamoDbBean public static class FirstNest { @Setter @Getter String firstNestId; @Setter @Getter SecondNest secondNest; } @NoArgsConstructor @DynamoDbBean public static class SecondNest { @Setter @Getter(onMethod_=@DynamoDbEncryptionSignOnly) String secondNestedId; } }
4,927
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient/invaliddatamodels/InvalidDeepFlatten.java
package software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.invaliddatamodels; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbFlatten; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionSignOnly; @NoArgsConstructor @DynamoDbBean public class InvalidDeepFlatten { @Setter @Getter(onMethod_= {@DynamoDbPartitionKey, @DynamoDbAttribute(value = "partition_key")}) String partitionKey; @Setter @Getter(onMethod_= {@DynamoDbSortKey, @DynamoDbAttribute(value = "sort_key")}) int sortKey; @Setter @Getter(onMethod_= {@DynamoDbAttribute(value = "nestedObject")}) FirstNest firstNest; @NoArgsConstructor @DynamoDbBean public static class FirstNest { @Setter @Getter String firstNestId; @Setter @Getter(onMethod_= {@DynamoDbFlatten}) SecondNest secondNest; } @NoArgsConstructor @DynamoDbBean public static class SecondNest { @Setter @Getter(onMethod_=@DynamoDbEncryptionSignOnly) String secondNestedId; } }
4,928
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient/invaliddatamodels/InvalidDoubleAnnotationClass.java
package software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.invaliddatamodels; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionDoNothing; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionSignOnly; /** * This class is used by the Enhanced Client Tests */ @DynamoDbBean public class InvalidDoubleAnnotationClass { private String id; private String sortKey; private String invalid; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } @DynamoDbSortKey public String getSortKey() { return this.sortKey; } public void setSortKey(String sortKey) { this.sortKey = sortKey; } @DynamoDbEncryptionSignOnly @DynamoDbEncryptionDoNothing public String getInvalid() { return this.invalid; } public void setInvalid(String invalid) { this.invalid = invalid; } }
4,929
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient/invaliddatamodels/ConflictingFlattenedBean.java
package software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.invaliddatamodels; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbFlatten; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionDoNothing; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionSignOnly; /** * This is an INVALID use of DynamoDbEncryption annotations on top level attributes. * The DynamoDbEncryption annotations are placed on elements that are NOT * DynamoDB Attributes but that will be replaced by the flattened class.<p> * * Worse yet, the top level annotation conflicts with annotations given in * the subfields.<p> */ @DynamoDbBean public class ConflictingFlattenedBean { private String partitionKey; private int sortKey; private NestedBean nestedEncrypted; private AnotherNestedBean nestedSigned; private FinalNestedBean nestedIgnored; @DynamoDbPartitionKey @DynamoDbAttribute(value = "partition_key") public String getPartitionKey() { return this.partitionKey; } public void setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; } @DynamoDbSortKey @DynamoDbAttribute(value = "sort_key") public int getSortKey() { return this.sortKey; } public void setSortKey(int sortKey) { this.sortKey = sortKey; } @DynamoDbFlatten public NestedBean getNestedEncrypted() { return this.nestedEncrypted; } public void setNestedEncrypted(NestedBean nested) { this.nestedEncrypted = nested; } @DynamoDbFlatten @DynamoDbEncryptionSignOnly //This annotation is IGNORED public AnotherNestedBean getNestedSigned() { return this.nestedSigned; } public void setNestedSigned(AnotherNestedBean nested) { this.nestedSigned = nested; } @DynamoDbFlatten @DynamoDbEncryptionDoNothing //This annotation is IGNORED public FinalNestedBean getNestedIgnored() { return this.nestedIgnored; } public void setNestedIgnored(FinalNestedBean nestedIgnored) { this.nestedIgnored = nestedIgnored; } @DynamoDbBean public static class NestedBean { private String id; private String firstName; private String lastName; public NestedBean() {}; NestedBean(String id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } // By Default, DB-ESDK for DDB will Encrypt & Sign this field public String getId() { return this.id; } public void setId(String id) { this.id = id; } @DynamoDbEncryptionSignOnly //This annotation is respected public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @DynamoDbEncryptionDoNothing //This annotation is respected public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NestedBean other = (NestedBean) obj; if (id == null) { if (other.getId() != null) return false; } else if (!id.equals(other.getId())) return false; if (firstName == null) { if (other.getFirstName() != null) return false; } else if (!firstName.equals(other.getFirstName())) return false; if (lastName == null) { if (other.getLastName() != null) return false; } else if (!lastName.equals(other.getLastName())) return false; return true; } } @DynamoDbBean public static class AnotherNestedBean { private String anotherId; private String anotherFirstName; private String anotherLastName; public AnotherNestedBean() {}; AnotherNestedBean(String id, String firstName, String lastName) { this.anotherId = id; this.anotherFirstName = firstName; this.anotherLastName = lastName; } // By Default, DB-ESDK for DDB will Encrypt & Sign this field public String getAnotherId() { return this.anotherId; } public void setAnotherId(String anotherId) { this.anotherId = anotherId; } @DynamoDbEncryptionSignOnly //This annotation is respected public String getAnotherFirstName() { return anotherFirstName; } public void setAnotherFirstName(String anotherFirstName) { this.anotherFirstName = anotherFirstName; } @DynamoDbEncryptionDoNothing //This annotation is respected public String getAnotherLastName() { return anotherLastName; } public void setAnotherLastName(String anotherLastName) { this.anotherLastName = anotherLastName; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AnotherNestedBean other = (AnotherNestedBean) obj; if (anotherId == null) { if (other.getAnotherId() != null) return false; } else if (!anotherId.equals(other.getAnotherId())) return false; if (anotherFirstName == null) { if (other.getAnotherFirstName() != null) return false; } else if (!anotherFirstName.equals(other.getAnotherFirstName())) return false; if (anotherLastName == null) { if (other.getAnotherLastName() != null) return false; } else if (!anotherLastName.equals(other.getAnotherLastName())) return false; return true; } } @DynamoDbBean public static class FinalNestedBean { private String finalId; private String finalFirstName; private String finalLastName; public FinalNestedBean() {}; FinalNestedBean(String id, String firstName, String lastName) { this.finalId = id; this.finalFirstName = firstName; this.finalLastName = lastName; } // By Default, DB-ESDK for DDB will Encrypt & Sign this field public String getFinalId() { return this.finalId; } public void setFinalId(String finalId) { this.finalId = finalId; } @DynamoDbEncryptionSignOnly //This annotation is respected public String getFinalFirstName() { return finalFirstName; } public void setFinalFirstName(String finalFirstName) { this.finalFirstName = finalFirstName; } @DynamoDbEncryptionDoNothing //This annotation is respected public String getFinalLastName() { return finalLastName; } public void setFinalLastName(String finalLastName) { this.finalLastName = finalLastName; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FinalNestedBean other = (FinalNestedBean) obj; if (finalId == null) { if (other.getFinalId() != null) return false; } else if (!finalId.equals(other.getFinalId())) return false; if (finalFirstName == null) { if (other.getFinalFirstName() != null) return false; } else if (!finalFirstName.equals(other.getFinalFirstName())) return false; if (finalLastName == null) { if (other.getFinalLastName() != null) return false; } else if (!finalLastName.equals(other.getFinalLastName())) return false; return true; } } }
4,930
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient/invaliddatamodels/ConflictingAnnotatedNestedBean.java
package software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.invaliddatamodels; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionDoNothing; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionSignOnly; /** * This is an INVALID use of DynamoDbEncryption annotations on nested attributes. * The DynamoDbEncryption annotations are placed on elements that are NOT * DynamoDB Attributes but that will be mapped together into one DynamoDB * Attribute that is a Map.<p> * Worse yet, the top level annotation conflicts with annotations given in * the subfields.<p> */ @DynamoDbBean public class ConflictingAnnotatedNestedBean { private String partitionKey; private int sortKey; private NestedBean nestedEncrypted; private NestedBean nestedSigned; private NestedBean nestedIgnored; @DynamoDbPartitionKey @DynamoDbAttribute(value = "partition_key") public String getPartitionKey() { return this.partitionKey; } public void setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; } @DynamoDbSortKey @DynamoDbAttribute(value = "sort_key") public int getSortKey() { return this.sortKey; } public void setSortKey(int sortKey) { this.sortKey = sortKey; } // By Default, DB-ESDK for DDB will Encrypt & Sign this field public NestedBean getNestedEncrypted() { return this.nestedEncrypted; } public void setNestedEncrypted(NestedBean nested) { this.nestedEncrypted = nested; } @DynamoDbEncryptionSignOnly //This annotation is respected public NestedBean getNestedSigned() { return this.nestedSigned; } public void setNestedSigned(NestedBean nested) { this.nestedSigned = nested; } @DynamoDbEncryptionDoNothing //This annotation is respected public NestedBean getNestedIgnored() { return this.nestedIgnored; } public void setNestedIgnored(NestedBean nestedIgnored) { this.nestedIgnored = nestedIgnored; } @DynamoDbBean public static class NestedBean { private String id; private String firstName; private String lastName; public NestedBean() {}; NestedBean(String id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } // Ignored DynamoDb Annotation @DynamoDbAttribute("id") public String getId() { return this.id; } public void setId(String id) { this.id = id; } // Ignored DynamoDb & DynamoDbEncryption Annotations @DynamoDbEncryptionSignOnly @DynamoDbAttribute("firstName") public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } // Ignored DynamoDb & DynamoDbEncryption Annotations @DynamoDbEncryptionDoNothing @DynamoDbAttribute("lastName") public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NestedBean other = (NestedBean) obj; if (id == null) { if (other.getId() != null) return false; } else if (!id.equals(other.getId())) return false; if (firstName == null) { if (other.getFirstName() != null) return false; } else if (!firstName.equals(other.getFirstName())) return false; if (lastName == null) { if (other.getLastName() != null) return false; } else if (!lastName.equals(other.getLastName())) return false; return true; } } }
4,931
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient/invaliddatamodels/InvalidAnnotatedPartitionClass.java
package software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.invaliddatamodels; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionDoNothing; @DynamoDbBean public class InvalidAnnotatedPartitionClass { private String id; @DynamoDbEncryptionDoNothing @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } }
4,932
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient/invaliddatamodels/InvalidAnnotatedNestedBean.java
package software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.invaliddatamodels; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionDoNothing; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionSignOnly; /** * This is an INVALID use of DynamoDbEncryption annotations on nested attributes. * The DynamoDbEncryption annotations are placed on elements that are NOT * DynamoDB Attributes but that will be mapped together into one DynamoDB * Attribute that is a Map.<p> */ @DynamoDbBean public class InvalidAnnotatedNestedBean { private String partitionKey; private int sortKey; private NestedBean nestedBeanClass; @DynamoDbPartitionKey @DynamoDbAttribute(value = "partition_key") public String getPartitionKey() { return this.partitionKey; } public void setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; } @DynamoDbSortKey @DynamoDbAttribute(value = "sort_key") public int getSortKey() { return this.sortKey; } public void setSortKey(int sortKey) { this.sortKey = sortKey; } public NestedBean getNestedBeanClass() { return this.nestedBeanClass; } public void setNestedBeanClass(NestedBean nestedBeanClass) { this.nestedBeanClass = nestedBeanClass; } @DynamoDbBean public static class NestedBean { private String id; private String firstName; private String lastName; public NestedBean() {}; NestedBean(String id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } @DynamoDbAttribute("id") //This annotation is IGNORED public String getId() { return this.id; } public void setId(String id) { this.id = id; } @DynamoDbEncryptionSignOnly //This annotation is IGNORED @DynamoDbAttribute("firstName") //This annotation is IGNORED public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @DynamoDbEncryptionDoNothing //This annotation is IGNORED @DynamoDbAttribute("lastName") //This annotation is IGNORED public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NestedBean other = (NestedBean) obj; if (id == null) { if (other.getId() != null) return false; } else if (!id.equals(other.getId())) return false; if (firstName == null) { if (other.getFirstName() != null) return false; } else if (!firstName.equals(other.getFirstName())) return false; if (lastName == null) { if (other.getLastName() != null) return false; } else if (!lastName.equals(other.getLastName())) return false; return true; } } }
4,933
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient/invaliddatamodels/InvalidAnnotatedSortClass.java
package software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.invaliddatamodels; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionDoNothing; @DynamoDbBean public class InvalidAnnotatedSortClass { private String id; private String sortKey; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } @DynamoDbEncryptionDoNothing @DynamoDbSortKey public String getSortKey() { return this.sortKey; } public void setSortKey(String sortKey) { this.sortKey = sortKey; } }
4,934
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient/validdatamodels/SignOnlyClass.java
package software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.validdatamodels; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionSignOnly; @DynamoDbBean public class SignOnlyClass { private String partitionKey; private int sortKey; private String attr1; private String attr2; @DynamoDbPartitionKey @DynamoDbAttribute(value = "partition_key") public String getPartitionKey() { return this.partitionKey; } public void setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; } @DynamoDbSortKey @DynamoDbAttribute(value = "sort_key") public int getSortKey() { return this.sortKey; } public void setSortKey(int sortKey) { this.sortKey = sortKey; } @DynamoDbEncryptionSignOnly public String getAttr1() { return this.attr1; } public void setAttr1(String attr1) { this.attr1 = attr1; } @DynamoDbEncryptionSignOnly public String getAttr2() { return this.attr2; } public void setAttr2(String attr2) { this.attr2 = attr2; } }
4,935
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient/validdatamodels/SimpleClass.java
package software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.validdatamodels; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionDoNothing; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionSignOnly; /** * This class is used by the Enhanced Client Tests */ @DynamoDbBean public class SimpleClass { private String partitionKey; private int sortKey; private String encryptAndSign; private String doNothing; private String signOnly; @DynamoDbPartitionKey @DynamoDbAttribute(value = "partition_key") public String getPartitionKey() { return this.partitionKey; } public void setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; } @DynamoDbSortKey @DynamoDbAttribute(value = "sort_key") public int getSortKey() { return this.sortKey; } public void setSortKey(int sortKey) { this.sortKey = sortKey; } public String getEncryptAndSign() { return this.encryptAndSign; } public void setEncryptAndSign(String encryptAndSign) { this.encryptAndSign = encryptAndSign; } @DynamoDbEncryptionSignOnly public String getSignOnly() { return this.signOnly; } public void setSignOnly(String signOnly) { this.signOnly = signOnly; } @DynamoDbEncryptionDoNothing public String getDoNothing() { return this.doNothing; } public void setDoNothing(String doNothing) { this.doNothing = doNothing; } }
4,936
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient/validdatamodels/AnnotatedConvertedBy.java
package software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.validdatamodels; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbConvertedBy; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionDoNothing; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionSignOnly; /** * This is a valid use of DynamoDbEncryption annotations attributes with * DynamoDbConvertedBy.<p> * The DynamoDbEncryption annotations are placed on elements that are converted * to Maps.<p> * In this case, only {@code nestedEncrypted} will be written to the DynamoDB Table as a * binary. {@code nestedSigned} and {@code nestedIgnored} are recorded as DynamoDB Maps. */ @DynamoDbBean public class AnnotatedConvertedBy { private String partitionKey; private int sortKey; private ConvertedByNestedBean nestedEncrypted; private ConvertedByNestedBean nestedSigned; private ConvertedByNestedBean nestedIgnored; @DynamoDbPartitionKey @DynamoDbAttribute(value = "partition_key") public String getPartitionKey() { return this.partitionKey; } public void setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; } @DynamoDbSortKey @DynamoDbAttribute(value = "sort_key") public int getSortKey() { return this.sortKey; } public void setSortKey(int sortKey) { this.sortKey = sortKey; } @DynamoDbConvertedBy(ConvertedByNestedBean.NestedBeanConverter.class) @DynamoDbAttribute("nestedEncrypted") public ConvertedByNestedBean getNestedEncrypted() { return this.nestedEncrypted; } public void setNestedEncrypted(ConvertedByNestedBean nested) { this.nestedEncrypted = nested; } @DynamoDbConvertedBy(ConvertedByNestedBean.NestedBeanConverter.class) @DynamoDbEncryptionSignOnly @DynamoDbAttribute("nestedSigned") public ConvertedByNestedBean getNestedSigned() { return this.nestedSigned; } public void setNestedSigned(ConvertedByNestedBean nested) { this.nestedSigned = nested; } @DynamoDbConvertedBy(ConvertedByNestedBean.NestedBeanConverter.class) @DynamoDbEncryptionDoNothing @DynamoDbAttribute("nestedIgnored") public ConvertedByNestedBean getNestedIgnored() { return this.nestedIgnored; } public void setNestedIgnored(ConvertedByNestedBean nested) { this.nestedIgnored = nested; } public static class ConvertedByNestedBean { private String id; private String firstName; private String lastName; // A Default Empty constructor is needed by the Enhanced Client public ConvertedByNestedBean() {}; public ConvertedByNestedBean(String id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ConvertedByNestedBean other = (ConvertedByNestedBean) obj; if (id == null) { if (other.getId() != null) return false; } else if (!id.equals(other.getId())) return false; if (firstName == null) { if (other.getFirstName() != null) return false; } else if (!firstName.equals(other.getFirstName())) return false; if (lastName == null) { if (other.getLastName() != null) return false; } else if (!lastName.equals(other.getLastName())) return false; return true; } public static final class NestedBeanConverter implements AttributeConverter<ConvertedByNestedBean> { @Override public AttributeValue transformFrom(ConvertedByNestedBean ConvertedByNestedBean) { Map<String, AttributeValue> map = new HashMap<>(3); map.put("id", AttributeValue.fromS(ConvertedByNestedBean.getId())); map.put("firstName", AttributeValue.fromS(ConvertedByNestedBean.getFirstName())); map.put("lastName", AttributeValue.fromS(ConvertedByNestedBean.getLastName())); return AttributeValue.fromM(map); } @Override public ConvertedByNestedBean transformTo(AttributeValue attributeValue) { Map<String, AttributeValue> map = attributeValue.m(); return new ConvertedByNestedBean( map.get("id").s(), map.get("firstName").s(), map.get("lastName").s()); } @Override public EnhancedType<ConvertedByNestedBean> type() { return EnhancedType.of(ConvertedByNestedBean.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.M; } } } }
4,937
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient/validdatamodels/LegacyClass.java
package software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.validdatamodels; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotEncrypt; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotTouch; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionDoNothing; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionSignOnly; import static software.amazon.cryptography.dbencryptionsdk.dynamodb.TestUtils.TEST_TABLE_NAME; /** * This class is used by the Enhanced Client Tests */ @DynamoDbBean @DynamoDBTable(tableName = TEST_TABLE_NAME) public class LegacyClass { private String partitionKey; private int sortKey; private String encryptAndSign; private String doNothing; private String signOnly; @DynamoDbPartitionKey @DynamoDbAttribute(value = "partition_key") @DynamoDBHashKey(attributeName = "partition_key") public String getPartitionKey() { return this.partitionKey; } public void setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; } @DynamoDbSortKey @DynamoDbAttribute(value = "sort_key") @DynamoDBRangeKey(attributeName = "sort_key") public int getSortKey() { return this.sortKey; } public void setSortKey(int sortKey) { this.sortKey = sortKey; } @DynamoDBAttribute public String getEncryptAndSign() { return this.encryptAndSign; } public void setEncryptAndSign(String encryptAndSign) { this.encryptAndSign = encryptAndSign; } @DynamoDBAttribute @DoNotEncrypt @DynamoDbEncryptionSignOnly public String getSignOnly() { return this.signOnly; } public void setSignOnly(String signOnly) { this.signOnly = signOnly; } @DynamoDBAttribute @DoNotTouch @DynamoDbEncryptionDoNothing public String getDoNothing() { return this.doNothing; } public void setDoNothing(String doNothing) { this.doNothing = doNothing; } }
4,938
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient/validdatamodels/AnnotatedFlattenedBean.java
package software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.validdatamodels; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbFlatten; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionDoNothing; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionSignOnly; /** * This is a valid use of DynamoDbEncryption annotations on nested attributes. * Currently, the ONLY WAY to properly specify DynamoDbEncryption actions * on nested attributes is via the @DynamoDbFlatten attribute.<p> * * Note that you MUST NOT use a DynamoDbEncryption annotation on the * Flattened Attribute itself.<p> * Only on it's sub-fields.<p> */ @DynamoDbBean public class AnnotatedFlattenedBean { private String partitionKey; private int sortKey; private FlattenedNestedBean nestedBeanClass; @DynamoDbPartitionKey @DynamoDbAttribute(value = "partition_key") public String getPartitionKey() { return this.partitionKey; } public void setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; } @DynamoDbSortKey @DynamoDbAttribute(value = "sort_key") public int getSortKey() { return this.sortKey; } public void setSortKey(int sortKey) { this.sortKey = sortKey; } // Any @DynamoDbEncryption annotation here would be IGNORED // Instead, the Annotations MUST BE placed on the Getter Methods of // FlattenedNestedBean. @DynamoDbFlatten public FlattenedNestedBean getNestedBeanClass() { return this.nestedBeanClass; } public void setNestedBeanClass(FlattenedNestedBean nestedBeanClass) { this.nestedBeanClass = nestedBeanClass; } @DynamoDbBean public static class FlattenedNestedBean { private String id; private String firstName; private String lastName; public FlattenedNestedBean() {}; public FlattenedNestedBean(String id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } @DynamoDbAttribute("id") public String getId() { return this.id; } public void setId(String id) { this.id = id; } @DynamoDbEncryptionSignOnly @DynamoDbAttribute("firstName") public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @DynamoDbEncryptionDoNothing @DynamoDbAttribute("lastName") public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FlattenedNestedBean other = (FlattenedNestedBean) obj; if (id == null) { if (other.getId() != null) return false; } else if (!id.equals(other.getId())) return false; if (firstName == null) { if (other.getFirstName() != null) return false; } else if (!firstName.equals(other.getFirstName())) return false; if (lastName == null) { if (other.getLastName() != null) return false; } else if (!lastName.equals(other.getLastName())) return false; return true; } } }
4,939
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/encryption/NumberAttributeTestClass.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBIgnore; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Calendar; import java.util.Date; /** Simple domain class with numeric attributes */ @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public class NumberAttributeTestClass { private String key; private int intAttribute; private Integer integerAttribute; private double doubleAttribute; private Double doubleObjectAttribute; private float floatAttribute; private Float floatObjectAttribute; private BigDecimal bigDecimalAttribute; private BigInteger bigIntegerAttribute; private long longAttribute; private Long longObjectAttribute; private short shortAttribute; private Short shortObjectAttribute; private byte byteAttribute; private Byte byteObjectAttribute; private Date dateAttribute; private Calendar calendarAttribute; private Boolean booleanObjectAttribute; private boolean booleanAttribute; private String ignored = "notSent"; @DynamoDBAutoGeneratedKey @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } public int getIntAttribute() { return intAttribute; } public void setIntAttribute(int intAttribute) { this.intAttribute = intAttribute; } public Integer getIntegerAttribute() { return integerAttribute; } public void setIntegerAttribute(Integer integerAttribute) { this.integerAttribute = integerAttribute; } public double getDoubleAttribute() { return doubleAttribute; } public void setDoubleAttribute(double doubleAttribute) { this.doubleAttribute = doubleAttribute; } public Double getDoubleObjectAttribute() { return doubleObjectAttribute; } public void setDoubleObjectAttribute(Double doubleObjectAttribute) { this.doubleObjectAttribute = doubleObjectAttribute; } @DynamoDBAttribute public float getFloatAttribute() { return floatAttribute; } public void setFloatAttribute(float floatAttribute) { this.floatAttribute = floatAttribute; } public Float getFloatObjectAttribute() { return floatObjectAttribute; } public void setFloatObjectAttribute(Float floatObjectAttribute) { this.floatObjectAttribute = floatObjectAttribute; } public BigDecimal getBigDecimalAttribute() { return bigDecimalAttribute; } public void setBigDecimalAttribute(BigDecimal bigDecimalAttribute) { this.bigDecimalAttribute = bigDecimalAttribute; } public BigInteger getBigIntegerAttribute() { return bigIntegerAttribute; } public void setBigIntegerAttribute(BigInteger bigIntegerAttribute) { this.bigIntegerAttribute = bigIntegerAttribute; } public long getLongAttribute() { return longAttribute; } public void setLongAttribute(long longAttribute) { this.longAttribute = longAttribute; } public Long getLongObjectAttribute() { return longObjectAttribute; } public void setLongObjectAttribute(Long longObjectAttribute) { this.longObjectAttribute = longObjectAttribute; } public byte getByteAttribute() { return byteAttribute; } public void setByteAttribute(byte byteAttribute) { this.byteAttribute = byteAttribute; } public Byte getByteObjectAttribute() { return byteObjectAttribute; } public void setByteObjectAttribute(Byte byteObjectAttribute) { this.byteObjectAttribute = byteObjectAttribute; } public Date getDateAttribute() { return dateAttribute; } public void setDateAttribute(Date dateAttribute) { this.dateAttribute = dateAttribute; } public Calendar getCalendarAttribute() { return calendarAttribute; } public void setCalendarAttribute(Calendar calendarAttribute) { this.calendarAttribute = calendarAttribute; } public Boolean getBooleanObjectAttribute() { return booleanObjectAttribute; } public void setBooleanObjectAttribute(Boolean booleanObjectAttribute) { this.booleanObjectAttribute = booleanObjectAttribute; } public boolean isBooleanAttribute() { return booleanAttribute; } public void setBooleanAttribute(boolean booleanAttribute) { this.booleanAttribute = booleanAttribute; } @DynamoDBIgnore public String getIgnored() { return ignored; } public void setIgnored(String ignored) { this.ignored = ignored; } public short getShortAttribute() { return shortAttribute; } public void setShortAttribute(short shortAttribute) { this.shortAttribute = shortAttribute; } public Short getShortObjectAttribute() { return shortObjectAttribute; } public void setShortObjectAttribute(Short shortObjectAttribute) { this.shortObjectAttribute = shortObjectAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((bigDecimalAttribute == null) ? 0 : bigDecimalAttribute.hashCode()); result = prime * result + ((bigIntegerAttribute == null) ? 0 : bigIntegerAttribute.hashCode()); result = prime * result + (booleanAttribute ? 1231 : 1237); result = prime * result + ((booleanObjectAttribute == null) ? 0 : booleanObjectAttribute.hashCode()); result = prime * result + byteAttribute; result = prime * result + ((byteObjectAttribute == null) ? 0 : byteObjectAttribute.hashCode()); result = prime * result + ((calendarAttribute == null) ? 0 : calendarAttribute.hashCode()); result = prime * result + ((dateAttribute == null) ? 0 : dateAttribute.hashCode()); long temp; temp = Double.doubleToLongBits(doubleAttribute); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((doubleObjectAttribute == null) ? 0 : doubleObjectAttribute.hashCode()); result = prime * result + Float.floatToIntBits(floatAttribute); result = prime * result + ((floatObjectAttribute == null) ? 0 : floatObjectAttribute.hashCode()); result = prime * result + ((ignored == null) ? 0 : ignored.hashCode()); result = prime * result + intAttribute; result = prime * result + ((integerAttribute == null) ? 0 : integerAttribute.hashCode()); result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + (int) (longAttribute ^ (longAttribute >>> 32)); result = prime * result + ((longObjectAttribute == null) ? 0 : longObjectAttribute.hashCode()); result = prime * result + shortAttribute; result = prime * result + ((shortObjectAttribute == null) ? 0 : shortObjectAttribute.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NumberAttributeTestClass other = (NumberAttributeTestClass) obj; if (bigDecimalAttribute == null) { if (other.bigDecimalAttribute != null) return false; } else if (!bigDecimalAttribute.equals(other.bigDecimalAttribute)) return false; if (bigIntegerAttribute == null) { if (other.bigIntegerAttribute != null) return false; } else if (!bigIntegerAttribute.equals(other.bigIntegerAttribute)) return false; if (booleanAttribute != other.booleanAttribute) return false; if (booleanObjectAttribute == null) { if (other.booleanObjectAttribute != null) return false; } else if (!booleanObjectAttribute.equals(other.booleanObjectAttribute)) return false; if (byteAttribute != other.byteAttribute) return false; if (byteObjectAttribute == null) { if (other.byteObjectAttribute != null) return false; } else if (!byteObjectAttribute.equals(other.byteObjectAttribute)) return false; if (calendarAttribute == null) { if (other.calendarAttribute != null) return false; } else if (!calendarAttribute.equals(other.calendarAttribute)) return false; if (dateAttribute == null) { if (other.dateAttribute != null) return false; } else if (!dateAttribute.equals(other.dateAttribute)) return false; if (Double.doubleToLongBits(doubleAttribute) != Double.doubleToLongBits(other.doubleAttribute)) return false; if (doubleObjectAttribute == null) { if (other.doubleObjectAttribute != null) return false; } else if (!doubleObjectAttribute.equals(other.doubleObjectAttribute)) return false; if (Float.floatToIntBits(floatAttribute) != Float.floatToIntBits(other.floatAttribute)) return false; if (floatObjectAttribute == null) { if (other.floatObjectAttribute != null) return false; } else if (!floatObjectAttribute.equals(other.floatObjectAttribute)) return false; if (ignored == null) { if (other.ignored != null) return false; } else if (!ignored.equals(other.ignored)) return false; if (intAttribute != other.intAttribute) return false; if (integerAttribute == null) { if (other.integerAttribute != null) return false; } else if (!integerAttribute.equals(other.integerAttribute)) return false; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (longAttribute != other.longAttribute) return false; if (longObjectAttribute == null) { if (other.longObjectAttribute != null) return false; } else if (!longObjectAttribute.equals(other.longObjectAttribute)) return false; if (shortAttribute != other.shortAttribute) return false; if (shortObjectAttribute == null) { if (other.shortObjectAttribute != null) return false; } else if (!shortObjectAttribute.equals(other.shortObjectAttribute)) return false; return true; } }
4,940
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/encryption/BinaryAttributeByteBufferTestClass.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import java.nio.ByteBuffer; import java.util.Set; /** Test domain class with byteBuffer attribute, byteBuffer set and a string key */ @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public class BinaryAttributeByteBufferTestClass { private String key; private ByteBuffer binaryAttribute; private Set<ByteBuffer> binarySetAttribute; @DynamoDBHashKey(attributeName = "key") public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAttribute(attributeName = "binaryAttribute") public ByteBuffer getBinaryAttribute() { return binaryAttribute; } public void setBinaryAttribute(ByteBuffer binaryAttribute) { this.binaryAttribute = binaryAttribute; } @DynamoDBAttribute(attributeName = "binarySetAttribute") public Set<ByteBuffer> getBinarySetAttribute() { return binarySetAttribute; } public void setBinarySetAttribute(Set<ByteBuffer> binarySetAttribute) { this.binarySetAttribute = binarySetAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((binaryAttribute == null) ? 0 : binaryAttribute.hashCode()); result = prime * result + ((binarySetAttribute == null) ? 0 : binarySetAttribute.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BinaryAttributeByteBufferTestClass other = (BinaryAttributeByteBufferTestClass) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (binaryAttribute == null) { if (other.binaryAttribute != null) return false; } else if (!binaryAttribute.equals(other.binaryAttribute)) return false; if (binarySetAttribute == null) { if (other.binarySetAttribute != null) return false; } else if (!binarySetAttribute.equals(other.binarySetAttribute)) return false; return true; } }
4,941
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/encryption/RangeKeyTestClass.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBVersionAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotEncrypt; import java.math.BigDecimal; import java.util.Set; /** Comprehensive domain class */ @DynamoDBTable(tableName = "aws-java-sdk-range-test-crypto") public class RangeKeyTestClass { private long key; private double rangeKey; private Long version; private Set<Integer> integerSetAttribute; private Set<String> stringSetAttribute; private BigDecimal bigDecimalAttribute; private String stringAttribute; @DynamoDBHashKey public long getKey() { return key; } public void setKey(long key) { this.key = key; } @DynamoDBRangeKey public double getRangeKey() { return rangeKey; } public void setRangeKey(double rangeKey) { this.rangeKey = rangeKey; } @DynamoDBAttribute(attributeName = "integerSetAttribute") public Set<Integer> getIntegerAttribute() { return integerSetAttribute; } public void setIntegerAttribute(Set<Integer> integerAttribute) { this.integerSetAttribute = integerAttribute; } @DynamoDBAttribute public Set<String> getStringSetAttribute() { return stringSetAttribute; } public void setStringSetAttribute(Set<String> stringSetAttribute) { this.stringSetAttribute = stringSetAttribute; } @DoNotEncrypt @DynamoDBAttribute public BigDecimal getBigDecimalAttribute() { return bigDecimalAttribute; } public void setBigDecimalAttribute(BigDecimal bigDecimalAttribute) { this.bigDecimalAttribute = bigDecimalAttribute; } @DynamoDBAttribute public String getStringAttribute() { return stringAttribute; } public void setStringAttribute(String stringAttribute) { this.stringAttribute = stringAttribute; } @DoNotEncrypt @DynamoDBVersionAttribute public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((bigDecimalAttribute == null) ? 0 : bigDecimalAttribute.hashCode()); result = prime * result + ((integerSetAttribute == null) ? 0 : integerSetAttribute.hashCode()); result = prime * result + (int) (key ^ (key >>> 32)); long temp; temp = Double.doubleToLongBits(rangeKey); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((stringAttribute == null) ? 0 : stringAttribute.hashCode()); result = prime * result + ((stringSetAttribute == null) ? 0 : stringSetAttribute.hashCode()); result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RangeKeyTestClass other = (RangeKeyTestClass) obj; if (bigDecimalAttribute == null) { if (other.bigDecimalAttribute != null) return false; } else if (!bigDecimalAttribute.equals(other.bigDecimalAttribute)) return false; if (integerSetAttribute == null) { if (other.integerSetAttribute != null) return false; } else if (!integerSetAttribute.equals(other.integerSetAttribute)) return false; if (key != other.key) return false; if (Double.doubleToLongBits(rangeKey) != Double.doubleToLongBits(other.rangeKey)) return false; if (stringAttribute == null) { if (other.stringAttribute != null) return false; } else if (!stringAttribute.equals(other.stringAttribute)) return false; if (stringSetAttribute == null) { if (other.stringSetAttribute != null) return false; } else if (!stringSetAttribute.equals(other.stringSetAttribute)) return false; if (version == null) { if (other.version != null) return false; } else if (!version.equals(other.version)) return false; return true; } @Override public String toString() { return "RangeKeyTestClass [key=" + key + ", rangeKey=" + rangeKey + ", version=" + version + ", integerSetAttribute=" + integerSetAttribute + ", stringSetAttribute=" + stringSetAttribute + ", bigDecimalAttribute=" + bigDecimalAttribute + ", stringAttribute=" + stringAttribute + "]"; } }
4,942
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/encryption/NumberSetAttributeTestClass.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Calendar; import java.util.Date; import java.util.Set; /** Simple domain class with numeric attributes */ @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public class NumberSetAttributeTestClass { private String key; private Set<Integer> integerAttribute; private Set<Double> doubleObjectAttribute; private Set<Float> floatObjectAttribute; private Set<BigDecimal> bigDecimalAttribute; private Set<BigInteger> bigIntegerAttribute; private Set<Long> longObjectAttribute; private Set<Byte> byteObjectAttribute; private Set<Date> dateAttribute; private Set<Calendar> calendarAttribute; private Set<Boolean> booleanAttribute; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAttribute public Set<Integer> getIntegerAttribute() { return integerAttribute; } public void setIntegerAttribute(Set<Integer> integerAttribute) { this.integerAttribute = integerAttribute; } @DynamoDBAttribute public Set<Double> getDoubleObjectAttribute() { return doubleObjectAttribute; } public void setDoubleObjectAttribute(Set<Double> doubleObjectAttribute) { this.doubleObjectAttribute = doubleObjectAttribute; } @DynamoDBAttribute public Set<Float> getFloatObjectAttribute() { return floatObjectAttribute; } public void setFloatObjectAttribute(Set<Float> floatObjectAttribute) { this.floatObjectAttribute = floatObjectAttribute; } @DynamoDBAttribute public Set<BigDecimal> getBigDecimalAttribute() { return bigDecimalAttribute; } public void setBigDecimalAttribute(Set<BigDecimal> bigDecimalAttribute) { this.bigDecimalAttribute = bigDecimalAttribute; } @DynamoDBAttribute public Set<BigInteger> getBigIntegerAttribute() { return bigIntegerAttribute; } public void setBigIntegerAttribute(Set<BigInteger> bigIntegerAttribute) { this.bigIntegerAttribute = bigIntegerAttribute; } @DynamoDBAttribute public Set<Long> getLongObjectAttribute() { return longObjectAttribute; } public void setLongObjectAttribute(Set<Long> longObjectAttribute) { this.longObjectAttribute = longObjectAttribute; } @DynamoDBAttribute public Set<Byte> getByteObjectAttribute() { return byteObjectAttribute; } public void setByteObjectAttribute(Set<Byte> byteObjectAttribute) { this.byteObjectAttribute = byteObjectAttribute; } @DynamoDBAttribute public Set<Date> getDateAttribute() { return dateAttribute; } public void setDateAttribute(Set<Date> dateAttribute) { this.dateAttribute = dateAttribute; } @DynamoDBAttribute public Set<Calendar> getCalendarAttribute() { return calendarAttribute; } public void setCalendarAttribute(Set<Calendar> calendarAttribute) { this.calendarAttribute = calendarAttribute; } @DynamoDBAttribute public Set<Boolean> getBooleanAttribute() { return booleanAttribute; } public void setBooleanAttribute(Set<Boolean> booleanAttribute) { this.booleanAttribute = booleanAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((bigDecimalAttribute == null) ? 0 : bigDecimalAttribute.hashCode()); result = prime * result + ((bigIntegerAttribute == null) ? 0 : bigIntegerAttribute.hashCode()); result = prime * result + ((booleanAttribute == null) ? 0 : booleanAttribute.hashCode()); result = prime * result + ((byteObjectAttribute == null) ? 0 : byteObjectAttribute.hashCode()); result = prime * result + ((calendarAttribute == null) ? 0 : calendarAttribute.hashCode()); result = prime * result + ((dateAttribute == null) ? 0 : dateAttribute.hashCode()); result = prime * result + ((doubleObjectAttribute == null) ? 0 : doubleObjectAttribute.hashCode()); result = prime * result + ((floatObjectAttribute == null) ? 0 : floatObjectAttribute.hashCode()); result = prime * result + ((integerAttribute == null) ? 0 : integerAttribute.hashCode()); result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((longObjectAttribute == null) ? 0 : longObjectAttribute.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NumberSetAttributeTestClass other = (NumberSetAttributeTestClass) obj; if (bigDecimalAttribute == null) { if (other.bigDecimalAttribute != null) return false; } else if (!bigDecimalAttribute.equals(other.bigDecimalAttribute)) return false; if (bigIntegerAttribute == null) { if (other.bigIntegerAttribute != null) return false; } else if (!bigIntegerAttribute.equals(other.bigIntegerAttribute)) return false; if (booleanAttribute == null) { if (other.booleanAttribute != null) return false; } else if (!booleanAttribute.equals(other.booleanAttribute)) return false; if (byteObjectAttribute == null) { if (other.byteObjectAttribute != null) return false; } else if (!byteObjectAttribute.equals(other.byteObjectAttribute)) return false; if (calendarAttribute == null) { if (other.calendarAttribute != null) return false; } else if (!calendarAttribute.equals(other.calendarAttribute)) return false; if (dateAttribute == null) { if (other.dateAttribute != null) return false; } else if (!dateAttribute.equals(other.dateAttribute)) return false; if (doubleObjectAttribute == null) { if (other.doubleObjectAttribute != null) return false; } else if (!doubleObjectAttribute.equals(other.doubleObjectAttribute)) return false; if (floatObjectAttribute == null) { if (other.floatObjectAttribute != null) return false; } else if (!floatObjectAttribute.equals(other.floatObjectAttribute)) return false; if (integerAttribute == null) { if (other.integerAttribute != null) return false; } else if (!integerAttribute.equals(other.integerAttribute)) return false; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (longObjectAttribute == null) { if (other.longObjectAttribute != null) return false; } else if (!longObjectAttribute.equals(other.longObjectAttribute)) return false; return true; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "NumberSetAttributeTestClass [key=" + key; // + ", integerAttribute=" + integerAttribute // + ", doubleObjectAttribute=" + doubleObjectAttribute + ", // floatObjectAttribute=" + floatObjectAttribute // + ", bigDecimalAttribute=" + bigDecimalAttribute + ", bigIntegerAttribute=" + // bigIntegerAttribute // + ", longObjectAttribute=" + longObjectAttribute + ", byteObjectAttribute=" + // byteObjectAttribute // + ", dateAttribute=" + dateAttribute + ", calendarAttribute=" + // calendarAttribute // + ", booleanAttribute=" + booleanAttribute + "]"; } }
4,943
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/encryption/StringAttributeTestClass.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; /** Test domain class with a single string attribute and a string key */ @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public class StringAttributeTestClass { private String key; private String stringAttribute; private String renamedAttribute; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAttribute public String getStringAttribute() { return stringAttribute; } public void setStringAttribute(String stringAttribute) { this.stringAttribute = stringAttribute; } @DynamoDBAttribute(attributeName = "originalName") public String getRenamedAttribute() { return renamedAttribute; } public void setRenamedAttribute(String renamedAttribute) { this.renamedAttribute = renamedAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((renamedAttribute == null) ? 0 : renamedAttribute.hashCode()); result = prime * result + ((stringAttribute == null) ? 0 : stringAttribute.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; StringAttributeTestClass other = (StringAttributeTestClass) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (renamedAttribute == null) { if (other.renamedAttribute != null) return false; } else if (!renamedAttribute.equals(other.renamedAttribute)) return false; if (stringAttribute == null) { if (other.stringAttribute != null) return false; } else if (!stringAttribute.equals(other.stringAttribute)) return false; return true; } }
4,944
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/encryption/TestEncryptionMaterialsProvider.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.EncryptionMaterialsProvider; import com.amazonaws.util.StringMapBuilder; import java.security.Key; import java.util.Map; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class TestEncryptionMaterialsProvider implements EncryptionMaterialsProvider { private final EncryptionMaterials em = new EncryptionMaterials() { @Override public Map<String, String> getMaterialDescription() { return new StringMapBuilder("id", "test").build(); } @Override public SecretKey getEncryptionKey() { return new SecretKeySpec(new byte[32], "AES"); } @Override public Key getSigningKey() { return new SecretKeySpec(new byte[32], "HmacSHA256"); } }; private final DecryptionMaterials dm = new DecryptionMaterials() { @Override public Map<String, String> getMaterialDescription() { return new StringMapBuilder("id", "test").build(); } @Override public SecretKey getDecryptionKey() { return new SecretKeySpec(new byte[32], "AES"); } @Override public Key getVerificationKey() { return new SecretKeySpec(new byte[32], "HmacSHA256"); } }; @Override public DecryptionMaterials getDecryptionMaterials(EncryptionContext context) { return dm; } @Override public EncryptionMaterials getEncryptionMaterials(EncryptionContext context) { return em; } @Override public void refresh() {} }
4,945
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/encryption/TestDynamoDBMapperFactory.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.datamodeling.AttributeEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; public class TestDynamoDBMapperFactory { public static DynamoDBMapper createDynamoDBMapper(AmazonDynamoDB dynamo) { return new DynamoDBMapper( dynamo, DynamoDBMapperConfig.builder() .withSaveBehavior(DynamoDBMapperConfig.SaveBehavior.PUT) .build(), new AttributeEncryptor(new TestEncryptionMaterialsProvider())); } public static DynamoDBMapper createDynamoDBMapper( AmazonDynamoDB dynamo, DynamoDBMapperConfig config) { return new DynamoDBMapper( dynamo, config, new AttributeEncryptor(new TestEncryptionMaterialsProvider())); } }
4,946
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/encryption/MapperQueryExpressionCryptoTest.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBIndexHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBIndexRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.ComparisonOperator; import com.amazonaws.services.dynamodbv2.model.Condition; import com.amazonaws.services.dynamodbv2.model.QueryRequest; import com.amazonaws.util.ImmutableMapParameter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Unit test for the private method DynamoDBMapper#createQueryRequestFromExpression */ public class MapperQueryExpressionCryptoTest { private static final String TABLE_NAME = "table_name_crypto"; private static final Condition RANGE_KEY_CONDITION = new Condition() .withAttributeValueList(new AttributeValue("some value")) .withComparisonOperator(ComparisonOperator.EQ); private static DynamoDBMapper mapper; private static Method testedMethod; @BeforeClass public static void setUp() throws SecurityException, NoSuchMethodException { AmazonDynamoDB dynamo = new AmazonDynamoDBClient(); mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); testedMethod = DynamoDBMapper.class.getDeclaredMethod( "createQueryRequestFromExpression", Class.class, DynamoDBQueryExpression.class, DynamoDBMapperConfig.class); testedMethod.setAccessible(true); } @DynamoDBTable(tableName = TABLE_NAME) public final class HashOnlyClass { @DynamoDBHashKey @DynamoDBIndexHashKey(globalSecondaryIndexNames = "GSI-primary-hash") private String primaryHashKey; @DynamoDBIndexHashKey(globalSecondaryIndexNames = {"GSI-index-hash-1", "GSI-index-hash-2"}) private String indexHashKey; @DynamoDBIndexHashKey(globalSecondaryIndexNames = {"GSI-another-index-hash"}) private String anotherIndexHashKey; public HashOnlyClass(String primaryHashKey, String indexHashKey, String anotherIndexHashKey) { this.primaryHashKey = primaryHashKey; this.indexHashKey = indexHashKey; this.anotherIndexHashKey = anotherIndexHashKey; } public String getPrimaryHashKey() { return primaryHashKey; } public void setPrimaryHashKey(String primaryHashKey) { this.primaryHashKey = primaryHashKey; } public String getIndexHashKey() { return indexHashKey; } public void setIndexHashKey(String indexHashKey) { this.indexHashKey = indexHashKey; } public String getAnotherIndexHashKey() { return anotherIndexHashKey; } public void setAnotherIndexHashKey(String anotherIndexHashKey) { this.anotherIndexHashKey = anotherIndexHashKey; } } /** Tests different scenarios of hash-only query */ @Test public void testHashConditionOnly() { // Primary hash only QueryRequest queryRequest = testCreateQueryRequestFromExpression( HashOnlyClass.class, new DynamoDBQueryExpression<HashOnlyClass>() .withHashKeyValues(new HashOnlyClass("foo", null, null))); assertTrue(queryRequest.getKeyConditions().size() == 1); assertEquals("primaryHashKey", queryRequest.getKeyConditions().keySet().iterator().next()); assertEquals( new Condition() .withAttributeValueList(new AttributeValue("foo")) .withComparisonOperator(ComparisonOperator.EQ), queryRequest.getKeyConditions().get("primaryHashKey")); assertNull(queryRequest.getIndexName()); // Primary hash used for a GSI queryRequest = testCreateQueryRequestFromExpression( HashOnlyClass.class, new DynamoDBQueryExpression<HashOnlyClass>() .withHashKeyValues(new HashOnlyClass("foo", null, null)) .withIndexName("GSI-primary-hash")); assertTrue(queryRequest.getKeyConditions().size() == 1); assertEquals("primaryHashKey", queryRequest.getKeyConditions().keySet().iterator().next()); assertEquals( new Condition() .withAttributeValueList(new AttributeValue("foo")) .withComparisonOperator(ComparisonOperator.EQ), queryRequest.getKeyConditions().get("primaryHashKey")); assertEquals("GSI-primary-hash", queryRequest.getIndexName()); // Primary hash query takes higher priority then index hash query queryRequest = testCreateQueryRequestFromExpression( HashOnlyClass.class, new DynamoDBQueryExpression<HashOnlyClass>() .withHashKeyValues(new HashOnlyClass("foo", "bar", null))); assertTrue(queryRequest.getKeyConditions().size() == 1); assertEquals("primaryHashKey", queryRequest.getKeyConditions().keySet().iterator().next()); assertEquals( new Condition() .withAttributeValueList(new AttributeValue("foo")) .withComparisonOperator(ComparisonOperator.EQ), queryRequest.getKeyConditions().get("primaryHashKey")); assertNull(queryRequest.getIndexName()); // Ambiguous query on multiple index hash keys queryRequest = testCreateQueryRequestFromExpression( HashOnlyClass.class, new DynamoDBQueryExpression<HashOnlyClass>() .withHashKeyValues(new HashOnlyClass(null, "bar", "charlie")), "Ambiguous query expression: More than one index hash key EQ conditions"); // Ambiguous query when not specifying index name queryRequest = testCreateQueryRequestFromExpression( HashOnlyClass.class, new DynamoDBQueryExpression<HashOnlyClass>() .withHashKeyValues(new HashOnlyClass(null, "bar", null)), "Ambiguous query expression: More than one GSIs"); // Explicitly specify a GSI. queryRequest = testCreateQueryRequestFromExpression( HashOnlyClass.class, new DynamoDBQueryExpression<HashOnlyClass>() .withHashKeyValues(new HashOnlyClass("foo", "bar", null)) .withIndexName("GSI-index-hash-1")); assertTrue(queryRequest.getKeyConditions().size() == 1); assertEquals("indexHashKey", queryRequest.getKeyConditions().keySet().iterator().next()); assertEquals( new Condition() .withAttributeValueList(new AttributeValue("bar")) .withComparisonOperator(ComparisonOperator.EQ), queryRequest.getKeyConditions().get("indexHashKey")); assertEquals("GSI-index-hash-1", queryRequest.getIndexName()); // Non-existent GSI queryRequest = testCreateQueryRequestFromExpression( HashOnlyClass.class, new DynamoDBQueryExpression<HashOnlyClass>() .withHashKeyValues(new HashOnlyClass("foo", "bar", null)) .withIndexName("some fake gsi"), "No hash key condition is applicable to the specified index"); // No hash key condition specified queryRequest = testCreateQueryRequestFromExpression( HashOnlyClass.class, new DynamoDBQueryExpression<HashOnlyClass>() .withHashKeyValues(new HashOnlyClass(null, null, null)), "Illegal query expression: No hash key condition is found in the query"); } @DynamoDBTable(tableName = TABLE_NAME) public final class HashRangeClass { private String primaryHashKey; private String indexHashKey; private String primaryRangeKey; private String indexRangeKey; private String anotherIndexRangeKey; public HashRangeClass(String primaryHashKey, String indexHashKey) { this.primaryHashKey = primaryHashKey; this.indexHashKey = indexHashKey; } @DynamoDBHashKey @DynamoDBIndexHashKey( globalSecondaryIndexNames = { "GSI-primary-hash-index-range-1", "GSI-primary-hash-index-range-2" }) public String getPrimaryHashKey() { return primaryHashKey; } public void setPrimaryHashKey(String primaryHashKey) { this.primaryHashKey = primaryHashKey; } @DynamoDBIndexHashKey( globalSecondaryIndexNames = { "GSI-index-hash-primary-range", "GSI-index-hash-index-range-1", "GSI-index-hash-index-range-2" }) public String getIndexHashKey() { return indexHashKey; } public void setIndexHashKey(String indexHashKey) { this.indexHashKey = indexHashKey; } @DynamoDBRangeKey @DynamoDBIndexRangeKey( globalSecondaryIndexNames = {"GSI-index-hash-primary-range"}, localSecondaryIndexName = "LSI-primary-range") public String getPrimaryRangeKey() { return primaryRangeKey; } public void setPrimaryRangeKey(String primaryRangeKey) { this.primaryRangeKey = primaryRangeKey; } @DynamoDBIndexRangeKey( globalSecondaryIndexNames = { "GSI-primary-hash-index-range-1", "GSI-index-hash-index-range-1", "GSI-index-hash-index-range-2" }, localSecondaryIndexNames = {"LSI-index-range-1", "LSI-index-range-2"}) public String getIndexRangeKey() { return indexRangeKey; } public void setIndexRangeKey(String indexRangeKey) { this.indexRangeKey = indexRangeKey; } @DynamoDBIndexRangeKey( localSecondaryIndexName = "LSI-index-range-3", globalSecondaryIndexName = "GSI-primary-hash-index-range-2") public String getAnotherIndexRangeKey() { return anotherIndexRangeKey; } public void setAnotherIndexRangeKey(String anotherIndexRangeKey) { this.anotherIndexRangeKey = anotherIndexRangeKey; } } /** Tests hash + range query */ @Test public void testHashAndRangeCondition() { // Primary hash + primary range QueryRequest queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass("foo", null)) .withRangeKeyCondition("primaryRangeKey", RANGE_KEY_CONDITION)); assertTrue(queryRequest.getKeyConditions().size() == 2); assertTrue(queryRequest.getKeyConditions().containsKey("primaryHashKey")); assertEquals( new Condition() .withAttributeValueList(new AttributeValue("foo")) .withComparisonOperator(ComparisonOperator.EQ), queryRequest.getKeyConditions().get("primaryHashKey")); assertTrue(queryRequest.getKeyConditions().containsKey("primaryRangeKey")); assertEquals(RANGE_KEY_CONDITION, queryRequest.getKeyConditions().get("primaryRangeKey")); assertNull(queryRequest.getIndexName()); // Primary hash + primary range on a LSI queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass("foo", null)) .withRangeKeyCondition("primaryRangeKey", RANGE_KEY_CONDITION) .withIndexName("LSI-primary-range")); assertTrue(queryRequest.getKeyConditions().size() == 2); assertTrue(queryRequest.getKeyConditions().containsKey("primaryHashKey")); assertEquals( new Condition() .withAttributeValueList(new AttributeValue("foo")) .withComparisonOperator(ComparisonOperator.EQ), queryRequest.getKeyConditions().get("primaryHashKey")); assertTrue(queryRequest.getKeyConditions().containsKey("primaryRangeKey")); assertEquals(RANGE_KEY_CONDITION, queryRequest.getKeyConditions().get("primaryRangeKey")); assertEquals("LSI-primary-range", queryRequest.getIndexName()); // Primary hash + index range used by multiple LSI. But also a GSI hash + range queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass("foo", null)) .withRangeKeyCondition("indexRangeKey", RANGE_KEY_CONDITION)); assertTrue(queryRequest.getKeyConditions().size() == 2); assertTrue(queryRequest.getKeyConditions().containsKey("primaryHashKey")); assertEquals( new Condition() .withAttributeValueList(new AttributeValue("foo")) .withComparisonOperator(ComparisonOperator.EQ), queryRequest.getKeyConditions().get("primaryHashKey")); assertTrue(queryRequest.getKeyConditions().containsKey("indexRangeKey")); assertEquals(RANGE_KEY_CONDITION, queryRequest.getKeyConditions().get("indexRangeKey")); assertEquals("GSI-primary-hash-index-range-1", queryRequest.getIndexName()); // Primary hash + index range on a LSI queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass("foo", null)) .withRangeKeyCondition("indexRangeKey", RANGE_KEY_CONDITION) .withIndexName("LSI-index-range-1")); assertTrue(queryRequest.getKeyConditions().size() == 2); assertTrue(queryRequest.getKeyConditions().containsKey("primaryHashKey")); assertEquals( new Condition() .withAttributeValueList(new AttributeValue("foo")) .withComparisonOperator(ComparisonOperator.EQ), queryRequest.getKeyConditions().get("primaryHashKey")); assertTrue(queryRequest.getKeyConditions().containsKey("indexRangeKey")); assertEquals(RANGE_KEY_CONDITION, queryRequest.getKeyConditions().get("indexRangeKey")); assertEquals("LSI-index-range-1", queryRequest.getIndexName()); // Non-existent LSI queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass("foo", null)) .withRangeKeyCondition("indexRangeKey", RANGE_KEY_CONDITION) .withIndexName("some fake lsi"), "No range key condition is applicable to the specified index"); // Illegal query: Primary hash + primary range on a GSI queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass("foo", null)) .withRangeKeyCondition("indexRangeKey", RANGE_KEY_CONDITION) .withIndexName("GSI-index-hash-index-range-1"), "Illegal query expression: No hash key condition is applicable to the specified index"); // GSI hash + GSI range queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass(null, "foo")) .withRangeKeyCondition("primaryRangeKey", RANGE_KEY_CONDITION)); assertTrue(queryRequest.getKeyConditions().size() == 2); assertTrue(queryRequest.getKeyConditions().containsKey("indexHashKey")); assertEquals( new Condition() .withAttributeValueList(new AttributeValue("foo")) .withComparisonOperator(ComparisonOperator.EQ), queryRequest.getKeyConditions().get("indexHashKey")); assertTrue(queryRequest.getKeyConditions().containsKey("primaryRangeKey")); assertEquals(RANGE_KEY_CONDITION, queryRequest.getKeyConditions().get("primaryRangeKey")); assertEquals("GSI-index-hash-primary-range", queryRequest.getIndexName()); // Ambiguous query: GSI hash + index range used by multiple GSIs queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass(null, "foo")) .withRangeKeyCondition("indexRangeKey", RANGE_KEY_CONDITION), "Illegal query expression: Cannot infer the index name from the query expression."); // Explicitly specify the GSI name queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass(null, "foo")) .withRangeKeyCondition("indexRangeKey", RANGE_KEY_CONDITION) .withIndexName("GSI-index-hash-index-range-2")); assertTrue(queryRequest.getKeyConditions().size() == 2); assertTrue(queryRequest.getKeyConditions().containsKey("indexHashKey")); assertEquals( new Condition() .withAttributeValueList(new AttributeValue("foo")) .withComparisonOperator(ComparisonOperator.EQ), queryRequest.getKeyConditions().get("indexHashKey")); assertTrue(queryRequest.getKeyConditions().containsKey("indexRangeKey")); assertEquals(RANGE_KEY_CONDITION, queryRequest.getKeyConditions().get("indexRangeKey")); assertEquals("GSI-index-hash-index-range-2", queryRequest.getIndexName()); // Ambiguous query: (1) primary hash + LSI range OR (2) GSI hash + range queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass("foo", null)) .withRangeKeyCondition("anotherIndexRangeKey", RANGE_KEY_CONDITION), "Ambiguous query expression: Found multiple valid queries:"); // Multiple range key conditions specified queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass("foo", null)) .withRangeKeyConditions( ImmutableMapParameter.of( "primaryRangeKey", RANGE_KEY_CONDITION, "indexRangeKey", RANGE_KEY_CONDITION)), "Illegal query expression: Conditions on multiple range keys"); // Using an un-annotated range key queryRequest = testCreateQueryRequestFromExpression( HashRangeClass.class, new DynamoDBQueryExpression<HashRangeClass>() .withHashKeyValues(new HashRangeClass("foo", null)) .withRangeKeyCondition("indexHashKey", RANGE_KEY_CONDITION), "not annotated with either @DynamoDBRangeKey or @DynamoDBIndexRangeKey."); } @DynamoDBTable(tableName = TABLE_NAME) public final class LSIRangeKeyTestClass { private String primaryHashKey; private String primaryRangeKey; private String lsiRangeKey; public LSIRangeKeyTestClass(String primaryHashKey, String primaryRangeKey) { this.primaryHashKey = primaryHashKey; this.primaryRangeKey = primaryRangeKey; } @DynamoDBHashKey public String getPrimaryHashKey() { return primaryHashKey; } public void setPrimaryHashKey(String primaryHashKey) { this.primaryHashKey = primaryHashKey; } @DynamoDBRangeKey public String getPrimaryRangeKey() { return primaryRangeKey; } public void setPrimaryRangeKey(String primaryRangeKey) { this.primaryRangeKey = primaryRangeKey; } @DynamoDBIndexRangeKey(localSecondaryIndexName = "LSI") public String getLsiRangeKey() { return lsiRangeKey; } public void setLsiRangeKey(String lsiRangeKey) { this.lsiRangeKey = lsiRangeKey; } } @Test public void testHashOnlyQueryOnHashRangeTable() { // Primary hash only query on a Hash+Range table QueryRequest queryRequest = testCreateQueryRequestFromExpression( LSIRangeKeyTestClass.class, new DynamoDBQueryExpression<LSIRangeKeyTestClass>() .withHashKeyValues(new LSIRangeKeyTestClass("foo", null))); assertTrue(queryRequest.getKeyConditions().size() == 1); assertTrue(queryRequest.getKeyConditions().containsKey("primaryHashKey")); assertNull(queryRequest.getIndexName()); // Hash+Range query on a LSI queryRequest = testCreateQueryRequestFromExpression( LSIRangeKeyTestClass.class, new DynamoDBQueryExpression<LSIRangeKeyTestClass>() .withHashKeyValues(new LSIRangeKeyTestClass("foo", null)) .withRangeKeyCondition("lsiRangeKey", RANGE_KEY_CONDITION) .withIndexName("LSI")); assertTrue(queryRequest.getKeyConditions().size() == 2); assertTrue(queryRequest.getKeyConditions().containsKey("primaryHashKey")); assertTrue(queryRequest.getKeyConditions().containsKey("lsiRangeKey")); assertEquals("LSI", queryRequest.getIndexName()); // Hash-only query on a LSI queryRequest = testCreateQueryRequestFromExpression( LSIRangeKeyTestClass.class, new DynamoDBQueryExpression<LSIRangeKeyTestClass>() .withHashKeyValues(new LSIRangeKeyTestClass("foo", null)) .withIndexName("LSI")); assertTrue(queryRequest.getKeyConditions().size() == 1); assertTrue(queryRequest.getKeyConditions().containsKey("primaryHashKey")); assertEquals("LSI", queryRequest.getIndexName()); } private static <T> QueryRequest testCreateQueryRequestFromExpression( Class<T> clazz, DynamoDBQueryExpression<T> queryExpression) { return testCreateQueryRequestFromExpression(clazz, queryExpression, null); } private static <T> QueryRequest testCreateQueryRequestFromExpression( Class<T> clazz, DynamoDBQueryExpression<T> queryExpression, String expectedErrorMessage) { try { QueryRequest request = (QueryRequest) testedMethod.invoke(mapper, clazz, queryExpression, DynamoDBMapperConfig.DEFAULT); if (expectedErrorMessage != null) { fail("Exception containing messsage (" + expectedErrorMessage + ") is expected."); } return request; } catch (InvocationTargetException ite) { if (expectedErrorMessage != null) { assertTrue( "Exception message [" + ite.getCause().getMessage() + "] does not contain " + "the expected message [" + expectedErrorMessage + "].", ite.getCause().getMessage().contains(expectedErrorMessage)); } else { ite.getCause().printStackTrace(); fail("Internal error when calling createQueryRequestFromExpressio method"); } } catch (Exception e) { fail(e.getMessage()); } return null; } }
4,947
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/encryption/CrossSDKVerificationTestClass.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBVersionAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotEncrypt; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Calendar; import java.util.Date; import java.util.Set; /** Exhaustive exercise of DynamoDB domain mapping, exercising every supported data type. */ @DynamoDBTable(tableName = "aws-xsdk-crypto") public class CrossSDKVerificationTestClass { private String key; private String rangeKey; private Long version; private String lastUpdater; private Integer integerAttribute; private Long longAttribute; private Double doubleAttribute; private Float floatAttribute; private BigDecimal bigDecimalAttribute; private BigInteger bigIntegerAttribute; private Byte byteAttribute; private Date dateAttribute; private Calendar calendarAttribute; private Boolean booleanAttribute; private Set<String> stringSetAttribute; private Set<Integer> integerSetAttribute; private Set<Double> doubleSetAttribute; private Set<Float> floatSetAttribute; private Set<BigDecimal> bigDecimalSetAttribute; private Set<BigInteger> bigIntegerSetAttribute; private Set<Long> longSetAttribute; private Set<Byte> byteSetAttribute; private Set<Date> dateSetAttribute; private Set<Calendar> calendarSetAttribute; // these are kind of pointless, but here for completeness private Set<Boolean> booleanSetAttribute; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBRangeKey public String getRangeKey() { return rangeKey; } public void setRangeKey(String rangeKey) { this.rangeKey = rangeKey; } @DoNotEncrypt @DynamoDBVersionAttribute public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } public String getLastUpdater() { return lastUpdater; } public void setLastUpdater(String lastUpdater) { this.lastUpdater = lastUpdater; } public Integer getIntegerAttribute() { return integerAttribute; } public void setIntegerAttribute(Integer integerAttribute) { this.integerAttribute = integerAttribute; } public Long getLongAttribute() { return longAttribute; } public void setLongAttribute(Long longAttribute) { this.longAttribute = longAttribute; } public Double getDoubleAttribute() { return doubleAttribute; } public void setDoubleAttribute(Double doubleAttribute) { this.doubleAttribute = doubleAttribute; } public Float getFloatAttribute() { return floatAttribute; } public void setFloatAttribute(Float floatAttribute) { this.floatAttribute = floatAttribute; } public BigDecimal getBigDecimalAttribute() { return bigDecimalAttribute; } public void setBigDecimalAttribute(BigDecimal bigDecimalAttribute) { this.bigDecimalAttribute = bigDecimalAttribute; } public BigInteger getBigIntegerAttribute() { return bigIntegerAttribute; } public void setBigIntegerAttribute(BigInteger bigIntegerAttribute) { this.bigIntegerAttribute = bigIntegerAttribute; } public Byte getByteAttribute() { return byteAttribute; } public void setByteAttribute(Byte byteAttribute) { this.byteAttribute = byteAttribute; } public Date getDateAttribute() { return dateAttribute; } public void setDateAttribute(Date dateAttribute) { this.dateAttribute = dateAttribute; } public Calendar getCalendarAttribute() { return calendarAttribute; } public void setCalendarAttribute(Calendar calendarAttribute) { this.calendarAttribute = calendarAttribute; } public Boolean getBooleanAttribute() { return booleanAttribute; } public void setBooleanAttribute(Boolean booleanAttribute) { this.booleanAttribute = booleanAttribute; } public Set<Integer> getIntegerSetAttribute() { return integerSetAttribute; } public void setIntegerSetAttribute(Set<Integer> integerSetAttribute) { this.integerSetAttribute = integerSetAttribute; } public Set<Double> getDoubleSetAttribute() { return doubleSetAttribute; } public void setDoubleSetAttribute(Set<Double> doubleSetAttribute) { this.doubleSetAttribute = doubleSetAttribute; } public Set<Float> getFloatSetAttribute() { return floatSetAttribute; } public void setFloatSetAttribute(Set<Float> floatSetAttribute) { this.floatSetAttribute = floatSetAttribute; } public Set<BigDecimal> getBigDecimalSetAttribute() { return bigDecimalSetAttribute; } public void setBigDecimalSetAttribute(Set<BigDecimal> bigDecimalSetAttribute) { this.bigDecimalSetAttribute = bigDecimalSetAttribute; } public Set<BigInteger> getBigIntegerSetAttribute() { return bigIntegerSetAttribute; } public void setBigIntegerSetAttribute(Set<BigInteger> bigIntegerSetAttribute) { this.bigIntegerSetAttribute = bigIntegerSetAttribute; } public Set<Long> getLongSetAttribute() { return longSetAttribute; } public void setLongSetAttribute(Set<Long> longSetAttribute) { this.longSetAttribute = longSetAttribute; } public Set<Byte> getByteSetAttribute() { return byteSetAttribute; } public void setByteSetAttribute(Set<Byte> byteSetAttribute) { this.byteSetAttribute = byteSetAttribute; } public Set<Date> getDateSetAttribute() { return dateSetAttribute; } public void setDateSetAttribute(Set<Date> dateSetAttribute) { this.dateSetAttribute = dateSetAttribute; } public Set<Calendar> getCalendarSetAttribute() { return calendarSetAttribute; } public void setCalendarSetAttribute(Set<Calendar> calendarSetAttribute) { this.calendarSetAttribute = calendarSetAttribute; } public Set<Boolean> getBooleanSetAttribute() { return booleanSetAttribute; } public void setBooleanSetAttribute(Set<Boolean> booleanSetAttribute) { this.booleanSetAttribute = booleanSetAttribute; } public Set<String> getStringSetAttribute() { return stringSetAttribute; } public void setStringSetAttribute(Set<String> stringSetAttribute) { this.stringSetAttribute = stringSetAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((bigDecimalAttribute == null) ? 0 : bigDecimalAttribute.hashCode()); result = prime * result + ((bigDecimalSetAttribute == null) ? 0 : bigDecimalSetAttribute.hashCode()); result = prime * result + ((bigIntegerAttribute == null) ? 0 : bigIntegerAttribute.hashCode()); result = prime * result + ((bigIntegerSetAttribute == null) ? 0 : bigIntegerSetAttribute.hashCode()); result = prime * result + ((booleanAttribute == null) ? 0 : booleanAttribute.hashCode()); result = prime * result + ((booleanSetAttribute == null) ? 0 : booleanSetAttribute.hashCode()); result = prime * result + ((byteAttribute == null) ? 0 : byteAttribute.hashCode()); result = prime * result + ((byteSetAttribute == null) ? 0 : byteSetAttribute.hashCode()); result = prime * result + ((calendarAttribute == null) ? 0 : calendarAttribute.hashCode()); result = prime * result + ((calendarSetAttribute == null) ? 0 : calendarSetAttribute.hashCode()); result = prime * result + ((dateAttribute == null) ? 0 : dateAttribute.hashCode()); result = prime * result + ((dateSetAttribute == null) ? 0 : dateSetAttribute.hashCode()); result = prime * result + ((doubleAttribute == null) ? 0 : doubleAttribute.hashCode()); result = prime * result + ((doubleSetAttribute == null) ? 0 : doubleSetAttribute.hashCode()); result = prime * result + ((floatAttribute == null) ? 0 : floatAttribute.hashCode()); result = prime * result + ((floatSetAttribute == null) ? 0 : floatSetAttribute.hashCode()); result = prime * result + ((integerAttribute == null) ? 0 : integerAttribute.hashCode()); result = prime * result + ((integerSetAttribute == null) ? 0 : integerSetAttribute.hashCode()); result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((lastUpdater == null) ? 0 : lastUpdater.hashCode()); result = prime * result + ((longAttribute == null) ? 0 : longAttribute.hashCode()); result = prime * result + ((longSetAttribute == null) ? 0 : longSetAttribute.hashCode()); result = prime * result + ((rangeKey == null) ? 0 : rangeKey.hashCode()); result = prime * result + ((stringSetAttribute == null) ? 0 : stringSetAttribute.hashCode()); result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CrossSDKVerificationTestClass other = (CrossSDKVerificationTestClass) obj; if (bigDecimalAttribute == null) { if (other.bigDecimalAttribute != null) return false; } else if (!bigDecimalAttribute.equals(other.bigDecimalAttribute)) return false; if (bigDecimalSetAttribute == null) { if (other.bigDecimalSetAttribute != null) return false; } else if (!bigDecimalSetAttribute.equals(other.bigDecimalSetAttribute)) return false; if (bigIntegerAttribute == null) { if (other.bigIntegerAttribute != null) return false; } else if (!bigIntegerAttribute.equals(other.bigIntegerAttribute)) return false; if (bigIntegerSetAttribute == null) { if (other.bigIntegerSetAttribute != null) return false; } else if (!bigIntegerSetAttribute.equals(other.bigIntegerSetAttribute)) return false; if (booleanAttribute == null) { if (other.booleanAttribute != null) return false; } else if (!booleanAttribute.equals(other.booleanAttribute)) return false; if (booleanSetAttribute == null) { if (other.booleanSetAttribute != null) return false; } else if (!booleanSetAttribute.equals(other.booleanSetAttribute)) return false; if (byteAttribute == null) { if (other.byteAttribute != null) return false; } else if (!byteAttribute.equals(other.byteAttribute)) return false; if (byteSetAttribute == null) { if (other.byteSetAttribute != null) return false; } else if (!byteSetAttribute.equals(other.byteSetAttribute)) return false; if (calendarAttribute == null) { if (other.calendarAttribute != null) return false; } else if (!calendarAttribute.equals(other.calendarAttribute)) return false; if (calendarSetAttribute == null) { if (other.calendarSetAttribute != null) return false; } else if (!calendarSetAttribute.equals(other.calendarSetAttribute)) return false; if (dateAttribute == null) { if (other.dateAttribute != null) return false; } else if (!dateAttribute.equals(other.dateAttribute)) return false; if (dateSetAttribute == null) { if (other.dateSetAttribute != null) return false; } else if (!dateSetAttribute.equals(other.dateSetAttribute)) return false; if (doubleAttribute == null) { if (other.doubleAttribute != null) return false; } else if (!doubleAttribute.equals(other.doubleAttribute)) return false; if (doubleSetAttribute == null) { if (other.doubleSetAttribute != null) return false; } else if (!doubleSetAttribute.equals(other.doubleSetAttribute)) return false; if (floatAttribute == null) { if (other.floatAttribute != null) return false; } else if (!floatAttribute.equals(other.floatAttribute)) return false; if (floatSetAttribute == null) { if (other.floatSetAttribute != null) return false; } else if (!floatSetAttribute.equals(other.floatSetAttribute)) return false; if (integerAttribute == null) { if (other.integerAttribute != null) return false; } else if (!integerAttribute.equals(other.integerAttribute)) return false; if (integerSetAttribute == null) { if (other.integerSetAttribute != null) return false; } else if (!integerSetAttribute.equals(other.integerSetAttribute)) return false; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (lastUpdater == null) { if (other.lastUpdater != null) return false; } else if (!lastUpdater.equals(other.lastUpdater)) return false; if (longAttribute == null) { if (other.longAttribute != null) return false; } else if (!longAttribute.equals(other.longAttribute)) return false; if (longSetAttribute == null) { if (other.longSetAttribute != null) return false; } else if (!longSetAttribute.equals(other.longSetAttribute)) return false; if (rangeKey == null) { if (other.rangeKey != null) return false; } else if (!rangeKey.equals(other.rangeKey)) return false; if (stringSetAttribute == null) { if (other.stringSetAttribute != null) return false; } else if (!stringSetAttribute.equals(other.stringSetAttribute)) return false; if (version == null) { if (other.version != null) return false; } else if (!version.equals(other.version)) return false; return true; } }
4,948
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/encryption/StringSetAttributeTestClass.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import java.util.Set; /** Test domain class with a string set attribute and a string key */ @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public class StringSetAttributeTestClass { private String key; private Set<String> stringSetAttribute; private Set<String> StringSetAttributeRenamed; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAttribute public Set<String> getStringSetAttribute() { return stringSetAttribute; } public void setStringSetAttribute(Set<String> stringSetAttribute) { this.stringSetAttribute = stringSetAttribute; } @DynamoDBAttribute(attributeName = "originalName") public Set<String> getStringSetAttributeRenamed() { return StringSetAttributeRenamed; } public void setStringSetAttributeRenamed(Set<String> stringSetAttributeRenamed) { StringSetAttributeRenamed = stringSetAttributeRenamed; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((StringSetAttributeRenamed == null) ? 0 : StringSetAttributeRenamed.hashCode()); result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((stringSetAttribute == null) ? 0 : stringSetAttribute.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; StringSetAttributeTestClass other = (StringSetAttributeTestClass) obj; if (StringSetAttributeRenamed == null) { if (other.StringSetAttributeRenamed != null) return false; } else if (!StringSetAttributeRenamed.equals(other.StringSetAttributeRenamed)) return false; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (stringSetAttribute == null) { if (other.stringSetAttribute != null) return false; } else if (!stringSetAttribute.equals(other.stringSetAttribute)) return false; return true; } }
4,949
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/encryption/NoSuchTableTestClass.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; @DynamoDBTable(tableName = "tableNotExist") public class NoSuchTableTestClass { private String key; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } }
4,950
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/encryption/BinaryAttributeByteArrayTestClass.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import java.util.Set; /** Test domain class with byte[] attribute, byte[] set and a string key */ @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public class BinaryAttributeByteArrayTestClass { private String key; private byte[] binaryAttribute; private Set<byte[]> binarySetAttribute; @DynamoDBHashKey(attributeName = "key") public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAttribute(attributeName = "binaryAttribute") public byte[] getBinaryAttribute() { return binaryAttribute; } public void setBinaryAttribute(byte[] binaryAttribute) { this.binaryAttribute = binaryAttribute; } @DynamoDBAttribute(attributeName = "binarySetAttribute") public Set<byte[]> getBinarySetAttribute() { return binarySetAttribute; } public void setBinarySetAttribute(Set<byte[]> binarySetAttribute) { this.binarySetAttribute = binarySetAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((binaryAttribute == null) ? 0 : binaryAttribute.hashCode()); result = prime * result + ((binarySetAttribute == null) ? 0 : binarySetAttribute.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BinaryAttributeByteArrayTestClass other = (BinaryAttributeByteArrayTestClass) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (binaryAttribute == null) { if (other.binaryAttribute != null) return false; } else if (!binaryAttribute.equals(other.binaryAttribute)) return false; if (binarySetAttribute == null) { if (other.binarySetAttribute != null) return false; } else if (!binarySetAttribute.equals(other.binarySetAttribute)) return false; return true; } }
4,951
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/encryption/IndexRangeKeyTestClass.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.encryption; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBIndexRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBVersionAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotEncrypt; /** Comprehensive domain class */ @DynamoDBTable(tableName = "aws-java-sdk-index-range-test-crypto") public class IndexRangeKeyTestClass { private long key; private double rangeKey; private Double indexFooRangeKey; private Double indexBarRangeKey; private Double multipleIndexRangeKey; private Long version; private String fooAttribute; private String barAttribute; @DynamoDBHashKey public long getKey() { return key; } public void setKey(long key) { this.key = key; } @DynamoDBRangeKey public double getRangeKey() { return rangeKey; } public void setRangeKey(double rangeKey) { this.rangeKey = rangeKey; } @DoNotEncrypt @DynamoDBIndexRangeKey(localSecondaryIndexName = "index_foo", attributeName = "indexFooRangeKey") public Double getIndexFooRangeKeyWithFakeName() { return indexFooRangeKey; } public void setIndexFooRangeKeyWithFakeName(Double indexFooRangeKey) { this.indexFooRangeKey = indexFooRangeKey; } @DoNotEncrypt @DynamoDBIndexRangeKey(localSecondaryIndexName = "index_bar") public Double getIndexBarRangeKey() { return indexBarRangeKey; } public void setIndexBarRangeKey(Double indexBarRangeKey) { this.indexBarRangeKey = indexBarRangeKey; } @DoNotEncrypt @DynamoDBIndexRangeKey(localSecondaryIndexNames = {"index_foo_copy", "index_bar_copy"}) public Double getMultipleIndexRangeKey() { return multipleIndexRangeKey; } public void setMultipleIndexRangeKey(Double multipleIndexRangeKey) { this.multipleIndexRangeKey = multipleIndexRangeKey; } @DynamoDBAttribute public String getFooAttribute() { return fooAttribute; } public void setFooAttribute(String fooAttribute) { this.fooAttribute = fooAttribute; } @DynamoDBAttribute public String getBarAttribute() { return barAttribute; } public void setBarAttribute(String barAttribute) { this.barAttribute = barAttribute; } @DoNotEncrypt @DynamoDBVersionAttribute public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((fooAttribute == null) ? 0 : fooAttribute.hashCode()); result = prime * result + ((barAttribute == null) ? 0 : barAttribute.hashCode()); result = prime * result + (int) (key ^ (key >>> 32)); long temp; temp = Double.doubleToLongBits(rangeKey); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(indexFooRangeKey); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(indexBarRangeKey); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; IndexRangeKeyTestClass other = (IndexRangeKeyTestClass) obj; if (fooAttribute == null) { if (other.fooAttribute != null) return false; } else if (!fooAttribute.equals(other.fooAttribute)) return false; if (barAttribute == null) { if (other.barAttribute != null) return false; } else if (!barAttribute.equals(other.barAttribute)) return false; if (key != other.key) return false; if (Double.doubleToLongBits(rangeKey) != Double.doubleToLongBits(other.rangeKey)) return false; if (Double.doubleToLongBits(indexFooRangeKey) != Double.doubleToLongBits(other.indexFooRangeKey)) return false; if (Double.doubleToLongBits(indexBarRangeKey) != Double.doubleToLongBits(other.indexBarRangeKey)) return false; if (version == null) { if (other.version != null) return false; } else if (!version.equals(other.version)) return false; return true; } @Override public String toString() { return "IndexRangeKeyTestClass [key=" + key + ", rangeKey=" + rangeKey + ", version=" + version + ", indexFooRangeKey=" + indexFooRangeKey + ", indexBarRangeKey=" + indexBarRangeKey + ", fooAttribute=" + fooAttribute + ", barAttribute=" + barAttribute + "]"; } }
4,952
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/MapperSaveConfigITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionFlags; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestEncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import java.security.GeneralSecurityException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; /** * Tests the behavior of save method of DynamoDBMapper under different SaveBehavior configurations. */ public class MapperSaveConfigITCase extends MapperSaveConfigCryptoIntegrationTestBase { @AfterClass public static void teatDown() throws Exception { try { // dynamo.deleteTable(new DeleteTableRequest(tableName)); } catch (Exception e) { } } /********************************************* ** UPDATE (default) ** *********************************************/ /** * Tests that a key-only object could be saved with UPDATE configuration, even when the key has * already existed in the table. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testDefaultWithOnlyKeyAttributesSpecifiedRecordInTable() throws Exception { /* First put a new item (with non-key attribute)*/ TestItem testItem = putRandomUniqueItem("foo", null); /* Put an key-only object with the same key */ testItem.setNonKeyAttribute(null); dynamoMapper.save(testItem, defaultConfig); /* The non-key attribute should be nulled out. */ TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertNull(returnedObject.getNonKeyAttribute()); } /** * Tests an edge case that we have fixed according a forum bug report. If the object is only * specified with key attributes, and such key is not present in the table, we should add this * object by a key-only put request even if it is using UPDATE configuration. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testDefaultWithOnlyKeyAttributesSpecifiedRecordNotInTable() throws Exception { TestItem testItem = new TestItem(); testItem.setHashKey(UUID.randomUUID().toString()); testItem.setRangeKey(System.currentTimeMillis()); dynamoMapper.save(testItem, defaultConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertNull(returnedObject.getNonKeyAttribute()); } /** Update an existing item in the table. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testDefaultWithKeyAndNonKeyAttributesSpecifiedRecordInTable() throws Exception { /* First put a new item (without non-key attribute)*/ TestItem testItem = putRandomUniqueItem(null, null); String hashKeyValue = testItem.getHashKey(); Long rangeKeyValue = testItem.getRangeKey(); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(hashKeyValue, returnedObject.getHashKey()); assertEquals(rangeKeyValue, returnedObject.getRangeKey()); assertNull(returnedObject.getNonKeyAttribute()); /* Put an updated object with the same key and an additional non-key attribute. */ testItem.setHashKey(hashKeyValue); testItem.setRangeKey(rangeKeyValue); testItem.setNonKeyAttribute("update"); dynamoMapper.save(testItem, defaultConfig); returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals(testItem.getNonKeyAttribute(), returnedObject.getNonKeyAttribute()); } /** Use UPDATE to put a new item in the table. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testDefaultWithKeyAndNonKeyAttributesSpecifiedRecordNotInTable() throws Exception { TestItem testItem = new TestItem(); testItem.setHashKey(UUID.randomUUID().toString()); testItem.setRangeKey(System.currentTimeMillis()); testItem.setNonKeyAttribute("new item"); dynamoMapper.save(testItem, defaultConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals(testItem.getNonKeyAttribute(), returnedObject.getNonKeyAttribute()); } /********************************************* ** UPDATE_SKIP_NULL_ATTRIBUTES ** *********************************************/ /** * When using UPDATE_SKIP_NULL_ATTRIBUTES, key-only update on existing item should not affect the * item at all, since all the null-valued non-key attributes are ignored. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testUpdateSkipNullWithOnlyKeyAttributesSpecifiedRecordInTable() throws Exception { /* First put a new item (with non-key attribute)*/ TestItem testItem = putRandomUniqueItem("foo", null); /* Put an key-only object with the same key */ testItem.setNonKeyAttribute(null); dynamoMapper.save(testItem, updateSkipNullConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); /* The non-key attribute should not be removed */ assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals("foo", returnedObject.getNonKeyAttribute()); } /** The behavior should be the same as UPDATE. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testUpdateSkipNullWithOnlyKeyAttributesSpecifiedRecordNotInTable() throws Exception { TestItem testItem = new TestItem(); testItem.setHashKey(UUID.randomUUID().toString()); testItem.setRangeKey(System.currentTimeMillis()); dynamoMapper.save(testItem, updateSkipNullConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertNull(returnedObject.getNonKeyAttribute()); } /** Use UPDATE_SKIP_NULL_ATTRIBUTES to update an existing item in the table. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testUpdateSkipNullWithKeyAndNonKeyAttributesSpecifiedRecordInTable() throws Exception { /* First put a new item (without non-key attribute)*/ TestItem testItem = putRandomUniqueItem(null, null); String hashKeyValue = testItem.getHashKey(); Long rangeKeyValue = testItem.getRangeKey(); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(hashKeyValue, returnedObject.getHashKey()); assertEquals(rangeKeyValue, returnedObject.getRangeKey()); assertNull(returnedObject.getNonKeyAttribute()); /* Put an updated object with the same key and an additional non-key attribute. */ String nonKeyAttributeValue = "update"; testItem.setHashKey(hashKeyValue); testItem.setRangeKey(rangeKeyValue); testItem.setNonKeyAttribute(nonKeyAttributeValue); dynamoMapper.save(testItem, updateSkipNullConfig); returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals(testItem.getNonKeyAttribute(), returnedObject.getNonKeyAttribute()); /* At last, save the object again, but with non-key attribute set as null. * This should not change the existing item. */ testItem.setNonKeyAttribute(null); dynamoMapper.save(testItem, updateSkipNullConfig); returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals(nonKeyAttributeValue, returnedObject.getNonKeyAttribute()); } /** Use UPDATE_SKIP_NULL_ATTRIBUTES to put a new item in the table. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testUpdateSkipNullWithKeyAndNonKeyAttributesSpecifiedRecordNotInTable() throws Exception { TestItem testItem = new TestItem(); testItem.setHashKey(UUID.randomUUID().toString()); testItem.setRangeKey(System.currentTimeMillis()); testItem.setNonKeyAttribute("new item"); dynamoMapper.save(testItem, updateSkipNullConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals(testItem.getNonKeyAttribute(), returnedObject.getNonKeyAttribute()); } /********************************************* ** APPEND_SET ** *********************************************/ /** The behavior should be the same as UPDATE_SKIP_NULL_ATTRIBUTES. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testAppendSetWithOnlyKeyAttributesSpecifiedRecordInTable() throws Exception { /* First put a new item (with non-key attributes)*/ Set<String> randomSet = generateRandomStringSet(3); TestItem testItem = putRandomUniqueItem("foo", randomSet); /* Put an key-only object with the same key */ testItem.setNonKeyAttribute(null); testItem.setStringSetAttribute(null); dynamoMapper.save(testItem, appendSetConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); /* The non-key attribute should not be removed */ assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals("foo", returnedObject.getNonKeyAttribute()); assertTrue(assertSetEquals(randomSet, returnedObject.getStringSetAttribute())); } /** The behavior should be the same as UPDATE and UPDATE_SKIP_NULL_ATTRIBUTES. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testAppendSetWithOnlyKeyAttributesSpecifiedRecordNotInTable() throws Exception { TestItem testItem = new TestItem(); testItem.setHashKey(UUID.randomUUID().toString()); testItem.setRangeKey(System.currentTimeMillis()); dynamoMapper.save(testItem, appendSetConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertNull(returnedObject.getNonKeyAttribute()); assertNull(returnedObject.getStringSetAttribute()); } /** Use APPEND_SET to update an existing item in the table. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testAppendSetWithKeyAndNonKeyAttributesSpecifiedRecordInTable() throws Exception { /* First put a new item (without non-key attribute)*/ TestItem testItem = putRandomUniqueItem(null, null); String hashKeyValue = testItem.getHashKey(); Long rangeKeyValue = testItem.getRangeKey(); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(hashKeyValue, returnedObject.getHashKey()); assertEquals(rangeKeyValue, returnedObject.getRangeKey()); assertNull(returnedObject.getNonKeyAttribute()); assertNull(returnedObject.getStringSetAttribute()); /* Put an updated object with the same key and an additional non-key attribute. */ String nonKeyAttributeValue = "update"; Set<String> stringSetAttributeValue = generateRandomStringSet(3); testItem.setHashKey(hashKeyValue); testItem.setRangeKey(rangeKeyValue); testItem.setNonKeyAttribute(nonKeyAttributeValue); testItem.setStringSetAttribute(stringSetAttributeValue); dynamoMapper.save(testItem, appendSetConfig); returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals(testItem.getNonKeyAttribute(), returnedObject.getNonKeyAttribute()); assertTrue( assertSetEquals(testItem.getStringSetAttribute(), returnedObject.getStringSetAttribute())); /* Override nonKeyAttribute and append stringSetAttribute */ testItem.setNonKeyAttribute("blabla"); Set<String> appendSetAttribute = generateRandomStringSet(3); testItem.setStringSetAttribute(appendSetAttribute); dynamoMapper.save(testItem, appendSetConfig); returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals("blabla", returnedObject.getNonKeyAttribute()); // expected set after the append stringSetAttributeValue.addAll(appendSetAttribute); assertTrue(assertSetEquals(stringSetAttributeValue, returnedObject.getStringSetAttribute())); /* Append on an existing scalar attribute would result in an exception */ TestAppendToScalarItem testAppendToScalarItem = new TestAppendToScalarItem(); testAppendToScalarItem.setHashKey(testItem.getHashKey()); testAppendToScalarItem.setRangeKey(testItem.getRangeKey()); // this fake set attribute actually points to a scalar attribute testAppendToScalarItem.setFakeStringSetAttribute(generateRandomStringSet(1)); try { dynamoMapper.save(testAppendToScalarItem, appendSetConfig); fail("Should have thrown a 'Type mismatch' service exception."); } catch (AmazonServiceException ase) { assertEquals("ValidationException", ase.getErrorCode()); } } /** Use APPEND_SET to put a new item in the table. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testAppendSetWithKeyAndNonKeyAttributesSpecifiedRecordNotInTable() throws Exception { TestItem testItem = new TestItem(); testItem.setHashKey(UUID.randomUUID().toString()); testItem.setRangeKey(System.currentTimeMillis()); testItem.setNonKeyAttribute("new item"); testItem.setStringSetAttribute(generateRandomStringSet(3)); dynamoMapper.save(testItem, appendSetConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals(testItem.getNonKeyAttribute(), returnedObject.getNonKeyAttribute()); assertEquals(testItem.getStringSetAttribute(), returnedObject.getStringSetAttribute()); } /********************************************* ** CLOBBER ** *********************************************/ /** Use CLOBBER to override the existing item by saving a key-only object. */ @Test public void testClobberWithOnlyKeyAttributesSpecifiedRecordInTable() throws Exception { /* Put the item with non-key attribute */ TestItem testItem = putRandomUniqueItem("foo", null); /* Override the item by saving a key-only object. */ testItem.setNonKeyAttribute(null); dynamoMapper.save(testItem, clobberConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertNull(returnedObject.getNonKeyAttribute()); } /** Use CLOBBER to put a new item with only key attributes. */ @Test public void testClobberWithOnlyKeyAttributesSpecifiedRecordNotInTable() throws Exception { TestItem testItem = new TestItem(); testItem.setHashKey(UUID.randomUUID().toString()); testItem.setRangeKey(System.currentTimeMillis()); dynamoMapper.save(testItem, clobberConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertNull(returnedObject.getNonKeyAttribute()); } /** Use CLOBBER to override the existing item. */ @Test public void testClobberWithKeyAndNonKeyAttributesSpecifiedRecordInTable() throws Exception { /* Put the item with non-key attribute */ TestItem testItem = putRandomUniqueItem("foo", null); /* Override the item. */ testItem.setNonKeyAttribute("not foo"); dynamoMapper.save(testItem, clobberConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals(testItem.getNonKeyAttribute(), returnedObject.getNonKeyAttribute()); } /** Use CLOBBER to put a new item. */ @Test public void testClobberWithKeyAndNonKeyAttributesSpecifiedRecordNotInTable() throws Exception { TestItem testItem = new TestItem(); testItem.setHashKey(UUID.randomUUID().toString()); testItem.setRangeKey(System.currentTimeMillis()); testItem.setNonKeyAttribute("new item"); dynamoMapper.save(testItem, clobberConfig); TestItem returnedObject = (TestItem) dynamoMapper.load(testItem); assertNotNull(returnedObject); assertEquals(testItem.getHashKey(), returnedObject.getHashKey()); assertEquals(testItem.getRangeKey(), returnedObject.getRangeKey()); assertEquals(testItem.getNonKeyAttribute(), returnedObject.getNonKeyAttribute()); } private static TestItem putRandomUniqueItem( String nonKeyAttributeValue, Set<String> stringSetAttributeValue) throws GeneralSecurityException { String hashKeyValue = UUID.randomUUID().toString(); Long rangeKeyValue = System.currentTimeMillis(); Map<String, AttributeValue> item = new HashMap<String, AttributeValue>(); item.put(hashKeyName, new AttributeValue().withS(hashKeyValue)); item.put(rangeKeyName, new AttributeValue().withN(rangeKeyValue.toString())); if (null != nonKeyAttributeValue) { item.put(nonKeyAttributeName, new AttributeValue().withS(nonKeyAttributeValue)); } if (null != stringSetAttributeValue) { item.put(stringSetAttributeName, new AttributeValue().withSS(stringSetAttributeValue)); } DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(new TestEncryptionMaterialsProvider()); EncryptionContext context = new EncryptionContext.Builder() .withHashKeyName(hashKeyName) .withRangeKeyName(rangeKeyName) .withTableName(tableName) .build(); Map<String, Set<EncryptionFlags>> flags = encryptor.allEncryptionFlagsExcept(item, hashKeyName, rangeKeyName); // completely exclude the nonKeyAttributeName; otherwise some of the // updateSkipNullConfig test will never work flags.remove(nonKeyAttributeName); flags.remove(stringSetAttributeName); item = encryptor.encryptRecord(item, flags, context); // item = encryptor.encryptAllFieldsExcept(item, context, hashKeyName, rangeKeyName); dynamo.putItem(new PutItemRequest().withTableName(tableName).withItem(item)); /* Returns the item as a modeled object. */ TestItem testItem = new TestItem(); testItem.setHashKey(hashKeyValue); testItem.setRangeKey(rangeKeyValue); testItem.setNonKeyAttribute(nonKeyAttributeValue); testItem.setStringSetAttribute(stringSetAttributeValue); return testItem; } private static Set<String> generateRandomStringSet(int size) { Set<String> result = new HashSet<String>(); for (int i = 0; i < size; i++) { result.add(UUID.randomUUID().toString()); } return result; } private static boolean assertSetEquals(Set<?> expected, Set<?> actual) { if (expected == null || actual == null) { return (expected == null && actual == null); } if (expected.size() != actual.size()) { return false; } for (Object item : expected) { if (!actual.contains(item)) { return false; } } return true; } }
4,953
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/PlaintextItemITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotTouch; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import java.util.HashMap; import java.util.Map; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class PlaintextItemITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static final String STRING_ATTRIBUTE = "stringAttribute"; private static Map<String, AttributeValue> plaintextItem = new HashMap<>(); // Test data static { plaintextItem.put(KEY_NAME, new AttributeValue().withS("" + startKey++)); plaintextItem.put(STRING_ATTRIBUTE, new AttributeValue().withS("" + startKey++)); } @BeforeClass public static void setUp() throws Exception { DynamoDBMapperCryptoIntegrationTestBase.setUp(); // Insert the data dynamo.putItem(new PutItemRequest(TABLE_NAME, plaintextItem)); } @Test public void testLoadWithPlaintextItem() { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); UntouchedTable load = util.load(UntouchedTable.class, plaintextItem.get(KEY_NAME).getS()); assertEquals(load.getKey(), plaintextItem.get(KEY_NAME).getS()); assertEquals(load.getStringAttribute(), plaintextItem.get(STRING_ATTRIBUTE).getS()); } @Test public void testLoadWithPlaintextItemWithModelHavingNewEncryptedAttribute() { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); UntouchedWithNewEncryptedAttributeTable load = util.load( UntouchedWithNewEncryptedAttributeTable.class, plaintextItem.get(KEY_NAME).getS()); assertEquals(load.getKey(), plaintextItem.get(KEY_NAME).getS()); assertEquals(load.getStringAttribute(), plaintextItem.get(STRING_ATTRIBUTE).getS()); assertNull(load.getNewAttribute()); } @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public static class UntouchedTable { private String key; private String stringAttribute; @DynamoDBHashKey @DoNotTouch public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAttribute @DoNotTouch public String getStringAttribute() { return stringAttribute; } public void setStringAttribute(String stringAttribute) { this.stringAttribute = stringAttribute; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UntouchedTable that = (UntouchedTable) o; return key.equals(that.key) && stringAttribute.equals(that.stringAttribute); } } public static final class UntouchedWithNewEncryptedAttributeTable extends UntouchedTable { private String newAttribute; public String getNewAttribute() { return newAttribute; } public void setNewAttribute(String newAttribute) { this.newAttribute = newAttribute; } } }
4,954
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/InheritanceITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import java.util.ArrayList; import java.util.List; import org.testng.annotations.Test; /** Tests inheritance behavior in DynamoDB mapper. */ public class InheritanceITCase extends DynamoDBMapperCryptoIntegrationTestBase { @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public static class BaseClass { protected String key; protected String normalStringAttribute; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAttribute public String getNormalStringAttribute() { return normalStringAttribute; } public void setNormalStringAttribute(String normalStringAttribute) { this.normalStringAttribute = normalStringAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((normalStringAttribute == null) ? 0 : normalStringAttribute.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BaseClass other = (BaseClass) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (normalStringAttribute == null) { if (other.normalStringAttribute != null) return false; } else if (!normalStringAttribute.equals(other.normalStringAttribute)) return false; return true; } } public static class SubClass extends BaseClass { private String subField; public String getSubField() { return subField; } public void setSubField(String subField) { this.subField = subField; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((subField == null) ? 0 : subField.hashCode()); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; SubClass other = (SubClass) obj; if (subField == null) { if (other.subField != null) return false; } else if (!subField.equals(other.subField)) return false; return true; } } public static class SubSubClass extends SubClass { private String subSubField; public String getSubSubField() { return subSubField; } public void setSubSubField(String subSubField) { this.subSubField = subSubField; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((subSubField == null) ? 0 : subSubField.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; SubSubClass other = (SubSubClass) obj; if (subSubField == null) { if (other.subSubField != null) return false; } else if (!subSubField.equals(other.subSubField)) return false; return true; } } @Test public void testSubClass() throws Exception { List<Object> objs = new ArrayList<Object>(); for (int i = 0; i < 5; i++) { SubClass obj = getUniqueObject(new SubClass()); obj.setSubField("" + startKey++); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (Object obj : objs) { util.save(obj); assertEquals(util.load(SubClass.class, ((SubClass) obj).getKey()), obj); } } @Test public void testSubSubClass() throws Exception { List<SubSubClass> objs = new ArrayList<SubSubClass>(); for (int i = 0; i < 5; i++) { SubSubClass obj = getUniqueObject(new SubSubClass()); obj.setSubField("" + startKey++); obj.setSubSubField("" + startKey++); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (SubSubClass obj : objs) { util.save(obj); assertEquals(util.load(SubSubClass.class, obj.getKey()), obj); } } @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public static interface Interface { @DynamoDBHashKey public String getKey(); public void setKey(String key); @DynamoDBAttribute public String getAttribute(); public void setAttribute(String attribute); } public static class Implementation implements Interface { private String key; private String attribute; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getAttribute() { return attribute; } public void setAttribute(String attribute) { this.attribute = attribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((attribute == null) ? 0 : attribute.hashCode()); result = prime * result + ((key == null) ? 0 : key.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Implementation other = (Implementation) obj; if (attribute == null) { if (other.attribute != null) return false; } else if (!attribute.equals(other.attribute)) return false; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; return true; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testImplementation() throws Exception { List<Implementation> objs = new ArrayList<Implementation>(); for (int i = 0; i < 5; i++) { Implementation obj = new Implementation(); obj.setKey("" + startKey++); obj.setAttribute("" + startKey++); objs.add(obj); } // Saving new objects with a null version field should populate it DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (Interface obj : objs) { util.save(obj); assertEquals(util.load(Implementation.class, obj.getKey()), obj); } } private <T extends BaseClass> T getUniqueObject(T obj) { obj.setKey("" + startKey++); obj.setNormalStringAttribute("" + startKey++); return obj; } }
4,955
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/QueryITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.ConsistentReads; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression; import com.amazonaws.services.dynamodbv2.mapper.encryption.RangeKeyTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.ComparisonOperator; import com.amazonaws.services.dynamodbv2.model.Condition; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Random; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Integration tests for the query operation on DynamoDBMapper. */ public class QueryITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static final boolean DEBUG = true; private static final long HASH_KEY = System.currentTimeMillis(); private static RangeKeyTestClass hashKeyObject; private static final int TEST_ITEM_NUMBER = 500; private static DynamoDBMapper mapper; @BeforeClass public static void setUp() throws Exception { setUpTableWithRangeAttribute(); DynamoDBMapperConfig mapperConfig = new DynamoDBMapperConfig(ConsistentReads.CONSISTENT); mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo, mapperConfig); putTestData(mapper, TEST_ITEM_NUMBER); hashKeyObject = new RangeKeyTestClass(); hashKeyObject.setKey(HASH_KEY); } @Test public void testQueryWithPrimaryRangeKey() throws Exception { DynamoDBQueryExpression<RangeKeyTestClass> queryExpression = new DynamoDBQueryExpression<RangeKeyTestClass>() .withHashKeyValues(hashKeyObject) .withRangeKeyCondition( "rangeKey", new Condition() .withComparisonOperator(ComparisonOperator.GT) .withAttributeValueList(new AttributeValue().withN("1.0"))) .withLimit(11); List<RangeKeyTestClass> list = mapper.query(RangeKeyTestClass.class, queryExpression); int count = 0; Iterator<RangeKeyTestClass> iterator = list.iterator(); while (iterator.hasNext()) { count++; RangeKeyTestClass next = iterator.next(); assertTrue(next.getRangeKey() > 1.00); } int numMatchingObjects = TEST_ITEM_NUMBER - 2; if (DEBUG) System.err.println("count=" + count + ", numMatchingObjects=" + numMatchingObjects); assertTrue(count == numMatchingObjects); assertTrue(numMatchingObjects == list.size()); assertNotNull(list.get(list.size() / 2)); assertTrue(list.contains(list.get(list.size() / 2))); assertTrue(numMatchingObjects == list.toArray().length); Thread.sleep(250); int totalCount = mapper.count(RangeKeyTestClass.class, queryExpression); assertTrue(numMatchingObjects == totalCount); /** Tests query with only hash key */ queryExpression = new DynamoDBQueryExpression<RangeKeyTestClass>().withHashKeyValues(hashKeyObject); list = mapper.query(RangeKeyTestClass.class, queryExpression); assertTrue(TEST_ITEM_NUMBER == list.size()); } /** Tests making queries using query filter on non-key attributes. */ @Test public void testQueryFilter() { // A random filter condition to be applied to the query. Random random = new Random(); int randomFilterValue = random.nextInt(TEST_ITEM_NUMBER); Condition filterCondition = new Condition() .withComparisonOperator(ComparisonOperator.LT) .withAttributeValueList( new AttributeValue().withN(Integer.toString(randomFilterValue))); /* * (1) Apply the filter on the range key, in form of key condition */ DynamoDBQueryExpression<RangeKeyTestClass> queryWithRangeKeyCondition = new DynamoDBQueryExpression<RangeKeyTestClass>() .withHashKeyValues(hashKeyObject) .withRangeKeyCondition("rangeKey", filterCondition); List<RangeKeyTestClass> rangeKeyConditionResult = mapper.query(RangeKeyTestClass.class, queryWithRangeKeyCondition); /* * (2) Apply the filter on the bigDecimalAttribute, in form of query * filter */ DynamoDBQueryExpression<RangeKeyTestClass> queryWithQueryFilterCondition = new DynamoDBQueryExpression<RangeKeyTestClass>() .withHashKeyValues(hashKeyObject) .withQueryFilter(Collections.singletonMap("bigDecimalAttribute", filterCondition)); List<RangeKeyTestClass> queryFilterResult = mapper.query(RangeKeyTestClass.class, queryWithQueryFilterCondition); if (DEBUG) { System.err.println( "rangeKeyConditionResult.size()=" + rangeKeyConditionResult.size() + ", queryFilterResult.size()=" + queryFilterResult.size()); } assertTrue(rangeKeyConditionResult.size() == queryFilterResult.size()); for (int i = 0; i < rangeKeyConditionResult.size(); i++) { assertEquals(rangeKeyConditionResult.get(i), queryFilterResult.get(i)); } } /** * Tests that exception should be raised when user provides an index name when making query with * the primary range key. */ @Test public void testUnnecessaryIndexNameException() { try { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); long hashKey = System.currentTimeMillis(); RangeKeyTestClass keyObject = new RangeKeyTestClass(); keyObject.setKey(hashKey); DynamoDBQueryExpression<RangeKeyTestClass> queryExpression = new DynamoDBQueryExpression<RangeKeyTestClass>().withHashKeyValues(keyObject); queryExpression .withRangeKeyCondition( "rangeKey", new Condition() .withComparisonOperator(ComparisonOperator.GT.toString()) .withAttributeValueList(new AttributeValue().withN("1.0"))) .withLimit(11) .withIndexName("some_index"); mapper.query(RangeKeyTestClass.class, queryExpression); fail("User should not provide index name when making query with the primary range key"); } catch (IllegalArgumentException expected) { System.out.println(expected.getMessage()); } catch (Exception e) { fail("Should trigger AmazonClientException."); } } /** * Use BatchSave to put some test data into the tested table. Each item is hash-keyed by the same * value, and range-keyed by numbers starting from 0. */ private static void putTestData(DynamoDBMapper mapper, int itemNumber) { List<RangeKeyTestClass> objs = new ArrayList<RangeKeyTestClass>(); for (int i = 0; i < itemNumber; i++) { RangeKeyTestClass obj = new RangeKeyTestClass(); obj.setKey(HASH_KEY); obj.setRangeKey(i); obj.setBigDecimalAttribute(new BigDecimal(i)); objs.add(obj); } mapper.batchSave(objs); } }
4,956
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/DynamoDBMapperCryptoIntegrationTestBase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import com.amazonaws.services.dynamodbv2.mapper.encryption.BinaryAttributeByteBufferTestClass; import java.nio.ByteBuffer; import java.util.HashSet; import java.util.Set; public class DynamoDBMapperCryptoIntegrationTestBase extends DynamoDBCryptoIntegrationTestBase { public static void setUpMapperTestBase() { DynamoDBCryptoIntegrationTestBase.setUpTestBase(); } /* * Utility methods */ protected static BinaryAttributeByteBufferTestClass getUniqueByteBufferObject(int contentLength) { BinaryAttributeByteBufferTestClass obj = new BinaryAttributeByteBufferTestClass(); obj.setKey(String.valueOf(startKey++)); obj.setBinaryAttribute(ByteBuffer.wrap(generateByteArray(contentLength))); Set<ByteBuffer> byteBufferSet = new HashSet<ByteBuffer>(); byteBufferSet.add(ByteBuffer.wrap(generateByteArray(contentLength))); obj.setBinarySetAttribute(byteBufferSet); return obj; } }
4,957
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/SimpleStringAttributesITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.ConsistentReads; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.SaveBehavior; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.mapper.encryption.StringAttributeTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestEncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Tests simple string attributes */ public class SimpleStringAttributesITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static final String ORIGINAL_NAME_ATTRIBUTE = "originalName"; private static final String STRING_ATTRIBUTE = "stringAttribute"; private static final List<Map<String, AttributeValue>> attrs = new LinkedList<Map<String, AttributeValue>>(); // Test data static { for (int i = 0; i < 5; i++) { Map<String, AttributeValue> attr = new HashMap<String, AttributeValue>(); attr.put(KEY_NAME, new AttributeValue().withS("" + startKey++)); attr.put(STRING_ATTRIBUTE, new AttributeValue().withS("" + startKey++)); attr.put(ORIGINAL_NAME_ATTRIBUTE, new AttributeValue().withS("" + startKey++)); attrs.add(attr); } } ; @BeforeClass public static void setUp() throws Exception { DynamoDBMapperCryptoIntegrationTestBase.setUp(); DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(new TestEncryptionMaterialsProvider()); EncryptionContext context = new EncryptionContext.Builder().withHashKeyName(KEY_NAME).withTableName(TABLE_NAME).build(); // Insert the data for (Map<String, AttributeValue> attr : attrs) { attr = encryptor.encryptAllFieldsExcept(attr, context, KEY_NAME); dynamo.putItem(new PutItemRequest(TABLE_NAME, attr)); } } @Test public void testLoad() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (Map<String, AttributeValue> attr : attrs) { StringAttributeTestClass x = util.load(StringAttributeTestClass.class, attr.get(KEY_NAME).getS()); assertEquals(x.getKey(), attr.get(KEY_NAME).getS()); assertEquals(x.getStringAttribute(), attr.get(STRING_ATTRIBUTE).getS()); assertEquals(x.getRenamedAttribute(), attr.get(ORIGINAL_NAME_ATTRIBUTE).getS()); } } @Test public void testSave() { List<StringAttributeTestClass> objs = new ArrayList<StringAttributeTestClass>(); for (int i = 0; i < 5; i++) { StringAttributeTestClass obj = getUniqueObject(); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (StringAttributeTestClass obj : objs) { util.save(obj); } for (StringAttributeTestClass obj : objs) { StringAttributeTestClass loaded = util.load(StringAttributeTestClass.class, obj.getKey()); assertEquals(obj, loaded); } } /** Tests saving an incomplete object into DynamoDB */ @Test public void testIncompleteObject() { StringAttributeTestClass obj = getUniqueObject(); obj.setStringAttribute(null); DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.save(obj); assertEquals(obj, util.load(StringAttributeTestClass.class, obj.getKey())); // test removing an attribute assertNotNull(obj.getRenamedAttribute()); obj.setRenamedAttribute(null); util.save(obj); assertEquals(obj, util.load(StringAttributeTestClass.class, obj.getKey())); } @Test public void testUpdate() { List<StringAttributeTestClass> objs = new ArrayList<StringAttributeTestClass>(); for (int i = 0; i < 5; i++) { StringAttributeTestClass obj = getUniqueObject(); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (StringAttributeTestClass obj : objs) { util.save(obj); } for (StringAttributeTestClass obj : objs) { StringAttributeTestClass replacement = getUniqueObject(); replacement.setKey(obj.getKey()); util.save(replacement); assertEquals(replacement, util.load(StringAttributeTestClass.class, obj.getKey())); } } @Test public void testSaveOnlyKey() { KeyOnly obj = new KeyOnly(); obj.setKey("" + startKey++); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.save(obj); KeyOnly loaded = mapper.load( KeyOnly.class, obj.getKey(), new DynamoDBMapperConfig(ConsistentReads.CONSISTENT)); assertEquals(obj, loaded); // saving again shouldn't be an error mapper.save(obj); } @Test public void testSaveOnlyKeyClobber() { KeyOnly obj = new KeyOnly(); obj.setKey("" + startKey++); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.save(obj, new DynamoDBMapperConfig(SaveBehavior.CLOBBER)); KeyOnly loaded = mapper.load( KeyOnly.class, obj.getKey(), new DynamoDBMapperConfig(ConsistentReads.CONSISTENT)); assertEquals(obj, loaded); // saving again shouldn't be an error mapper.save(obj, new DynamoDBMapperConfig(SaveBehavior.CLOBBER)); } @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public static final class KeyOnly { private String key; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; KeyOnly other = (KeyOnly) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; return true; } } private StringAttributeTestClass getUniqueObject() { StringAttributeTestClass obj = new StringAttributeTestClass(); obj.setKey(String.valueOf(startKey++)); obj.setRenamedAttribute(String.valueOf(startKey++)); obj.setStringAttribute(String.valueOf(startKey++)); return obj; } }
4,958
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/DynamoDBTestBase.java
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.fail; import static org.testng.AssertJUnit.assertTrue; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded; import java.math.BigDecimal; import java.util.Collection; import java.util.HashSet; import java.util.Set; public class DynamoDBTestBase { protected static AmazonDynamoDB dynamo; public static void setUpTestBase() { dynamo = DynamoDBEmbedded.create().amazonDynamoDB(); } public static AmazonDynamoDB getClient() { if (dynamo == null) { setUpTestBase(); } return dynamo; } protected static <T extends Object> Set<T> toSet(T... array) { Set<T> set = new HashSet<T>(); for (T t : array) { set.add(t); } return set; } protected static <T extends Object> void assertSetsEqual( Collection<T> expected, Collection<T> given) { Set<T> givenCopy = new HashSet<T>(); givenCopy.addAll(given); for (T e : expected) { if (!givenCopy.remove(e)) { fail("Expected element not found: " + e); } } assertTrue("Unexpected elements found: " + givenCopy, givenCopy.isEmpty()); } protected static void assertNumericSetsEquals( Set<? extends Number> expected, Collection<String> given) { Set<BigDecimal> givenCopy = new HashSet<BigDecimal>(); for (String s : given) { BigDecimal bd = new BigDecimal(s); givenCopy.add(bd.setScale(0)); } Set<BigDecimal> expectedCopy = new HashSet<BigDecimal>(); for (Number n : expected) { BigDecimal bd = new BigDecimal(n.toString()); expectedCopy.add(bd.setScale(0)); } assertSetsEqual(expectedCopy, givenCopy); } protected static <T extends Object> Set<T> toSet(Collection<T> collection) { Set<T> set = new HashSet<T>(); for (T t : collection) { set.add(t); } return set; } protected static byte[] generateByteArray(int length) { byte[] bytes = new byte[length]; for (int i = 0; i < length; i++) { bytes[i] = (byte) (i % Byte.MAX_VALUE); } return bytes; } }
4,959
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/IndexRangeKeyAttributesITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.mapper.encryption.IndexRangeKeyTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestEncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.ComparisonOperator; import com.amazonaws.services.dynamodbv2.model.Condition; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.UUID; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Tests that index range keys are properly handled as common attribute when items are loaded, * saved/updated by using primary key. Also tests using index range keys for queries. */ public class IndexRangeKeyAttributesITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static DynamoDBMapper mapper; private static final String RANGE_KEY = "rangeKey"; private static final String INDEX_FOO_RANGE_KEY = "indexFooRangeKey"; private static final String INDEX_BAR_RANGE_KEY = "indexBarRangeKey"; private static final String MULTIPLE_INDEX_RANGE_KEY = "multipleIndexRangeKey"; private static final String FOO_ATTRIBUTE = "fooAttribute"; private static final String BAR_ATTRIBUTE = "barAttribute"; private static final String VERSION_ATTRIBUTE = "version"; // We don't start with the current system millis like other tests because // it's out of the range of some data types private static int start = 1; private static final List<Map<String, AttributeValue>> attrs = new LinkedList<Map<String, AttributeValue>>(); private static final List<Long> hashKeyValues = new LinkedList<Long>(); private static final int totalHash = 5; private static final int rangePerHash = 64; private static final int indexFooRangeStep = 2; private static final int indexBarRangeStep = 4; private static final int multipleIndexRangeStep = 8; // Test data static { for (int i = 0; i < totalHash; i++) { long hashKeyValue = startKey++; hashKeyValues.add(hashKeyValue); for (int j = 0; j < rangePerHash; j++) { Map<String, AttributeValue> attr = new HashMap<String, AttributeValue>(); attr.put(KEY_NAME, new AttributeValue().withN("" + hashKeyValue)); attr.put(RANGE_KEY, new AttributeValue().withN("" + j)); if (j % indexFooRangeStep == 0) attr.put(INDEX_FOO_RANGE_KEY, new AttributeValue().withN("" + j)); if (j % indexBarRangeStep == 0) attr.put(INDEX_BAR_RANGE_KEY, new AttributeValue().withN("" + j)); if (j % multipleIndexRangeStep == 0) attr.put(MULTIPLE_INDEX_RANGE_KEY, new AttributeValue().withN("" + j)); attr.put(FOO_ATTRIBUTE, new AttributeValue().withS(UUID.randomUUID().toString())); attr.put(BAR_ATTRIBUTE, new AttributeValue().withS(UUID.randomUUID().toString())); attr.put(VERSION_ATTRIBUTE, new AttributeValue().withN("1")); attrs.add(attr); } } } ; @BeforeClass public static void setUp() throws Exception { boolean recreateTable = false; setUpTableWithIndexRangeAttribute(recreateTable); DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(new TestEncryptionMaterialsProvider()); EncryptionContext context = new EncryptionContext.Builder() .withHashKeyName(KEY_NAME) .withRangeKeyName(RANGE_KEY) .withTableName(TABLE_WITH_INDEX_RANGE_ATTRIBUTE) .build(); // Insert the data for (Map<String, AttributeValue> attr : attrs) { attr = encryptor.encryptAllFieldsExcept( attr, context, KEY_NAME, RANGE_KEY, INDEX_FOO_RANGE_KEY, INDEX_BAR_RANGE_KEY, MULTIPLE_INDEX_RANGE_KEY, VERSION_ATTRIBUTE); dynamo.putItem(new PutItemRequest(TABLE_WITH_INDEX_RANGE_ATTRIBUTE, attr)); } mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); } /** * Tests that attribute annotated with @DynamoDBIndexRangeKey is properly set in the loaded * object. */ @Test public void testLoad() throws Exception { for (Map<String, AttributeValue> attr : attrs) { IndexRangeKeyTestClass x = mapper.load( newIndexRangeKey( Long.parseLong(attr.get(KEY_NAME).getN()), Double.parseDouble(attr.get(RANGE_KEY).getN()))); // Convert all numbers to the most inclusive type for easy // comparison assertEquals(new BigDecimal(x.getKey()), new BigDecimal(attr.get(KEY_NAME).getN())); assertEquals(new BigDecimal(x.getRangeKey()), new BigDecimal(attr.get(RANGE_KEY).getN())); if (null == attr.get(INDEX_FOO_RANGE_KEY)) assertNull(x.getIndexFooRangeKeyWithFakeName()); else assertEquals( new BigDecimal(x.getIndexFooRangeKeyWithFakeName()), new BigDecimal(attr.get(INDEX_FOO_RANGE_KEY).getN())); if (null == attr.get(INDEX_BAR_RANGE_KEY)) assertNull(x.getIndexBarRangeKey()); else assertEquals( new BigDecimal(x.getIndexBarRangeKey()), new BigDecimal(attr.get(INDEX_BAR_RANGE_KEY).getN())); assertEquals( new BigDecimal(x.getVersion()), new BigDecimal(attr.get(VERSION_ATTRIBUTE).getN())); assertEquals(x.getFooAttribute(), attr.get(FOO_ATTRIBUTE).getS()); assertEquals(x.getBarAttribute(), attr.get(BAR_ATTRIBUTE).getS()); } } private IndexRangeKeyTestClass newIndexRangeKey(long hashKey, double rangeKey) { IndexRangeKeyTestClass obj = new IndexRangeKeyTestClass(); obj.setKey(hashKey); obj.setRangeKey(rangeKey); return obj; } /** Tests that attribute annotated with @DynamoDBIndexRangeKey is properly saved. */ @Test public void testSave() throws Exception { List<IndexRangeKeyTestClass> objs = new ArrayList<IndexRangeKeyTestClass>(); for (int i = 0; i < 5; i++) { IndexRangeKeyTestClass obj = getUniqueObject(); objs.add(obj); } for (IndexRangeKeyTestClass obj : objs) { mapper.save(obj); } for (IndexRangeKeyTestClass obj : objs) { IndexRangeKeyTestClass loaded = mapper.load(IndexRangeKeyTestClass.class, obj.getKey(), obj.getRangeKey()); assertEquals(obj, loaded); } } /** Tests that version attribute is still working as expected. */ @Test public void testUpdate() throws Exception { List<IndexRangeKeyTestClass> objs = new ArrayList<IndexRangeKeyTestClass>(); for (int i = 0; i < 5; i++) { IndexRangeKeyTestClass obj = getUniqueObject(); objs.add(obj); } for (IndexRangeKeyTestClass obj : objs) { mapper.save(obj); } for (IndexRangeKeyTestClass obj : objs) { IndexRangeKeyTestClass replacement = getUniqueObject(); replacement.setKey(obj.getKey()); replacement.setRangeKey(obj.getRangeKey()); replacement.setVersion(obj.getVersion()); mapper.save(replacement); IndexRangeKeyTestClass loadedObject = mapper.load(IndexRangeKeyTestClass.class, obj.getKey(), obj.getRangeKey()); assertEquals(replacement, loadedObject); // If we try to update the old version, we should get an error replacement.setVersion(replacement.getVersion() - 1); try { mapper.save(replacement); fail("Should have thrown an exception"); } catch (Exception expected) { } } } /** Tests making queries on local secondary index */ @Test public void testQueryWithIndexRangekey() { int indexFooRangePerHash = rangePerHash / indexFooRangeStep; int indexBarRangePerHash = rangePerHash / indexBarRangeStep; for (long hashKeyValue : hashKeyValues) { IndexRangeKeyTestClass hashKeyItem = new IndexRangeKeyTestClass(); hashKeyItem.setKey(hashKeyValue); /** Query items by primary range key */ List<IndexRangeKeyTestClass> result = mapper.query( IndexRangeKeyTestClass.class, new DynamoDBQueryExpression<IndexRangeKeyTestClass>() .withHashKeyValues(hashKeyItem) .withRangeKeyCondition( RANGE_KEY, new Condition() .withAttributeValueList(new AttributeValue().withN("0")) .withComparisonOperator(ComparisonOperator.GE.toString()))); assertTrue(rangePerHash == result.size()); // check that all attributes are retrieved for (IndexRangeKeyTestClass itemInFooIndex : result) { assertNotNull(itemInFooIndex.getFooAttribute()); assertNotNull(itemInFooIndex.getBarAttribute()); } /** Query items on index_foo */ result = mapper.query( IndexRangeKeyTestClass.class, new DynamoDBQueryExpression<IndexRangeKeyTestClass>() .withHashKeyValues(hashKeyItem) .withRangeKeyCondition( INDEX_FOO_RANGE_KEY, new Condition() .withAttributeValueList(new AttributeValue().withN("0")) .withComparisonOperator(ComparisonOperator.GE.toString()))); assertTrue(indexFooRangePerHash == result.size()); // check that only the projected attributes are retrieved for (IndexRangeKeyTestClass itemInFooIndex : result) { assertNotNull(itemInFooIndex.getFooAttribute()); assertNotNull(itemInFooIndex.getBarAttribute()); } /** Query items on index_bar */ result = mapper.query( IndexRangeKeyTestClass.class, new DynamoDBQueryExpression<IndexRangeKeyTestClass>() .withHashKeyValues(hashKeyItem) .withRangeKeyCondition( INDEX_BAR_RANGE_KEY, new Condition() .withAttributeValueList(new AttributeValue().withN("0")) .withComparisonOperator(ComparisonOperator.GE.toString()))); assertTrue(indexBarRangePerHash == result.size()); // check that only the projected attributes are retrieved for (IndexRangeKeyTestClass itemInBarIndex : result) { assertNotNull(itemInBarIndex.getFooAttribute()); assertNotNull(itemInBarIndex.getBarAttribute()); } } } /** Tests the exception when user specifies an invalid range key name in the query. */ @Test public void testInvalidRangeKeyNameException() { IndexRangeKeyTestClass hashKeyItem = new IndexRangeKeyTestClass(); hashKeyItem.setKey(0); try { mapper.query( IndexRangeKeyTestClass.class, new DynamoDBQueryExpression<IndexRangeKeyTestClass>() .withHashKeyValues(hashKeyItem) .withRangeKeyCondition( "some_range_key", new Condition() .withAttributeValueList(new AttributeValue().withN("0")) .withComparisonOperator(ComparisonOperator.GE.toString()))); fail("some_range_key is not a valid range key name."); } catch (DynamoDBMappingException e) { System.out.println(e.getMessage()); } catch (Exception e) { fail("Should trigger an DynamoDBMappingException."); } } /** Tests the exception when user specifies an invalid index name in the query. */ @Test public void testInvalidIndexNameException() { IndexRangeKeyTestClass hashKeyItem = new IndexRangeKeyTestClass(); hashKeyItem.setKey(0); try { mapper.query( IndexRangeKeyTestClass.class, new DynamoDBQueryExpression<IndexRangeKeyTestClass>() .withHashKeyValues(hashKeyItem) .withRangeKeyCondition( INDEX_BAR_RANGE_KEY, new Condition() .withAttributeValueList(new AttributeValue().withN("0")) .withComparisonOperator(ComparisonOperator.GE.toString())) .withIndexName("some_index")); fail("some_index is not a valid index name."); } catch (IllegalArgumentException iae) { System.out.println(iae.getMessage()); } catch (Exception e) { fail("Should trigger an IllegalArgumentException."); } } /** Tests making queries by using range key that is shared by multiple indexes. */ @Test public void testQueryWithRangeKeyForMultipleIndexes() { int multipleIndexRangePerHash = rangePerHash / multipleIndexRangeStep; for (long hashKeyValue : hashKeyValues) { IndexRangeKeyTestClass hashKeyItem = new IndexRangeKeyTestClass(); hashKeyItem.setKey(hashKeyValue); /** Query items by a range key that is shared by multiple indexes */ List<IndexRangeKeyTestClass> result = mapper.query( IndexRangeKeyTestClass.class, new DynamoDBQueryExpression<IndexRangeKeyTestClass>() .withHashKeyValues(hashKeyItem) .withRangeKeyCondition( MULTIPLE_INDEX_RANGE_KEY, new Condition() .withAttributeValueList(new AttributeValue().withN("0")) .withComparisonOperator(ComparisonOperator.GE.toString())) .withIndexName("index_foo_copy")); assertTrue(multipleIndexRangePerHash == result.size()); // check that only the projected attributes are retrieved for (IndexRangeKeyTestClass itemInFooIndex : result) { assertNotNull(itemInFooIndex.getFooAttribute()); assertNotNull(itemInFooIndex.getBarAttribute()); } result = mapper.query( IndexRangeKeyTestClass.class, new DynamoDBQueryExpression<IndexRangeKeyTestClass>() .withHashKeyValues(hashKeyItem) .withRangeKeyCondition( MULTIPLE_INDEX_RANGE_KEY, new Condition() .withAttributeValueList(new AttributeValue().withN("0")) .withComparisonOperator(ComparisonOperator.GE.toString())) .withIndexName("index_bar_copy")); assertTrue(multipleIndexRangePerHash == result.size()); // check that only the projected attributes are retrieved for (IndexRangeKeyTestClass itemInFooIndex : result) { assertNotNull(itemInFooIndex.getFooAttribute()); assertNotNull(itemInFooIndex.getBarAttribute()); } /** Exception when user doesn't specify which index to use */ try { mapper.query( IndexRangeKeyTestClass.class, new DynamoDBQueryExpression<IndexRangeKeyTestClass>() .withHashKeyValues(hashKeyItem) .withRangeKeyCondition( MULTIPLE_INDEX_RANGE_KEY, new Condition() .withAttributeValueList(new AttributeValue().withN("0")) .withComparisonOperator(ComparisonOperator.GE.toString()))); fail("No index name is specified when query with a range key shared by multiple indexes"); } catch (IllegalArgumentException iae) { System.out.println(iae.getMessage()); } catch (Exception e) { fail("Should trigger an IllegalArgumentException."); } /** Exception when user uses an invalid index name */ try { mapper.query( IndexRangeKeyTestClass.class, new DynamoDBQueryExpression<IndexRangeKeyTestClass>() .withHashKeyValues(hashKeyItem) .withRangeKeyCondition( MULTIPLE_INDEX_RANGE_KEY, new Condition() .withAttributeValueList(new AttributeValue().withN("0")) .withComparisonOperator(ComparisonOperator.GE.toString())) .withIndexName("index_foo")); fail( "index_foo is not annotated as part of the localSecondaryIndexNames in " + "the @DynamoDBIndexRangeKey annotation of multipleIndexRangeKey"); } catch (IllegalArgumentException iae) { System.out.println(iae.getMessage()); } catch (Exception e) { fail("Should trigger an IllegalArgumentException."); } } } private IndexRangeKeyTestClass getUniqueObject() { IndexRangeKeyTestClass obj = new IndexRangeKeyTestClass(); obj.setKey(startKey++); obj.setRangeKey((double) start++); obj.setIndexFooRangeKeyWithFakeName((double) start++); obj.setIndexBarRangeKey((double) start++); obj.setFooAttribute("" + startKey++); obj.setBarAttribute("" + startKey++); return obj; } }
4,960
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/MapperLoadingStrategyConfigITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.ConsistentReads; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.PaginationLoadingStrategy; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBScanExpression; import com.amazonaws.services.dynamodbv2.datamodeling.PaginatedList; import com.amazonaws.services.dynamodbv2.mapper.encryption.RangeKeyTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.ComparisonOperator; import com.amazonaws.services.dynamodbv2.model.Condition; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Integration tests for PaginationLoadingStrategy configuration */ public class MapperLoadingStrategyConfigITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static long hashKey = System.currentTimeMillis(); private static int PAGE_SIZE = 5; private static int PARALLEL_SEGMENT = 3; private static int OBJECTS_NUM = 50; private static int RESULTS_NUM = OBJECTS_NUM - 2; // condition: rangeKey > 1.0 @BeforeClass public static void setUp() throws Exception { setUpTableWithRangeAttribute(); createTestData(); } @Test public void testLazyLoading() { // Get all the paginated lists using the tested loading strategy PaginatedList<RangeKeyTestClass> queryList = getTestPaginatedQueryList(PaginationLoadingStrategy.LAZY_LOADING); PaginatedList<RangeKeyTestClass> scanList = getTestPaginatedScanList(PaginationLoadingStrategy.LAZY_LOADING); PaginatedList<RangeKeyTestClass> parallelScanList = getTestPaginatedParallelScanList(PaginationLoadingStrategy.LAZY_LOADING); // check that only at most one page of results are loaded up to this point assertTrue(getLoadedResultsNumber(queryList) <= PAGE_SIZE); assertTrue(getLoadedResultsNumber(scanList) <= PAGE_SIZE); assertTrue(getLoadedResultsNumber(parallelScanList) <= PAGE_SIZE * PARALLEL_SEGMENT); testAllPaginatedListOperations(queryList); testAllPaginatedListOperations(scanList); testAllPaginatedListOperations(parallelScanList); // Re-construct the paginated lists and test the iterator behavior queryList = getTestPaginatedQueryList(PaginationLoadingStrategy.LAZY_LOADING); scanList = getTestPaginatedScanList(PaginationLoadingStrategy.LAZY_LOADING); parallelScanList = getTestPaginatedParallelScanList(PaginationLoadingStrategy.LAZY_LOADING); testPaginatedListIterator(queryList); testPaginatedListIterator(scanList); testPaginatedListIterator(parallelScanList); } @Test public void testEagerLoading() { // Get all the paginated lists using the tested loading strategy PaginatedList<RangeKeyTestClass> queryList = getTestPaginatedQueryList(PaginationLoadingStrategy.EAGER_LOADING); PaginatedList<RangeKeyTestClass> scanList = getTestPaginatedScanList(PaginationLoadingStrategy.EAGER_LOADING); PaginatedList<RangeKeyTestClass> parallelScanList = getTestPaginatedParallelScanList(PaginationLoadingStrategy.EAGER_LOADING); // check that all results have been loaded assertTrue(RESULTS_NUM == getLoadedResultsNumber(queryList)); assertTrue(RESULTS_NUM == getLoadedResultsNumber(scanList)); assertTrue(RESULTS_NUM == getLoadedResultsNumber(parallelScanList)); testAllPaginatedListOperations(queryList); testAllPaginatedListOperations(scanList); testAllPaginatedListOperations(parallelScanList); // Re-construct the paginated lists and test the iterator behavior queryList = getTestPaginatedQueryList(PaginationLoadingStrategy.LAZY_LOADING); scanList = getTestPaginatedScanList(PaginationLoadingStrategy.LAZY_LOADING); parallelScanList = getTestPaginatedParallelScanList(PaginationLoadingStrategy.LAZY_LOADING); testPaginatedListIterator(queryList); testPaginatedListIterator(scanList); testPaginatedListIterator(parallelScanList); } @Test public void testIterationOnly() { // Get all the paginated lists using the tested loading strategy PaginatedList<RangeKeyTestClass> queryList = getTestPaginatedQueryList(PaginationLoadingStrategy.ITERATION_ONLY); PaginatedList<RangeKeyTestClass> scanList = getTestPaginatedScanList(PaginationLoadingStrategy.ITERATION_ONLY); PaginatedList<RangeKeyTestClass> parallelScanList = getTestPaginatedParallelScanList(PaginationLoadingStrategy.ITERATION_ONLY); // check that only at most one page of results are loaded up to this point assertTrue(getLoadedResultsNumber(queryList) <= PAGE_SIZE); assertTrue(getLoadedResultsNumber(scanList) <= PAGE_SIZE); assertTrue(getLoadedResultsNumber(parallelScanList) <= PAGE_SIZE * PARALLEL_SEGMENT); testIterationOnlyPaginatedListOperations(queryList); testIterationOnlyPaginatedListOperations(scanList); testIterationOnlyPaginatedListOperations(parallelScanList); } private static void createTestData() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); List<RangeKeyTestClass> objs = new ArrayList<RangeKeyTestClass>(); for (int i = 0; i < OBJECTS_NUM; i++) { RangeKeyTestClass obj = new RangeKeyTestClass(); obj.setKey(hashKey); obj.setRangeKey(i); objs.add(obj); } mapper.batchSave(objs); } private static PaginatedList<RangeKeyTestClass> getTestPaginatedQueryList( PaginationLoadingStrategy paginationLoadingStrategy) { DynamoDBMapperConfig mapperConfig = new DynamoDBMapperConfig(ConsistentReads.CONSISTENT); DynamoDBMapper mapper = new DynamoDBMapper(dynamo, mapperConfig); // Construct the query expression for the tested hash-key value and any range-key value greater // that 1.0 RangeKeyTestClass keyObject = new RangeKeyTestClass(); keyObject.setKey(hashKey); DynamoDBQueryExpression<RangeKeyTestClass> queryExpression = new DynamoDBQueryExpression<RangeKeyTestClass>().withHashKeyValues(keyObject); queryExpression .withRangeKeyCondition( "rangeKey", new Condition() .withComparisonOperator(ComparisonOperator.GT.toString()) .withAttributeValueList(new AttributeValue().withN("1.0"))) .withLimit(PAGE_SIZE); return mapper.query( RangeKeyTestClass.class, queryExpression, new DynamoDBMapperConfig(paginationLoadingStrategy)); } private static PaginatedList<RangeKeyTestClass> getTestPaginatedScanList( PaginationLoadingStrategy paginationLoadingStrategy) { DynamoDBMapperConfig mapperConfig = new DynamoDBMapperConfig(ConsistentReads.CONSISTENT); DynamoDBMapper mapper = new DynamoDBMapper(dynamo, mapperConfig); // Construct the scan expression with the exact same conditions DynamoDBScanExpression scanExpression = new DynamoDBScanExpression(); scanExpression.addFilterCondition( "key", new Condition() .withComparisonOperator(ComparisonOperator.EQ) .withAttributeValueList(new AttributeValue().withN(Long.toString(hashKey)))); scanExpression.addFilterCondition( "rangeKey", new Condition() .withComparisonOperator(ComparisonOperator.GT) .withAttributeValueList(new AttributeValue().withN("1.0"))); scanExpression.setLimit(PAGE_SIZE); return mapper.scan( RangeKeyTestClass.class, scanExpression, new DynamoDBMapperConfig(paginationLoadingStrategy)); } private static PaginatedList<RangeKeyTestClass> getTestPaginatedParallelScanList( PaginationLoadingStrategy paginationLoadingStrategy) { DynamoDBMapperConfig mapperConfig = new DynamoDBMapperConfig(ConsistentReads.CONSISTENT); DynamoDBMapper mapper = new DynamoDBMapper(dynamo, mapperConfig); // Construct the scan expression with the exact same conditions DynamoDBScanExpression scanExpression = new DynamoDBScanExpression(); scanExpression.addFilterCondition( "key", new Condition() .withComparisonOperator(ComparisonOperator.EQ) .withAttributeValueList(new AttributeValue().withN(Long.toString(hashKey)))); scanExpression.addFilterCondition( "rangeKey", new Condition() .withComparisonOperator(ComparisonOperator.GT) .withAttributeValueList(new AttributeValue().withN("1.0"))); scanExpression.setLimit(PAGE_SIZE); return mapper.parallelScan( RangeKeyTestClass.class, scanExpression, PARALLEL_SEGMENT, new DynamoDBMapperConfig(paginationLoadingStrategy)); } private static void testAllPaginatedListOperations(PaginatedList<RangeKeyTestClass> list) { // (1) isEmpty() assertFalse(list.isEmpty()); // (2) get(int n) assertNotNull(list.get(RESULTS_NUM / 2)); // (3) contains(Object org0) RangeKeyTestClass obj = new RangeKeyTestClass(); obj.setKey(hashKey); obj.setRangeKey(0); assertFalse(list.contains(obj)); obj.setRangeKey(2); assertTrue(list.contains(obj)); // (4) subList(int org0, int arg1) List<RangeKeyTestClass> subList = list.subList(0, RESULTS_NUM); assertTrue(RESULTS_NUM == subList.size()); try { list.subList(0, RESULTS_NUM + 1); fail("IndexOutOfBoundsException is IndexOutOfBoundsException but not thrown"); } catch (IndexOutOfBoundsException e) { } // (5) indexOf(Object org0) assertTrue(list.indexOf(obj) < RESULTS_NUM); // (6) loadAllResults() list.loadAllResults(); // (7) size() assertTrue(RESULTS_NUM == list.size()); } private static void testPaginatedListIterator(PaginatedList<RangeKeyTestClass> list) { for (RangeKeyTestClass item : list) { assertTrue(hashKey == item.getKey()); assertTrue(item.getRangeKey() < OBJECTS_NUM); } // make sure the list could be iterated again for (RangeKeyTestClass item : list) { assertTrue(hashKey == item.getKey()); assertTrue(item.getRangeKey() < OBJECTS_NUM); } } private static void testIterationOnlyPaginatedListOperations( PaginatedList<RangeKeyTestClass> list) { // Unsupported operations // (1) isEmpty() try { list.isEmpty(); fail("UnsupportedOperationException expected but is not thrown"); } catch (UnsupportedOperationException e) { } // (2) get(int n) try { list.get(RESULTS_NUM / 2); fail("UnsupportedOperationException expected but is not thrown"); } catch (UnsupportedOperationException e) { } // (3) contains(Object org0) try { list.contains(new RangeKeyTestClass()); fail("UnsupportedOperationException expected but is not thrown"); } catch (UnsupportedOperationException e) { } // (4) subList(int org0, int arg1) try { list.subList(0, RESULTS_NUM); fail("UnsupportedOperationException expected but is not thrown"); } catch (UnsupportedOperationException e) { } // (5) indexOf(Object org0) try { list.indexOf(new RangeKeyTestClass()); fail("UnsupportedOperationException expected but is not thrown"); } catch (UnsupportedOperationException e) { } // (6) loadAllResults() try { list.loadAllResults(); fail("UnsupportedOperationException expected but is not thrown"); } catch (UnsupportedOperationException e) { } // (7) size() try { list.size(); fail("UnsupportedOperationException expected but is not thrown"); } catch (UnsupportedOperationException e) { } ; // Could be iterated once for (RangeKeyTestClass item : list) { assertTrue(hashKey == item.getKey()); assertTrue(item.getRangeKey() < OBJECTS_NUM); // At most one page of results in memeory assertTrue(getLoadedResultsNumber(list) <= PAGE_SIZE); } // not twice try { for (@SuppressWarnings("unused") RangeKeyTestClass item : list) { fail("UnsupportedOperationException expected but is not thrown"); } } catch (UnsupportedOperationException e) { } } /** Use reflection to get the size of the private allResults field * */ @SuppressWarnings("unchecked") private static int getLoadedResultsNumber(PaginatedList<RangeKeyTestClass> list) { Field privateAllResults = null; try { privateAllResults = list.getClass().getSuperclass().getDeclaredField("allResults"); } catch (SecurityException e) { fail(e.getMessage()); } catch (NoSuchFieldException e) { fail(e.getMessage()); } privateAllResults.setAccessible(true); List<RangeKeyTestClass> allResults = null; try { allResults = (List<RangeKeyTestClass>) privateAllResults.get(list); } catch (IllegalArgumentException e) { fail(e.getMessage()); } catch (IllegalAccessException e) { fail(e.getMessage()); } return allResults.size(); } }
4,961
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/RangeKeyAttributesITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.fail; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.mapper.encryption.RangeKeyTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestEncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Tests range and hash key combination */ public class RangeKeyAttributesITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static final String RANGE_KEY = "rangeKey"; private static final String INTEGER_ATTRIBUTE = "integerSetAttribute"; private static final String BIG_DECIMAL_ATTRIBUTE = "bigDecimalAttribute"; private static final String STRING_SET_ATTRIBUTE = "stringSetAttribute"; private static final String STRING_ATTRIBUTE = "stringAttribute"; private static final String VERSION_ATTRIBUTE = "version"; // We don't start with the current system millis like other tests because // it's out of the range of some data types private static int start = 1; private static final List<Map<String, AttributeValue>> attrs = new LinkedList<Map<String, AttributeValue>>(); // Test data static { for (int i = 0; i < 5; i++) { Map<String, AttributeValue> attr = new HashMap<String, AttributeValue>(); attr.put(KEY_NAME, new AttributeValue().withN("" + startKey++)); attr.put(RANGE_KEY, new AttributeValue().withN("" + start++)); attr.put( INTEGER_ATTRIBUTE, new AttributeValue().withNS("" + start++, "" + start++, "" + start++)); attr.put(BIG_DECIMAL_ATTRIBUTE, new AttributeValue().withN("" + start++)); attr.put(STRING_ATTRIBUTE, new AttributeValue().withS("" + start++)); attr.put( STRING_SET_ATTRIBUTE, new AttributeValue().withSS("" + start++, "" + start++, "" + start++)); attr.put(VERSION_ATTRIBUTE, new AttributeValue().withN("1")); attrs.add(attr); } } ; @BeforeClass public static void setUp() throws Exception { setUpTableWithRangeAttribute(); DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(new TestEncryptionMaterialsProvider()); EncryptionContext context = new EncryptionContext.Builder() .withHashKeyName(KEY_NAME) .withRangeKeyName(RANGE_KEY) .withTableName(TABLE_WITH_RANGE_ATTRIBUTE) .build(); // Insert the data for (Map<String, AttributeValue> attr : attrs) { attr = encryptor.encryptAllFieldsExcept( attr, context, KEY_NAME, RANGE_KEY, VERSION_ATTRIBUTE, BIG_DECIMAL_ATTRIBUTE); dynamo.putItem(new PutItemRequest(TABLE_WITH_RANGE_ATTRIBUTE, attr)); } } @Test public void testLoad() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (Map<String, AttributeValue> attr : attrs) { RangeKeyTestClass x = util.load( newRangeKey( Long.parseLong(attr.get(KEY_NAME).getN()), Double.parseDouble(attr.get(RANGE_KEY).getN()))); // Convert all numbers to the most inclusive type for easy // comparison assertEquals(new BigDecimal(x.getKey()), new BigDecimal(attr.get(KEY_NAME).getN())); assertEquals(new BigDecimal(x.getRangeKey()), new BigDecimal(attr.get(RANGE_KEY).getN())); assertEquals( new BigDecimal(x.getVersion()), new BigDecimal(attr.get(VERSION_ATTRIBUTE).getN())); assertEquals( x.getBigDecimalAttribute(), new BigDecimal(attr.get(BIG_DECIMAL_ATTRIBUTE).getN())); assertNumericSetsEquals(x.getIntegerAttribute(), attr.get(INTEGER_ATTRIBUTE).getNS()); assertEquals(x.getStringAttribute(), attr.get(STRING_ATTRIBUTE).getS()); assertSetsEqual(x.getStringSetAttribute(), toSet(attr.get(STRING_SET_ATTRIBUTE).getSS())); } } private RangeKeyTestClass newRangeKey(long hashKey, double rangeKey) { RangeKeyTestClass obj = new RangeKeyTestClass(); obj.setKey(hashKey); obj.setRangeKey(rangeKey); return obj; } @Test public void testSave() throws Exception { List<RangeKeyTestClass> objs = new ArrayList<RangeKeyTestClass>(); for (int i = 0; i < 5; i++) { RangeKeyTestClass obj = getUniqueObject(); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (RangeKeyTestClass obj : objs) { util.save(obj); } for (RangeKeyTestClass obj : objs) { RangeKeyTestClass loaded = util.load(RangeKeyTestClass.class, obj.getKey(), obj.getRangeKey()); assertEquals(obj, loaded); } } @Test public void testUpdate() throws Exception { List<RangeKeyTestClass> objs = new ArrayList<RangeKeyTestClass>(); for (int i = 0; i < 5; i++) { RangeKeyTestClass obj = getUniqueObject(); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (RangeKeyTestClass obj : objs) { util.save(obj); } for (RangeKeyTestClass obj : objs) { RangeKeyTestClass replacement = getUniqueObject(); replacement.setKey(obj.getKey()); replacement.setRangeKey(obj.getRangeKey()); replacement.setVersion(obj.getVersion()); util.save(replacement); RangeKeyTestClass loadedObject = util.load(RangeKeyTestClass.class, obj.getKey(), obj.getRangeKey()); assertEquals(replacement, loadedObject); // If we try to update the old version, we should get an error replacement.setVersion(replacement.getVersion() - 1); try { util.save(replacement); fail("Should have thrown an exception"); } catch (Exception expected) { } } } private RangeKeyTestClass getUniqueObject() { RangeKeyTestClass obj = new RangeKeyTestClass(); obj.setKey(startKey++); obj.setIntegerAttribute(toSet(start++, start++, start++)); obj.setBigDecimalAttribute(new BigDecimal(startKey++)); obj.setRangeKey(start++); obj.setStringAttribute("" + startKey++); obj.setStringSetAttribute(toSet("" + startKey++, "" + startKey++, "" + startKey++)); return obj; } }
4,962
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/HashKeyOnlyTableWithGSIITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBIndexHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBIndexRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.PaginatedQueryList; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotEncrypt; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.ComparisonOperator; import com.amazonaws.services.dynamodbv2.model.Condition; import com.amazonaws.services.dynamodbv2.model.CreateTableRequest; import com.amazonaws.services.dynamodbv2.model.GlobalSecondaryIndex; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.Projection; import com.amazonaws.services.dynamodbv2.model.ProjectionType; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType; import com.amazonaws.services.dynamodbv2.util.TableUtils; import java.util.ArrayList; import java.util.List; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Integration test for GSI support with a table that has no primary range key (only a primary hash * key). */ public class HashKeyOnlyTableWithGSIITCase extends DynamoDBMapperCryptoIntegrationTestBase { public static final String HASH_KEY_ONLY_TABLE_NAME = "no-primary-range-key-gsi-test-crypto"; @BeforeClass public static void setUp() throws Exception { DynamoDBTestBase.setUpTestBase(); List<KeySchemaElement> keySchema = new ArrayList<KeySchemaElement>(); keySchema.add(new KeySchemaElement("id", KeyType.HASH)); CreateTableRequest req = new CreateTableRequest(HASH_KEY_ONLY_TABLE_NAME, keySchema) .withProvisionedThroughput(new ProvisionedThroughput(10L, 10L)) .withAttributeDefinitions( new AttributeDefinition("id", ScalarAttributeType.S), new AttributeDefinition("status", ScalarAttributeType.S), new AttributeDefinition("ts", ScalarAttributeType.S)) .withGlobalSecondaryIndexes( new GlobalSecondaryIndex() .withProvisionedThroughput(new ProvisionedThroughput(10L, 10L)) .withIndexName("statusAndCreation") .withKeySchema( new KeySchemaElement("status", KeyType.HASH), new KeySchemaElement("ts", KeyType.RANGE)) .withProjection(new Projection().withProjectionType(ProjectionType.ALL))); TableUtils.createTableIfNotExists(dynamo, req); TableUtils.waitUntilActive(dynamo, HASH_KEY_ONLY_TABLE_NAME); } @AfterClass public static void tearDown() throws Exception { dynamo.deleteTable(HASH_KEY_ONLY_TABLE_NAME); } @DynamoDBTable(tableName = HASH_KEY_ONLY_TABLE_NAME) public static class User { private String id; private String status; private String ts; @DynamoDBHashKey public String getId() { return id; } public void setId(String id) { this.id = id; } @DoNotEncrypt @DynamoDBIndexHashKey(globalSecondaryIndexName = "statusAndCreation") public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @DoNotEncrypt @DynamoDBIndexRangeKey(globalSecondaryIndexName = "statusAndCreation") public String getTs() { return ts; } public void setTs(String ts) { this.ts = ts; } } /** Tests that we can query using the hash/range GSI on our hash-key only table. */ @Test public void testGSIQuery() throws Exception { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); String status = "foo-status"; User user = new User(); user.setId("123"); user.setStatus(status); user.setTs("321"); mapper.save(user); DynamoDBQueryExpression<User> expr = new DynamoDBQueryExpression<User>() .withIndexName("statusAndCreation") .withLimit(100) .withConsistentRead(false) .withHashKeyValues(user) .withRangeKeyCondition( "ts", new Condition() .withComparisonOperator(ComparisonOperator.GT) .withAttributeValueList(new AttributeValue("100"))); PaginatedQueryList<User> query = mapper.query(User.class, expr); int size = query.size(); if (DEBUG) System.err.println("size=" + size); assertTrue(1 == size); assertEquals(status, query.get(0).getStatus()); } private static final boolean DEBUG = false; }
4,963
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/SimpleNumericAttributesITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.mapper.encryption.NumberAttributeTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestEncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.GetItemRequest; import com.amazonaws.services.dynamodbv2.model.GetItemResult; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Tests numeric attributes */ public class SimpleNumericAttributesITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static final String INT_ATTRIBUTE = "intAttribute"; private static final String INTEGER_ATTRIBUTE = "integerAttribute"; private static final String FLOAT_ATTRIBUTE = "floatAttribute"; private static final String FLOAT_OBJECT_ATTRIBUTE = "floatObjectAttribute"; private static final String DOUBLE_ATTRIBUTE = "doubleAttribute"; private static final String DOUBLE_OBJECT_ATTRIBUTE = "doubleObjectAttribute"; private static final String BIG_INTEGER_ATTRIBUTE = "bigIntegerAttribute"; private static final String BIG_DECIMAL_ATTRIBUTE = "bigDecimalAttribute"; private static final String LONG_ATTRIBUTE = "longAttribute"; private static final String LONG_OBJECT_ATTRIBUTE = "longObjectAttribute"; private static final String BYTE_ATTRIBUTE = "byteAttribute"; private static final String BYTE_OBJECT_ATTRIBUTE = "byteObjectAttribute"; private static final String BOOLEAN_ATTRIBUTE = "booleanAttribute"; private static final String BOOLEAN_OBJECT_ATTRIBUTE = "booleanObjectAttribute"; private static final String SHORT_ATTRIBUTE = "shortAttribute"; private static final String SHORT_OBJECT_ATTRIBUTE = "shortObjectAttribute"; // We don't start with the current system millis like other tests because // it's out of the range of some data types private static int start = 1; private static int byteStart = -127; private static final List<Map<String, AttributeValue>> attrs = new LinkedList<Map<String, AttributeValue>>(); // Test data static { for (int i = 0; i < 5; i++) { Map<String, AttributeValue> attr = new HashMap<String, AttributeValue>(); attr.put(KEY_NAME, new AttributeValue().withS("" + start++)); attr.put(INT_ATTRIBUTE, new AttributeValue().withN("" + start++)); attr.put(INTEGER_ATTRIBUTE, new AttributeValue().withN("" + start++)); attr.put(FLOAT_ATTRIBUTE, new AttributeValue().withN("" + start++)); attr.put(FLOAT_OBJECT_ATTRIBUTE, new AttributeValue().withN("" + start++)); attr.put(DOUBLE_ATTRIBUTE, new AttributeValue().withN("" + start++)); attr.put(DOUBLE_OBJECT_ATTRIBUTE, new AttributeValue().withN("" + start++)); attr.put(BIG_INTEGER_ATTRIBUTE, new AttributeValue().withN("" + start++)); attr.put(BIG_DECIMAL_ATTRIBUTE, new AttributeValue().withN("" + start++)); attr.put(LONG_ATTRIBUTE, new AttributeValue().withN("" + start++)); attr.put(LONG_OBJECT_ATTRIBUTE, new AttributeValue().withN("" + start++)); attr.put(BYTE_ATTRIBUTE, new AttributeValue().withN("" + byteStart++)); attr.put(BYTE_OBJECT_ATTRIBUTE, new AttributeValue().withN("" + byteStart++)); attr.put(BOOLEAN_ATTRIBUTE, new AttributeValue().withN(start++ % 2 == 0 ? "1" : "0")); attr.put(BOOLEAN_OBJECT_ATTRIBUTE, new AttributeValue().withN(start++ % 2 == 0 ? "1" : "0")); attr.put(SHORT_ATTRIBUTE, new AttributeValue().withN("" + byteStart++)); attr.put(SHORT_OBJECT_ATTRIBUTE, new AttributeValue().withN("" + byteStart++)); attrs.add(attr); } } ; @BeforeClass public static void setUp() throws Exception { DynamoDBMapperCryptoIntegrationTestBase.setUp(); DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(new TestEncryptionMaterialsProvider()); EncryptionContext context = new EncryptionContext.Builder().withHashKeyName(KEY_NAME).withTableName(TABLE_NAME).build(); // Insert the data for (Map<String, AttributeValue> attr : attrs) { attr = encryptor.encryptAllFieldsExcept(attr, context, KEY_NAME); dynamo.putItem(new PutItemRequest(TABLE_NAME, attr)); } } private NumberAttributeTestClass getKeyObject(String key) { NumberAttributeTestClass obj = new NumberAttributeTestClass(); obj.setKey(key); return obj; } @Test public void testLoad() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (Map<String, AttributeValue> attr : attrs) { NumberAttributeTestClass x = util.load(getKeyObject(attr.get(KEY_NAME).getS())); assertEquals(x.getKey(), attr.get(KEY_NAME).getS()); // Convert all numbers to the most inclusive type for easy comparison assertEquals( x.getBigDecimalAttribute(), new BigDecimal(attr.get(BIG_DECIMAL_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getBigIntegerAttribute()), new BigDecimal(attr.get(BIG_INTEGER_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getFloatAttribute()), new BigDecimal(attr.get(FLOAT_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getFloatObjectAttribute()), new BigDecimal(attr.get(FLOAT_OBJECT_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getDoubleAttribute()), new BigDecimal(attr.get(DOUBLE_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getDoubleObjectAttribute()), new BigDecimal(attr.get(DOUBLE_OBJECT_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getIntAttribute()), new BigDecimal(attr.get(INT_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getIntegerAttribute()), new BigDecimal(attr.get(INTEGER_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getLongAttribute()), new BigDecimal(attr.get(LONG_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getLongObjectAttribute()), new BigDecimal(attr.get(LONG_OBJECT_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getByteAttribute()), new BigDecimal(attr.get(BYTE_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getByteObjectAttribute()), new BigDecimal(attr.get(BYTE_OBJECT_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getShortAttribute()), new BigDecimal(attr.get(SHORT_ATTRIBUTE).getN())); assertEquals( new BigDecimal(x.getShortObjectAttribute()), new BigDecimal(attr.get(SHORT_OBJECT_ATTRIBUTE).getN())); assertEquals(x.isBooleanAttribute(), attr.get(BOOLEAN_ATTRIBUTE).getN().equals("1")); assertEquals( (Object) x.getBooleanObjectAttribute(), (Object) attr.get(BOOLEAN_OBJECT_ATTRIBUTE).getN().equals("1")); } // Test loading an object that doesn't exist assertNull(util.load(getKeyObject("does not exist"))); } @Test public void testSave() throws Exception { List<NumberAttributeTestClass> objs = new ArrayList<NumberAttributeTestClass>(); for (int i = 0; i < 5; i++) { NumberAttributeTestClass obj = getUniqueObject(); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (NumberAttributeTestClass obj : objs) { util.save(obj); } for (NumberAttributeTestClass obj : objs) { NumberAttributeTestClass loaded = util.load(obj); loaded.setIgnored(obj.getIgnored()); assertEquals(obj, loaded); } } @Test public void testUpdate() throws Exception { List<NumberAttributeTestClass> objs = new ArrayList<NumberAttributeTestClass>(); for (int i = 0; i < 5; i++) { NumberAttributeTestClass obj = getUniqueObject(); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (NumberAttributeTestClass obj : objs) { util.save(obj); } for (NumberAttributeTestClass obj : objs) { NumberAttributeTestClass replacement = getUniqueObject(); replacement.setKey(obj.getKey()); util.save(replacement); NumberAttributeTestClass loadedObject = util.load(obj); assertFalse(replacement.getIgnored().equals(loadedObject.getIgnored())); loadedObject.setIgnored(replacement.getIgnored()); assertEquals(replacement, loadedObject); } } /** Tests automatically setting a hash key upon saving. */ @Test public void testSetHashKey() throws Exception { List<NumberAttributeTestClass> objs = new ArrayList<NumberAttributeTestClass>(); for (int i = 0; i < 5; i++) { NumberAttributeTestClass obj = getUniqueObject(); obj.setKey(null); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (NumberAttributeTestClass obj : objs) { assertNull(obj.getKey()); util.save(obj); assertNotNull(obj.getKey()); NumberAttributeTestClass loadedObject = util.load(obj); assertFalse(obj.getIgnored().equals(loadedObject.getIgnored())); loadedObject.setIgnored(obj.getIgnored()); assertEquals(obj, loadedObject); } } @Test public void testDelete() throws Exception { NumberAttributeTestClass obj = getUniqueObject(); DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.save(obj); NumberAttributeTestClass loaded = util.load(NumberAttributeTestClass.class, obj.getKey()); loaded.setIgnored(obj.getIgnored()); assertEquals(obj, loaded); util.delete(obj); assertNull(util.load(NumberAttributeTestClass.class, obj.getKey())); } @Test public void performanceTest() throws Exception { NumberAttributeTestClass obj = getUniqueObject(); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.save(obj); HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>(); key.put(KEY_NAME, new AttributeValue().withS(obj.getKey())); GetItemResult item = dynamo.getItem(new GetItemRequest().withTableName("aws-java-sdk-util-crypto").withKey(key)); long start = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { mapper.marshallIntoObject(NumberAttributeTestClass.class, item.getItem()); } long end = System.currentTimeMillis(); System.err.println("time: " + (end - start)); } private NumberAttributeTestClass getUniqueObject() { NumberAttributeTestClass obj = new NumberAttributeTestClass(); obj.setKey(String.valueOf(startKey++)); obj.setBigDecimalAttribute(new BigDecimal(startKey++)); obj.setBigIntegerAttribute(new BigInteger("" + startKey++)); obj.setByteAttribute((byte) byteStart++); obj.setByteObjectAttribute(new Byte("" + byteStart++)); obj.setDoubleAttribute(new Double("" + start++)); obj.setDoubleObjectAttribute(new Double("" + start++)); obj.setFloatAttribute(new Float("" + start++)); obj.setFloatObjectAttribute(new Float("" + start++)); obj.setIntAttribute(new Integer("" + start++)); obj.setIntegerAttribute(new Integer("" + start++)); obj.setLongAttribute(new Long("" + start++)); obj.setLongObjectAttribute(new Long("" + start++)); obj.setShortAttribute(new Short("" + start++)); obj.setShortObjectAttribute(new Short("" + start++)); obj.setDateAttribute(new Date(startKey++)); obj.setBooleanAttribute(start++ % 2 == 0); obj.setBooleanObjectAttribute(start++ % 2 == 0); obj.setIgnored("" + start++); Calendar cal = GregorianCalendar.getInstance(); cal.setTime(new Date(startKey++)); obj.setCalendarAttribute(cal); return obj; } }
4,964
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/NumericSetAttributesITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.mapper.encryption.NumberSetAttributeTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestEncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Tests string set attributes */ public class NumericSetAttributesITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static final String INTEGER_ATTRIBUTE = "integerAttribute"; private static final String FLOAT_OBJECT_ATTRIBUTE = "floatObjectAttribute"; private static final String DOUBLE_OBJECT_ATTRIBUTE = "doubleObjectAttribute"; private static final String BIG_INTEGER_ATTRIBUTE = "bigIntegerAttribute"; private static final String BIG_DECIMAL_ATTRIBUTE = "bigDecimalAttribute"; private static final String LONG_OBJECT_ATTRIBUTE = "longObjectAttribute"; private static final String BYTE_OBJECT_ATTRIBUTE = "byteObjectAttribute"; private static final String BOOLEAN_ATTRIBUTE = "booleanAttribute"; // We don't start with the current system millis like other tests because // it's out of the range of some data types private static int start = 1; private static int byteStart = 1; private static final List<Map<String, AttributeValue>> attrs = new LinkedList<Map<String, AttributeValue>>(); // Test data static { for (int i = 0; i < 5; i++) { Map<String, AttributeValue> attr = new HashMap<String, AttributeValue>(); attr.put(KEY_NAME, new AttributeValue().withS("" + start++)); attr.put( INTEGER_ATTRIBUTE, new AttributeValue().withNS("" + start++, "" + start++, "" + start++)); attr.put( FLOAT_OBJECT_ATTRIBUTE, new AttributeValue().withNS("" + start++, "" + start++, "" + start++)); attr.put( DOUBLE_OBJECT_ATTRIBUTE, new AttributeValue().withNS("" + start++, "" + start++, "" + start++)); attr.put( BIG_INTEGER_ATTRIBUTE, new AttributeValue().withNS("" + start++, "" + start++, "" + start++)); attr.put( BIG_DECIMAL_ATTRIBUTE, new AttributeValue().withNS("" + start++, "" + start++, "" + start++)); attr.put( LONG_OBJECT_ATTRIBUTE, new AttributeValue().withNS("" + start++, "" + start++, "" + start++)); attr.put( BYTE_OBJECT_ATTRIBUTE, new AttributeValue().withNS("" + byteStart++, "" + byteStart++, "" + byteStart++)); attr.put(BOOLEAN_ATTRIBUTE, new AttributeValue().withNS("0", "1")); attrs.add(attr); } } ; @BeforeClass public static void setUp() throws Exception { DynamoDBMapperCryptoIntegrationTestBase.setUp(); DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(new TestEncryptionMaterialsProvider()); EncryptionContext context = new EncryptionContext.Builder().withHashKeyName(KEY_NAME).withTableName(TABLE_NAME).build(); // Insert the data for (Map<String, AttributeValue> attr : attrs) { attr = encryptor.encryptAllFieldsExcept(attr, context, KEY_NAME); dynamo.putItem(new PutItemRequest(TABLE_NAME, attr)); } } @Test public void testLoad() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (Map<String, AttributeValue> attr : attrs) { NumberSetAttributeTestClass x = util.load(NumberSetAttributeTestClass.class, attr.get(KEY_NAME).getS()); assertEquals(x.getKey(), attr.get(KEY_NAME).getS()); // Convert all numbers to the most inclusive type for easy comparison assertNumericSetsEquals(x.getBigDecimalAttribute(), attr.get(BIG_DECIMAL_ATTRIBUTE).getNS()); assertNumericSetsEquals(x.getBigIntegerAttribute(), attr.get(BIG_INTEGER_ATTRIBUTE).getNS()); assertNumericSetsEquals( x.getFloatObjectAttribute(), attr.get(FLOAT_OBJECT_ATTRIBUTE).getNS()); assertNumericSetsEquals( x.getDoubleObjectAttribute(), attr.get(DOUBLE_OBJECT_ATTRIBUTE).getNS()); assertNumericSetsEquals(x.getIntegerAttribute(), attr.get(INTEGER_ATTRIBUTE).getNS()); assertNumericSetsEquals(x.getLongObjectAttribute(), attr.get(LONG_OBJECT_ATTRIBUTE).getNS()); assertNumericSetsEquals(x.getByteObjectAttribute(), attr.get(BYTE_OBJECT_ATTRIBUTE).getNS()); assertSetsEqual(toSet("0", "1"), attr.get(BOOLEAN_ATTRIBUTE).getNS()); } } @Test public void testSave() throws Exception { List<NumberSetAttributeTestClass> objs = new ArrayList<NumberSetAttributeTestClass>(); for (int i = 0; i < 5; i++) { NumberSetAttributeTestClass obj = getUniqueObject(); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (NumberSetAttributeTestClass obj : objs) { util.save(obj); } for (NumberSetAttributeTestClass obj : objs) { NumberSetAttributeTestClass loaded = util.load(NumberSetAttributeTestClass.class, obj.getKey()); assertEquals(obj, loaded); } } @Test public void testUpdate() throws Exception { List<NumberSetAttributeTestClass> objs = new ArrayList<NumberSetAttributeTestClass>(); for (int i = 0; i < 5; i++) { NumberSetAttributeTestClass obj = getUniqueObject(); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (NumberSetAttributeTestClass obj : objs) { util.save(obj); } for (NumberSetAttributeTestClass obj : objs) { NumberSetAttributeTestClass replacement = getUniqueObject(); replacement.setKey(obj.getKey()); util.save(replacement); assertEquals(replacement, util.load(NumberSetAttributeTestClass.class, obj.getKey())); } } private NumberSetAttributeTestClass getUniqueObject() { NumberSetAttributeTestClass obj = new NumberSetAttributeTestClass(); obj.setKey(String.valueOf(startKey++)); obj.setBigDecimalAttribute( toSet(new BigDecimal(startKey++), new BigDecimal(startKey++), new BigDecimal(startKey++))); obj.setBigIntegerAttribute( toSet( new BigInteger("" + startKey++), new BigInteger("" + startKey++), new BigInteger("" + startKey++))); obj.setByteObjectAttribute( toSet(new Byte("" + byteStart++), new Byte("" + byteStart++), new Byte("" + byteStart++))); obj.setDoubleObjectAttribute( toSet(new Double("" + start++), new Double("" + start++), new Double("" + start++))); obj.setFloatObjectAttribute( toSet(new Float("" + start++), new Float("" + start++), new Float("" + start++))); obj.setIntegerAttribute( toSet(new Integer("" + start++), new Integer("" + start++), new Integer("" + start++))); obj.setLongObjectAttribute( toSet(new Long("" + start++), new Long("" + start++), new Long("" + start++))); obj.setBooleanAttribute(toSet(true, false)); obj.setDateAttribute(toSet(new Date(startKey++), new Date(startKey++), new Date(startKey++))); Set<Calendar> cals = new HashSet<Calendar>(); for (Date d : obj.getDateAttribute()) { Calendar cal = GregorianCalendar.getInstance(); cal.setTime(d); cals.add(cal); } obj.setCalendarAttribute(toSet(cals)); return obj; } }
4,965
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/BinaryAttributesITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.mapper.encryption.BinaryAttributeByteArrayTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.BinaryAttributeByteBufferTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestEncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Tests simple string attributes */ public class BinaryAttributesITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static final String BINARY_ATTRIBUTE = "binaryAttribute"; private static final String BINARY_SET_ATTRIBUTE = "binarySetAttribute"; private static final List<Map<String, AttributeValue>> attrs = new LinkedList<Map<String, AttributeValue>>(); private static final int contentLength = 512; // Test data static { Map<String, AttributeValue> attr = new HashMap<String, AttributeValue>(); attr.put(KEY_NAME, new AttributeValue().withS("" + startKey++)); attr.put( BINARY_ATTRIBUTE, new AttributeValue().withB(ByteBuffer.wrap(generateByteArray(contentLength)))); attr.put( BINARY_SET_ATTRIBUTE, new AttributeValue() .withBS( ByteBuffer.wrap(generateByteArray(contentLength)), ByteBuffer.wrap(generateByteArray(contentLength + 1)))); attrs.add(attr); } ; @BeforeClass public static void setUp() throws Exception { DynamoDBMapperCryptoIntegrationTestBase.setUp(); DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(new TestEncryptionMaterialsProvider()); EncryptionContext context = new EncryptionContext.Builder().withHashKeyName(KEY_NAME).withTableName(TABLE_NAME).build(); // Insert the data for (Map<String, AttributeValue> attr : attrs) { attr = encryptor.encryptAllFieldsExcept(attr, context, KEY_NAME); dynamo.putItem(new PutItemRequest(TABLE_NAME, attr)); } } @Test public void testLoad() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (Map<String, AttributeValue> attr : attrs) { // test BinaryAttributeClass BinaryAttributeByteBufferTestClass x = util.load(BinaryAttributeByteBufferTestClass.class, attr.get(KEY_NAME).getS()); assertEquals(x.getKey(), attr.get(KEY_NAME).getS()); assertEquals(x.getBinaryAttribute(), ByteBuffer.wrap(generateByteArray(contentLength))); assertTrue( x.getBinarySetAttribute().contains(ByteBuffer.wrap(generateByteArray(contentLength)))); assertTrue( x.getBinarySetAttribute() .contains(ByteBuffer.wrap(generateByteArray(contentLength + 1)))); // test BinaryAttributeByteArrayTestClass BinaryAttributeByteArrayTestClass y = util.load(BinaryAttributeByteArrayTestClass.class, attr.get(KEY_NAME).getS()); assertEquals(y.getKey(), attr.get(KEY_NAME).getS()); assertTrue(Arrays.equals(y.getBinaryAttribute(), (generateByteArray(contentLength)))); assertTrue(2 == y.getBinarySetAttribute().size()); assertTrue(setContainsBytes(y.getBinarySetAttribute(), generateByteArray(contentLength))); assertTrue(setContainsBytes(y.getBinarySetAttribute(), generateByteArray(contentLength + 1))); } } @Test public void testSave() { // test BinaryAttributeClass List<BinaryAttributeByteBufferTestClass> byteBufferObjs = new ArrayList<BinaryAttributeByteBufferTestClass>(); for (int i = 0; i < 5; i++) { BinaryAttributeByteBufferTestClass obj = getUniqueByteBufferObject(contentLength); byteBufferObjs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (BinaryAttributeByteBufferTestClass obj : byteBufferObjs) { util.save(obj); } for (BinaryAttributeByteBufferTestClass obj : byteBufferObjs) { BinaryAttributeByteBufferTestClass loaded = util.load(BinaryAttributeByteBufferTestClass.class, obj.getKey()); assertEquals(loaded.getKey(), obj.getKey()); assertEquals(loaded.getBinaryAttribute(), ByteBuffer.wrap(generateByteArray(contentLength))); assertTrue( loaded .getBinarySetAttribute() .contains(ByteBuffer.wrap(generateByteArray(contentLength)))); } // test BinaryAttributeByteArrayTestClass List<BinaryAttributeByteArrayTestClass> bytesObjs = new ArrayList<BinaryAttributeByteArrayTestClass>(); for (int i = 0; i < 5; i++) { BinaryAttributeByteArrayTestClass obj = getUniqueBytesObject(contentLength); bytesObjs.add(obj); } for (BinaryAttributeByteArrayTestClass obj : bytesObjs) { util.save(obj); } for (BinaryAttributeByteArrayTestClass obj : bytesObjs) { BinaryAttributeByteArrayTestClass loaded = util.load(BinaryAttributeByteArrayTestClass.class, obj.getKey()); assertEquals(loaded.getKey(), obj.getKey()); assertTrue(Arrays.equals(loaded.getBinaryAttribute(), (generateByteArray(contentLength)))); assertTrue(1 == loaded.getBinarySetAttribute().size()); assertTrue( setContainsBytes(loaded.getBinarySetAttribute(), generateByteArray(contentLength))); } } /** Tests saving an incomplete object into DynamoDB */ @Test public void testIncompleteObject() { // test BinaryAttributeClass BinaryAttributeByteBufferTestClass byteBufferObj = getUniqueByteBufferObject(contentLength); byteBufferObj.setBinarySetAttribute(null); DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.save(byteBufferObj); BinaryAttributeByteBufferTestClass loadedX = util.load(BinaryAttributeByteBufferTestClass.class, byteBufferObj.getKey()); assertEquals(loadedX.getKey(), byteBufferObj.getKey()); assertEquals(loadedX.getBinaryAttribute(), ByteBuffer.wrap(generateByteArray(contentLength))); assertEquals(loadedX.getBinarySetAttribute(), null); // test removing an attribute assertNotNull(byteBufferObj.getBinaryAttribute()); byteBufferObj.setBinaryAttribute(null); util.save(byteBufferObj); loadedX = util.load(BinaryAttributeByteBufferTestClass.class, byteBufferObj.getKey()); assertEquals(loadedX.getKey(), byteBufferObj.getKey()); assertEquals(loadedX.getBinaryAttribute(), null); assertEquals(loadedX.getBinarySetAttribute(), null); // test BinaryAttributeByteArrayTestClass BinaryAttributeByteArrayTestClass bytesObj = getUniqueBytesObject(contentLength); bytesObj.setBinarySetAttribute(null); util.save(bytesObj); BinaryAttributeByteArrayTestClass loadedY = util.load(BinaryAttributeByteArrayTestClass.class, bytesObj.getKey()); assertEquals(loadedY.getKey(), bytesObj.getKey()); assertTrue(Arrays.equals(loadedY.getBinaryAttribute(), generateByteArray(contentLength))); assertEquals(loadedY.getBinarySetAttribute(), null); // test removing an attribute assertNotNull(bytesObj.getBinaryAttribute()); bytesObj.setBinaryAttribute(null); util.save(bytesObj); loadedY = util.load(BinaryAttributeByteArrayTestClass.class, bytesObj.getKey()); assertEquals(loadedY.getKey(), bytesObj.getKey()); assertEquals(loadedY.getBinaryAttribute(), null); assertEquals(loadedY.getBinarySetAttribute(), null); } @Test public void testUpdate() { // test BinaryAttributeClass List<BinaryAttributeByteBufferTestClass> byteBufferObjs = new ArrayList<BinaryAttributeByteBufferTestClass>(); for (int i = 0; i < 5; i++) { BinaryAttributeByteBufferTestClass obj = getUniqueByteBufferObject(contentLength); byteBufferObjs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (BinaryAttributeByteBufferTestClass obj : byteBufferObjs) { util.save(obj); } for (BinaryAttributeByteBufferTestClass obj : byteBufferObjs) { BinaryAttributeByteBufferTestClass replacement = getUniqueByteBufferObject(contentLength - 1); replacement.setKey(obj.getKey()); util.save(replacement); BinaryAttributeByteBufferTestClass loaded = util.load(BinaryAttributeByteBufferTestClass.class, obj.getKey()); assertEquals(loaded.getKey(), obj.getKey()); assertEquals( loaded.getBinaryAttribute(), ByteBuffer.wrap(generateByteArray(contentLength - 1))); assertTrue( loaded .getBinarySetAttribute() .contains(ByteBuffer.wrap(generateByteArray(contentLength - 1)))); } // test BinaryAttributeByteArrayTestClass List<BinaryAttributeByteArrayTestClass> bytesObj = new ArrayList<BinaryAttributeByteArrayTestClass>(); for (int i = 0; i < 5; i++) { BinaryAttributeByteArrayTestClass obj = getUniqueBytesObject(contentLength); bytesObj.add(obj); } for (BinaryAttributeByteArrayTestClass obj : bytesObj) { util.save(obj); } for (BinaryAttributeByteArrayTestClass obj : bytesObj) { BinaryAttributeByteArrayTestClass replacement = getUniqueBytesObject(contentLength - 1); replacement.setKey(obj.getKey()); util.save(replacement); BinaryAttributeByteArrayTestClass loaded = util.load(BinaryAttributeByteArrayTestClass.class, obj.getKey()); assertEquals(loaded.getKey(), obj.getKey()); assertTrue( Arrays.equals(loaded.getBinaryAttribute(), (generateByteArray(contentLength - 1)))); assertTrue(1 == loaded.getBinarySetAttribute().size()); assertTrue( setContainsBytes(loaded.getBinarySetAttribute(), generateByteArray(contentLength - 1))); } } @Test public void testDelete() throws Exception { // test BinaryAttributeClass BinaryAttributeByteBufferTestClass byteBufferObj = getUniqueByteBufferObject(contentLength); DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.save(byteBufferObj); util.delete(byteBufferObj); assertNull(util.load(BinaryAttributeByteBufferTestClass.class, byteBufferObj.getKey())); // test BinaryAttributeByteArrayTestClass BinaryAttributeByteArrayTestClass bytesObj = getUniqueBytesObject(contentLength); util.save(bytesObj); util.delete(bytesObj); assertNull(util.load(BinaryAttributeByteArrayTestClass.class, bytesObj.getKey())); } private BinaryAttributeByteArrayTestClass getUniqueBytesObject(int contentLength) { BinaryAttributeByteArrayTestClass obj = new BinaryAttributeByteArrayTestClass(); obj.setKey(String.valueOf(startKey++)); obj.setBinaryAttribute(generateByteArray(contentLength)); Set<byte[]> byteArray = new HashSet<byte[]>(); byteArray.add(generateByteArray(contentLength)); obj.setBinarySetAttribute(byteArray); return obj; } private boolean setContainsBytes(Set<byte[]> set, byte[] bytes) { Iterator<byte[]> iter = set.iterator(); while (iter.hasNext()) { if (Arrays.equals(iter.next(), bytes)) return true; } return false; } }
4,966
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/ScanITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBScanExpression; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.PaginatedParallelScanList; import com.amazonaws.services.dynamodbv2.datamodeling.ScanResultPage; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.ComparisonOperator; import com.amazonaws.services.dynamodbv2.model.Condition; import com.amazonaws.services.dynamodbv2.model.ConditionalOperator; import com.amazonaws.services.dynamodbv2.model.CreateTableRequest; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType; import com.amazonaws.services.dynamodbv2.util.TableUtils; import com.amazonaws.util.ImmutableMapParameter; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.UUID; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Integration tests for the scan operation on DynamoDBMapper. */ public class ScanITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static final String TABLE_NAME = "aws-java-sdk-util-scan-crypto"; /** * We set a small limit in order to test the behavior of PaginatedList when it could not load all * the scan result in one batch. */ private static final int SCAN_LIMIT = 10; private static final int PARALLEL_SCAN_SEGMENTS = 5; private static void createTestData() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (int i = 0; i < 500; i++) { util.save(new SimpleClass(Integer.toString(i), Integer.toString(i))); } } @BeforeClass public static void setUpTestData() throws Exception { String keyName = "id"; CreateTableRequest createTableRequest = new CreateTableRequest() .withTableName(TABLE_NAME) .withKeySchema( new KeySchemaElement().withAttributeName(keyName).withKeyType(KeyType.HASH)) .withAttributeDefinitions( new AttributeDefinition() .withAttributeName(keyName) .withAttributeType(ScalarAttributeType.S)); createTableRequest.setProvisionedThroughput( new ProvisionedThroughput().withReadCapacityUnits(10L).withWriteCapacityUnits(5L)); TableUtils.createTableIfNotExists(dynamo, createTableRequest); TableUtils.waitUntilActive(dynamo, TABLE_NAME); createTestData(); } @Test public void testScan() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); DynamoDBScanExpression scanExpression = new DynamoDBScanExpression().withLimit(SCAN_LIMIT); scanExpression.addFilterCondition( "value", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL.toString())); scanExpression.addFilterCondition( "extraData", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL.toString())); List<SimpleClass> list = util.scan(SimpleClass.class, scanExpression); int count = 0; Iterator<SimpleClass> iterator = list.iterator(); while (iterator.hasNext()) { count++; SimpleClass next = iterator.next(); assertNotNull(next.getExtraData()); assertNotNull(next.getValue()); } int totalCount = util.count(SimpleClass.class, scanExpression); assertNotNull(list.get(totalCount / 2)); assertTrue(totalCount == count); assertTrue(totalCount == list.size()); assertTrue(list.contains(list.get(list.size() / 2))); assertTrue(count == list.toArray().length); } /** Tests scanning the table with AND/OR logic operator. */ @Test public void testScanWithConditionalOperator() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); DynamoDBScanExpression scanExpression = new DynamoDBScanExpression() .withLimit(SCAN_LIMIT) .withScanFilter( ImmutableMapParameter.of( "value", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL), "non-existent-field", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL))) .withConditionalOperator(ConditionalOperator.AND); List<SimpleClass> andConditionResult = mapper.scan(SimpleClass.class, scanExpression); assertTrue(andConditionResult.isEmpty()); List<SimpleClass> orConditionResult = mapper.scan( SimpleClass.class, scanExpression.withConditionalOperator(ConditionalOperator.OR)); assertFalse(orConditionResult.isEmpty()); } @Test public void testParallelScan() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); DynamoDBScanExpression scanExpression = new DynamoDBScanExpression().withLimit(SCAN_LIMIT); scanExpression.addFilterCondition( "value", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL.toString())); scanExpression.addFilterCondition( "extraData", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL.toString())); PaginatedParallelScanList<SimpleClass> parallelScanList = util.parallelScan(SimpleClass.class, scanExpression, PARALLEL_SCAN_SEGMENTS); int count = 0; Iterator<SimpleClass> iterator = parallelScanList.iterator(); HashMap<String, Boolean> allDataAppearance = new HashMap<String, Boolean>(); for (int i = 0; i < 500; i++) { allDataAppearance.put("" + i, false); } while (iterator.hasNext()) { count++; SimpleClass next = iterator.next(); assertNotNull(next.getExtraData()); assertNotNull(next.getValue()); allDataAppearance.put(next.getId(), true); } assertFalse(allDataAppearance.values().contains(false)); int totalCount = util.count(SimpleClass.class, scanExpression); assertNotNull(parallelScanList.get(totalCount / 2)); assertTrue(totalCount == count); assertTrue(totalCount == parallelScanList.size()); assertTrue(parallelScanList.contains(parallelScanList.get(parallelScanList.size() / 2))); assertTrue(count == parallelScanList.toArray().length); } @Test public void testParallelScanExceptionHandling() { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); int INVALID_LIMIT = 0; DynamoDBScanExpression scanExpression = new DynamoDBScanExpression().withLimit(INVALID_LIMIT); try { // Using 2 segments to reduce the chance of a RejectedExecutionException occurring when too // many threads are spun up // An alternative would be to maintain a higher segment count, but re-test when a // RejectedExecutionException occurs PaginatedParallelScanList<SimpleClass> parallelScanList = util.parallelScan(SimpleClass.class, scanExpression, 2); fail("Test succeeded when it should have failed"); } catch (AmazonServiceException ase) { assertNotNull(ase.getErrorCode()); assertNotNull(ase.getErrorType()); assertNotNull(ase.getMessage()); } catch (Exception e) { fail("Should have seen the AmazonServiceException"); } } @Test public void testScanPage() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); DynamoDBScanExpression scanExpression = new DynamoDBScanExpression(); scanExpression.addFilterCondition( "value", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL.toString())); scanExpression.addFilterCondition( "extraData", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL.toString())); int limit = 3; scanExpression.setLimit(limit); ScanResultPage<SimpleClass> result = util.scanPage(SimpleClass.class, scanExpression); int count = 0; Iterator<SimpleClass> iterator = result.getResults().iterator(); Set<SimpleClass> seen = new HashSet<ScanITCase.SimpleClass>(); while (iterator.hasNext()) { count++; SimpleClass next = iterator.next(); assertNotNull(next.getExtraData()); assertNotNull(next.getValue()); assertTrue(seen.add(next)); } assertTrue(limit == count); assertTrue(count == result.getResults().toArray().length); scanExpression.setExclusiveStartKey(result.getLastEvaluatedKey()); result = util.scanPage(SimpleClass.class, scanExpression); iterator = result.getResults().iterator(); count = 0; while (iterator.hasNext()) { count++; SimpleClass next = iterator.next(); assertNotNull(next.getExtraData()); assertNotNull(next.getValue()); assertTrue(seen.add(next)); } assertTrue(limit == count); assertTrue(count == result.getResults().toArray().length); } @DynamoDBTable(tableName = "aws-java-sdk-util-scan-crypto") public static final class SimpleClass { private String id; private String value; private String extraData; public SimpleClass() {} public SimpleClass(String id, String value) { this.id = id; this.value = value; this.extraData = UUID.randomUUID().toString(); } @DynamoDBHashKey public String getId() { return id; } public void setId(String id) { this.id = id; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getExtraData() { return extraData; } public void setExtraData(String extraData) { this.extraData = extraData; } } }
4,967
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/ExceptionHandlingITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBVersionAttribute; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.annotations.Test; /** Tests of exception handling */ public class ExceptionHandlingITCase extends DynamoDBMapperCryptoIntegrationTestBase { public static class NoTableAnnotation { private String key; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testNoTableAnnotation() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.save(new NoTableAnnotation()); } @Test(expectedExceptions = DynamoDBMappingException.class) public void testNoTableAnnotationLoad() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.load(NoTableAnnotation.class, "abc"); } @DynamoDBTable(tableName = TABLE_NAME) public static class NoDefaultConstructor { private String key; private String attribute; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getAttribute() { return attribute; } public void setAttribute(String attribute) { this.attribute = attribute; } public NoDefaultConstructor(String key, String attribute) { super(); this.key = key; this.attribute = attribute; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testNoDefaultConstructor() { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); NoDefaultConstructor obj = new NoDefaultConstructor("" + startKey++, "abc"); util.save(obj); util.load(NoDefaultConstructor.class, obj.getKey()); } @DynamoDBTable(tableName = TABLE_NAME) public static class NoKeyGetterDefined { @SuppressWarnings("unused") private String key; } @Test(expectedExceptions = DynamoDBMappingException.class) public void testNoHashKeyGetter() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.save(new NoKeyGetterDefined()); } @Test(expectedExceptions = DynamoDBMappingException.class) public void testNoHashKeyGetterLoad() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.load(NoKeyGetterDefined.class, "abc"); } @DynamoDBTable(tableName = TABLE_NAME) public static class PrivateKeyGetter { private String key; @SuppressWarnings("unused") @DynamoDBHashKey public String getKey() { return key; } @SuppressWarnings("unused") private void setKey(String key) { this.key = key; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testPrivateKeyGetter() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.save(new PrivateKeyGetter()); } @Test(expectedExceptions = DynamoDBMappingException.class) public void testPrivateKeyGetterLoad() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.load(PrivateKeyGetter.class, "abc"); } @DynamoDBTable(tableName = TABLE_NAME) public static class PrivateKeySetter { private String key; @DynamoDBHashKey @DynamoDBAutoGeneratedKey public String getKey() { return key; } @SuppressWarnings("unused") private void setKey(String key) { this.key = key; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testPrivateKeySetter() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.save(new PrivateKeySetter()); } /* * To trigger this error, we need for a service object to be present, so * we'll insert one manually. */ @Test(expectedExceptions = DynamoDBMappingException.class) public void testPrivateKeySetterLoad() throws Exception { Map<String, AttributeValue> attr = new HashMap<String, AttributeValue>(); attr.put(KEY_NAME, new AttributeValue().withS("abc")); dynamo.putItem(new PutItemRequest().withTableName(TABLE_NAME).withItem(attr)); DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.load(PrivateKeySetter.class, "abc"); } @DynamoDBTable(tableName = TABLE_NAME) public static class PrivateSetter { private String key; private String StringProperty; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getStringProperty() { return StringProperty; } private void setStringProperty(String stringProperty) { StringProperty = stringProperty; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testPrivateSetterLoad() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); PrivateSetter object = new PrivateSetter(); object.setStringProperty("value"); util.save(object); util.load(PrivateSetter.class, object.getKey()); } @DynamoDBTable(tableName = TABLE_NAME) public static class OverloadedSetter { private String key; private String attribute; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getAttribute() { return attribute; } public void setAttribute(String attribute, String unused) { this.attribute = attribute; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testOverloadedSetter() { OverloadedSetter obj = new OverloadedSetter(); obj.setKey("" + startKey++); obj.setAttribute("abc", "123"); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.save(obj); mapper.load(OverloadedSetter.class, obj.getKey()); } @DynamoDBTable(tableName = TABLE_NAME) public static class WrongTypeForSetter { private String key; private String attribute; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getAttribute() { return attribute; } public void setAttribute(Integer attribute) { this.attribute = String.valueOf(attribute); } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testWrongTypeForSetter() { WrongTypeForSetter obj = new WrongTypeForSetter(); obj.setKey("" + startKey++); obj.setAttribute(123); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.save(obj); mapper.load(WrongTypeForSetter.class, obj.getKey()); } @DynamoDBTable(tableName = TABLE_NAME) public static class NumericFields { private String key; private Integer integerProperty; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } public Integer getIntegerProperty() { return integerProperty; } public void setIntegerProperty(Integer integerProperty) { this.integerProperty = integerProperty; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testWrongDataType() { Map<String, AttributeValue> attr = new HashMap<String, AttributeValue>(); attr.put("integerProperty", new AttributeValue().withS("abc")); attr.put(KEY_NAME, new AttributeValue().withS("" + startKey++)); dynamo.putItem(new PutItemRequest().withTableName(TABLE_NAME).withItem(attr)); DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.load(NumericFields.class, attr.get(KEY_NAME).getS()); } @Test(expectedExceptions = DynamoDBMappingException.class) public void testWrongDataType2() { Map<String, AttributeValue> attr = new HashMap<String, AttributeValue>(); attr.put("integerProperty", new AttributeValue().withNS("1", "2", "3")); attr.put(KEY_NAME, new AttributeValue().withS("" + startKey++)); dynamo.putItem(new PutItemRequest().withTableName(TABLE_NAME).withItem(attr)); DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.load(NumericFields.class, attr.get(KEY_NAME).getS()); } @DynamoDBTable(tableName = TABLE_NAME) public static class ComplexType { public String key; public ComplexType type; public ComplexType(String key, ComplexType type) { super(); this.key = key; this.type = type; } @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } public ComplexType getType() { return type; } public void setType(ComplexType type) { this.type = type; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testComplexTypeFailure() { ComplexType complexType = new ComplexType("" + startKey++, new ComplexType("" + startKey++, null)); DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.save(complexType); } @DynamoDBTable(tableName = TABLE_NAME) public static class ComplexHashKeyType { private ComplexType key; private String attribute; @DynamoDBHashKey public ComplexType getKey() { return key; } public void setKey(ComplexType key) { this.key = key; } public String getAttribute() { return attribute; } public void setAttribute(String attribute) { this.attribute = attribute; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testUnsupportedHashKeyType() { ComplexType complexType = new ComplexType("" + startKey++, new ComplexType("" + startKey++, null)); ComplexHashKeyType obj = new ComplexHashKeyType(); obj.setKey(complexType); obj.setAttribute("abc"); DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.save(obj); } @DynamoDBTable(tableName = TABLE_NAME) public static class NonSetCollectionType { private String key; private List<String> badlyMapped; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } public List<String> getBadlyMapped() { return badlyMapped; } public void setBadlyMapped(List<String> badlyMapped) { this.badlyMapped = badlyMapped; } } @Test public void testNonSetCollection() { NonSetCollectionType obj = new NonSetCollectionType(); obj.setKey("" + startKey++); obj.setBadlyMapped(new ArrayList<String>()); obj.getBadlyMapped().add("abc"); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.save(obj); } @DynamoDBTable(tableName = TABLE_NAME) public static class FractionalVersionAttribute { private String key; private Double version; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBVersionAttribute public Double getVersion() { return version; } public void setVersion(Double version) { this.version = version; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testFractionalVersionAttribute() { FractionalVersionAttribute obj = new FractionalVersionAttribute(); obj.setKey("" + startKey++); obj.setVersion(0d); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.save(obj); } @DynamoDBTable(tableName = TABLE_NAME) public static class AutoGeneratedIntegerKey { private Integer key; private String value; @DynamoDBHashKey @DynamoDBAutoGeneratedKey public Integer getKey() { return key; } public void setKey(Integer key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testAutoGeneratedIntegerHashKey() { AutoGeneratedIntegerKey obj = new AutoGeneratedIntegerKey(); obj.setValue("fdgfdsgf"); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.save(obj); } @DynamoDBTable(tableName = TABLE_NAME) public static class AutoGeneratedIntegerRangeKey { private String key; private Integer rangekey; private String value; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAutoGeneratedKey @DynamoDBRangeKey public Integer getRangekey() { return rangekey; } public void setRangekey(Integer rangekey) { this.rangekey = rangekey; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testAutoGeneratedIntegerRangeKey() { AutoGeneratedIntegerRangeKey obj = new AutoGeneratedIntegerRangeKey(); obj.setKey("Bldadsfa"); obj.setValue("fdgfdsgf"); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.save(obj); } }
4,968
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/KeyOnlyPutITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; public class KeyOnlyPutITCase extends DynamoDBCryptoIntegrationTestBase { @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public static class HashAndAttribute { protected String key; protected String normalStringAttribute; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAttribute public String getNormalStringAttribute() { return normalStringAttribute; } public void setNormalStringAttribute(String normalStringAttribute) { this.normalStringAttribute = normalStringAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((normalStringAttribute == null) ? 0 : normalStringAttribute.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; HashAndAttribute other = (HashAndAttribute) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (normalStringAttribute == null) { if (other.normalStringAttribute != null) return false; } else if (!normalStringAttribute.equals(other.normalStringAttribute)) return false; return true; } } private <T extends HashAndAttribute> T getUniqueObject(T obj) { obj.setKey("" + startKey++); return obj; } }
4,969
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/MapperSaveConfigCryptoIntegrationTestBase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.SaveBehavior; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotTouch; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.CreateTableRequest; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType; import com.amazonaws.services.dynamodbv2.model.TableDescription; import com.amazonaws.services.dynamodbv2.util.TableUtils; import java.util.Set; import org.testng.annotations.BeforeClass; public class MapperSaveConfigCryptoIntegrationTestBase extends DynamoDBCryptoIntegrationTestBase { protected static DynamoDBMapper dynamoMapper; protected static final DynamoDBMapperConfig defaultConfig = new DynamoDBMapperConfig(SaveBehavior.UPDATE); protected static final DynamoDBMapperConfig updateSkipNullConfig = new DynamoDBMapperConfig(SaveBehavior.UPDATE_SKIP_NULL_ATTRIBUTES); protected static final DynamoDBMapperConfig appendSetConfig = new DynamoDBMapperConfig(SaveBehavior.APPEND_SET); protected static final DynamoDBMapperConfig clobberConfig = new DynamoDBMapperConfig(SaveBehavior.CLOBBER); protected static final String tableName = "aws-java-sdk-dynamodb-mapper-save-config-test-crypto"; protected static final String hashKeyName = "hashKey"; protected static final String rangeKeyName = "rangeKey"; protected static final String nonKeyAttributeName = "nonKeyAttribute"; protected static final String stringSetAttributeName = "stringSetAttribute"; /** Read capacity for the test table being created in Amazon DynamoDB. */ protected static final Long READ_CAPACITY = 10L; /** Write capacity for the test table being created in Amazon DynamoDB. */ protected static final Long WRITE_CAPACITY = 5L; /** Provisioned Throughput for the test table created in Amazon DynamoDB */ protected static final ProvisionedThroughput DEFAULT_PROVISIONED_THROUGHPUT = new ProvisionedThroughput() .withReadCapacityUnits(READ_CAPACITY) .withWriteCapacityUnits(WRITE_CAPACITY); @BeforeClass public static void setUp() throws Exception { DynamoDBCryptoIntegrationTestBase.setUp(); dynamoMapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); CreateTableRequest createTableRequest = new CreateTableRequest() .withTableName(tableName) .withKeySchema( new KeySchemaElement().withAttributeName(hashKeyName).withKeyType(KeyType.HASH)) .withKeySchema( new KeySchemaElement().withAttributeName(rangeKeyName).withKeyType(KeyType.RANGE)) .withAttributeDefinitions( new AttributeDefinition() .withAttributeName(hashKeyName) .withAttributeType(ScalarAttributeType.S)) .withAttributeDefinitions( new AttributeDefinition() .withAttributeName(rangeKeyName) .withAttributeType(ScalarAttributeType.N)); createTableRequest.setProvisionedThroughput(DEFAULT_PROVISIONED_THROUGHPUT); if (TableUtils.createTableIfNotExists(dynamo, createTableRequest)) { TableUtils.waitUntilActive(dynamo, tableName); } } @DynamoDBTable(tableName = tableName) public static class TestItem { private String hashKey; private Long rangeKey; private String nonKeyAttribute; private Set<String> stringSetAttribute; @DynamoDBHashKey(attributeName = hashKeyName) public String getHashKey() { return hashKey; } public void setHashKey(String hashKey) { this.hashKey = hashKey; } @DynamoDBRangeKey(attributeName = rangeKeyName) public Long getRangeKey() { return rangeKey; } public void setRangeKey(Long rangeKey) { this.rangeKey = rangeKey; } @DoNotTouch @DynamoDBAttribute(attributeName = nonKeyAttributeName) public String getNonKeyAttribute() { return nonKeyAttribute; } public void setNonKeyAttribute(String nonKeyAttribute) { this.nonKeyAttribute = nonKeyAttribute; } @DoNotTouch @DynamoDBAttribute(attributeName = stringSetAttributeName) public Set<String> getStringSetAttribute() { return stringSetAttribute; } public void setStringSetAttribute(Set<String> stringSetAttribute) { this.stringSetAttribute = stringSetAttribute; } } @DynamoDBTable(tableName = tableName) public static class TestAppendToScalarItem { private String hashKey; private Long rangeKey; private Set<String> fakeStringSetAttribute; @DynamoDBHashKey(attributeName = hashKeyName) public String getHashKey() { return hashKey; } public void setHashKey(String hashKey) { this.hashKey = hashKey; } @DynamoDBRangeKey(attributeName = rangeKeyName) public Long getRangeKey() { return rangeKey; } public void setRangeKey(Long rangeKey) { this.rangeKey = rangeKey; } @DynamoDBAttribute(attributeName = nonKeyAttributeName) public Set<String> getFakeStringSetAttribute() { return fakeStringSetAttribute; } public void setFakeStringSetAttribute(Set<String> stringSetAttribute) { this.fakeStringSetAttribute = stringSetAttribute; } } /** Helper method to create a table in Amazon DynamoDB */ protected static void createTestTable(ProvisionedThroughput provisionedThroughput) { CreateTableRequest createTableRequest = new CreateTableRequest() .withTableName(tableName) .withKeySchema( new KeySchemaElement().withAttributeName(hashKeyName).withKeyType(KeyType.HASH)) .withKeySchema( new KeySchemaElement().withAttributeName(rangeKeyName).withKeyType(KeyType.RANGE)) .withAttributeDefinitions( new AttributeDefinition() .withAttributeName(hashKeyName) .withAttributeType(ScalarAttributeType.S)) .withAttributeDefinitions( new AttributeDefinition() .withAttributeName(rangeKeyName) .withAttributeType(ScalarAttributeType.N)); createTableRequest.setProvisionedThroughput(provisionedThroughput); TableDescription createdTableDescription = dynamo.createTable(createTableRequest).getTableDescription(); System.out.println("Created Table: " + createdTableDescription); assertEquals(tableName, createdTableDescription.getTableName()); assertNotNull(createdTableDescription.getTableStatus()); assertEquals(hashKeyName, createdTableDescription.getKeySchema().get(0).getAttributeName()); assertEquals( KeyType.HASH.toString(), createdTableDescription.getKeySchema().get(0).getKeyType()); assertEquals(rangeKeyName, createdTableDescription.getKeySchema().get(1).getAttributeName()); assertEquals( KeyType.RANGE.toString(), createdTableDescription.getKeySchema().get(1).getKeyType()); } }
4,970
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/DynamoDBCryptoIntegrationTestBase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.model.AmazonDynamoDBException; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.CreateTableRequest; import com.amazonaws.services.dynamodbv2.model.DeleteTableRequest; import com.amazonaws.services.dynamodbv2.model.DescribeTableRequest; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.LocalSecondaryIndex; import com.amazonaws.services.dynamodbv2.model.Projection; import com.amazonaws.services.dynamodbv2.model.ProjectionType; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType; import com.amazonaws.services.dynamodbv2.model.TableDescription; import com.amazonaws.services.dynamodbv2.util.TableUtils; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import org.testng.annotations.BeforeClass; public class DynamoDBCryptoIntegrationTestBase extends DynamoDBTestBase { protected static final boolean DEBUG = false; protected static final String KEY_NAME = "key"; protected static final String TABLE_NAME = "aws-java-sdk-util-crypto"; protected static long startKey = System.currentTimeMillis(); protected static final String TABLE_WITH_RANGE_ATTRIBUTE = "aws-java-sdk-range-test-crypto"; protected static final String TABLE_WITH_INDEX_RANGE_ATTRIBUTE = "aws-java-sdk-index-range-test-crypto"; protected static Logger log = Logger.getLogger("DynamoDBCryptoITCaseBase"); @BeforeClass public static void setUp() throws Exception { // Create a table DynamoDBTestBase.setUpTestBase(); String keyName = KEY_NAME; CreateTableRequest createTableRequest = new CreateTableRequest() .withTableName(TABLE_NAME) .withKeySchema( new KeySchemaElement().withAttributeName(keyName).withKeyType(KeyType.HASH)) .withAttributeDefinitions( new AttributeDefinition() .withAttributeName(keyName) .withAttributeType(ScalarAttributeType.S)); createTableRequest.setProvisionedThroughput( new ProvisionedThroughput().withReadCapacityUnits(10L).withWriteCapacityUnits(5L)); if (TableUtils.createTableIfNotExists(dynamo, createTableRequest)) { TableUtils.waitUntilActive(dynamo, TABLE_NAME); } } /** Utility method to delete tables used in the integration test */ public static void deleteCryptoIntegrationTestTables() { List<String> integrationTestTables = new ArrayList<>(); integrationTestTables.add(TABLE_NAME); integrationTestTables.add(TABLE_WITH_INDEX_RANGE_ATTRIBUTE); integrationTestTables.add(TABLE_WITH_RANGE_ATTRIBUTE); for (String name : integrationTestTables) { dynamo.deleteTable(new DeleteTableRequest().withTableName(name)); } } protected static void setUpTableWithRangeAttribute() throws Exception { setUp(); String keyName = DynamoDBCryptoIntegrationTestBase.KEY_NAME; String rangeKeyAttributeName = "rangeKey"; CreateTableRequest createTableRequest = new CreateTableRequest() .withTableName(TABLE_WITH_RANGE_ATTRIBUTE) .withKeySchema( new KeySchemaElement().withAttributeName(keyName).withKeyType(KeyType.HASH), new KeySchemaElement() .withAttributeName(rangeKeyAttributeName) .withKeyType(KeyType.RANGE)) .withAttributeDefinitions( new AttributeDefinition() .withAttributeName(keyName) .withAttributeType(ScalarAttributeType.N), new AttributeDefinition() .withAttributeName(rangeKeyAttributeName) .withAttributeType(ScalarAttributeType.N)); createTableRequest.setProvisionedThroughput( new ProvisionedThroughput().withReadCapacityUnits(10L).withWriteCapacityUnits(5L)); if (TableUtils.createTableIfNotExists(dynamo, createTableRequest)) { TableUtils.waitUntilActive(dynamo, TABLE_WITH_RANGE_ATTRIBUTE); } } protected static void setUpTableWithIndexRangeAttribute(boolean recreateTable) throws Exception { setUp(); if (recreateTable) { dynamo.deleteTable(new DeleteTableRequest().withTableName(TABLE_WITH_INDEX_RANGE_ATTRIBUTE)); waitForTableToBecomeDeleted(TABLE_WITH_INDEX_RANGE_ATTRIBUTE); } String keyName = DynamoDBCryptoIntegrationTestBase.KEY_NAME; String rangeKeyAttributeName = "rangeKey"; String indexFooRangeKeyAttributeName = "indexFooRangeKey"; String indexBarRangeKeyAttributeName = "indexBarRangeKey"; String multipleIndexRangeKeyAttributeName = "multipleIndexRangeKey"; String indexFooName = "index_foo"; String indexBarName = "index_bar"; String indexFooCopyName = "index_foo_copy"; String indexBarCopyName = "index_bar_copy"; CreateTableRequest createTableRequest = new CreateTableRequest() .withTableName(TABLE_WITH_INDEX_RANGE_ATTRIBUTE) .withKeySchema( new KeySchemaElement().withAttributeName(keyName).withKeyType(KeyType.HASH), new KeySchemaElement() .withAttributeName(rangeKeyAttributeName) .withKeyType(KeyType.RANGE)) .withLocalSecondaryIndexes( new LocalSecondaryIndex() .withIndexName(indexFooName) .withKeySchema( new KeySchemaElement().withAttributeName(keyName).withKeyType(KeyType.HASH), new KeySchemaElement() .withAttributeName(indexFooRangeKeyAttributeName) .withKeyType(KeyType.RANGE)) .withProjection(new Projection().withProjectionType(ProjectionType.ALL)), new LocalSecondaryIndex() .withIndexName(indexBarName) .withKeySchema( new KeySchemaElement().withAttributeName(keyName).withKeyType(KeyType.HASH), new KeySchemaElement() .withAttributeName(indexBarRangeKeyAttributeName) .withKeyType(KeyType.RANGE)) .withProjection(new Projection().withProjectionType(ProjectionType.ALL)), new LocalSecondaryIndex() .withIndexName(indexFooCopyName) .withKeySchema( new KeySchemaElement().withAttributeName(keyName).withKeyType(KeyType.HASH), new KeySchemaElement() .withAttributeName(multipleIndexRangeKeyAttributeName) .withKeyType(KeyType.RANGE)) .withProjection(new Projection().withProjectionType(ProjectionType.ALL)), new LocalSecondaryIndex() .withIndexName(indexBarCopyName) .withKeySchema( new KeySchemaElement().withAttributeName(keyName).withKeyType(KeyType.HASH), new KeySchemaElement() .withAttributeName(multipleIndexRangeKeyAttributeName) .withKeyType(KeyType.RANGE)) .withProjection(new Projection().withProjectionType(ProjectionType.ALL))) .withAttributeDefinitions( new AttributeDefinition() .withAttributeName(keyName) .withAttributeType(ScalarAttributeType.N), new AttributeDefinition() .withAttributeName(rangeKeyAttributeName) .withAttributeType(ScalarAttributeType.N), new AttributeDefinition() .withAttributeName(indexFooRangeKeyAttributeName) .withAttributeType(ScalarAttributeType.N), new AttributeDefinition() .withAttributeName(indexBarRangeKeyAttributeName) .withAttributeType(ScalarAttributeType.N), new AttributeDefinition() .withAttributeName(multipleIndexRangeKeyAttributeName) .withAttributeType(ScalarAttributeType.N)); createTableRequest.setProvisionedThroughput( new ProvisionedThroughput().withReadCapacityUnits(10L).withWriteCapacityUnits(5L)); if (TableUtils.createTableIfNotExists(dynamo, createTableRequest)) { TableUtils.waitUntilActive(dynamo, TABLE_WITH_INDEX_RANGE_ATTRIBUTE); } } protected static void waitForTableToBecomeDeleted(String tableName) { waitForTableToBecomeDeleted(dynamo, tableName); } public static void waitForTableToBecomeDeleted(AmazonDynamoDB dynamo, String tableName) { log.info(() -> "Waiting for " + tableName + " to become Deleted..."); long startTime = System.currentTimeMillis(); long endTime = startTime + (60_000); while (System.currentTimeMillis() < endTime) { try { Thread.sleep(5_000); } catch (Exception e) { // Ignored or expected. } try { DescribeTableRequest request = new DescribeTableRequest(tableName); TableDescription table = dynamo.describeTable(request).getTable(); log.info(() -> " - current state: " + table.getTableStatus()); if (table.getTableStatus() == "DELETING") { continue; } } catch (AmazonDynamoDBException exception) { if (exception.getErrorCode().equalsIgnoreCase("ResourceNotFoundException")) { log.info(() -> "successfully deleted"); return; } } } throw new RuntimeException("Table " + tableName + " never went deleted"); } public static void main(String[] args) throws Exception { setUp(); deleteCryptoIntegrationTestTables(); } }
4,971
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/AutoGeneratedKeysITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.fail; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBSaveExpression; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; import com.amazonaws.services.dynamodbv2.model.ConditionalOperator; import com.amazonaws.services.dynamodbv2.model.CreateTableRequest; import com.amazonaws.services.dynamodbv2.model.ExpectedAttributeValue; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType; import com.amazonaws.services.dynamodbv2.util.TableUtils; import com.amazonaws.util.ImmutableMapParameter; import java.util.Collections; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Tests using auto-generated keys for range keys, hash keys, or both. */ public class AutoGeneratedKeysITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static final String TABLE_NAME = "aws-java-sdk-string-range-crypto"; @BeforeClass public static void setUp() throws Exception { DynamoDBMapperCryptoIntegrationTestBase.setUp(); // Create a table String keyName = DynamoDBMapperCryptoIntegrationTestBase.KEY_NAME; String rangeKeyAttributeName = "rangeKey"; CreateTableRequest createTableRequest = new CreateTableRequest() .withTableName(TABLE_NAME) .withKeySchema( new KeySchemaElement().withAttributeName(keyName).withKeyType(KeyType.HASH), new KeySchemaElement() .withAttributeName(rangeKeyAttributeName) .withKeyType(KeyType.RANGE)) .withAttributeDefinitions( new AttributeDefinition() .withAttributeName(keyName) .withAttributeType(ScalarAttributeType.S), new AttributeDefinition() .withAttributeName(rangeKeyAttributeName) .withAttributeType(ScalarAttributeType.S)); createTableRequest.setProvisionedThroughput( new ProvisionedThroughput().withReadCapacityUnits(10L).withWriteCapacityUnits(5L)); if (TableUtils.createTableIfNotExists(dynamo, createTableRequest)) { TableUtils.waitUntilActive(dynamo, TABLE_NAME); } } @DynamoDBTable(tableName = "aws-java-sdk-string-range-crypto") public static class HashKeyRangeKeyBothAutoGenerated { private String key; private String rangeKey; private String otherAttribute; @DynamoDBAutoGeneratedKey @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAutoGeneratedKey @DynamoDBRangeKey public String getRangeKey() { return rangeKey; } public void setRangeKey(String rangeKey) { this.rangeKey = rangeKey; } public String getOtherAttribute() { return otherAttribute; } public void setOtherAttribute(String otherAttribute) { this.otherAttribute = otherAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((otherAttribute == null) ? 0 : otherAttribute.hashCode()); result = prime * result + ((rangeKey == null) ? 0 : rangeKey.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; HashKeyRangeKeyBothAutoGenerated other = (HashKeyRangeKeyBothAutoGenerated) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (otherAttribute == null) { if (other.otherAttribute != null) return false; } else if (!otherAttribute.equals(other.otherAttribute)) return false; if (rangeKey == null) { if (other.rangeKey != null) return false; } else if (!rangeKey.equals(other.rangeKey)) return false; return true; } } @Test public void testHashKeyRangeKeyBothAutogenerated() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); HashKeyRangeKeyBothAutoGenerated obj = new HashKeyRangeKeyBothAutoGenerated(); obj.setOtherAttribute("blah"); assertNull(obj.getKey()); assertNull(obj.getRangeKey()); mapper.save(obj); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); HashKeyRangeKeyBothAutoGenerated other = mapper.load(HashKeyRangeKeyBothAutoGenerated.class, obj.getKey(), obj.getRangeKey()); assertEquals(other, obj); } @Test public void testHashKeyRangeKeyBothAutogeneratedBatchWrite() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); HashKeyRangeKeyBothAutoGenerated obj = new HashKeyRangeKeyBothAutoGenerated(); obj.setOtherAttribute("blah"); HashKeyRangeKeyBothAutoGenerated obj2 = new HashKeyRangeKeyBothAutoGenerated(); obj2.setOtherAttribute("blah"); assertNull(obj.getKey()); assertNull(obj.getRangeKey()); assertNull(obj2.getKey()); assertNull(obj2.getRangeKey()); mapper.batchSave(obj, obj2); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); assertNotNull(obj2.getKey()); assertNotNull(obj2.getRangeKey()); assertEquals( mapper.load(HashKeyRangeKeyBothAutoGenerated.class, obj.getKey(), obj.getRangeKey()), obj); assertEquals( mapper.load(HashKeyRangeKeyBothAutoGenerated.class, obj2.getKey(), obj2.getRangeKey()), obj2); } /** Tests providing additional expected conditions when saving item with auto-generated keys. */ @Test public void testAutogeneratedKeyWithUserProvidedExpectedConditions() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); HashKeyRangeKeyBothAutoGenerated obj = new HashKeyRangeKeyBothAutoGenerated(); obj.setOtherAttribute("blah"); assertNull(obj.getKey()); assertNull(obj.getRangeKey()); // Add additional expected conditions via DynamoDBSaveExpression. // Expected conditions joined by AND are compatible with the conditions // for auto-generated keys. DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression(); saveExpression .withExpected(Collections.singletonMap("otherAttribute", new ExpectedAttributeValue(false))) .withConditionalOperator(ConditionalOperator.AND); // The save should succeed since the user provided conditions are joined by AND. mapper.save(obj, saveExpression); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); HashKeyRangeKeyBothAutoGenerated other = mapper.load(HashKeyRangeKeyBothAutoGenerated.class, obj.getKey(), obj.getRangeKey()); assertEquals(other, obj); // Change the conditional operator to OR. // IllegalArgumentException is expected since the additional expected // conditions cannot be joined with the conditions for auto-generated // keys. saveExpression.setConditionalOperator(ConditionalOperator.OR); try { mapper.save(new HashKeyRangeKeyBothAutoGenerated(), saveExpression); } catch (IllegalArgumentException expected) { } // User-provided OR conditions should work if they completely override the generated conditions. saveExpression .withExpected( ImmutableMapParameter.of( "otherAttribute", new ExpectedAttributeValue(false), "key", new ExpectedAttributeValue(false), "rangeKey", new ExpectedAttributeValue(false))) .withConditionalOperator(ConditionalOperator.OR); mapper.save(new HashKeyRangeKeyBothAutoGenerated(), saveExpression); saveExpression .withExpected( ImmutableMapParameter.of( "otherAttribute", new ExpectedAttributeValue(new AttributeValue("non-existent-value")), "key", new ExpectedAttributeValue(new AttributeValue("non-existent-value")), "rangeKey", new ExpectedAttributeValue(new AttributeValue("non-existent-value")))) .withConditionalOperator(ConditionalOperator.OR); try { mapper.save(new HashKeyRangeKeyBothAutoGenerated(), saveExpression); } catch (ConditionalCheckFailedException expected) { } } @DynamoDBTable(tableName = "aws-java-sdk-string-range-crypto") public static class HashKeyAutoGenerated { private String key; private String rangeKey; private String otherAttribute; @DynamoDBAutoGeneratedKey @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBRangeKey public String getRangeKey() { return rangeKey; } public void setRangeKey(String rangeKey) { this.rangeKey = rangeKey; } public String getOtherAttribute() { return otherAttribute; } public void setOtherAttribute(String otherAttribute) { this.otherAttribute = otherAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((otherAttribute == null) ? 0 : otherAttribute.hashCode()); result = prime * result + ((rangeKey == null) ? 0 : rangeKey.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; HashKeyAutoGenerated other = (HashKeyAutoGenerated) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (otherAttribute == null) { if (other.otherAttribute != null) return false; } else if (!otherAttribute.equals(other.otherAttribute)) return false; if (rangeKey == null) { if (other.rangeKey != null) return false; } else if (!rangeKey.equals(other.rangeKey)) return false; return true; } } @Test public void testHashKeyAutogenerated() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); HashKeyAutoGenerated obj = new HashKeyAutoGenerated(); obj.setOtherAttribute("blah"); obj.setRangeKey("" + System.currentTimeMillis()); assertNull(obj.getKey()); assertNotNull(obj.getRangeKey()); mapper.save(obj); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); HashKeyAutoGenerated other = mapper.load(HashKeyAutoGenerated.class, obj.getKey(), obj.getRangeKey()); assertEquals(other, obj); } @DynamoDBTable(tableName = "aws-java-sdk-string-range-crypto") public static class RangeKeyAutoGenerated { private String key; private String rangeKey; private String otherAttribute; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAutoGeneratedKey @DynamoDBRangeKey public String getRangeKey() { return rangeKey; } public void setRangeKey(String rangeKey) { this.rangeKey = rangeKey; } public String getOtherAttribute() { return otherAttribute; } public void setOtherAttribute(String otherAttribute) { this.otherAttribute = otherAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((otherAttribute == null) ? 0 : otherAttribute.hashCode()); result = prime * result + ((rangeKey == null) ? 0 : rangeKey.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RangeKeyAutoGenerated other = (RangeKeyAutoGenerated) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (otherAttribute == null) { if (other.otherAttribute != null) return false; } else if (!otherAttribute.equals(other.otherAttribute)) return false; if (rangeKey == null) { if (other.rangeKey != null) return false; } else if (!rangeKey.equals(other.rangeKey)) return false; return true; } } @Test public void testRangeKeyAutogenerated() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); RangeKeyAutoGenerated obj = new RangeKeyAutoGenerated(); obj.setOtherAttribute("blah"); obj.setKey("" + System.currentTimeMillis()); assertNotNull(obj.getKey()); assertNull(obj.getRangeKey()); mapper.save(obj); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); RangeKeyAutoGenerated other = mapper.load(RangeKeyAutoGenerated.class, obj.getKey(), obj.getRangeKey()); assertEquals(other, obj); } @DynamoDBTable(tableName = "aws-java-sdk-string-range-crypto") public static class NothingAutoGenerated { private String key; private String rangeKey; private String otherAttribute; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBRangeKey public String getRangeKey() { return rangeKey; } public void setRangeKey(String rangeKey) { this.rangeKey = rangeKey; } public String getOtherAttribute() { return otherAttribute; } public void setOtherAttribute(String otherAttribute) { this.otherAttribute = otherAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((otherAttribute == null) ? 0 : otherAttribute.hashCode()); result = prime * result + ((rangeKey == null) ? 0 : rangeKey.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NothingAutoGenerated other = (NothingAutoGenerated) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (otherAttribute == null) { if (other.otherAttribute != null) return false; } else if (!otherAttribute.equals(other.otherAttribute)) return false; if (rangeKey == null) { if (other.rangeKey != null) return false; } else if (!rangeKey.equals(other.rangeKey)) return false; return true; } } @Test public void testNothingAutogenerated() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); NothingAutoGenerated obj = new NothingAutoGenerated(); obj.setOtherAttribute("blah"); obj.setKey("" + System.currentTimeMillis()); obj.setRangeKey("" + System.currentTimeMillis()); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); mapper.save(obj); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); NothingAutoGenerated other = mapper.load(NothingAutoGenerated.class, obj.getKey(), obj.getRangeKey()); assertEquals(other, obj); } @Test public void testNothingAutogeneratedErrors() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); NothingAutoGenerated obj = new NothingAutoGenerated(); try { mapper.save(obj); fail("Expected a mapping exception"); } catch (DynamoDBMappingException expected) { } obj.setKey("" + System.currentTimeMillis()); try { mapper.save(obj); fail("Expected a mapping exception"); } catch (DynamoDBMappingException expected) { } obj.setRangeKey("" + System.currentTimeMillis()); obj.setKey(null); try { mapper.save(obj); fail("Expected a mapping exception"); } catch (DynamoDBMappingException expected) { } obj.setRangeKey(""); obj.setKey("" + System.currentTimeMillis()); try { mapper.save(obj); fail("Expected a mapping exception"); } catch (DynamoDBMappingException expected) { } obj.setRangeKey("" + System.currentTimeMillis()); mapper.save(obj); } @DynamoDBTable(tableName = "aws-java-sdk-string-range-crypto") public static class HashKeyRangeKeyBothAutoGeneratedKeyOnly { private String key; private String rangeKey; @DynamoDBAutoGeneratedKey @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAutoGeneratedKey @DynamoDBRangeKey public String getRangeKey() { return rangeKey; } public void setRangeKey(String rangeKey) { this.rangeKey = rangeKey; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((rangeKey == null) ? 0 : rangeKey.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; HashKeyRangeKeyBothAutoGeneratedKeyOnly other = (HashKeyRangeKeyBothAutoGeneratedKeyOnly) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (rangeKey == null) { if (other.rangeKey != null) return false; } else if (!rangeKey.equals(other.rangeKey)) return false; return true; } } @Test public void testHashKeyRangeKeyBothAutogeneratedKeyOnly() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); HashKeyRangeKeyBothAutoGeneratedKeyOnly obj = new HashKeyRangeKeyBothAutoGeneratedKeyOnly(); assertNull(obj.getKey()); assertNull(obj.getRangeKey()); mapper.save(obj); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); HashKeyRangeKeyBothAutoGeneratedKeyOnly other = mapper.load(HashKeyRangeKeyBothAutoGeneratedKeyOnly.class, obj.getKey(), obj.getRangeKey()); assertEquals(other, obj); } @DynamoDBTable(tableName = "aws-java-sdk-string-range-crypto") public static class HashKeyAutoGeneratedKeyOnly { private String key; private String rangeKey; @DynamoDBAutoGeneratedKey @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBRangeKey public String getRangeKey() { return rangeKey; } public void setRangeKey(String rangeKey) { this.rangeKey = rangeKey; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((rangeKey == null) ? 0 : rangeKey.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; HashKeyAutoGeneratedKeyOnly other = (HashKeyAutoGeneratedKeyOnly) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (rangeKey == null) { if (other.rangeKey != null) return false; } else if (!rangeKey.equals(other.rangeKey)) return false; return true; } } @Test public void testHashKeyAutogeneratedKeyOnly() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); HashKeyAutoGeneratedKeyOnly obj = new HashKeyAutoGeneratedKeyOnly(); obj.setRangeKey("" + System.currentTimeMillis()); assertNull(obj.getKey()); assertNotNull(obj.getRangeKey()); mapper.save(obj); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); HashKeyAutoGeneratedKeyOnly other = mapper.load(HashKeyAutoGeneratedKeyOnly.class, obj.getKey(), obj.getRangeKey()); assertEquals(other, obj); } @DynamoDBTable(tableName = "aws-java-sdk-string-range-crypto") public static class RangeKeyAutoGeneratedKeyOnly { private String key; private String rangeKey; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAutoGeneratedKey @DynamoDBRangeKey public String getRangeKey() { return rangeKey; } public void setRangeKey(String rangeKey) { this.rangeKey = rangeKey; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((rangeKey == null) ? 0 : rangeKey.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RangeKeyAutoGeneratedKeyOnly other = (RangeKeyAutoGeneratedKeyOnly) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (rangeKey == null) { if (other.rangeKey != null) return false; } else if (!rangeKey.equals(other.rangeKey)) return false; return true; } } @Test public void testRangeKeyAutogeneratedKeyOnly() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); RangeKeyAutoGeneratedKeyOnly obj = new RangeKeyAutoGeneratedKeyOnly(); obj.setKey("" + System.currentTimeMillis()); assertNotNull(obj.getKey()); assertNull(obj.getRangeKey()); mapper.save(obj); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); RangeKeyAutoGeneratedKeyOnly other = mapper.load(RangeKeyAutoGeneratedKeyOnly.class, obj.getKey(), obj.getRangeKey()); assertEquals(other, obj); } @DynamoDBTable(tableName = "aws-java-sdk-string-range-crypto") public static class NothingAutoGeneratedKeyOnly { private String key; private String rangeKey; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBRangeKey public String getRangeKey() { return rangeKey; } public void setRangeKey(String rangeKey) { this.rangeKey = rangeKey; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((rangeKey == null) ? 0 : rangeKey.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NothingAutoGeneratedKeyOnly other = (NothingAutoGeneratedKeyOnly) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (rangeKey == null) { if (other.rangeKey != null) return false; } else if (!rangeKey.equals(other.rangeKey)) return false; return true; } } @Test public void testNothingAutogeneratedKeyOnly() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); NothingAutoGeneratedKeyOnly obj = new NothingAutoGeneratedKeyOnly(); obj.setKey("" + System.currentTimeMillis()); obj.setRangeKey("" + System.currentTimeMillis()); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); mapper.save(obj); assertNotNull(obj.getKey()); assertNotNull(obj.getRangeKey()); NothingAutoGeneratedKeyOnly other = mapper.load(NothingAutoGeneratedKeyOnly.class, obj.getKey(), obj.getRangeKey()); assertEquals(other, obj); } @Test public void testNothingAutogeneratedKeyOnlyErrors() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); NothingAutoGeneratedKeyOnly obj = new NothingAutoGeneratedKeyOnly(); try { mapper.save(obj); fail("Expected a mapping exception"); } catch (DynamoDBMappingException expected) { } obj.setKey("" + System.currentTimeMillis()); try { mapper.save(obj); fail("Expected a mapping exception"); } catch (DynamoDBMappingException expected) { } obj.setRangeKey("" + System.currentTimeMillis()); obj.setKey(null); try { mapper.save(obj); fail("Expected a mapping exception"); } catch (DynamoDBMappingException expected) { } obj.setRangeKey(""); obj.setKey("" + System.currentTimeMillis()); try { mapper.save(obj); fail("Expected a mapping exception"); } catch (DynamoDBMappingException expected) { } obj.setRangeKey("" + System.currentTimeMillis()); mapper.save(obj); } }
4,972
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/ConfigurationITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.fail; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.SaveBehavior; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.TableNameOverride; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.mapper.encryption.NumberAttributeTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.UUID; import org.testng.annotations.Test; /** Tests of the configuration object */ public class ConfigurationITCase extends DynamoDBMapperCryptoIntegrationTestBase { // We don't start with the current system millis like other tests because // it's out of the range of some data types private static int start = 1; private static int byteStart = -127; @Test public void testClobber() throws Exception { DynamoDBMapper util = new DynamoDBMapper(dynamo, new DynamoDBMapperConfig(SaveBehavior.CLOBBER)); NumberAttributeTestClassExtended obj = getUniqueObject(); util.save(obj); assertEquals(obj, util.load(obj.getClass(), obj.getKey())); NumberAttributeTestClass copy = copy(obj); util.save(copy); assertEquals(copy, util.load(copy.getClass(), obj.getKey())); // We should have lost the extra field because of the clobber behavior assertNull(util.load(NumberAttributeTestClassExtended.class, obj.getKey()).getExtraField()); // Now test overriding the clobber behavior on a per-save basis obj = getUniqueObject(); util.save(obj); assertEquals(obj, util.load(obj.getClass(), obj.getKey())); copy = copy(obj); util.save(copy, new DynamoDBMapperConfig(SaveBehavior.UPDATE)); assertEquals(copy, util.load(copy.getClass(), obj.getKey())); // We shouldn't have lost any extra info assertNotNull(util.load(NumberAttributeTestClassExtended.class, obj.getKey()).getExtraField()); } @Test public void testTableOverride() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); TableOverrideTestClass obj = new TableOverrideTestClass(); obj.setOtherField(UUID.randomUUID().toString()); try { util.save(obj); fail("Expected an exception"); } catch (Exception e) { } util.save(obj, new DynamoDBMapperConfig(new TableNameOverride("aws-java-sdk-util-crypto"))); try { util.load(TableOverrideTestClass.class, obj.getKey()); fail("Expected an exception"); } catch (Exception e) { } Object loaded = util.load( TableOverrideTestClass.class, obj.getKey(), new DynamoDBMapperConfig(TableNameOverride.withTableNamePrefix("aws-"))); assertEquals(loaded, obj); try { util.delete(obj); fail("Expected an exception"); } catch (Exception e) { } util.delete(obj, new DynamoDBMapperConfig(TableNameOverride.withTableNamePrefix("aws-"))); } private NumberAttributeTestClassExtended getUniqueObject() { NumberAttributeTestClassExtended obj = new NumberAttributeTestClassExtended(); obj.setKey(String.valueOf(startKey++)); obj.setBigDecimalAttribute(new BigDecimal(startKey++)); obj.setBigIntegerAttribute(new BigInteger("" + startKey++)); obj.setByteAttribute((byte) byteStart++); obj.setByteObjectAttribute(new Byte("" + byteStart++)); obj.setDoubleAttribute(new Double("" + start++)); obj.setDoubleObjectAttribute(new Double("" + start++)); obj.setFloatAttribute(new Float("" + start++)); obj.setFloatObjectAttribute(new Float("" + start++)); obj.setIntAttribute(new Integer("" + start++)); obj.setIntegerAttribute(new Integer("" + start++)); obj.setLongAttribute(new Long("" + start++)); obj.setLongObjectAttribute(new Long("" + start++)); obj.setDateAttribute(new Date(startKey++)); obj.setBooleanAttribute(start++ % 2 == 0); obj.setBooleanObjectAttribute(start++ % 2 == 0); obj.setExtraField("" + startKey++); Calendar cal = GregorianCalendar.getInstance(); cal.setTime(new Date(startKey++)); obj.setCalendarAttribute(cal); return obj; } private NumberAttributeTestClass copy(NumberAttributeTestClassExtended obj) { NumberAttributeTestClass copy = new NumberAttributeTestClass(); copy.setKey(obj.getKey()); copy.setBigDecimalAttribute(obj.getBigDecimalAttribute()); copy.setBigIntegerAttribute(obj.getBigIntegerAttribute()); copy.setByteAttribute(obj.getByteAttribute()); copy.setByteObjectAttribute(obj.getByteObjectAttribute()); copy.setDoubleAttribute(obj.getDoubleAttribute()); copy.setDoubleObjectAttribute(obj.getDoubleObjectAttribute()); copy.setFloatAttribute(obj.getFloatAttribute()); copy.setFloatObjectAttribute(obj.getFloatObjectAttribute()); copy.setIntAttribute(obj.getIntAttribute()); copy.setIntegerAttribute(obj.getIntegerAttribute()); copy.setLongAttribute(obj.getLongAttribute()); copy.setLongObjectAttribute(obj.getLongObjectAttribute()); copy.setDateAttribute(obj.getDateAttribute()); copy.setBooleanAttribute(obj.isBooleanAttribute()); copy.setBooleanObjectAttribute(obj.getBooleanObjectAttribute()); return copy; } @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public static final class NumberAttributeTestClassExtended extends NumberAttributeTestClass { private String extraField; public String getExtraField() { return extraField; } public void setExtraField(String extraField) { this.extraField = extraField; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((extraField == null) ? 0 : extraField.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; NumberAttributeTestClassExtended other = (NumberAttributeTestClassExtended) obj; if (extraField == null) { if (other.extraField != null) return false; } else if (!extraField.equals(other.extraField)) return false; return true; } } @DynamoDBTable(tableName = "java-sdk-util-crypto") // doesn't exist public static final class TableOverrideTestClass { private String key; private String otherField; @DynamoDBAutoGeneratedKey @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getOtherField() { return otherField; } public void setOtherField(String otherField) { this.otherField = otherField; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((otherField == null) ? 0 : otherField.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TableOverrideTestClass other = (TableOverrideTestClass) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (otherField == null) { if (other.otherField != null) return false; } else if (!otherField.equals(other.otherField)) return false; return true; } } }
4,973
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/VersionAttributeUpdateITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.fail; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBDeleteExpression; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.SaveBehavior; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBSaveExpression; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBVersionAttribute; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; import com.amazonaws.services.dynamodbv2.model.ConditionalOperator; import com.amazonaws.services.dynamodbv2.model.ExpectedAttributeValue; import com.amazonaws.util.ImmutableMapParameter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.annotations.Test; /** Tests updating version fields correctly */ public class VersionAttributeUpdateITCase extends DynamoDBMapperCryptoIntegrationTestBase { @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public static class VersionFieldBaseClass { protected String key; protected String normalStringAttribute; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @DynamoDBAttribute public String getNormalStringAttribute() { return normalStringAttribute; } public void setNormalStringAttribute(String normalStringAttribute) { this.normalStringAttribute = normalStringAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((normalStringAttribute == null) ? 0 : normalStringAttribute.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; VersionFieldBaseClass other = (VersionFieldBaseClass) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (normalStringAttribute == null) { if (other.normalStringAttribute != null) return false; } else if (!normalStringAttribute.equals(other.normalStringAttribute)) return false; return true; } } public static class StringVersionField extends VersionFieldBaseClass { private String version; @DynamoDBVersionAttribute public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; StringVersionField other = (StringVersionField) obj; if (version == null) { if (other.version != null) return false; } else if (!version.equals(other.version)) return false; return true; } } @Test(expectedExceptions = DynamoDBMappingException.class) public void testStringVersion() throws Exception { List<StringVersionField> objs = new ArrayList<StringVersionField>(); for (int i = 0; i < 5; i++) { StringVersionField obj = getUniqueObject(new StringVersionField()); objs.add(obj); } // Saving new objects with a null version field should populate it DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (StringVersionField obj : objs) { assertNull(obj.getVersion()); util.save(obj); assertNotNull(obj.getVersion()); assertEquals(obj, util.load(StringVersionField.class, obj.getKey())); } } public static class BigIntegerVersionField extends VersionFieldBaseClass { private BigInteger version; @DynamoDBVersionAttribute public BigInteger getVersion() { return version; } public void setVersion(BigInteger version) { this.version = version; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; BigIntegerVersionField other = (BigIntegerVersionField) obj; if (version == null) { if (other.version != null) return false; } else if (!version.equals(other.version)) return false; return true; } @Override public String toString() { return "BigIntegerVersionField [version=" + version + ", key=" + key + ", normalStringAttribute=" + normalStringAttribute + "]"; } } @Test public void testBigIntegerVersion() { List<BigIntegerVersionField> objs = new ArrayList<BigIntegerVersionField>(); for (int i = 0; i < 5; i++) { BigIntegerVersionField obj = getUniqueObject(new BigIntegerVersionField()); objs.add(obj); } // Saving new objects with a null version field should populate it DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (BigIntegerVersionField obj : objs) { assertNull(obj.getVersion()); util.save(obj); assertNotNull(obj.getVersion()); assertEquals(obj, util.load(BigIntegerVersionField.class, obj.getKey())); } for (BigIntegerVersionField obj : objs) { BigIntegerVersionField replacement = getUniqueObject(new BigIntegerVersionField()); replacement.setKey(obj.getKey()); replacement.setVersion(obj.getVersion()); util.save(replacement); // The version field should have changed in memory assertFalse(obj.getVersion().equals(replacement.getVersion())); BigIntegerVersionField loadedObject = util.load(BigIntegerVersionField.class, obj.getKey()); assertEquals(replacement, loadedObject); // Trying to update the object again should trigger a concurrency // exception try { util.save(obj); fail("Should have thrown an exception"); } catch (Exception expected) { } // Now try again overlaying the correct version number by using a saveExpression // this should not throw the conditional check failed exception try { DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression(); Map<String, ExpectedAttributeValue> expected = new HashMap<String, ExpectedAttributeValue>(); ExpectedAttributeValue expectedVersion = new ExpectedAttributeValue() .withValue( new AttributeValue() .withN(obj.getVersion().add(BigInteger.valueOf(1)).toString())); expected.put("version", expectedVersion); saveExpression.setExpected(expected); util.save(obj, saveExpression); } catch (Exception expected) { fail("This should succeed, version was updated."); } } } public static final class IntegerVersionField extends VersionFieldBaseClass { private Integer notCalledVersion; // Making sure that we can substitute attribute names as necessary @DynamoDBVersionAttribute(attributeName = "version") public Integer getNotCalledVersion() { return notCalledVersion; } public void setNotCalledVersion(Integer notCalledVersion) { this.notCalledVersion = notCalledVersion; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((notCalledVersion == null) ? 0 : notCalledVersion.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; IntegerVersionField other = (IntegerVersionField) obj; if (notCalledVersion == null) { if (other.notCalledVersion != null) return false; } else if (!notCalledVersion.equals(other.notCalledVersion)) return false; return true; } } @Test public void testIntegerVersion() { List<IntegerVersionField> objs = new ArrayList<IntegerVersionField>(); for (int i = 0; i < 5; i++) { IntegerVersionField obj = getUniqueObject(new IntegerVersionField()); objs.add(obj); } // Saving new objects with a null version field should populate it DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (IntegerVersionField obj : objs) { assertNull(obj.getNotCalledVersion()); util.save(obj); assertNotNull(obj.getNotCalledVersion()); assertEquals(obj, util.load(IntegerVersionField.class, obj.getKey())); } for (IntegerVersionField obj : objs) { IntegerVersionField replacement = getUniqueObject(new IntegerVersionField()); replacement.setKey(obj.getKey()); replacement.setNotCalledVersion(obj.getNotCalledVersion()); util.save(replacement); // The version field should have changed in memory assertFalse(obj.getNotCalledVersion().equals(replacement.getNotCalledVersion())); IntegerVersionField loadedObject = util.load(IntegerVersionField.class, obj.getKey()); assertEquals(replacement, loadedObject); // Trying to update the object again should trigger a concurrency // exception try { util.save(obj); fail("Should have thrown an exception"); } catch (Exception expected) { } // Trying to delete the object should also fail try { util.delete(obj); fail("Should have thrown an exception"); } catch (Exception expected) { } // But specifying CLOBBER will allow deletion util.save(obj, new DynamoDBMapperConfig(SaveBehavior.CLOBBER)); // Trying to delete with the wrong version should fail try { // version is now 2 in db, set object version to 3. obj.setNotCalledVersion(3); util.delete(obj); fail("Should have thrown an exception"); } catch (Exception expected) { } // Now try deleting again overlaying the correct version number by using a deleteExpression // this should not throw the conditional check failed exception try { DynamoDBDeleteExpression deleteExpression = new DynamoDBDeleteExpression(); Map<String, ExpectedAttributeValue> expected = new HashMap<String, ExpectedAttributeValue>(); ExpectedAttributeValue expectedVersion = new ExpectedAttributeValue() .withValue(new AttributeValue().withN("2")); // version is still 2 in db expected.put("version", expectedVersion); deleteExpression.setExpected(expected); util.delete(obj, deleteExpression); } catch (Exception expected) { fail("This should succeed, version was updated."); } } } /** * Tests providing additional expected conditions when saving and deleting item with versioned * fields. */ @Test public void testVersionedAttributeWithUserProvidedExpectedConditions() { DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); IntegerVersionField versionedObject = getUniqueObject(new IntegerVersionField()); assertNull(versionedObject.getNotCalledVersion()); // Add additional expected conditions via DynamoDBSaveExpression. // Expected conditions joined by AND are compatible with the conditions // for auto-generated keys. DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression() .withExpected( Collections.singletonMap("otherAttribute", new ExpectedAttributeValue(false))) .withConditionalOperator(ConditionalOperator.AND); // The save should succeed since the user provided conditions are joined by AND. mapper.save(versionedObject, saveExpression); // The version field should be populated assertNotNull(versionedObject.getNotCalledVersion()); IntegerVersionField other = mapper.load(IntegerVersionField.class, versionedObject.getKey()); assertEquals(other, versionedObject); // delete should also work DynamoDBDeleteExpression deleteExpression = new DynamoDBDeleteExpression() .withExpected( Collections.singletonMap("otherAttribute", new ExpectedAttributeValue(false))) .withConditionalOperator(ConditionalOperator.AND); mapper.delete(versionedObject, deleteExpression); // Change the conditional operator to OR. // IllegalArgumentException is expected since the additional expected // conditions cannot be joined with the conditions for auto-generated // keys. saveExpression.setConditionalOperator(ConditionalOperator.OR); deleteExpression.setConditionalOperator(ConditionalOperator.OR); try { mapper.save(getUniqueObject(new IntegerVersionField()), saveExpression); } catch (IllegalArgumentException expected) { } try { mapper.delete(getUniqueObject(new IntegerVersionField()), deleteExpression); } catch (IllegalArgumentException expected) { } // User-provided OR conditions should work if they completely override // the generated conditions for the version field. Map<String, ExpectedAttributeValue> goodConditions = ImmutableMapParameter.of( "otherAttribute", new ExpectedAttributeValue(false), "version", new ExpectedAttributeValue(false)); Map<String, ExpectedAttributeValue> badConditions = ImmutableMapParameter.of( "otherAttribute", new ExpectedAttributeValue(new AttributeValue("non-existent-value")), "version", new ExpectedAttributeValue(new AttributeValue().withN("-1"))); IntegerVersionField newObj = getUniqueObject(new IntegerVersionField()); saveExpression.setExpected(badConditions); try { mapper.save(newObj, saveExpression); } catch (ConditionalCheckFailedException expected) { } saveExpression.setExpected(goodConditions); mapper.save(newObj, saveExpression); deleteExpression.setExpected(badConditions); try { mapper.delete(newObj, deleteExpression); } catch (ConditionalCheckFailedException expected) { } deleteExpression.setExpected(goodConditions); mapper.delete(newObj, deleteExpression); } public static final class ByteVersionField extends VersionFieldBaseClass { private Byte version; @DynamoDBVersionAttribute public Byte getVersion() { return version; } public void setVersion(Byte version) { this.version = version; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; ByteVersionField other = (ByteVersionField) obj; if (version == null) { if (other.version != null) return false; } else if (!version.equals(other.version)) return false; return true; } } @Test public void testByteVersion() { List<ByteVersionField> objs = new ArrayList<ByteVersionField>(); for (int i = 0; i < 5; i++) { ByteVersionField obj = getUniqueObject(new ByteVersionField()); objs.add(obj); } // Saving new objects with a null version field should populate it DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (ByteVersionField obj : objs) { assertNull(obj.getVersion()); util.save(obj); assertNotNull(obj.getVersion()); assertEquals(obj, util.load(ByteVersionField.class, obj.getKey())); } for (ByteVersionField obj : objs) { ByteVersionField replacement = getUniqueObject(new ByteVersionField()); replacement.setKey(obj.getKey()); replacement.setVersion(obj.getVersion()); util.save(replacement); // The version field should have changed in memory assertFalse(obj.getVersion().equals(replacement.getVersion())); ByteVersionField loadedObject = util.load(ByteVersionField.class, obj.getKey()); assertEquals(replacement, loadedObject); // Trying to update the object again should trigger a concurrency // exception try { util.save(obj); fail("Should have thrown an exception"); } catch (Exception expected) { } } } public static final class LongVersionField extends VersionFieldBaseClass { private Long version; @DynamoDBVersionAttribute public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; LongVersionField other = (LongVersionField) obj; if (version == null) { if (other.version != null) return false; } else if (!version.equals(other.version)) return false; return true; } } @Test public void testLongVersion() { List<LongVersionField> objs = new ArrayList<LongVersionField>(); for (int i = 0; i < 5; i++) { LongVersionField obj = getUniqueObject(new LongVersionField()); objs.add(obj); } // Saving new objects with a null version field should populate it DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (LongVersionField obj : objs) { assertNull(obj.getVersion()); util.save(obj); assertNotNull(obj.getVersion()); assertEquals(obj, util.load(LongVersionField.class, obj.getKey())); } for (LongVersionField obj : objs) { LongVersionField replacement = getUniqueObject(new LongVersionField()); replacement.setKey(obj.getKey()); replacement.setVersion(obj.getVersion()); util.save(replacement); // The version field should have changed in memory assertFalse(obj.getVersion().equals(replacement.getVersion())); LongVersionField loadedObject = util.load(LongVersionField.class, obj.getKey()); assertEquals(replacement, loadedObject); // Trying to update the object again should trigger a concurrency // exception try { util.save(obj); fail("Should have thrown an exception"); } catch (Exception expected) { } } } private <T extends VersionFieldBaseClass> T getUniqueObject(T obj) { obj.setKey("" + startKey++); obj.setNormalStringAttribute("" + startKey++); return obj; } }
4,974
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/StringSetAttributesITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionFlags; import com.amazonaws.services.dynamodbv2.mapper.encryption.StringSetAttributeTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestEncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Tests string set attributes */ public class StringSetAttributesITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static final String ORIGINAL_NAME_ATTRIBUTE = "originalName"; private static final String STRING_SET_ATTRIBUTE = "stringSetAttribute"; private static final String EXTRA_ATTRIBUTE = "extra"; private static final List<Map<String, AttributeValue>> attrs = new LinkedList<Map<String, AttributeValue>>(); // Test data static { for (int i = 0; i < 5; i++) { Map<String, AttributeValue> attr = new HashMap<String, AttributeValue>(); attr.put(KEY_NAME, new AttributeValue().withS("" + startKey++)); attr.put( STRING_SET_ATTRIBUTE, new AttributeValue().withSS("" + ++startKey, "" + ++startKey, "" + ++startKey)); attr.put( ORIGINAL_NAME_ATTRIBUTE, new AttributeValue().withSS("" + ++startKey, "" + ++startKey, "" + ++startKey)); attr.put( EXTRA_ATTRIBUTE, new AttributeValue().withSS("" + ++startKey, "" + ++startKey, "" + ++startKey)); attrs.add(attr); } } ; @BeforeClass public static void setUp() throws Exception { DynamoDBMapperCryptoIntegrationTestBase.setUp(); DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(new TestEncryptionMaterialsProvider()); EncryptionContext context = new EncryptionContext.Builder().withHashKeyName(KEY_NAME).withTableName(TABLE_NAME).build(); // Insert the data for (Map<String, AttributeValue> attr : attrs) { Map<String, Set<EncryptionFlags>> flags = encryptor.allEncryptionFlagsExcept(attr, KEY_NAME); flags.remove(EXTRA_ATTRIBUTE); // exclude "extra" entirely since // it's not defined in the // StringSetAttributeTestClass pojo attr = encryptor.encryptRecord(attr, flags, context); dynamo.putItem(new PutItemRequest(TABLE_NAME, attr)); } } @Test public void testLoad() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (Map<String, AttributeValue> attr : attrs) { StringSetAttributeTestClass x = util.load(StringSetAttributeTestClass.class, attr.get(KEY_NAME).getS()); assertEquals(x.getKey(), attr.get(KEY_NAME).getS()); assertSetsEqual(x.getStringSetAttribute(), toSet(attr.get(STRING_SET_ATTRIBUTE).getSS())); assertSetsEqual( x.getStringSetAttributeRenamed(), toSet(attr.get(ORIGINAL_NAME_ATTRIBUTE).getSS())); } } /** Tests saving only some attributes of an object. */ @Test public void testIncompleteObject() { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); StringSetAttributeTestClass obj = getUniqueObject(); obj.setStringSetAttribute(null); util.save(obj); assertEquals(obj, util.load(StringSetAttributeTestClass.class, obj.getKey())); obj.setStringSetAttributeRenamed(null); util.save(obj); assertEquals(obj, util.load(StringSetAttributeTestClass.class, obj.getKey())); } @Test public void testSave() throws Exception { List<StringSetAttributeTestClass> objs = new ArrayList<StringSetAttributeTestClass>(); for (int i = 0; i < 5; i++) { StringSetAttributeTestClass obj = getUniqueObject(); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (StringSetAttributeTestClass obj : objs) { util.save(obj); } for (StringSetAttributeTestClass obj : objs) { StringSetAttributeTestClass loaded = util.load(StringSetAttributeTestClass.class, obj.getKey()); assertEquals(obj, loaded); } } @Test public void testUpdate() throws Exception { List<StringSetAttributeTestClass> objs = new ArrayList<StringSetAttributeTestClass>(); for (int i = 0; i < 5; i++) { StringSetAttributeTestClass obj = getUniqueObject(); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (StringSetAttributeTestClass obj : objs) { util.save(obj); } for (StringSetAttributeTestClass obj : objs) { StringSetAttributeTestClass replacement = getUniqueObject(); replacement.setKey(obj.getKey()); util.save(replacement); assertEquals(replacement, util.load(StringSetAttributeTestClass.class, obj.getKey())); } } private StringSetAttributeTestClass getUniqueObject() { StringSetAttributeTestClass obj = new StringSetAttributeTestClass(); obj.setKey(String.valueOf(startKey++)); obj.setStringSetAttribute( toSet(String.valueOf(startKey++), String.valueOf(startKey++), String.valueOf(startKey++))); obj.setStringSetAttributeRenamed( toSet(String.valueOf(startKey++), String.valueOf(startKey++), String.valueOf(startKey++))); return obj; } }
4,975
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/ComplexTypeITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMarshalling; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.JsonMarshaller; import com.amazonaws.services.dynamodbv2.mapper.encryption.NumberAttributeTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.MappingJsonFactory; import java.io.StringReader; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import org.testng.annotations.Test; /** Tests of the configuration object */ public class ComplexTypeITCase extends DynamoDBMapperCryptoIntegrationTestBase { // We don't start with the current system millis like other tests because // it's out of the range of some data types private static int start = 1; private static int byteStart = -127; @Test public void testComplexTypes() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); ComplexClass obj = getUniqueObject(); util.save(obj); ComplexClass loaded = util.load(ComplexClass.class, obj.getKey()); assertEquals(obj, loaded); } private ComplexClass getUniqueObject() { ComplexClass obj = new ComplexClass(); obj.setKey(String.valueOf(startKey++)); obj.setBigDecimalAttribute(new BigDecimal(startKey++)); obj.setBigIntegerAttribute(new BigInteger("" + startKey++)); obj.setByteAttribute((byte) byteStart++); obj.setByteObjectAttribute(new Byte("" + byteStart++)); obj.setDoubleAttribute(new Double("" + start++)); obj.setDoubleObjectAttribute(new Double("" + start++)); obj.setFloatAttribute(new Float("" + start++)); obj.setFloatObjectAttribute(new Float("" + start++)); obj.setIntAttribute(new Integer("" + start++)); obj.setIntegerAttribute(new Integer("" + start++)); obj.setLongAttribute(new Long("" + start++)); obj.setLongObjectAttribute(new Long("" + start++)); obj.setDateAttribute(new Date(startKey++)); obj.setBooleanAttribute(start++ % 2 == 0); obj.setBooleanObjectAttribute(start++ % 2 == 0); obj.setExtraField("" + startKey++); Calendar cal = GregorianCalendar.getInstance(); cal.setTime(new Date(startKey++)); obj.setCalendarAttribute(cal); obj.setComplexNestedType( new ComplexNestedType( "" + start++, start++, new ComplexNestedType("" + start++, start++, null))); List<ComplexNestedType> complexTypes = new ArrayList<ComplexTypeITCase.ComplexNestedType>(); complexTypes.add( new ComplexNestedType( "" + start++, start++, new ComplexNestedType("" + start++, start++, null))); complexTypes.add( new ComplexNestedType( "" + start++, start++, new ComplexNestedType("" + start++, start++, null))); complexTypes.add( new ComplexNestedType( "" + start++, start++, new ComplexNestedType("" + start++, start++, null))); obj.setComplexNestedTypeList(complexTypes); return obj; } /* * Type with a complex nested field for working with marshallers */ public static final class ComplexNestedTypeMarshaller extends JsonMarshaller<ComplexNestedType> {} public static final class ComplexNestedListTypeMarshaller extends JsonMarshaller<List<ComplexNestedType>> { /* (non-Javadoc) * @see com.amazonaws.services.dynamodbv2.datamodeling.JsonMarshaller#unmarshall(java.lang.Class, java.lang.String) */ @Override public List<ComplexNestedType> unmarshall(Class<List<ComplexNestedType>> clazz, String obj) { try { JsonFactory jsonFactory = new MappingJsonFactory(); JsonParser jsonParser = jsonFactory.createJsonParser(new StringReader(obj)); return jsonParser.readValueAs(new TypeReference<List<ComplexNestedType>>() {}); } catch (Exception e) { throw new RuntimeException(e); } } } @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public static final class ComplexClass extends NumberAttributeTestClass { private String extraField; private ComplexNestedType complexNestedType; private List<ComplexNestedType> complexNestedTypeList; @DynamoDBMarshalling(marshallerClass = ComplexNestedTypeMarshaller.class) public ComplexNestedType getComplexNestedType() { return complexNestedType; } public void setComplexNestedType(ComplexNestedType complexNestedType) { this.complexNestedType = complexNestedType; } @DynamoDBMarshalling(marshallerClass = ComplexNestedListTypeMarshaller.class) public List<ComplexNestedType> getComplexNestedTypeList() { return complexNestedTypeList; } public void setComplexNestedTypeList(List<ComplexNestedType> complexNestedTypeList) { this.complexNestedTypeList = complexNestedTypeList; } public String getExtraField() { return extraField; } public void setExtraField(String extraField) { this.extraField = extraField; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((complexNestedType == null) ? 0 : complexNestedType.hashCode()); result = prime * result + ((complexNestedTypeList == null) ? 0 : complexNestedTypeList.hashCode()); result = prime * result + ((extraField == null) ? 0 : extraField.hashCode()); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; ComplexClass other = (ComplexClass) obj; if (complexNestedType == null) { if (other.complexNestedType != null) return false; } else if (!complexNestedType.equals(other.complexNestedType)) return false; if (complexNestedTypeList == null) { if (other.complexNestedTypeList != null) return false; } else if (!complexNestedTypeList.equals(other.complexNestedTypeList)) return false; if (extraField == null) { if (other.extraField != null) return false; } else if (!extraField.equals(other.extraField)) return false; return true; } } public static final class ComplexNestedType { private String stringValue; private Integer intValue; private ComplexNestedType nestedType; public ComplexNestedType() {} public ComplexNestedType(String stringValue, Integer intValue, ComplexNestedType nestedType) { super(); this.stringValue = stringValue; this.intValue = intValue; this.nestedType = nestedType; } public String getStringValue() { return stringValue; } public void setStringValue(String stringValue) { this.stringValue = stringValue; } public Integer getIntValue() { return intValue; } public void setIntValue(Integer intValue) { this.intValue = intValue; } public ComplexNestedType getNestedType() { return nestedType; } public void setNestedType(ComplexNestedType nestedType) { this.nestedType = nestedType; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((intValue == null) ? 0 : intValue.hashCode()); result = prime * result + ((nestedType == null) ? 0 : nestedType.hashCode()); result = prime * result + ((stringValue == null) ? 0 : stringValue.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ComplexNestedType other = (ComplexNestedType) obj; if (intValue == null) { if (other.intValue != null) return false; } else if (!intValue.equals(other.intValue)) return false; if (nestedType == null) { if (other.nestedType != null) return false; } else if (!nestedType.equals(other.nestedType)) return false; if (stringValue == null) { if (other.stringValue != null) return false; } else if (!stringValue.equals(other.stringValue)) return false; return true; } } @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public static final class ComplexKey { private ComplexNestedType key; private String otherAttribute; @DynamoDBHashKey @DynamoDBMarshalling(marshallerClass = ComplexNestedTypeMarshaller.class) public ComplexNestedType getKey() { return key; } public void setKey(ComplexNestedType key) { this.key = key; } public String getOtherAttribute() { return otherAttribute; } public void setOtherAttribute(String otherAttribute) { this.otherAttribute = otherAttribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((otherAttribute == null) ? 0 : otherAttribute.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ComplexKey other = (ComplexKey) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (otherAttribute == null) { if (other.otherAttribute != null) return false; } else if (!otherAttribute.equals(other.otherAttribute)) return false; return true; } } /** Tests using a complex type for a (string) key */ @Test public void testComplexKey() throws Exception { ComplexKey obj = new ComplexKey(); ComplexNestedType key = new ComplexNestedType(); key.setIntValue(start++); key.setStringValue("" + start++); obj.setKey(key); obj.setOtherAttribute("" + start++); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.save(obj); ComplexKey loaded = mapper.load(ComplexKey.class, obj.getKey()); assertEquals(obj, loaded); } }
4,976
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/mapper/integration/BatchWriteITCase.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.FailedBatch; import com.amazonaws.services.dynamodbv2.mapper.encryption.BinaryAttributeByteBufferTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.NoSuchTableTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.NumberSetAttributeTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.RangeKeyTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Tests batch write calls */ public class BatchWriteITCase extends DynamoDBMapperCryptoIntegrationTestBase { // We don't start with the current system millis like other tests because // it's out of the range of some data types private static int start = 1; private static int byteStart = 1; private static int startKeyDebug = 1; @BeforeClass public static void setUp() throws Exception { setUpTableWithRangeAttribute(); } @Test public void testBatchSave() throws Exception { List<NumberSetAttributeTestClass> objs = new ArrayList<NumberSetAttributeTestClass>(); for (int i = 0; i < 40; i++) { NumberSetAttributeTestClass obj = getUniqueNumericObject(); objs.add(obj); } DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); List<FailedBatch> failedBatches = mapper.batchSave(objs); assertTrue(0 == failedBatches.size()); for (NumberSetAttributeTestClass obj : objs) { NumberSetAttributeTestClass loaded = mapper.load(NumberSetAttributeTestClass.class, obj.getKey()); assertEquals(obj, loaded); } } @Test public void testBatchSaveAsArray() throws Exception { List<NumberSetAttributeTestClass> objs = new ArrayList<NumberSetAttributeTestClass>(); for (int i = 0; i < 40; i++) { NumberSetAttributeTestClass obj = getUniqueNumericObject(); objs.add(obj); } DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); NumberSetAttributeTestClass[] objsArray = objs.toArray(new NumberSetAttributeTestClass[objs.size()]); mapper.batchSave((Object[]) objsArray); for (NumberSetAttributeTestClass obj : objs) { NumberSetAttributeTestClass loaded = mapper.load(NumberSetAttributeTestClass.class, obj.getKey()); assertEquals(obj, loaded); } } @Test public void testBatchSaveAsListFromArray() throws Exception { List<NumberSetAttributeTestClass> objs = new ArrayList<NumberSetAttributeTestClass>(); for (int i = 0; i < 40; i++) { NumberSetAttributeTestClass obj = getUniqueNumericObject(); objs.add(obj); } DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); NumberSetAttributeTestClass[] objsArray = objs.toArray(new NumberSetAttributeTestClass[objs.size()]); mapper.batchSave(Arrays.asList(objsArray)); for (NumberSetAttributeTestClass obj : objs) { NumberSetAttributeTestClass loaded = mapper.load(NumberSetAttributeTestClass.class, obj.getKey()); assertEquals(obj, loaded); } } @Test public void testBatchDelete() throws Exception { List<NumberSetAttributeTestClass> objs = new ArrayList<NumberSetAttributeTestClass>(); for (int i = 0; i < 40; i++) { NumberSetAttributeTestClass obj = getUniqueNumericObject(); objs.add(obj); } DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.batchSave(objs); for (NumberSetAttributeTestClass obj : objs) { NumberSetAttributeTestClass loaded = mapper.load(NumberSetAttributeTestClass.class, obj.getKey()); assertEquals(obj, loaded); } // Delete the odd ones int i = 0; List<NumberSetAttributeTestClass> toDelete = new LinkedList<NumberSetAttributeTestClass>(); for (NumberSetAttributeTestClass obj : objs) { if (i++ % 2 == 0) toDelete.add(obj); } mapper.batchDelete(toDelete); i = 0; for (NumberSetAttributeTestClass obj : objs) { NumberSetAttributeTestClass loaded = mapper.load(NumberSetAttributeTestClass.class, obj.getKey()); if (i++ % 2 == 0) { assertNull(loaded); } else { assertEquals(obj, loaded); } } } @Test public void testBatchSaveAndDelete() throws Exception { List<NumberSetAttributeTestClass> objs = new ArrayList<NumberSetAttributeTestClass>(); for (int i = 0; i < 40; i++) { NumberSetAttributeTestClass obj = getUniqueNumericObject(); objs.add(obj); } DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.batchSave(objs); for (NumberSetAttributeTestClass obj : objs) { NumberSetAttributeTestClass loaded = mapper.load(NumberSetAttributeTestClass.class, obj.getKey()); assertEquals(obj, loaded); } // Delete the odd ones int i = 0; List<NumberSetAttributeTestClass> toDelete = new LinkedList<NumberSetAttributeTestClass>(); for (NumberSetAttributeTestClass obj : objs) { if (i++ % 2 == 0) toDelete.add(obj); } // And add a bunch of new ones List<NumberSetAttributeTestClass> toSave = new LinkedList<NumberSetAttributeTestClass>(); for (i = 0; i < 50; i++) { NumberSetAttributeTestClass obj = getUniqueNumericObject(); toSave.add(obj); } mapper.batchWrite(toSave, toDelete); i = 0; for (NumberSetAttributeTestClass obj : objs) { NumberSetAttributeTestClass loaded = mapper.load(NumberSetAttributeTestClass.class, obj.getKey()); if (i++ % 2 == 0) { assertNull(loaded); } else { assertEquals(obj, loaded); } } for (NumberSetAttributeTestClass obj : toSave) { NumberSetAttributeTestClass loaded = mapper.load(NumberSetAttributeTestClass.class, obj.getKey()); assertEquals(obj, loaded); } } @Test public void testMultipleTables() throws Exception { List<Object> objs = new ArrayList<Object>(); int numItems = 10; for (int i = 0; i < numItems; i++) { NumberSetAttributeTestClass obj = getUniqueNumericObject(); objs.add(obj); } for (int i = 0; i < numItems; i++) { RangeKeyTestClass obj = getUniqueRangeKeyObject(); objs.add(obj); } Collections.shuffle(objs); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); List<FailedBatch> failedBatches = mapper.batchSave(objs); assertTrue(failedBatches.size() == 0); for (Object obj : objs) { Object loaded = null; if (obj instanceof NumberSetAttributeTestClass) { loaded = mapper.load( NumberSetAttributeTestClass.class, ((NumberSetAttributeTestClass) obj).getKey()); } else if (obj instanceof RangeKeyTestClass) { loaded = mapper.load( RangeKeyTestClass.class, ((RangeKeyTestClass) obj).getKey(), ((RangeKeyTestClass) obj).getRangeKey()); } else { fail(); } assertEquals(obj, loaded); } // Delete the odd ones int i = 0; List<Object> toDelete = new LinkedList<Object>(); for (Object obj : objs) { if (i++ % 2 == 0) toDelete.add(obj); } // And add a bunch of new ones List<Object> toSave = new LinkedList<Object>(); for (i = 0; i < numItems; i++) { if (i % 2 == 0) toSave.add(getUniqueNumericObject()); else toSave.add(getUniqueRangeKeyObject()); } failedBatches = mapper.batchWrite(toSave, toDelete); assertTrue(0 == failedBatches.size()); i = 0; for (Object obj : objs) { Object loaded = null; if (obj instanceof NumberSetAttributeTestClass) { loaded = mapper.load( NumberSetAttributeTestClass.class, ((NumberSetAttributeTestClass) obj).getKey()); } else if (obj instanceof RangeKeyTestClass) { loaded = mapper.load( RangeKeyTestClass.class, ((RangeKeyTestClass) obj).getKey(), ((RangeKeyTestClass) obj).getRangeKey()); } else { fail(); } if (i++ % 2 == 0) { assertNull(loaded); } else { assertEquals(obj, loaded); } } for (Object obj : toSave) { Object loaded = null; if (obj instanceof NumberSetAttributeTestClass) { loaded = mapper.load( NumberSetAttributeTestClass.class, ((NumberSetAttributeTestClass) obj).getKey()); } else if (obj instanceof RangeKeyTestClass) { loaded = mapper.load( RangeKeyTestClass.class, ((RangeKeyTestClass) obj).getKey(), ((RangeKeyTestClass) obj).getRangeKey()); } else { fail(); } assertEquals(obj, loaded); } } /** Test whether it finish processing all the items even if the first batch is failed. */ @Test public void testErrorHandling() { List<Object> objs = new ArrayList<Object>(); int numItems = 25; for (int i = 0; i < numItems; i++) { NoSuchTableTestClass obj = getuniqueBadObject(); objs.add(obj); } for (int i = 0; i < numItems; i++) { RangeKeyTestClass obj = getUniqueRangeKeyObject(); objs.add(obj); } DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); // The failed batch List<FailedBatch> failedBatches = mapper.batchSave(objs); assertTrue(1 == failedBatches.size()); assertTrue(numItems == failedBatches.get(0).getUnprocessedItems().get("tableNotExist").size()); // The second batch succeeds, get them back for (Object obj : objs.subList(25, 50)) { RangeKeyTestClass loaded = mapper.load( RangeKeyTestClass.class, ((RangeKeyTestClass) obj).getKey(), ((RangeKeyTestClass) obj).getRangeKey()); assertEquals(obj, loaded); } } /** Test whether we can split large batch request into small pieces. */ @Test public void testLargeRequestEntity() { // The total batch size is beyond 1M, test whether our client can split // the batch correctly List<BinaryAttributeByteBufferTestClass> objs = new ArrayList<BinaryAttributeByteBufferTestClass>(); int numItems = 25; final int CONTENT_LENGTH = 1024 * 25; for (int i = 0; i < numItems; i++) { BinaryAttributeByteBufferTestClass obj = getUniqueByteBufferObject(CONTENT_LENGTH); objs.add(obj); } DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); List<FailedBatch> failedBatches = mapper.batchSave(objs); assertEquals(failedBatches.size(), 0); // Get these objects back for (BinaryAttributeByteBufferTestClass obj : objs) { BinaryAttributeByteBufferTestClass loaded = mapper.load(BinaryAttributeByteBufferTestClass.class, obj.getKey()); assertEquals(obj, loaded); } // There are three super large item together with some small ones, test // whether we can successfully // save these small items. objs.clear(); numItems = 10; List<BinaryAttributeByteBufferTestClass> largeObjs = new ArrayList<BinaryAttributeByteBufferTestClass>(); // Put three super large item(beyond 64k) largeObjs.add(getUniqueByteBufferObject(CONTENT_LENGTH * 30)); largeObjs.add(getUniqueByteBufferObject(CONTENT_LENGTH * 30)); largeObjs.add(getUniqueByteBufferObject(CONTENT_LENGTH * 30)); for (int i = 0; i < numItems - 3; i++) { BinaryAttributeByteBufferTestClass obj = getUniqueByteBufferObject(CONTENT_LENGTH / 25); objs.add(obj); } objs.addAll(largeObjs); failedBatches = mapper.batchSave(objs); final int size = failedBatches.size(); if (DEBUG) System.err.println("failedBatches.size()=" + size); assertThat(size, equalTo(1)); objs.removeAll(largeObjs); mapper.batchSave(objs); // Get these small objects back for (BinaryAttributeByteBufferTestClass obj : objs) { BinaryAttributeByteBufferTestClass loaded = mapper.load(BinaryAttributeByteBufferTestClass.class, obj.getKey()); assertEquals(obj, loaded); } // The whole batch is super large objects, none of them will be // processed largeObjs.clear(); for (int i = 0; i < 5; i++) { BinaryAttributeByteBufferTestClass obj = getUniqueByteBufferObject(CONTENT_LENGTH * 30); largeObjs.add(obj); } if (DEBUG) System.err.println("failedBatches.size()=" + size); assertThat(failedBatches.size(), equalTo(1)); } private NoSuchTableTestClass getuniqueBadObject() { NoSuchTableTestClass obj = new NoSuchTableTestClass(); obj.setKey(String.valueOf(startKeyDebug++)); return obj; } private NumberSetAttributeTestClass getUniqueNumericObject() { NumberSetAttributeTestClass obj = new NumberSetAttributeTestClass(); obj.setKey(String.valueOf(startKeyDebug++)); obj.setBigDecimalAttribute( toSet(new BigDecimal(startKey++), new BigDecimal(startKey++), new BigDecimal(startKey++))); obj.setBigIntegerAttribute( toSet( new BigInteger("" + startKey++), new BigInteger("" + startKey++), new BigInteger("" + startKey++))); obj.setByteObjectAttribute( toSet(new Byte(nextByte()), new Byte(nextByte()), new Byte(nextByte()))); obj.setDoubleObjectAttribute( toSet(new Double("" + start++), new Double("" + start++), new Double("" + start++))); obj.setFloatObjectAttribute( toSet(new Float("" + start++), new Float("" + start++), new Float("" + start++))); obj.setIntegerAttribute( toSet(new Integer("" + start++), new Integer("" + start++), new Integer("" + start++))); obj.setLongObjectAttribute( toSet(new Long("" + start++), new Long("" + start++), new Long("" + start++))); obj.setBooleanAttribute(toSet(true, false)); obj.setDateAttribute(toSet(new Date(startKey++), new Date(startKey++), new Date(startKey++))); Set<Calendar> cals = new HashSet<Calendar>(); for (Date d : obj.getDateAttribute()) { Calendar cal = GregorianCalendar.getInstance(); cal.setTime(d); cals.add(cal); } obj.setCalendarAttribute(toSet(cals)); return obj; } private RangeKeyTestClass getUniqueRangeKeyObject() { RangeKeyTestClass obj = new RangeKeyTestClass(); obj.setKey(startKey++); obj.setIntegerAttribute(toSet(start++, start++, start++)); obj.setBigDecimalAttribute(new BigDecimal(startKey++)); obj.setRangeKey(start++); obj.setStringAttribute("" + startKey++); obj.setStringSetAttribute(toSet("" + startKey++, "" + startKey++, "" + startKey++)); return obj; } private String nextByte() { return "" + byteStart++ % Byte.MAX_VALUE; } }
4,977
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/AttributeValueMatcher.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import java.math.BigDecimal; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; public class AttributeValueMatcher extends BaseMatcher<AttributeValue> { private final AttributeValue expected; private final boolean invert; public static AttributeValueMatcher invert(AttributeValue expected) { return new AttributeValueMatcher(expected, true); } public static AttributeValueMatcher match(AttributeValue expected) { return new AttributeValueMatcher(expected, false); } public AttributeValueMatcher(AttributeValue expected, boolean invert) { this.expected = expected; this.invert = invert; } @Override public boolean matches(Object item) { AttributeValue other = (AttributeValue) item; return invert ^ attrEquals(expected, other); } @Override public void describeTo(Description description) {} public static boolean attrEquals(AttributeValue e, AttributeValue a) { if (!isEqual(e.getB(), a.getB()) || !isNumberEqual(e.getN(), a.getN()) || !isEqual(e.getS(), a.getS()) || !isEqual(e.getBS(), a.getBS()) || !isNumberEqual(e.getNS(), a.getNS()) || !isEqual(e.getSS(), a.getSS())) { return false; } return true; } private static boolean isNumberEqual(String o1, String o2) { if (o1 == null ^ o2 == null) { return false; } if (o1 == o2) return true; BigDecimal d1 = new BigDecimal(o1); BigDecimal d2 = new BigDecimal(o2); return d1.equals(d2); } private static boolean isEqual(Object o1, Object o2) { if (o1 == null ^ o2 == null) { return false; } if (o1 == o2) return true; return o1.equals(o2); } private static boolean isNumberEqual(Collection<String> c1, Collection<String> c2) { if (c1 == null ^ c2 == null) { return false; } if (c1 != null) { Set<BigDecimal> s1 = new HashSet<BigDecimal>(); Set<BigDecimal> s2 = new HashSet<BigDecimal>(); for (String s : c1) { s1.add(new BigDecimal(s)); } for (String s : c2) { s2.add(new BigDecimal(s)); } if (!s1.equals(s2)) { return false; } } return true; } private static <T> boolean isEqual(Collection<T> c1, Collection<T> c2) { if (c1 == null ^ c2 == null) { return false; } if (c1 != null) { Set<T> s1 = new HashSet<T>(c1); Set<T> s2 = new HashSet<T>(c2); if (!s1.equals(s2)) { return false; } } return true; } }
4,978
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/FakeKMS.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.regions.Region; import com.amazonaws.services.kms.AbstractAWSKMS; import com.amazonaws.services.kms.model.CreateKeyRequest; import com.amazonaws.services.kms.model.CreateKeyResult; import com.amazonaws.services.kms.model.DecryptRequest; import com.amazonaws.services.kms.model.DecryptResult; import com.amazonaws.services.kms.model.EncryptRequest; import com.amazonaws.services.kms.model.EncryptResult; import com.amazonaws.services.kms.model.GenerateDataKeyRequest; import com.amazonaws.services.kms.model.GenerateDataKeyResult; import com.amazonaws.services.kms.model.GenerateDataKeyWithoutPlaintextRequest; import com.amazonaws.services.kms.model.GenerateDataKeyWithoutPlaintextResult; import com.amazonaws.services.kms.model.InvalidCiphertextException; import com.amazonaws.services.kms.model.KeyMetadata; import com.amazonaws.services.kms.model.KeyUsageType; import java.nio.ByteBuffer; import java.security.SecureRandom; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class FakeKMS extends AbstractAWSKMS { private static final SecureRandom rnd = new SecureRandom(); private static final String ACCOUNT_ID = "01234567890"; private final Map<DecryptMapKey, DecryptResult> results_ = new HashMap<>(); @Override public CreateKeyResult createKey() throws AmazonServiceException, AmazonClientException { return createKey(new CreateKeyRequest()); } @Override public CreateKeyResult createKey(CreateKeyRequest req) throws AmazonServiceException, AmazonClientException { String keyId = UUID.randomUUID().toString(); String arn = "arn:aws:testing:kms:" + ACCOUNT_ID + ":key/" + keyId; CreateKeyResult result = new CreateKeyResult(); result.setKeyMetadata( new KeyMetadata() .withAWSAccountId(ACCOUNT_ID) .withCreationDate(new Date()) .withDescription(req.getDescription()) .withEnabled(true) .withKeyId(keyId) .withKeyUsage(KeyUsageType.ENCRYPT_DECRYPT) .withArn(arn)); return result; } @Override public DecryptResult decrypt(DecryptRequest req) throws AmazonServiceException, AmazonClientException { DecryptResult result = results_.get(new DecryptMapKey(req)); if (result != null) { return result; } else { throw new InvalidCiphertextException("Invalid Ciphertext"); } } @Override public EncryptResult encrypt(EncryptRequest req) throws AmazonServiceException, AmazonClientException { final byte[] cipherText = new byte[512]; rnd.nextBytes(cipherText); DecryptResult dec = new DecryptResult(); dec.withKeyId(req.getKeyId()).withPlaintext(req.getPlaintext().asReadOnlyBuffer()); ByteBuffer ctBuff = ByteBuffer.wrap(cipherText); results_.put(new DecryptMapKey(ctBuff, req.getEncryptionContext()), dec); return new EncryptResult().withCiphertextBlob(ctBuff).withKeyId(req.getKeyId()); } @Override public GenerateDataKeyResult generateDataKey(GenerateDataKeyRequest req) throws AmazonServiceException, AmazonClientException { byte[] pt; if (req.getKeySpec() != null) { if (req.getKeySpec().contains("256")) { pt = new byte[32]; } else if (req.getKeySpec().contains("128")) { pt = new byte[16]; } else { throw new UnsupportedOperationException(); } } else { pt = new byte[req.getNumberOfBytes()]; } rnd.nextBytes(pt); ByteBuffer ptBuff = ByteBuffer.wrap(pt); EncryptResult encryptResult = encrypt( new EncryptRequest() .withKeyId(req.getKeyId()) .withPlaintext(ptBuff) .withEncryptionContext(req.getEncryptionContext())); return new GenerateDataKeyResult() .withKeyId(req.getKeyId()) .withCiphertextBlob(encryptResult.getCiphertextBlob()) .withPlaintext(ptBuff); } @Override public GenerateDataKeyWithoutPlaintextResult generateDataKeyWithoutPlaintext( GenerateDataKeyWithoutPlaintextRequest req) throws AmazonServiceException, AmazonClientException { GenerateDataKeyResult generateDataKey = generateDataKey( new GenerateDataKeyRequest() .withEncryptionContext(req.getEncryptionContext()) .withNumberOfBytes(req.getNumberOfBytes())); return new GenerateDataKeyWithoutPlaintextResult() .withCiphertextBlob(generateDataKey.getCiphertextBlob()) .withKeyId(req.getKeyId()); } @Override public void setEndpoint(String arg0) throws IllegalArgumentException { // Do nothing } @Override public void setRegion(Region arg0) throws IllegalArgumentException { // Do nothing } @Override public void shutdown() { // Do nothing } public void dump() { System.out.println(results_); } public Map<String, String> getSingleEc() { if (results_.size() != 1) { throw new IllegalStateException("Unexpected number of ciphertexts"); } for (final DecryptMapKey k : results_.keySet()) { return k.ec; } throw new IllegalStateException("Unexpected number of ciphertexts"); } private static class DecryptMapKey { private final ByteBuffer cipherText; private final Map<String, String> ec; public DecryptMapKey(DecryptRequest req) { cipherText = req.getCiphertextBlob().asReadOnlyBuffer(); if (req.getEncryptionContext() != null) { ec = Collections.unmodifiableMap(new HashMap<String, String>(req.getEncryptionContext())); } else { ec = Collections.emptyMap(); } } public DecryptMapKey(ByteBuffer ctBuff, Map<String, String> ec) { cipherText = ctBuff.asReadOnlyBuffer(); if (ec != null) { this.ec = Collections.unmodifiableMap(new HashMap<String, String>(ec)); } else { this.ec = Collections.emptyMap(); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((cipherText == null) ? 0 : cipherText.hashCode()); result = prime * result + ((ec == null) ? 0 : ec.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DecryptMapKey other = (DecryptMapKey) obj; if (cipherText == null) { if (other.cipherText != null) return false; } else if (!cipherText.equals(other.cipherText)) return false; if (ec == null) { if (other.ec != null) return false; } else if (!ec.equals(other.ec)) return false; return true; } @Override public String toString() { return "DecryptMapKey [cipherText=" + cipherText + ", ec=" + ec + "]"; } } }
4,979
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/FakeParameters.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing; import com.amazonaws.services.dynamodbv2.datamodeling.AttributeTransformer; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Collections; import java.util.Map; public class FakeParameters<T> { public static <T> AttributeTransformer.Parameters<T> getInstance( Class<T> clazz, Map<String, AttributeValue> attribs, DynamoDBMapperConfig config, String tableName, String hashKeyName, String rangeKeyName) { return getInstance(clazz, attribs, config, tableName, hashKeyName, rangeKeyName, false); } public static <T> AttributeTransformer.Parameters<T> getInstance( Class<T> clazz, Map<String, AttributeValue> attribs, DynamoDBMapperConfig config, String tableName, String hashKeyName, String rangeKeyName, boolean isPartialUpdate) { // We use this relatively insane proxy setup so that modifications to the Parameters // interface doesn't break our tests (unless it actually impacts our code). FakeParameters<T> fakeParams = new FakeParameters<T>( clazz, attribs, config, tableName, hashKeyName, rangeKeyName, isPartialUpdate); @SuppressWarnings("unchecked") AttributeTransformer.Parameters<T> proxyObject = (AttributeTransformer.Parameters<T>) Proxy.newProxyInstance( AttributeTransformer.class.getClassLoader(), new Class[] {AttributeTransformer.Parameters.class}, new ParametersInvocationHandler<T>(fakeParams)); return proxyObject; } private static class ParametersInvocationHandler<T> implements InvocationHandler { private final FakeParameters<T> params; public ParametersInvocationHandler(FakeParameters<T> params) { this.params = params; } @Override public Object invoke(Object obj, Method method, Object[] args) throws Throwable { if (args != null && args.length > 0) { throw new UnsupportedOperationException(); } Method innerMethod = params.getClass().getMethod(method.getName()); return innerMethod.invoke(params); } } private final Map<String, AttributeValue> attrs; private final Class<T> clazz; private final DynamoDBMapperConfig config; private final String tableName; private final String hashKeyName; private final String rangeKeyName; private final boolean isPartialUpdate; private FakeParameters( Class<T> clazz, Map<String, AttributeValue> attribs, DynamoDBMapperConfig config, String tableName, String hashKeyName, String rangeKeyName, boolean isPartialUpdate) { super(); this.clazz = clazz; this.attrs = Collections.unmodifiableMap(attribs); this.config = config; this.tableName = tableName; this.hashKeyName = hashKeyName; this.rangeKeyName = rangeKeyName; this.isPartialUpdate = isPartialUpdate; } public Map<String, AttributeValue> getAttributeValues() { return attrs; } public Class<T> getModelClass() { return clazz; } public DynamoDBMapperConfig getMapperConfig() { return config; } public String getTableName() { return tableName; } public String getHashKeyName() { return hashKeyName; } public String getRangeKeyName() { return rangeKeyName; } public boolean isPartialUpdate() { return isPartialUpdate; } }
4,980
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/AttributeValueDeserializer.java
package com.amazonaws.services.dynamodbv2.testing; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Iterator; import java.util.Map; import java.util.Set; public class AttributeValueDeserializer extends JsonDeserializer<AttributeValue> { @Override public AttributeValue deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); JsonNode attribute = jp.getCodec().readTree(jp); for (Iterator<Map.Entry<String, JsonNode>> iter = attribute.fields(); iter.hasNext(); ) { Map.Entry<String, JsonNode> rawAttribute = iter.next(); // If there is more than one entry in this map, there is an error with our test data if (iter.hasNext()) { throw new IllegalStateException("Attribute value JSON has more than one value mapped."); } String typeString = rawAttribute.getKey(); JsonNode value = rawAttribute.getValue(); switch (typeString) { case "S": return new AttributeValue().withS(value.asText()); case "B": ByteBuffer b = ByteBuffer.wrap(java.util.Base64.getDecoder().decode(value.asText())); return new AttributeValue().withB(b); case "N": return new AttributeValue().withN(value.asText()); case "SS": final Set<String> stringSet = objectMapper.readValue( objectMapper.treeAsTokens(value), new TypeReference<Set<String>>() {}); return new AttributeValue().withSS(stringSet); case "NS": final Set<String> numSet = objectMapper.readValue( objectMapper.treeAsTokens(value), new TypeReference<Set<String>>() {}); return new AttributeValue().withNS(numSet); default: throw new IllegalStateException( "DDB JSON type " + typeString + " not implemented for test attribute value deserialization."); } } return null; } }
4,981
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/AttributeValueSerializer.java
package com.amazonaws.services.dynamodbv2.testing; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.util.Base64; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import java.io.IOException; import java.nio.ByteBuffer; public class AttributeValueSerializer extends JsonSerializer<AttributeValue> { @Override public void serialize(AttributeValue value, JsonGenerator jgen, SerializerProvider provider) throws IOException { if (value != null) { jgen.writeStartObject(); if (value.getS() != null) { jgen.writeStringField("S", value.getS()); } else if (value.getB() != null) { ByteBuffer valueBytes = value.getB(); byte[] arr = new byte[valueBytes.remaining()]; valueBytes.get(arr); jgen.writeStringField("B", Base64.encodeAsString(arr)); } else if (value.getN() != null) { jgen.writeStringField("N", value.getN()); } else if (value.getSS() != null) { jgen.writeFieldName("SS"); jgen.writeStartArray(); for (String s : value.getSS()) { jgen.writeString(s); } jgen.writeEndArray(); } else if (value.getNS() != null) { jgen.writeFieldName("NS"); jgen.writeStartArray(); for (String num : value.getNS()) { jgen.writeString(num); } jgen.writeEndArray(); } else { throw new IllegalStateException( "AttributeValue has no value or type not implemented for serialization."); } jgen.writeEndObject(); } } }
4,982
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/TestDelegatedKey.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DelegatedKey; import java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.Mac; import javax.crypto.NoSuchPaddingException; import javax.crypto.ShortBufferException; import javax.crypto.spec.IvParameterSpec; public class TestDelegatedKey implements DelegatedKey { private static final long serialVersionUID = 1L; private final Key realKey; public TestDelegatedKey(Key key) { this.realKey = key; } @Override public String getAlgorithm() { return "DELEGATED:" + realKey.getAlgorithm(); } @Override public byte[] getEncoded() { return realKey.getEncoded(); } @Override public String getFormat() { return realKey.getFormat(); } @Override public byte[] encrypt(byte[] plainText, byte[] additionalAssociatedData, String algorithm) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException { Cipher cipher = Cipher.getInstance(extractAlgorithm(algorithm)); cipher.init(Cipher.ENCRYPT_MODE, realKey); byte[] iv = cipher.getIV(); byte[] result = new byte[cipher.getOutputSize(plainText.length) + iv.length + 1]; result[0] = (byte) iv.length; System.arraycopy(iv, 0, result, 1, iv.length); try { cipher.doFinal(plainText, 0, plainText.length, result, iv.length + 1); } catch (ShortBufferException e) { throw new RuntimeException(e); } return result; } @Override public byte[] decrypt(byte[] cipherText, byte[] additionalAssociatedData, String algorithm) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { final byte ivLength = cipherText[0]; IvParameterSpec iv = new IvParameterSpec(cipherText, 1, ivLength); Cipher cipher = Cipher.getInstance(extractAlgorithm(algorithm)); cipher.init(Cipher.DECRYPT_MODE, realKey, iv); return cipher.doFinal(cipherText, ivLength + 1, cipherText.length - ivLength - 1); } @Override public byte[] wrap(Key key, byte[] additionalAssociatedData, String algorithm) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException { Cipher cipher = Cipher.getInstance(extractAlgorithm(algorithm)); cipher.init(Cipher.WRAP_MODE, realKey); return cipher.wrap(key); } @Override public Key unwrap( byte[] wrappedKey, String wrappedKeyAlgorithm, int wrappedKeyType, byte[] additionalAssociatedData, String algorithm) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { Cipher cipher = Cipher.getInstance(extractAlgorithm(algorithm)); cipher.init(Cipher.UNWRAP_MODE, realKey); return cipher.unwrap(wrappedKey, wrappedKeyAlgorithm, wrappedKeyType); } @Override public byte[] sign(byte[] dataToSign, String algorithm) throws NoSuchAlgorithmException, InvalidKeyException { Mac mac = Mac.getInstance(extractAlgorithm(algorithm)); mac.init(realKey); return mac.doFinal(dataToSign); } @Override public boolean verify(byte[] dataToSign, byte[] signature, String algorithm) { try { byte[] expected = sign(dataToSign, extractAlgorithm(algorithm)); return MessageDigest.isEqual(expected, signature); } catch (GeneralSecurityException ex) { return false; } } private String extractAlgorithm(String alg) { if (alg.startsWith(getAlgorithm())) { return alg.substring(10); } else { return alg; } } }
4,983
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/ScenarioManifest.java
package com.amazonaws.services.dynamodbv2.testing; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) public class ScenarioManifest { public static final String MOST_RECENT_PROVIDER_NAME = "most_recent"; public static final String WRAPPED_PROVIDER_NAME = "wrapped"; public static final String STATIC_PROVIDER_NAME = "static"; public static final String AWS_KMS_PROVIDER_NAME = "awskms"; public static final String SYMMETRIC_KEY_TYPE = "symmetric"; public List<Scenario> scenarios; @JsonProperty("keys") public String keyDataPath; @JsonIgnoreProperties(ignoreUnknown = true) public static class Scenario { @JsonProperty("ciphertext") public String ciphertextPath; @JsonProperty("provider") public String providerName; public String version; @JsonProperty("material_name") public String materialName; public Metastore metastore; public Keys keys; } @JsonIgnoreProperties(ignoreUnknown = true) public static class Metastore { @JsonProperty("ciphertext") public String path; @JsonProperty("table_name") public String tableName; @JsonProperty("provider") public String providerName; public Keys keys; } @JsonIgnoreProperties(ignoreUnknown = true) public static class Keys { @JsonProperty("encrypt") public String encryptName; @JsonProperty("sign") public String signName; @JsonProperty("decrypt") public String decryptName; @JsonProperty("verify") public String verifyName; } public static class KeyData { public String material; public String algorithm; public String encoding; @JsonProperty("type") public String keyType; public String keyId; } }
4,984
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/DdbRecordMatcher.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import java.util.Map; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; public class DdbRecordMatcher extends BaseMatcher<Map<String, AttributeValue>> { private final Map<String, AttributeValue> expected; private final boolean invert; public static DdbRecordMatcher invert(Map<String, AttributeValue> expected) { return new DdbRecordMatcher(expected, true); } public static DdbRecordMatcher match(Map<String, AttributeValue> expected) { return new DdbRecordMatcher(expected, false); } public DdbRecordMatcher(Map<String, AttributeValue> expected, boolean invert) { this.expected = expected; this.invert = invert; } @Override public boolean matches(Object item) { @SuppressWarnings("unchecked") Map<String, AttributeValue> actual = (Map<String, AttributeValue>) item; if (!expected.keySet().equals(actual.keySet())) { return invert; } for (String key : expected.keySet()) { AttributeValue e = expected.get(key); AttributeValue a = actual.get(key); if (!AttributeValueMatcher.attrEquals(a, e)) { return invert; } } return !invert; } @Override public void describeTo(Description description) {} }
4,985
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/AttrMatcher.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; public class AttrMatcher extends BaseMatcher<Map<String, AttributeValue>> { private final Map<String, AttributeValue> expected; private final boolean invert; public static AttrMatcher invert(Map<String, AttributeValue> expected) { return new AttrMatcher(expected, true); } public static AttrMatcher match(Map<String, AttributeValue> expected) { return new AttrMatcher(expected, false); } public AttrMatcher(Map<String, AttributeValue> expected, boolean invert) { this.expected = expected; this.invert = invert; } @Override public boolean matches(Object item) { @SuppressWarnings("unchecked") Map<String, AttributeValue> actual = (Map<String, AttributeValue>) item; if (!expected.keySet().equals(actual.keySet())) { return invert; } for (String key : expected.keySet()) { AttributeValue e = expected.get(key); AttributeValue a = actual.get(key); if (!attrEquals(a, e)) { return invert; } } return !invert; } public static boolean attrEquals(AttributeValue e, AttributeValue a) { if (!isEqual(e.getB(), a.getB()) || !isEqual(e.getBOOL(), a.getBOOL()) || !isSetEqual(e.getBS(), a.getBS()) || !isEqual(e.getN(), a.getN()) || !isSetEqual(e.getNS(), a.getNS()) || !isEqual(e.getNULL(), a.getNULL()) || !isEqual(e.getS(), a.getS()) || !isSetEqual(e.getSS(), a.getSS())) { return false; } // Recursive types need special handling if (e.getM() == null ^ a.getM() == null) { return false; } else if (e.getM() != null) { if (!e.getM().keySet().equals(a.getM().keySet())) { return false; } for (final String key : e.getM().keySet()) { if (!attrEquals(e.getM().get(key), a.getM().get(key))) { return false; } } } if (e.getL() == null ^ a.getL() == null) { return false; } else if (e.getL() != null) { if (e.getL().size() != a.getL().size()) { return false; } for (int x = 0; x < e.getL().size(); x++) { if (!attrEquals(e.getL().get(x), a.getL().get(x))) { return false; } } } return true; } @Override public void describeTo(Description description) {} private static boolean isEqual(Object o1, Object o2) { if (o1 == null ^ o2 == null) { return false; } if (o1 == o2) return true; return o1.equals(o2); } private static <T> boolean isSetEqual(Collection<T> c1, Collection<T> c2) { if (c1 == null ^ c2 == null) { return false; } if (c1 != null) { Set<T> s1 = new HashSet<T>(c1); Set<T> s2 = new HashSet<T>(c2); if (!s1.equals(s2)) { return false; } } return true; } }
4,986
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/types/UntouchedWithUnknownAttributeAnnotationWithNewAttribute.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotTouch; @DoNotTouch public class UntouchedWithUnknownAttributeAnnotationWithNewAttribute extends UntouchedWithUnknownAttributeAnnotation { private String newAttribute; public String getNewAttribute() { return newAttribute; } public void setNewAttribute(String newAttribute) { this.newAttribute = newAttribute; } }
4,987
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/types/KeysOnly.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; @DynamoDBTable(tableName = "TableName") public class KeysOnly { private int hashKey; private int rangeKey; public KeysOnly() {} public KeysOnly(int hashKey, int rangeKey) { this.hashKey = hashKey; this.rangeKey = rangeKey; } @DynamoDBRangeKey public int getRangeKey() { return rangeKey; } public void setRangeKey(int rangeKey) { this.rangeKey = rangeKey; } @DynamoDBHashKey public int getHashKey() { return hashKey; } public void setHashKey(int hashKey) { this.hashKey = hashKey; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + hashKey; result = prime * result + rangeKey; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; KeysOnly other = (KeysOnly) obj; if (hashKey != other.hashKey) return false; if (rangeKey != other.rangeKey) return false; return true; } }
4,988
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/types/DoNotTouchField.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotTouch; @DynamoDBTable(tableName = "TableName") public class DoNotTouchField extends Mixed { @DoNotTouch int value; public int getValue() { return value; } public void setValue(int value) { this.value = value; } @Override public int hashCode() { return 31 * super.hashCode() + value; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DoNotTouchField other = (DoNotTouchField) obj; if (value != other.value) return false; return true; } }
4,989
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/types/TableOverride.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.TableAadOverride; @TableAadOverride(tableName = "Override") public class TableOverride extends BaseClass {}
4,990
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/types/SignOnlyWithUnknownAttributeAnnotation.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotEncrypt; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.HandleUnknownAttributes; @DoNotEncrypt @HandleUnknownAttributes public class SignOnlyWithUnknownAttributeAnnotation extends BaseClass {}
4,991
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/types/UntouchedWithNewAttribute.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotTouch; @DoNotTouch public class UntouchedWithNewAttribute extends Untouched { private String newAttribute; public String getNewAttribute() { return newAttribute; } public void setNewAttribute(String newAttribute) { this.newAttribute = newAttribute; } }
4,992
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/types/BaseClass.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBVersionAttribute; import java.util.Arrays; import java.util.Set; @DynamoDBTable(tableName = "TableName") public class BaseClass { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(byteArrayValue); result = prime * result + hashKey; result = prime * result + ((intSet == null) ? 0 : intSet.hashCode()); result = prime * result + intValue; result = prime * result + rangeKey; result = prime * result + ((stringSet == null) ? 0 : stringSet.hashCode()); result = prime * result + ((stringValue == null) ? 0 : stringValue.hashCode()); result = prime * result + Double.valueOf(doubleValue).hashCode(); result = prime * result + ((doubleSet == null) ? 0 : doubleSet.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BaseClass other = (BaseClass) obj; if (!Arrays.equals(byteArrayValue, other.byteArrayValue)) return false; if (hashKey != other.hashKey) return false; if (intSet == null) { if (other.intSet != null) return false; } else if (!intSet.equals(other.intSet)) return false; if (intValue != other.intValue) return false; if (rangeKey != other.rangeKey) return false; if (stringSet == null) { if (other.stringSet != null) return false; } else if (!stringSet.equals(other.stringSet)) return false; if (stringValue == null) { if (other.stringValue != null) return false; } else if (!stringValue.equals(other.stringValue)) return false; if (doubleSet == null) { if (other.doubleSet != null) return false; } else if (!doubleSet.equals(other.doubleSet)) return false; return true; } private int hashKey; private int rangeKey; private String stringValue; private int intValue; private byte[] byteArrayValue; private Set<String> stringSet; private Set<Integer> intSet; private Integer version; private double doubleValue; private Set<Double> doubleSet; @DynamoDBHashKey public int getHashKey() { return hashKey; } public void setHashKey(int hashKey) { this.hashKey = hashKey; } @DynamoDBRangeKey public int getRangeKey() { return rangeKey; } public void setRangeKey(int rangeKey) { this.rangeKey = rangeKey; } public String getStringValue() { return stringValue; } public void setStringValue(String stringValue) { this.stringValue = stringValue; } public int getIntValue() { return intValue; } public void setIntValue(int intValue) { this.intValue = intValue; } public byte[] getByteArrayValue() { return byteArrayValue; } public void setByteArrayValue(byte[] byteArrayValue) { this.byteArrayValue = byteArrayValue; } public Set<String> getStringSet() { return stringSet; } public void setStringSet(Set<String> stringSet) { this.stringSet = stringSet; } public Set<Integer> getIntSet() { return intSet; } public void setIntSet(Set<Integer> intSet) { this.intSet = intSet; } public Set<Double> getDoubleSet() { return doubleSet; } public void setDoubleSet(Set<Double> doubleSet) { this.doubleSet = doubleSet; } public double getDoubleValue() { return doubleValue; } public void setDoubleValue(double doubleValue) { this.doubleValue = doubleValue; } @DynamoDBVersionAttribute public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } @Override public String toString() { return "BaseClass [hashKey=" + hashKey + ", rangeKey=" + rangeKey + ", stringValue=" + stringValue + ", intValue=" + intValue + ", byteArrayValue=" + Arrays.toString(byteArrayValue) + ", stringSet=" + stringSet + ", intSet=" + intSet + ", doubleValue=" + doubleValue + ", doubleSet=" + doubleSet + ", version=" + version + "]"; } }
4,993
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/types/BaseClassWithNewAttribute.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; public class BaseClassWithNewAttribute extends BaseClassWithUnknownAttributeAnnotation { private String newAttribute; public String getNewAttribute() { return newAttribute; } public void setNewAttribute(String newAttribute) { this.newAttribute = newAttribute; } }
4,994
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/types/HashKeyOnly.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; @DynamoDBTable(tableName = "HashKeyOnly") public class HashKeyOnly { private String hashKey; public HashKeyOnly() {} public HashKeyOnly(String hashKey) { this.hashKey = hashKey; } @DynamoDBHashKey public String getHashKey() { return hashKey; } public void setHashKey(String hashKey) { this.hashKey = hashKey; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((hashKey == null) ? 0 : hashKey.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; HashKeyOnly other = (HashKeyOnly) obj; if (hashKey == null) { if (other.hashKey != null) return false; } else if (!hashKey.equals(other.hashKey)) return false; return true; } }
4,995
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/types/Mixed.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotEncrypt; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotTouch; import java.util.Set; public class Mixed extends BaseClass { @Override @DoNotEncrypt public String getStringValue() { return super.getStringValue(); } @Override @DoNotEncrypt public double getDoubleValue() { return super.getDoubleValue(); } @Override @DoNotEncrypt public Set<Double> getDoubleSet() { return super.getDoubleSet(); } @Override @DoNotTouch public int getIntValue() { return super.getIntValue(); } }
4,996
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/types/SignOnly.java
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotEncrypt; @DoNotEncrypt public class SignOnly extends BaseClass {}
4,997
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/types/SignOnlyWithUnknownAttributeAnnotationWithNewAttribute.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotEncrypt; @DoNotEncrypt public class SignOnlyWithUnknownAttributeAnnotationWithNewAttribute extends SignOnlyWithUnknownAttributeAnnotation { private String newAttribute; public String getNewAttribute() { return newAttribute; } public void setNewAttribute(String newAttribute) { this.newAttribute = newAttribute; } }
4,998
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/types/BaseClassWithUnknownAttributeAnnotation.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.testing.types; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.HandleUnknownAttributes; @HandleUnknownAttributes public class BaseClassWithUnknownAttributeAnnotation extends BaseClass {}
4,999