Attempting to access the cached response metadata using the method getCachedResponseMetadata
without performing a null
check on the metadata can lead to null
dereference error. Add a null
check on the cached metadata that is returned by getCachedResponseMetadata
before accessing the metadata.
1public void getCachedResponseMetadataNoncompliant(AmazonWebServiceRequest request, AmazonS3 amazonS3Client) {
2 S3ResponseMetadata responseMetadata = amazonS3Client.getCachedResponseMetadata(request);
3 // Noncompliant: uses the result of getCachedResponseMetadata without null-checking it.
4 log.info("Request ID: " + responseMetadata.getRequestId());
5}
1public void getCachedResponseMetadataCompliant(AmazonWebServiceRequest request, AmazonS3 amazonS3Client) {
2 S3ResponseMetadata responseMetadata = amazonS3Client.getCachedResponseMetadata(request);
3 // Compliant: ensures that the result of getCachedResponseMetadata is not null before using it.
4 if (responseMetadata != null) {
5 log.info("Request ID: " + responseMetadata.getRequestId());
6 } else {
7 log.info("Could not obtain cached metadata.");
8 }
9}