This fetches a single client record out of DynamoDB
773698
def get_client_profile(self, client_id):
        
        try:
            response = self._table.get_item(Key={'client_id': client_id})
            compressed_bytes = response['Item']['json_payload'].value
            json_byte_data = zlib.decompress(compressed_bytes)
            json_str_data = json_byte_data.decode('utf8')
            return json.loads(json_str_data)
        except KeyError:
            # No client ID found - not really an error
            return None
        except Exception as e:
            # Return None on error.  The caller in ProfileFetcher will
            # handle error logging
            msg = "Error loading client data for {}.  Error: {}"
            self.logger.debug(msg.format(client_id, str(e)))
            return None
181112
<T> Method getHashKeyGetter(Class<T> clazz) {
        synchronized (hashKeyGetterCache) {
            if ( !hashKeyGetterCache.containsKey(clazz) ) {
                for ( Method method : getRelevantGetters(clazz) ) {
                    if ( method.getParameterTypes().length == 0 && method.isAnnotationPresent(DynamoDBHashKey.class)) {
                        hashKeyGetterCache.put(clazz, method);
                        break;
                    }
                }
            }
        }

        Method hashKeyMethod = hashKeyGetterCache.get(clazz);
        if ( hashKeyMethod == null ) {
            throw new DynamoDBMappingException("Public, zero-parameter hash key property must be annotated with "
                    + DynamoDBHashKey.class);
        }
        return hashKeyMethod;
    }
22300
def get_record(self, domain, record):
        
        rec_id = utils.get_id(record)
        domain_id = utils.get_id(domain)
        uri = "/domains/%s/records/%s" % (domain_id, rec_id)
        resp, resp_body = self._retry_get(uri)
        resp_body["domain_id"] = domain_id
        return CloudDNSRecord(self, resp_body, loaded=False)
615428
def create_async_dynamodb_table(self, table_name, read_capacity, write_capacity):
        
        try:
            dynamodb_table = self.dynamodb_client.describe_table(TableName=table_name)
            return False, dynamodb_table

        # catch this exception (triggered if the table doesn't exist)
        except botocore.exceptions.ClientError:
            dynamodb_table = self.dynamodb_client.create_table(
                AttributeDefinitions=[
                    {
                        'AttributeName': 'id',
                        'AttributeType': 'S'
                    }
                ],
                TableName=table_name,
                KeySchema=[
                    {
                        'AttributeName': 'id',
                        'KeyType': 'HASH'
                    },
                ],
                ProvisionedThroughput = {
                    'ReadCapacityUnits': read_capacity,
                    'WriteCapacityUnits': write_capacity
                }
            )
            if dynamodb_table:
                try:
                    self._set_async_dynamodb_table_ttl(table_name)
                except botocore.exceptions.ClientError:
                    # this fails because the operation is async, so retry
                    time.sleep(10)
                    self._set_async_dynamodb_table_ttl(table_name)

        return True, dynamodb_table
1344976
def getHighestVersion(name, region=None, table="credential-store",
                      **kwargs):
    '''
    
    '''
    session = get_session(**kwargs)

    dynamodb = session.resource('dynamodb', region_name=region)
    secrets = dynamodb.Table(table)

    response = secrets.query(Limit=1,
                             ScanIndexForward=False,
                             ConsistentRead=True,
                             KeyConditionExpression=boto3.dynamodb.conditions.Key(
                                 "name").eq(name),
                             ProjectionExpression="version")

    if response["Count"] == 0:
        return 0
    return response["Items"][0]["version"]
28225
def _get_conn(key=None,
              keyid=None,
              profile=None,
              region=None,
              **kwargs):
    '''
    
    '''
    client = None
    if profile:
        if isinstance(profile, six.string_types):
            if profile in __pillar__:
                profile = __pillar__[profile]
            elif profile in __opts__:
                profile = __opts__[profile]
    elif key or keyid or region:
        profile = {}
        if key:
            profile['key'] = key
        if keyid:
            profile['keyid'] = keyid
        if region:
            profile['region'] = region

    if isinstance(profile, dict):
        if 'region' in profile:
            profile['region_name'] = profile['region']
            profile.pop('region', None)
        if 'key' in profile:
            profile['aws_secret_access_key'] = profile['key']
            profile.pop('key', None)
        if 'keyid' in profile:
            profile['aws_access_key_id'] = profile['keyid']
            profile.pop('keyid', None)

        client = boto3.client('efs', **profile)
    else:
        client = boto3.client('efs')

    return client
410888
def _get_secret_from_vault(
        key, environment=None, stage=None, namespace=None,
        wait_exponential_multiplier=50, wait_exponential_max=5000,
        stop_max_delay=10000):
    """"""
    # Get the encrypted secret from DynamoDB
    table_name = _secrets_table_name(environment=environment, stage=stage)

    if namespace:
        key = "{}:{}".format(namespace, key)

    if table_name is None:
        logger.warning("Can't produce secrets table name: unable to retrieve "
                       "secret '{}'".format(key))
        return

    client = boto3.client('dynamodb')
    logger.info("Retriving key '{}' from table '{}'".format(
        key, table_name))

    @retry(retry_on_exception=_is_critical_exception,
           wait_exponential_multiplier=wait_exponential_multiplier,
           wait_exponential_max=wait_exponential_max,
           stop_max_delay=stop_max_delay)
    def get_item():
        try:
            return client.get_item(
                TableName=table_name,
                Key={'id': {'S': key}}).get('Item', {}).get(
                    'value', {}).get('B')
        except Exception as err:
            if _is_dynamodb_critical_exception(err):
                raise CriticalError(err)
            else:
                raise

    encrypted = get_item()

    if encrypted is None:
        return

    # Decrypt using KMS
    client = boto3.client('kms')
    try:
        value = client.decrypt(CiphertextBlob=encrypted)['Plaintext'].decode()
    except ClientError:
        logger.error("KMS error when trying to decrypt secret")
        traceback.print_exc()
        return

    try:
        value = json.loads(value)
    except (TypeError, ValueError):
        # It's ok, the client should know how to deal with the value
        pass

    return value
385261
private void extractUpdateDetails(DynamoDBPersistable dynamoDBPersistable, String prefix) {
        for (Iterator<String> dirtyFields = dynamoDBPersistable.__getDirtyFields(); dirtyFields.hasNext(); ) {
            String dirtyField = dirtyFields.next();

            processDirtyObject(dynamoDBPersistable.__get(dirtyField), prefix + getExpressionAttributeName(dirtyField));
        }
    }
473045
def client(self, id):
    """"""

    return self.query(Client).filter(Client.id==id).one()
11142
def reformat_record(record):
    """"""
    return {
        "key": record["dynamodb"].get("Keys", None),
        "new": record["dynamodb"].get("NewImage", None),
        "old": record["dynamodb"].get("OldImage", None),

        "meta": {
            "created_at": record["dynamodb"]["ApproximateCreationDateTime"],
            "event": {
                "id": record["eventID"],
                "type": record["eventName"].lower(),
                "version": record["eventVersion"]
            },
            "sequence_number": record["dynamodb"]["SequenceNumber"],
        }
    }
5403
public static function get()
    {
        // Use DynamoDB for distributed session storage if it's configured
        $awsDynamoDBSessionTable = Environment::getEnv('AWS_DYNAMODB_SESSION_TABLE');
        if (!empty($awsDynamoDBSessionTable)) {
            $awsRegionName = Environment::getEnv('AWS_REGION_NAME');
            $awsDynamoDBEndpoint = Environment::getEnv('AWS_DYNAMODB_ENDPOINT');
            $awsAccessKey = Environment::getEnv('AWS_ACCESS_KEY');
            $awsSecretKey = Environment::getEnv('AWS_SECRET_KEY');

            $dynamoOptions = array('region' => $awsRegionName);

            // This endpoint can be set for locally testing DynamoDB.
            // see http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html
            if (!empty($awsDynamoDBEndpoint)) {
                $dynamoOptions['endpoint'] = $awsDynamoDBEndpoint;
            }

            if (!empty($awsAccessKey) && !empty($awsSecretKey)) {
                $dynamoOptions['credentials']['key'] = $awsAccessKey;
                $dynamoOptions['credentials']['secret'] = $awsSecretKey;
            } else {
                // cache credentials when IAM fetches the credentials from EC2 metadata service
                // this will use doctrine/cache (included via composer) to do the actual caching into APCu
                // http://docs.aws.amazon.com/aws-sdk-php/guide/latest/performance.html#cache-instance-profile-credentials
                $dynamoOptions['credentials'] = new DoctrineCacheAdapter(new ApcuCache());
            }

            return new static($dynamoOptions, $awsDynamoDBSessionTable);
        }

        return null;
    }
1339070
def get_table(table_name):
    
    try:
        table = Table(table_name, connection=DYNAMODB_CONNECTION)
    except DynamoDBResponseError as error:
        dynamodb_error = error.body['__type'].rsplit('#', 1)[1]
        if dynamodb_error == 'ResourceNotFoundException':
            logger.error(
                '{0} - Table {1} not found'.format(table_name, table_name))

        raise

    return table
1247348
def _get(self, name, interval, config, timestamp, **kws):
    '''
    
    '''
    i_bucket = config['i_calc'].to_bucket(timestamp)
    fetch = kws.get('fetch')
    process_row = kws.get('process_row') or self._process_row

    rval = OrderedDict()
    query = {'name':name, 'interval':i_bucket}
    if config['coarse']:
      if fetch:
        record = fetch( self._client[interval], spec=query, method='find_one' )
      else:
        record = self._client[interval].find_one( query )

      if record:
        data = process_row( self._unescape(record['value']) )
        rval[ config['i_calc'].from_bucket(i_bucket) ] = data
      else:
        rval[ config['i_calc'].from_bucket(i_bucket) ] = self._type_no_value()
    else:
      sort = [('interval', ASCENDING), ('resolution', ASCENDING) ]
      if fetch:
        cursor = fetch( self._client[interval], spec=query, sort=sort, method='find' )
      else:
        cursor = self._client[interval].find( spec=query, sort=sort )

      idx = 0
      for record in cursor:
        rval[ config['r_calc'].from_bucket(record['resolution']) ] = \
          process_row(record['value'])

    return rval
980509
def _get_client(region, key, keyid, profile):
    '''
    
    '''
    session = _get_session(region, key, keyid, profile)
    if not session:
        log.error("Failed to get datapipeline client.")
        return None

    return session.client('datapipeline')
815046
public function getPublicKey($client_id = '0')
    {

        $result = $this->client->getItem(array(
            "TableName"=> $this->config['public_key_table'],
            "Key" => array('client_id'   => array('S' => $client_id))
        ));
        if ($result->count()==0) {
            return false ;
        }
        $token = $this->dynamo2array($result);

        return $token['public_key'];

    }
1078465
def fetch(bank, key):
    '''
    
    '''
    _init_client()
    etcd_key = '{0}/{1}/{2}'.format(path_prefix, bank, key)
    try:
        value = client.read(etcd_key).value
        return __context__['serial'].loads(base64.b64decode(value))
    except etcd.EtcdKeyNotFound:
        return {}
    except Exception as exc:
        raise SaltCacheError(
            'There was an error reading the key, {0}: {1}'.format(
                etcd_key, exc
            )
        )
1207779
static ByteBuffer getRowKeyRaw(int shardId, long tableUuid, byte[] contentKeyBytes) {
        checkArgument(shardId >= 0 && shardId < 256);

        // Assemble a single array which is "1 byte shard id + 8 byte table uuid + n-byte content key".
        ByteBuffer rowKey = ByteBuffer.allocate(9 + contentKeyBytes.length);
        rowKey.put((byte) shardId);
        rowKey.putLong(tableUuid);
        rowKey.put(contentKeyBytes);

        rowKey.flip();
        return rowKey;
    }