Missing null check for cache response metadata High

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.

Detector ID
java/null-check-cache-response-metadata@v1.0
Category
Common Weakness Enumeration (CWE) external icon

Noncompliant example

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}

Compliant example

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}