idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
30,800
public Waiter < DescribeTransformJobRequest > transformJobCompletedOrStopped ( ) { return new WaiterBuilder < DescribeTransformJobRequest , DescribeTransformJobResult > ( ) . withSdkFunction ( new DescribeTransformJobFunction ( client ) ) . withAcceptors ( new TransformJobCompletedOrStopped . IsCompletedMatcher ( ) , new TransformJobCompletedOrStopped . IsStoppedMatcher ( ) , new TransformJobCompletedOrStopped . IsFailedMatcher ( ) , new TransformJobCompletedOrStopped . IsValidationExceptionMatcher ( ) ) . withDefaultPollingStrategy ( new PollingStrategy ( new MaxAttemptsRetryStrategy ( 60 ) , new FixedDelayStrategy ( 60 ) ) ) . withExecutorService ( executorService ) . build ( ) ; }
Builds a TransformJobCompletedOrStopped waiter by using custom parameters waiterParameters and other parameters defined in the waiters specification and then polls until it determines whether the resource entered the desired state or not where polling criteria is bound by either default polling strategy or custom polling strategy .
30,801
public Waiter < DescribeTrainingJobRequest > trainingJobCompletedOrStopped ( ) { return new WaiterBuilder < DescribeTrainingJobRequest , DescribeTrainingJobResult > ( ) . withSdkFunction ( new DescribeTrainingJobFunction ( client ) ) . withAcceptors ( new TrainingJobCompletedOrStopped . IsCompletedMatcher ( ) , new TrainingJobCompletedOrStopped . IsStoppedMatcher ( ) , new TrainingJobCompletedOrStopped . IsFailedMatcher ( ) , new TrainingJobCompletedOrStopped . IsValidationExceptionMatcher ( ) ) . withDefaultPollingStrategy ( new PollingStrategy ( new MaxAttemptsRetryStrategy ( 180 ) , new FixedDelayStrategy ( 120 ) ) ) . withExecutorService ( executorService ) . build ( ) ; }
Builds a TrainingJobCompletedOrStopped waiter by using custom parameters waiterParameters and other parameters defined in the waiters specification and then polls until it determines whether the resource entered the desired state or not where polling criteria is bound by either default polling strategy or custom polling strategy .
30,802
public void setGroups ( java . util . Collection < GroupInformation > groups ) { if ( groups == null ) { this . groups = null ; return ; } this . groups = new java . util . ArrayList < GroupInformation > ( groups ) ; }
Information about a group .
30,803
private void tagResources ( List < String > resources , List < Tag > tags ) { CreateTagsRequest createTagsRequest = new CreateTagsRequest ( ) ; createTagsRequest . setResources ( resources ) ; createTagsRequest . setTags ( tags ) ; try { ec2 . createTags ( createTagsRequest ) ; } catch ( AmazonServiceException e ) { System . out . println ( "Error terminating instances" ) ; System . out . println ( "Caught Exception: " + e . getMessage ( ) ) ; System . out . println ( "Reponse Status Code: " + e . getStatusCode ( ) ) ; System . out . println ( "Error Code: " + e . getErrorCode ( ) ) ; System . out . println ( "Request ID: " + e . getRequestId ( ) ) ; } }
Tag any of the resources we specify .
30,804
protected void processRequestPayload ( SignableRequest < ? > request , byte [ ] signature , byte [ ] signingKey , AWS4SignerRequestParams signerRequestParams ) { if ( useChunkEncoding ( request ) ) { AwsChunkedEncodingInputStream chunkEncodededStream = new AwsChunkedEncodingInputStream ( request . getContent ( ) , signingKey , signerRequestParams . getFormattedSigningDateTime ( ) , signerRequestParams . getScope ( ) , BinaryUtils . toHex ( signature ) , this ) ; request . setContent ( chunkEncodededStream ) ; } }
If necessary creates a chunk - encoding wrapper on the request payload .
30,805
protected String calculateContentHash ( SignableRequest < ? > request ) { request . addHeader ( X_AMZ_CONTENT_SHA256 , "required" ) ; if ( isPayloadSigningEnabled ( request ) ) { if ( useChunkEncoding ( request ) ) { final String contentLength = request . getHeaders ( ) . get ( Headers . CONTENT_LENGTH ) ; final long originalContentLength ; if ( contentLength != null ) { originalContentLength = Long . parseLong ( contentLength ) ; } else { try { originalContentLength = getContentLength ( request ) ; } catch ( IOException e ) { throw new SdkClientException ( "Cannot get the content-length of the request content." , e ) ; } } request . addHeader ( "x-amz-decoded-content-length" , Long . toString ( originalContentLength ) ) ; request . addHeader ( Headers . CONTENT_LENGTH , Long . toString ( AwsChunkedEncodingInputStream . calculateStreamContentLength ( originalContentLength ) ) ) ; return CONTENT_SHA_256 ; } else { return super . calculateContentHash ( request ) ; } } return UNSIGNED_PAYLOAD ; }
Returns the pre - defined header value and set other necessary headers if the request needs to be chunk - encoded . Otherwise calls the superclass method which calculates the hash of the whole content for signing .
30,806
private boolean useChunkEncoding ( SignableRequest < ? > request ) { if ( ! isPayloadSigningEnabled ( request ) || isChunkedEncodingDisabled ( request ) ) { return false ; } if ( request . getOriginalRequestObject ( ) instanceof PutObjectRequest || request . getOriginalRequestObject ( ) instanceof UploadPartRequest ) { return true ; } return false ; }
Determine whether to use aws - chunked for signing
30,807
static long getContentLength ( SignableRequest < ? > request ) throws IOException { final InputStream content = request . getContent ( ) ; if ( ! content . markSupported ( ) ) throw new IllegalStateException ( "Bug: request input stream must have been made mark-and-resettable at this point" ) ; ReadLimitInfo info = request . getReadLimitInfo ( ) ; final int readLimit = info . getReadLimit ( ) ; long contentLength = 0 ; byte [ ] tmp = new byte [ 4096 ] ; int read ; content . mark ( readLimit ) ; while ( ( read = content . read ( tmp ) ) != - 1 ) { contentLength += read ; } try { content . reset ( ) ; } catch ( IOException ex ) { throw new ResetException ( "Failed to reset the input stream" , ex ) ; } return contentLength ; }
Read the content of the request to get the length of the stream . This method will wrap the stream by SdkBufferedInputStream if it is not mark - supported .
30,808
private static void addShapeAndMembers ( String shapeName , Map < String , ShapeModel > in , Map < String , ShapeModel > out ) { if ( shapeName == null ) return ; final ShapeModel shape = in . get ( shapeName ) ; if ( shape == null ) return ; if ( ! out . containsKey ( shapeName ) ) { out . put ( shapeName , in . get ( shapeName ) ) ; List < MemberModel > members = shape . getMembers ( ) ; if ( members != null ) { for ( MemberModel member : members ) { List < String > memberShapes = resolveMemberShapes ( member ) ; if ( memberShapes == null ) continue ; for ( String memberShape : memberShapes ) { addShapeAndMembers ( memberShape , in , out ) ; } } } } }
Adds the shape . Recursively adds the shapes represented by its members .
30,809
private static List < String > resolveMemberShapes ( MemberModel member ) { if ( member == null ) return new LinkedList < String > ( ) ; if ( member . getEnumType ( ) != null ) { return Collections . singletonList ( member . getEnumType ( ) ) ; } else if ( member . isList ( ) ) { return resolveMemberShapes ( member . getListModel ( ) . getListMemberModel ( ) ) ; } else if ( member . isMap ( ) ) { List < String > memberShapes = new LinkedList < String > ( ) ; memberShapes . addAll ( resolveMemberShapes ( member . getMapModel ( ) . getKeyModel ( ) ) ) ; memberShapes . addAll ( resolveMemberShapes ( member . getMapModel ( ) . getValueModel ( ) ) ) ; return memberShapes ; } else if ( member . isSimple ( ) ) { return new LinkedList < String > ( ) ; } else { return Collections . singletonList ( member . getVariable ( ) . getSimpleType ( ) ) ; } }
Recursively resolves the shapes represented by the member . When the member is a map both the key shape and the value shape of the map will be resolved so that the returning list could have more than one elements .
30,810
private List < IntermediateModelShapeProcessor > createShapeProcessors ( ) { final List < IntermediateModelShapeProcessor > processors = new ArrayList < > ( ) ; processors . add ( new AddInputShapes ( this ) ) ; processors . add ( new AddOutputShapes ( this ) ) ; processors . add ( new AddExceptionShapes ( this ) ) ; processors . add ( new AddModelShapes ( this ) ) ; processors . add ( new AddEmptyInputShape ( this ) ) ; processors . add ( new AddEmptyOutputShape ( this ) ) ; return processors ; }
Create default shape processors .
30,811
public String writePolicyToString ( Policy policy ) { if ( ! isNotNull ( policy ) ) throw new IllegalArgumentException ( "Policy cannot be null" ) ; try { return jsonStringOf ( policy ) ; } catch ( Exception e ) { String message = "Unable to serialize policy to JSON string: " + e . getMessage ( ) ; throw new IllegalArgumentException ( message , e ) ; } finally { try { writer . close ( ) ; } catch ( Exception e ) { } } }
Converts the specified AWS policy object to a JSON string suitable for passing to an AWS service .
30,812
private void writeConditions ( List < Condition > conditions ) throws JsonGenerationException , IOException { Map < String , ConditionsByKey > conditionsByType = groupConditionsByTypeAndKey ( conditions ) ; writeJsonObjectStart ( JsonDocumentFields . CONDITION ) ; ConditionsByKey conditionsByKey ; for ( Map . Entry < String , ConditionsByKey > entry : conditionsByType . entrySet ( ) ) { conditionsByKey = conditionsByType . get ( entry . getKey ( ) ) ; writeJsonObjectStart ( entry . getKey ( ) ) ; for ( String key : conditionsByKey . keySet ( ) ) { writeJsonArray ( key , conditionsByKey . getConditionsByKey ( key ) ) ; } writeJsonObjectEnd ( ) ; } writeJsonObjectEnd ( ) ; }
Writes the list of conditions to the JSONGenerator .
30,813
private void writeJsonArray ( String arrayName , List < String > values ) throws JsonGenerationException , IOException { writeJsonArrayStart ( arrayName ) ; for ( String value : values ) generator . writeString ( value ) ; writeJsonArrayEnd ( ) ; }
Writes an array along with its values to the JSONGenerator .
30,814
private void writeJsonKeyValue ( String fieldName , String value ) throws JsonGenerationException , IOException { generator . writeStringField ( fieldName , value ) ; }
Writes the given field and the value to the JsonGenerator
30,815
public java . util . concurrent . Future < ListPipelinesResult > listPipelinesAsync ( com . amazonaws . handlers . AsyncHandler < ListPipelinesRequest , ListPipelinesResult > asyncHandler ) { return listPipelinesAsync ( new ListPipelinesRequest ( ) , asyncHandler ) ; }
Simplified method form for invoking the ListPipelines operation with an AsyncHandler .
30,816
public EncryptedGetObjectRequest withExtraMaterialsDescription ( Map < String , String > supplemental ) { setExtraMaterialDescription ( supplemental == null ? null : new ExtraMaterialsDescription ( supplemental ) ) ; return this ; }
Fluent API to set the supplemental materials description for the encryption materials to be used with the current request .
30,817
public ExecuteSqlResult executeSql ( ExecuteSqlRequest request ) { request = beforeClientExecution ( request ) ; return executeExecuteSql ( request ) ; }
Executes any SQL statement on the target database synchronously
30,818
public Event withAttributes ( java . util . Map < String , String > attributes ) { setAttributes ( attributes ) ; return this ; }
Custom attributes that are associated with the event you re adding or updating .
30,819
public void setId3Insertions ( java . util . Collection < Id3Insertion > id3Insertions ) { if ( id3Insertions == null ) { this . id3Insertions = null ; return ; } this . id3Insertions = new java . util . ArrayList < Id3Insertion > ( id3Insertions ) ; }
Id3Insertions contains the array of Id3Insertion instances .
30,820
public ApplicationResponse withTags ( java . util . Map < String , String > tags ) { setTags ( tags ) ; return this ; }
The Tags for the application .
30,821
public AbstractSpecWithPrimaryKey < T > withPrimaryKey ( KeyAttribute ... components ) { if ( components == null ) this . keyComponents = null ; else this . keyComponents = Arrays . asList ( components ) ; return this ; }
Sets the primary key with the specified key components .
30,822
public AbstractSpecWithPrimaryKey < T > withPrimaryKey ( PrimaryKey primaryKey ) { if ( primaryKey == null ) this . keyComponents = null ; else { this . keyComponents = primaryKey . getComponents ( ) ; } return this ; }
Sets the primary key .
30,823
public AbstractSpecWithPrimaryKey < T > withPrimaryKey ( String hashKeyName , Object hashKeyValue ) { if ( hashKeyName == null ) throw new IllegalArgumentException ( ) ; withPrimaryKey ( new PrimaryKey ( hashKeyName , hashKeyValue ) ) ; return this ; }
Sets the primary key with the specified hash - only key name and value .
30,824
public AbstractSpecWithPrimaryKey < T > withPrimaryKey ( String hashKeyName , Object hashKeyValue , String rangeKeyName , Object rangeKeyValue ) { if ( hashKeyName == null ) throw new IllegalArgumentException ( "Invalid hash key name" ) ; if ( rangeKeyName == null ) throw new IllegalArgumentException ( "Invalid range key name" ) ; if ( hashKeyName . equals ( rangeKeyName ) ) throw new IllegalArgumentException ( "Names of hash and range keys must not be the same" ) ; withPrimaryKey ( new PrimaryKey ( hashKeyName , hashKeyValue , rangeKeyName , rangeKeyValue ) ) ; return this ; }
Sets the primary key with the specified hash key and range key .
30,825
public ScanSpec withNameMap ( Map < String , String > nameMap ) { if ( nameMap == null ) this . nameMap = null ; else this . nameMap = Collections . unmodifiableMap ( new LinkedHashMap < String , String > ( nameMap ) ) ; return this ; }
Applicable only when an expression has been specified . Used to specify the actual values for the attribute - name placeholders where the value in the map can either be string for simple attribute name or a JSON path expression .
30,826
public ScanSpec withValueMap ( Map < String , Object > valueMap ) { if ( valueMap == null ) this . valueMap = null ; else this . valueMap = Collections . unmodifiableMap ( new LinkedHashMap < String , Object > ( valueMap ) ) ; return this ; }
Applicable only when an expression has been specified . Used to specify the actual values for the attribute - value placeholders .
30,827
private String trimValueIfExceedsMaxLength ( String entry , String value ) { if ( value == null ) { return null ; } String result = value ; Integer maximumSize = ENTRY_TO_MAX_SIZE . get ( entry ) ; if ( maximumSize != null && value . length ( ) > maximumSize ) { result = value . substring ( 0 , maximumSize ) ; } return result ; }
If the entry exceeds the maximum length limit associated with the entry its value will be trimmed to meet its limit .
30,828
private String getDefaultUserAgent ( Request < ? > request ) { String userAgentMarker = request . getOriginalRequest ( ) . getRequestClientOptions ( ) . getClientMarker ( RequestClientOptions . Marker . USER_AGENT ) ; String userAgent = ClientConfiguration . DEFAULT_USER_AGENT ; if ( StringUtils . hasValue ( userAgentMarker ) ) { userAgent += " " + userAgentMarker ; } return userAgent ; }
Get the default user agent and append the user agent marker if there are any .
30,829
private Long calculateRequestLatency ( TimingInfo timingInfo ) { if ( timingInfo == null ) { return null ; } TimingInfo httpClientSendRequestTime = timingInfo . getLastSubMeasurement ( AWSRequestMetrics . Field . HttpClientSendRequestTime . name ( ) ) ; TimingInfo httpClientReceiveResponseTime = timingInfo . getLastSubMeasurement ( AWSRequestMetrics . Field . HttpClientReceiveResponseTime . name ( ) ) ; if ( httpClientSendRequestTime != null && httpClientSendRequestTime . getTimeTakenMillisIfKnown ( ) != null && httpClientReceiveResponseTime != null && httpClientReceiveResponseTime . getTimeTakenMillisIfKnown ( ) != null ) { return httpClientSendRequestTime . getTimeTakenMillisIfKnown ( ) . longValue ( ) + httpClientReceiveResponseTime . getTimeTakenMillisIfKnown ( ) . longValue ( ) ; } return null ; }
Calculate the request latency . RequestLatency = httpClientSendRequestTime + HttpClientReceiveResponseTime
30,830
public void setInputs ( java . util . Collection < String > inputs ) { if ( inputs == null ) { this . inputs = null ; return ; } this . inputs = new java . util . ArrayList < String > ( inputs ) ; }
The list of inputs currently using this Input Security Group .
30,831
public void setWhitelistRules ( java . util . Collection < InputWhitelistRule > whitelistRules ) { if ( whitelistRules == null ) { this . whitelistRules = null ; return ; } this . whitelistRules = new java . util . ArrayList < InputWhitelistRule > ( whitelistRules ) ; }
Whitelist rules and their sync status
30,832
public Waiter < DescribeCertificateRequest > certificateValidated ( ) { return new WaiterBuilder < DescribeCertificateRequest , DescribeCertificateResult > ( ) . withSdkFunction ( new DescribeCertificateFunction ( client ) ) . withAcceptors ( new CertificateValidated . IsSUCCESSMatcher ( ) , new CertificateValidated . IsPENDING_VALIDATIONMatcher ( ) , new CertificateValidated . IsFAILEDMatcher ( ) , new CertificateValidated . IsResourceNotFoundExceptionMatcher ( ) ) . withDefaultPollingStrategy ( new PollingStrategy ( new MaxAttemptsRetryStrategy ( 40 ) , new FixedDelayStrategy ( 60 ) ) ) . withExecutorService ( executorService ) . build ( ) ; }
Builds a CertificateValidated waiter by using custom parameters waiterParameters and other parameters defined in the waiters specification and then polls until it determines whether the resource entered the desired state or not where polling criteria is bound by either default polling strategy or custom polling strategy .
30,833
public HadoopJarStepConfig newScriptRunnerStep ( String script , String ... args ) { List < String > argsList = new ArrayList < String > ( ) ; argsList . add ( script ) ; for ( String arg : args ) { argsList . add ( arg ) ; } return new HadoopJarStepConfig ( ) . withJar ( "s3://" + bucket + "/libs/script-runner/script-runner.jar" ) . withArgs ( argsList ) ; }
Runs a specified script on the master node of your cluster .
30,834
public HadoopJarStepConfig newRunHiveScriptStepVersioned ( String script , String hiveVersion , String ... scriptArgs ) { List < String > hiveArgs = new ArrayList < String > ( ) ; hiveArgs . add ( "--hive-versions" ) ; hiveArgs . add ( hiveVersion ) ; hiveArgs . add ( "--run-hive-script" ) ; hiveArgs . add ( "--args" ) ; hiveArgs . add ( "-f" ) ; hiveArgs . add ( script ) ; hiveArgs . addAll ( Arrays . asList ( scriptArgs ) ) ; return newHivePigStep ( "hive" , hiveArgs . toArray ( new String [ 0 ] ) ) ; }
Step that runs a Hive script on your job flow using the specified Hive version .
30,835
public HadoopJarStepConfig newInstallPigStep ( String ... pigVersions ) { if ( pigVersions != null && pigVersions . length > 0 ) { return newHivePigStep ( "pig" , "--install-pig" , "--pig-versions" , StringUtils . join ( "," , pigVersions ) ) ; } return newHivePigStep ( "pig" , "--install-pig" , "--pig-versions" , "latest" ) ; }
Step that installs Pig on your job flow .
30,836
public HadoopJarStepConfig newRunPigScriptStep ( String script , String pigVersion , String ... scriptArgs ) { List < String > pigArgs = new ArrayList < String > ( ) ; pigArgs . add ( "--pig-versions" ) ; pigArgs . add ( pigVersion ) ; pigArgs . add ( "--run-pig-script" ) ; pigArgs . add ( "--args" ) ; pigArgs . add ( "-f" ) ; pigArgs . add ( script ) ; pigArgs . addAll ( Arrays . asList ( scriptArgs ) ) ; return newHivePigStep ( "pig" , pigArgs . toArray ( new String [ 0 ] ) ) ; }
Step that runs a Pig script on your job flow using the specified Pig version .
30,837
public void setColumnMetadata ( java . util . Collection < ColumnMetadata > columnMetadata ) { if ( columnMetadata == null ) { this . columnMetadata = null ; return ; } this . columnMetadata = new java . util . ArrayList < ColumnMetadata > ( columnMetadata ) ; }
List of columns and their types
30,838
public void setOutputGroupDetails ( java . util . Collection < OutputGroupDetail > outputGroupDetails ) { if ( outputGroupDetails == null ) { this . outputGroupDetails = null ; return ; } this . outputGroupDetails = new java . util . ArrayList < OutputGroupDetail > ( outputGroupDetails ) ; }
List of output group details
30,839
public void setInputs ( Collection < String > inputs ) { List < String > newInputs = new ArrayList < String > ( ) ; if ( inputs != null ) { newInputs . addAll ( inputs ) ; } this . inputs = newInputs ; }
Set the list of step input paths .
30,840
public StreamingStep withInputs ( String ... inputs ) { for ( String input : inputs ) { this . inputs . add ( input ) ; } return this ; }
Add more input paths to this step .
30,841
@ SuppressWarnings ( "deprecation" ) public static InputStream fetchFile ( final URI uri , final ClientConfiguration config ) throws IOException { HttpParams httpClientParams = new BasicHttpParams ( ) ; HttpProtocolParams . setUserAgent ( httpClientParams , getUserAgent ( config , null ) ) ; HttpConnectionParams . setConnectionTimeout ( httpClientParams , getConnectionTimeout ( config ) ) ; HttpConnectionParams . setSoTimeout ( httpClientParams , getSocketTimeout ( config ) ) ; DefaultHttpClient httpclient = new DefaultHttpClient ( httpClientParams ) ; if ( config != null ) { String proxyHost = config . getProxyHost ( ) ; int proxyPort = config . getProxyPort ( ) ; if ( proxyHost != null && proxyPort > 0 ) { HttpHost proxy = new HttpHost ( proxyHost , proxyPort ) ; httpclient . getParams ( ) . setParameter ( ConnRoutePNames . DEFAULT_PROXY , proxy ) ; if ( config . getProxyUsername ( ) != null && config . getProxyPassword ( ) != null ) { httpclient . getCredentialsProvider ( ) . setCredentials ( new AuthScope ( proxyHost , proxyPort ) , new NTCredentials ( config . getProxyUsername ( ) , config . getProxyPassword ( ) , config . getProxyWorkstation ( ) , config . getProxyDomain ( ) ) ) ; } } } HttpResponse response = httpclient . execute ( new HttpGet ( uri ) ) ; if ( response . getStatusLine ( ) . getStatusCode ( ) != 200 ) { throw new IOException ( "Error fetching file from " + uri + ": " + response ) ; } return new HttpClientWrappingInputStream ( httpclient , response . getEntity ( ) . getContent ( ) ) ; }
Fetches a file from the URI given and returns an input stream to it .
30,842
public static String calculateTreeHash ( File file ) throws AmazonClientException { ResettableInputStream is = null ; try { is = new ResettableInputStream ( file ) ; return calculateTreeHash ( is ) ; } catch ( IOException e ) { throw new AmazonClientException ( "Unable to compute hash for file: " + file . getAbsolutePath ( ) , e ) ; } finally { if ( is != null ) is . release ( ) ; } }
Calculates a hex encoded binary hash using a tree hashing algorithm for the data in the specified file .
30,843
public static String calculateTreeHash ( InputStream input ) throws AmazonClientException { try { TreeHashInputStream treeHashInputStream = new TreeHashInputStream ( input ) ; byte [ ] buffer = new byte [ 1024 ] ; while ( treeHashInputStream . read ( buffer , 0 , buffer . length ) != - 1 ) ; treeHashInputStream . close ( ) ; return calculateTreeHash ( treeHashInputStream . getChecksums ( ) ) ; } catch ( Exception e ) { throw new AmazonClientException ( "Unable to compute hash" , e ) ; } }
Calculates a hex encoded binary hash using a tree hashing algorithm for the data in the specified input stream . The method will consume all the inputStream and close it when returned .
30,844
public static String calculateTreeHash ( List < byte [ ] > checksums ) throws AmazonClientException { List < byte [ ] > hashes = new ArrayList < byte [ ] > ( ) ; hashes . addAll ( checksums ) ; while ( hashes . size ( ) > 1 ) { List < byte [ ] > treeHashes = new ArrayList < byte [ ] > ( ) ; for ( int i = 0 ; i < hashes . size ( ) / 2 ; i ++ ) { byte [ ] firstPart = hashes . get ( 2 * i ) ; byte [ ] secondPart = hashes . get ( 2 * i + 1 ) ; byte [ ] concatenation = new byte [ firstPart . length + secondPart . length ] ; System . arraycopy ( firstPart , 0 , concatenation , 0 , firstPart . length ) ; System . arraycopy ( secondPart , 0 , concatenation , firstPart . length , secondPart . length ) ; try { treeHashes . add ( computeSHA256Hash ( concatenation ) ) ; } catch ( Exception e ) { throw new AmazonClientException ( "Unable to compute hash" , e ) ; } } if ( hashes . size ( ) % 2 == 1 ) { treeHashes . add ( hashes . get ( hashes . size ( ) - 1 ) ) ; } hashes = treeHashes ; } return BinaryUtils . toHex ( hashes . get ( 0 ) ) ; }
Returns the hex encoded binary tree hash for the individual checksums given . The sums are assumed to have been generated from sequential 1MB portions of a larger file with the possible exception of the last part which may be less than a full MB .
30,845
public java . util . concurrent . Future < DescribeLoadBalancerPolicyTypesResult > describeLoadBalancerPolicyTypesAsync ( com . amazonaws . handlers . AsyncHandler < DescribeLoadBalancerPolicyTypesRequest , DescribeLoadBalancerPolicyTypesResult > asyncHandler ) { return describeLoadBalancerPolicyTypesAsync ( new DescribeLoadBalancerPolicyTypesRequest ( ) , asyncHandler ) ; }
Simplified method form for invoking the DescribeLoadBalancerPolicyTypes operation with an AsyncHandler .
30,846
public java . util . concurrent . Future < DescribeLoadBalancersResult > describeLoadBalancersAsync ( com . amazonaws . handlers . AsyncHandler < DescribeLoadBalancersRequest , DescribeLoadBalancersResult > asyncHandler ) { return describeLoadBalancersAsync ( new DescribeLoadBalancersRequest ( ) , asyncHandler ) ; }
Simplified method form for invoking the DescribeLoadBalancers operation with an AsyncHandler .
30,847
private AmazonServiceException unmarshallError ( ) throws Exception { errorResponse . setContent ( new ByteArrayInputStream ( BinaryUtils . copyBytesFrom ( cumulation . nioBuffer ( ) ) ) ) ; return errorResponseHandler . handle ( errorResponse ) ; }
We ve received all the error content so send it off to the error response handler to produce the service exception .
30,848
public static Map < String , AttributeValue > fromSimpleMap ( Map < String , Object > map ) { if ( map == null ) return null ; Map < String , AttributeValue > result = new LinkedHashMap < String , AttributeValue > ( ) ; for ( Map . Entry < String , Object > entry : map . entrySet ( ) ) result . put ( entry . getKey ( ) , toAttributeValue ( entry . getValue ( ) ) ) ; return result ; }
Converts a map of string to simple objects into the low - level representation ; or null if the input is null .
30,849
public int getEventCode ( ) { Integer legacyCode = legacyEventCodes . get ( eventType ) ; return legacyCode == null ? - 1 : legacyCode ; }
Returns the unique event code identifying the type of event this object represents .
30,850
public void setFindingTypes ( java . util . Collection < String > findingTypes ) { if ( findingTypes == null ) { this . findingTypes = null ; return ; } this . findingTypes = new java . util . ArrayList < String > ( findingTypes ) ; }
Types of sample findings that you want to generate .
30,851
public static JsonContent createJsonContent ( HttpResponse httpResponse , JsonFactory jsonFactory ) { byte [ ] rawJsonContent = null ; try { if ( httpResponse . getContent ( ) != null ) { rawJsonContent = IOUtils . toByteArray ( httpResponse . getContent ( ) ) ; } } catch ( Exception e ) { LOG . debug ( "Unable to read HTTP response content" , e ) ; } return new JsonContent ( rawJsonContent , new ObjectMapper ( jsonFactory ) . configure ( JsonParser . Feature . ALLOW_COMMENTS , true ) ) ; }
Static factory method to create a JsonContent object from the contents of the HttpResponse provided
30,852
public void addFilterCondition ( String attributeName , Condition condition ) { if ( scanFilter == null ) scanFilter = new HashMap < String , Condition > ( ) ; scanFilter . put ( attributeName , condition ) ; }
Adds a new filter condition to the current scan filter .
30,853
public DynamoDBScanExpression withFilterConditionEntry ( String attributeName , Condition condition ) { if ( scanFilter == null ) scanFilter = new HashMap < String , Condition > ( ) ; scanFilter . put ( attributeName , condition ) ; return this ; }
Adds a new filter condition to the current scan filter and returns a pointer to this object for method - chaining .
30,854
public void setDeployments ( java . util . Collection < Deployment > deployments ) { if ( deployments == null ) { this . deployments = null ; return ; } this . deployments = new java . util . ArrayList < Deployment > ( deployments ) ; }
A list of deployments for the requested groups .
30,855
public void setIngestEndpoints ( java . util . Collection < IngestEndpoint > ingestEndpoints ) { if ( ingestEndpoints == null ) { this . ingestEndpoints = null ; return ; } this . ingestEndpoints = new java . util . ArrayList < IngestEndpoint > ( ingestEndpoints ) ; }
A list of endpoints to which the source stream should be sent .
30,856
private < T > T privateMarshallIntoObject ( AttributeTransformer . Parameters < T > parameters ) { Class < T > clazz = parameters . getModelClass ( ) ; Map < String , AttributeValue > values = untransformAttributes ( parameters ) ; final DynamoDBMapperTableModel < T > model = getTableModel ( clazz , parameters . getMapperConfig ( ) ) ; return model . unconvert ( values ) ; }
The one true implementation of marshallIntoObject .
30,857
private boolean containsThrottlingException ( List < FailedBatch > failedBatches ) { for ( FailedBatch failedBatch : failedBatches ) { if ( failedBatch . isThrottling ( ) ) { return true ; } } return false ; }
Check whether there are throttling exception in the failed batches .
30,858
private FailedBatch doBatchWriteItemWithRetry ( Map < String , List < WriteRequest > > batch , BatchWriteRetryStrategy batchWriteRetryStrategy ) { BatchWriteItemResult result = null ; int retries = 0 ; int maxRetries = batchWriteRetryStrategy . getMaxRetryOnUnprocessedItems ( Collections . unmodifiableMap ( batch ) ) ; FailedBatch failedBatch = null ; Map < String , List < WriteRequest > > pendingItems = batch ; while ( true ) { try { result = db . batchWriteItem ( applyBatchOperationUserAgent ( new BatchWriteItemRequest ( ) . withRequestItems ( pendingItems ) ) ) ; } catch ( Exception e ) { failedBatch = new FailedBatch ( ) ; failedBatch . setUnprocessedItems ( pendingItems ) ; failedBatch . setException ( e ) ; return failedBatch ; } pendingItems = result . getUnprocessedItems ( ) ; if ( pendingItems . size ( ) > 0 ) { if ( maxRetries >= 0 && retries >= maxRetries ) { failedBatch = new FailedBatch ( ) ; failedBatch . setUnprocessedItems ( pendingItems ) ; failedBatch . setException ( null ) ; return failedBatch ; } pause ( batchWriteRetryStrategy . getDelayBeforeRetryUnprocessedItems ( Collections . unmodifiableMap ( pendingItems ) , retries ) ) ; retries ++ ; } else { break ; } } return failedBatch ; }
Continue trying to process the batch and retry on UnproccessedItems as according to the specified BatchWriteRetryStrategy
30,859
private static < T > boolean anyKeyGeneratable ( final DynamoDBMapperTableModel < T > model , final T object , final SaveBehavior saveBehavior ) { for ( final DynamoDBMapperFieldModel < T , Object > field : model . keys ( ) ) { if ( canGenerate ( model , object , saveBehavior , field ) ) { return true ; } } return false ; }
Determnes if any of the primary keys require auto - generation .
30,860
private static < T > boolean canGenerate ( final DynamoDBMapperTableModel < T > model , final T object , final SaveBehavior saveBehavior , final DynamoDBMapperFieldModel < T , Object > field ) { if ( field . getGenerateStrategy ( ) == null ) { return false ; } else if ( field . getGenerateStrategy ( ) == DynamoDBAutoGenerateStrategy . ALWAYS ) { return true ; } else if ( field . get ( object ) != null ) { return false ; } else if ( field . keyType ( ) != null || field . indexed ( ) ) { return true ; } else if ( saveBehavior == SaveBehavior . CLOBBER || saveBehavior == SaveBehavior . UPDATE || saveBehavior == SaveBehavior . PUT ) { return true ; } else if ( anyKeyGeneratable ( model , object , saveBehavior ) ) { return true ; } return false ; }
Determines if the mapping value can be auto - generated .
30,861
public < T , H , R > DynamoDBTableMapper < T , H , R > newTableMapper ( Class < T > clazz ) { DynamoDBMapperConfig config = mergeConfig ( null ) ; return new DynamoDBTableMapper < T , H , R > ( this . db , this , config , getTableModel ( clazz , config ) ) ; }
Creates a new table mapper using this mapper to perform operations .
30,862
private static void pause ( long delay ) { if ( delay <= 0 ) { return ; } try { Thread . sleep ( delay ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; throw new SdkClientException ( e . getMessage ( ) , e ) ; } }
Batch pause .
30,863
public void setArrayValues ( java . util . Collection < Value > arrayValues ) { if ( arrayValues == null ) { this . arrayValues = null ; return ; } this . arrayValues = new java . util . ArrayList < Value > ( arrayValues ) ; }
Arbitrarily nested arrays
30,864
public void setConfigurationSets ( java . util . Collection < String > configurationSets ) { if ( configurationSets == null ) { this . configurationSets = null ; return ; } this . configurationSets = new java . util . ArrayList < String > ( configurationSets ) ; }
An object that contains a list of configuration sets for your account in the current region .
30,865
public void assertIsValidReferencePath ( String path , String propertyName ) { if ( path == null ) { return ; } if ( path . isEmpty ( ) ) { problemReporter . report ( new Problem ( this , String . format ( "%s cannot be empty" , propertyName ) ) ) ; return ; } }
Asserts that the string represents a valid reference path expression .
30,866
public static int getStreamBufferSize ( ) { int streamBufferSize = DEFAULT_STREAM_BUFFER_SIZE ; String bufferSizeOverride = System . getProperty ( SDKGlobalConfiguration . DEFAULT_S3_STREAM_BUFFER_SIZE ) ; if ( bufferSizeOverride != null ) { try { streamBufferSize = Integer . parseInt ( bufferSizeOverride ) ; } catch ( Exception e ) { log . warn ( "Unable to parse buffer size override from value: " + bufferSizeOverride ) ; } } return streamBufferSize ; }
Returns the buffer size override if it is specified in the system property otherwise returns the default value .
30,867
public void setWhitelistRules ( java . util . Collection < InputWhitelistRuleCidr > whitelistRules ) { if ( whitelistRules == null ) { this . whitelistRules = null ; return ; } this . whitelistRules = new java . util . ArrayList < InputWhitelistRuleCidr > ( whitelistRules ) ; }
List of IPv4 CIDR addresses to whitelist
30,868
protected void parseXmlInputStream ( DefaultHandler handler , InputStream inputStream ) throws IOException { try { if ( log . isDebugEnabled ( ) ) { log . debug ( "Parsing XML response document with handler: " + handler . getClass ( ) ) ; } BufferedReader breader = new BufferedReader ( new InputStreamReader ( inputStream , Constants . DEFAULT_ENCODING ) ) ; xr . setContentHandler ( handler ) ; xr . setErrorHandler ( handler ) ; xr . parse ( new InputSource ( breader ) ) ; } catch ( IOException e ) { throw e ; } catch ( Throwable t ) { try { inputStream . close ( ) ; } catch ( IOException e ) { if ( log . isErrorEnabled ( ) ) { log . error ( "Unable to close response InputStream up after XML parse failure" , e ) ; } } throw new SdkClientException ( "Failed to parse XML document with handler " + handler . getClass ( ) , t ) ; } }
Parses an XML document from an input stream using a document handler .
30,869
private void disableExternalResourceFetching ( XMLReader reader ) throws SAXNotRecognizedException , SAXNotSupportedException { reader . setFeature ( "http://xml.org/sax/features/external-general-entities" , false ) ; reader . setFeature ( "http://xml.org/sax/features/external-parameter-entities" , false ) ; reader . setFeature ( "http://apache.org/xml/features/nonvalidating/load-external-dtd" , false ) ; }
Disables certain dangerous features that attempt to automatically fetch DTDs
30,870
private static String checkForEmptyString ( String s ) { if ( s == null ) return null ; if ( s . length ( ) == 0 ) return null ; return s ; }
Checks if the specified string is empty or null and if so returns null . Otherwise simply returns the string .
30,871
private static int parseInt ( String s ) { try { return Integer . parseInt ( s ) ; } catch ( NumberFormatException nfe ) { log . error ( "Unable to parse integer value '" + s + "'" , nfe ) ; } return - 1 ; }
Safely parses the specified string as an integer and returns the value . If a NumberFormatException occurs while parsing the integer an error is logged and - 1 is returned .
30,872
private static long parseLong ( String s ) { try { return Long . parseLong ( s ) ; } catch ( NumberFormatException nfe ) { log . error ( "Unable to parse long value '" + s + "'" , nfe ) ; } return - 1 ; }
Safely parses the specified string as a long and returns the value . If a NumberFormatException occurs while parsing the long an error is logged and - 1 is returned .
30,873
private static String decodeIfSpecified ( String value , boolean decode ) { return decode ? SdkHttpUtils . urlDecode ( value ) : value ; }
Perform a url decode on the given value if specified . Return value by default ;
30,874
public ListBucketHandler parseListBucketObjectsResponse ( InputStream inputStream , final boolean shouldSDKDecodeResponse ) throws IOException { ListBucketHandler handler = new ListBucketHandler ( shouldSDKDecodeResponse ) ; parseXmlInputStream ( handler , sanitizeXmlDocument ( handler , inputStream ) ) ; return handler ; }
Parses a ListBucket response XML document from an input stream .
30,875
public ListObjectsV2Handler parseListObjectsV2Response ( InputStream inputStream , final boolean shouldSDKDecodeResponse ) throws IOException { ListObjectsV2Handler handler = new ListObjectsV2Handler ( shouldSDKDecodeResponse ) ; parseXmlInputStream ( handler , sanitizeXmlDocument ( handler , inputStream ) ) ; return handler ; }
Parses a ListBucketV2 response XML document from an input stream .
30,876
public ListVersionsHandler parseListVersionsResponse ( InputStream inputStream , final boolean shouldSDKDecodeResponse ) throws IOException { ListVersionsHandler handler = new ListVersionsHandler ( shouldSDKDecodeResponse ) ; parseXmlInputStream ( handler , sanitizeXmlDocument ( handler , inputStream ) ) ; return handler ; }
Parses a ListVersions response XML document from an input stream .
30,877
public ListAllMyBucketsHandler parseListMyBucketsResponse ( InputStream inputStream ) throws IOException { ListAllMyBucketsHandler handler = new ListAllMyBucketsHandler ( ) ; parseXmlInputStream ( handler , sanitizeXmlDocument ( handler , inputStream ) ) ; return handler ; }
Parses a ListAllMyBuckets response XML document from an input stream .
30,878
public AccessControlListHandler parseAccessControlListResponse ( InputStream inputStream ) throws IOException { AccessControlListHandler handler = new AccessControlListHandler ( ) ; parseXmlInputStream ( handler , inputStream ) ; return handler ; }
Parses an AccessControlListHandler response XML document from an input stream .
30,879
public BucketLoggingConfigurationHandler parseLoggingStatusResponse ( InputStream inputStream ) throws IOException { BucketLoggingConfigurationHandler handler = new BucketLoggingConfigurationHandler ( ) ; parseXmlInputStream ( handler , inputStream ) ; return handler ; }
Parses a LoggingStatus response XML document for a bucket from an input stream .
30,880
public void setBrokerInstances ( java . util . Collection < BrokerInstance > brokerInstances ) { if ( brokerInstances == null ) { this . brokerInstances = null ; return ; } this . brokerInstances = new java . util . ArrayList < BrokerInstance > ( brokerInstances ) ; }
A list of information about allocated brokers .
30,881
public DescribeBrokerResult withTags ( java . util . Map < String , String > tags ) { setTags ( tags ) ; return this ; }
The list of all tags associated with this broker .
30,882
public static CopyMonitor create ( TransferManager manager , CopyImpl transfer , ExecutorService threadPool , CopyCallable multipartCopyCallable , CopyObjectRequest copyObjectRequest , ProgressListenerChain progressListenerChain ) { CopyMonitor copyMonitor = new CopyMonitor ( manager , transfer , threadPool , multipartCopyCallable , copyObjectRequest , progressListenerChain ) ; Future < CopyResult > thisFuture = threadPool . submit ( copyMonitor ) ; copyMonitor . futureReference . compareAndSet ( null , thisFuture ) ; return copyMonitor ; }
Constructs a new watcher for copy operation and then immediately submits it to the thread pool .
30,883
protected List < MetricDatum > metricOfRequestOrRetryCount ( Field metricType , Request < ? > req , Object resp ) { AWSRequestMetrics m = req . getAWSRequestMetrics ( ) ; TimingInfo ti = m . getTimingInfo ( ) ; Number counter = ti . getCounter ( Field . RequestCount . name ( ) ) ; if ( counter == null ) { return Collections . emptyList ( ) ; } int requestCount = counter . intValue ( ) ; if ( requestCount < 1 ) { LogFactory . getLog ( getClass ( ) ) . debug ( "request count must be at least one" ) ; return Collections . emptyList ( ) ; } final double count = metricType == Field . RequestCount ? requestCount : requestCount - 1 ; if ( count < 1 ) { return Collections . emptyList ( ) ; } else { return Collections . singletonList ( new MetricDatum ( ) . withMetricName ( req . getServiceName ( ) ) . withDimensions ( new Dimension ( ) . withName ( Dimensions . MetricType . name ( ) ) . withValue ( metricType . name ( ) ) ) . withUnit ( StandardUnit . Count ) . withValue ( Double . valueOf ( count ) ) . withTimestamp ( endTimestamp ( ti ) ) ) ; } }
Returns a list with a single metric datum for the specified retry or request count predefined metric ; or an empty list if there is none .
30,884
protected List < MetricDatum > latencyMetricOf ( MetricType metricType , Request < ? > req , Object response , boolean includesRequestType ) { AWSRequestMetrics m = req . getAWSRequestMetrics ( ) ; TimingInfo root = m . getTimingInfo ( ) ; final String metricName = metricType . name ( ) ; List < TimingInfo > subMeasures = root . getAllSubMeasurements ( metricName ) ; if ( subMeasures != null ) { List < MetricDatum > result = new ArrayList < MetricDatum > ( subMeasures . size ( ) ) ; for ( TimingInfo sub : subMeasures ) { if ( sub . isEndTimeKnown ( ) ) { List < Dimension > dims = new ArrayList < Dimension > ( ) ; dims . add ( new Dimension ( ) . withName ( Dimensions . MetricType . name ( ) ) . withValue ( metricName ) ) ; if ( includesRequestType ) { dims . add ( new Dimension ( ) . withName ( Dimensions . RequestType . name ( ) ) . withValue ( requestType ( req ) ) ) ; } MetricDatum datum = new MetricDatum ( ) . withMetricName ( req . getServiceName ( ) ) . withDimensions ( dims ) . withUnit ( StandardUnit . Milliseconds ) . withValue ( sub . getTimeTakenMillisIfKnown ( ) ) ; result . add ( datum ) ; } } return result ; } return Collections . emptyList ( ) ; }
Returns all the latency metric data recorded for the specified metric event type ; or an empty list if there is none . The number of metric datum in the returned list should be exactly one when there is no retries or more than one when there are retries .
30,885
protected List < MetricDatum > counterMetricOf ( MetricType type , Request < ? > req , Object resp , boolean includesRequestType ) { AWSRequestMetrics m = req . getAWSRequestMetrics ( ) ; TimingInfo ti = m . getTimingInfo ( ) ; final String metricName = type . name ( ) ; Number counter = ti . getCounter ( metricName ) ; if ( counter == null ) { return Collections . emptyList ( ) ; } int count = counter . intValue ( ) ; if ( count < 1 ) { LogFactory . getLog ( getClass ( ) ) . debug ( "Count must be at least one" ) ; return Collections . emptyList ( ) ; } final List < MetricDatum > result = new ArrayList < MetricDatum > ( ) ; final Dimension metricDimension = new Dimension ( ) . withName ( Dimensions . MetricType . name ( ) ) . withValue ( metricName ) ; final MetricDatum first = new MetricDatum ( ) . withMetricName ( req . getServiceName ( ) ) . withDimensions ( metricDimension ) . withUnit ( StandardUnit . Count ) . withValue ( Double . valueOf ( count ) ) . withTimestamp ( endTimestamp ( ti ) ) ; result . add ( first ) ; if ( includesRequestType ) { Dimension requestDimension = new Dimension ( ) . withName ( Dimensions . RequestType . name ( ) ) . withValue ( requestType ( req ) ) ; final MetricDatum second = newMetricDatum ( first , metricDimension , requestDimension ) ; result . add ( second ) ; } return result ; }
Returns a list of metric datum recorded for the specified counter metric type ; or an empty list if there is none .
30,886
public java . util . concurrent . Future < ListJobsResult > listJobsAsync ( com . amazonaws . handlers . AsyncHandler < ListJobsRequest , ListJobsResult > asyncHandler ) { return listJobsAsync ( new ListJobsRequest ( ) , asyncHandler ) ; }
Simplified method form for invoking the ListJobs operation with an AsyncHandler .
30,887
private Map < String , SignerConfig > mergeSignerMap ( JsonIndex < SignerConfigJsonHelper , SignerConfig > [ ] defaults , JsonIndex < SignerConfigJsonHelper , SignerConfig > [ ] overrides , String theme ) { Map < String , SignerConfig > map = buildSignerMap ( defaults , theme ) ; Map < String , SignerConfig > mapOverride = buildSignerMap ( overrides , theme ) ; map . putAll ( mapOverride ) ; return Collections . unmodifiableMap ( map ) ; }
Returns an immutable map by merging the override signer configuration into the default signer configuration for the given theme .
30,888
private Map < String , SignerConfig > buildSignerMap ( JsonIndex < SignerConfigJsonHelper , SignerConfig > [ ] signerIndexes , String theme ) { Map < String , SignerConfig > map = new HashMap < String , SignerConfig > ( ) ; if ( signerIndexes != null ) { for ( JsonIndex < SignerConfigJsonHelper , SignerConfig > index : signerIndexes ) { String region = index . getKey ( ) ; SignerConfig prev = map . put ( region , index . newReadOnlyConfig ( ) ) ; if ( prev != null ) { log . warn ( "Duplicate definition of signer for " + theme + " " + index . getKey ( ) ) ; } } } return map ; }
Builds and returns a signer configuration map .
30,889
public SignerConfig getSignerConfig ( String serviceName , String regionName ) { if ( serviceName == null ) throw new IllegalArgumentException ( ) ; SignerConfig signerConfig = null ; if ( regionName != null ) { String key = serviceName + SERVICE_REGION_DELIMITOR + regionName ; signerConfig = serviceRegionSigners . get ( key ) ; if ( signerConfig != null ) { return signerConfig ; } signerConfig = regionSigners . get ( regionName ) ; if ( signerConfig != null ) { return signerConfig ; } } signerConfig = serviceSigners . get ( serviceName ) ; return signerConfig == null ? defaultSignerConfig : signerConfig ; }
Returns the signer configuration for the specified service name and an optional region name .
30,890
public XMLWriter startElement ( String element ) { append ( "<" + element ) ; if ( rootElement && xmlns != null ) { append ( " xmlns=\"" + xmlns + "\"" ) ; rootElement = false ; } append ( ">" ) ; elementStack . push ( element ) ; return this ; }
Starts a new element with the specified name at the current position in the in - progress XML document .
30,891
public XMLWriter value ( ByteBuffer b ) { append ( escapeXMLEntities ( Base64 . encodeAsString ( BinaryUtils . copyBytesFrom ( b ) ) ) ) ; return this ; }
Adds the specified value as Base64 encoded text to the current position of the in progress XML document .
30,892
public static Future < ? > publishProgress ( final ProgressListener listener , final ProgressEventType type ) { if ( listener == ProgressListener . NOOP || listener == null || type == null ) { return null ; } return deliverEvent ( listener , new ProgressEvent ( type ) ) ; }
Used to deliver a progress event to the given listener .
30,893
public static Future < ? > publishResponseBytesDiscarded ( final ProgressListener listener , final long bytesDiscarded ) { return publishResetEvent ( listener , ProgressEventType . RESPONSE_BYTE_DISCARD_EVENT , bytesDiscarded ) ; }
Convenient method to publish a response bytes discard event to the given listener .
30,894
public void shutdown ( ) { shutDown = true ; try { while ( inflightReceiveMessageBatches > 0 ) Thread . sleep ( 100 ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } }
Prevents spawning of new retrieval batches and waits for all in - flight retrieval batches to finish
30,895
public QueueBufferFuture < ReceiveMessageRequest , ReceiveMessageResult > receiveMessageAsync ( ReceiveMessageRequest rq , QueueBufferCallback < ReceiveMessageRequest , ReceiveMessageResult > callback ) { if ( shutDown ) { throw new AmazonClientException ( "The client has been shut down." ) ; } int numMessages = 10 ; if ( rq . getMaxNumberOfMessages ( ) != null ) { numMessages = rq . getMaxNumberOfMessages ( ) ; } QueueBufferFuture < ReceiveMessageRequest , ReceiveMessageResult > toReturn = issueFuture ( numMessages , callback ) ; satisfyFuturesFromBuffer ( ) ; spawnMoreReceiveTasks ( ) ; return toReturn ; }
Submits the request for retrieval of messages from the queue and returns a future that will be signalled when the request is satisfied . The future may already be signalled by the time it is returned .
30,896
private ReceiveMessageFuture issueFuture ( int size , QueueBufferCallback < ReceiveMessageRequest , ReceiveMessageResult > callback ) { synchronized ( futures ) { ReceiveMessageFuture theFuture = new ReceiveMessageFuture ( callback , size ) ; futures . addLast ( theFuture ) ; return theFuture ; } }
Creates and returns a new future object . Sleeps if the list of already - issued but as yet unsatisfied futures is over a throttle limit .
30,897
private void satisfyFuturesFromBuffer ( ) { synchronized ( futures ) { synchronized ( finishedTasks ) { while ( ( ! futures . isEmpty ( ) ) && ( ! finishedTasks . isEmpty ( ) ) ) { pruneExpiredTasks ( ) ; if ( ! finishedTasks . isEmpty ( ) ) { fufillFuture ( futures . poll ( ) ) ; } } } } }
Attempts to satisfy some or all of the already - issued futures from the local buffer . If the buffer is empty or there are no futures this method won t do anything .
30,898
private void fufillFuture ( ReceiveMessageFuture future ) { ReceiveMessageBatchTask task = finishedTasks . getFirst ( ) ; ReceiveMessageResult result = new ReceiveMessageResult ( ) ; LinkedList < Message > messages = new LinkedList < Message > ( ) ; result . setMessages ( messages ) ; Exception exception = task . getException ( ) ; int numRetrieved = 0 ; boolean batchDone = false ; while ( numRetrieved < future . getRequestedSize ( ) ) { Message msg = task . removeMessage ( ) ; if ( msg != null ) { messages . add ( msg ) ; ++ numRetrieved ; } else { batchDone = true ; break ; } } batchDone = batchDone || task . isEmpty ( ) || ( exception != null ) ; if ( batchDone ) { finishedTasks . removeFirst ( ) ; } result . setMessages ( messages ) ; if ( exception != null ) { future . setFailure ( exception ) ; } else { future . setSuccess ( result ) ; } }
Fills the future with whatever results were received by the full batch currently at the head of the completed batch queue . Those results may be retrieved messages or an exception . This method assumes that you are holding the finished tasks lock locks when invoking it . violate this assumption at your own peril
30,899
private void pruneExpiredTasks ( ) { int numberExpiredTasksPruned = pruneHeadTasks ( new Predicate < ReceiveQueueBuffer . ReceiveMessageBatchTask > ( ) { public boolean test ( ReceiveMessageBatchTask t ) { return t . isExpired ( ) && t . getException ( ) == null ; } } ) ; if ( numberExpiredTasksPruned > 0 ) { pruneHeadTasks ( new Predicate < ReceiveQueueBuffer . ReceiveMessageBatchTask > ( ) { public boolean test ( ReceiveMessageBatchTask t ) { return t . isEmpty ( ) && t . getException ( ) == null ; } } ) ; } }
Prune any expired tasks that do not have an exception associated with them . This method assumes that you are holding the finishedTasks lock when invoking it