Spring boot Lambda Function throws null pointer exception for autowired dependency

Viewed 42

I have a spring boot application, building it as a .zip and using it as a lambda function in AWS. I tested the entire flow locally by use of a Postconstruct method(got rid of this test class in the zip folder that was uploaded).

@Component
public class LambdaMethodHandler implements RequestHandler<SQSEvent, String> {

    @Autowired
    public FileService fileService;

    @Autowired
    public SlackUtils slackUtils;

    @Override
    public String handleRequest(SQSEvent event, Context context){

        context.getLogger().log("Started processing messages in DLQ");
        List<String> failedMessages = new ArrayList<>();

        event.getRecords().stream().forEach(message -> {
            context.getLogger().log("Message body: "+message.getBody()+", Message sent on: "+message.getMessageAttributes().get("timestamp")+", Message ID: "+message.getMessageId());
            failedMessages.add(message.getBody());
        });
        File file = null;
        if(failedMessages != null && failedMessages.size()>0) {
            try {
                context.getLogger().log("Failed Messaged added to list, list size: "+failedMessages.size());
                context.getLogger().log("Failed Messaged added to list, list size Second Test log: "+failedMessages.size());
                String fileName = fileService.generateFileName(context);
                context.getLogger().log("File Name: "+fileName);
                file = new File(fileName);
                context.getLogger().log("File Path1: "+file.getAbsolutePath());
                FileUtils.writeLines(file, failedMessages);
                context.getLogger().log("File Path2: "+file.getAbsolutePath());
                URL fileUrl = fileService.uploadFileToS3(file, Constants.FOLDER_NAME, file.getName());
                context.getLogger().log("File URL: "+fileUrl.toString());
                SlackMessageAttachment slackMessageAttachment = slackUtils.buildSlackMessage(String.valueOf(fileUrl));
                slackUtils.sendMessage(slackMessageAttachment);
            } catch (Exception e) {
                context.getLogger().log("Exception caught "+e.toString());
            }finally {
                if(file != null) {
                    context.getLogger().log(("Deleting File: "+file.getName()));
                    file.delete();
                }
                else{
                    context.getLogger().log("File is null");
                }
            }
        }
        return event.toString();
    }
}

I can see the logs in cloudwatch till "Failed Messaged added to list, list size Second Test log: " this log. post that it throws a null pointer exception.

Complete Logs:

Started processing messages in DLQ
Message body: "Hello World", Message sent on: null, Message ID: 7938a2a7-991a-4b57-af58-132369243ef0
Failed Messaged added to list, list size: 1
Failed Messaged added to list, list size Second Test log: 1
Exception caught java.lang.NullPointerException
File is null

the line where I'm calling generateFileName() is throwing null pointer exception.

The dependency class:

@Component
@Slf4j
public class FileService {

    @Autowired
    private S3PlatformStatusUtils s3PlatformStatusUtils;

    public String generateFileName(Context context){
        context.getLogger().log("In method generate FileName");
        String timeStamp = new SimpleDateFormat("yyyy_MM_dd").format(new Timestamp(System.currentTimeMillis()));
        context.getLogger().log("TimeStamp: "+timeStamp);
        String fileName = Constants.BASE_FILE_NAME+timeStamp+Constants.TEXT_FILE_EXTENSION;
        context.getLogger().log("FileName: "+fileName);
        return fileName;
    }


    public URL uploadFileToS3(File file, String folder, String fileName) throws Exception {
        log.info("Start : uploadFileToS3");

        if(!file.exists()) {
            log.info("File does not exists in the specified location cannot upload the file to s3 : " + file.getAbsolutePath());
            throw new Exception("File does not exists in the specified location cannot upload the file to s3");
        } else {
            log.info("File Exists uploading file to s3 folder :" + folder);
            String response = null;
            try {
                //response = s3PlatformStatusUtils.uploadToS3(file, Constants.BUCKET_NAME, folder, null);
                response = s3PlatformStatusUtils.uploadToS3(file, Constants.BUCKET_NAME, folder, null);

            } catch(Exception e) {
                log.error("Exception in uploading file to s3 ", e);
                throw e;
            }
            if(response != null && response.contains("SUCCESS")) {
                log.info("File successfully uploaded s3 Response :: {}", response);
                return(generateUrl(Constants.BUCKET_NAME, folder + "/" + fileName));
                //return Constants.BUCKET_NAME + "/" + folder + "/" + fileName;
            }
        }
        return null;
    }

    private URL generateUrl(String bucketName, String objectKey) throws IOException {
        try {
            // Set the presigned URL to expire after one hour.
            java.util.Date expiration = new java.util.Date();
            long expTimeMillis = Instant.now().toEpochMilli();
            expTimeMillis += 1000 * 60 * 60;
            expiration.setTime(expTimeMillis);

            // Generate the presigned URL.
            System.out.println("Generating pre-signed URL.");
            GeneratePresignedUrlRequest generatePresignedUrlRequest =
                    new GeneratePresignedUrlRequest(bucketName, objectKey)
                            .withMethod(HttpMethod.GET)
                            .withExpiration(expiration);
            URL url = s3PlatformStatusUtils.getS3Config().getS3Client().generatePresignedUrl(generatePresignedUrlRequest);
            return url;

        } catch (AmazonServiceException e) {
            e.printStackTrace();
        } catch (SdkClientException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Main Class:

@SpringBootApplication
public class BOPlatformStatusLambda {
    public static void main(String[] args) {
        SpringApplication.run(BOPlatformStatusLambda.class, args);
    }
}

The code is working locally as expected using the test class. All the dependencies are injected and methods are called as expected. But not sure why the lambda function is throwing the exception.

0 Answers
Related