0

Please help me with my problem.. what I should do is when a user deletes a file, a trigger will check if there is existing file ID (File_Id__c) in the Custom_Object__c, if so, delete it in AWSS3 as well.

The trigger will run when a user deletes a file. This will query Custom_Object__c to find if the file Id is recorded in File_Id__c (Text field), if there is and if File_Saved__c is TRUE, then run Http Callout to delete file in AWSS3.

I'm getting this error System.ListException: List index out of bounds: 0

Please check what's wrong..

public class FileDeleteHandler {
    @future(callout=true)
    public static void fileDeleteMethod(Set<Id> fileIds) {
        List<CustomSettings__c> settings =  [SELECT BucketName__c, ClientKey__c, Region__c, SecretKey__c FROM CustomSettings__c LIMIT 1];

        String bucketName = '';
        String region = '';
        String clientKey = '';
        String secretKey = '';

        if(!settings.isEmpty()){
            bucketName = settings[0].BucketName__c;
            region = settings[0].Region__c;
            clientKey = settings[0].ClientKey__c;
            secretKey = settings[0].SecretKey__c;
            if(String.isBlank(bucketName)||String.isBlank(region)||
                String.isBlank(clientKey)||String.isBlank(secretKey)){
                return;
            }
        }

        List<Custom_Object__c> coList = [SELECT Id, Name, Path__c, File_ID__c, File_Saved__c FROM Custom_Object__c WHERE File_ID__c =: fileIds];

        if (!coList.isEmpty()) {
            if (coList[0].File_Saved__c== true) {
                List<ContentVersion> cvs = [SELECT Title, ContentDocumentId, FileExtension, FileType, VersionData FROM ContentVersion WHERE ContentDocumentId IN :fileIds]; //This is EMPTY!

                String path = coList[0].Path__c;

                String formattedDateString = Datetime.now().format('EEE, dd MMM yyyy HH:mm:ss z');
                Blob data = cvs[0].VersionData;

                HttpRequest req = new HttpRequest();
                Http http = new Http();

                req.setHeader('Content-Type', cvs[0].FileExtension);
                req.setMethod('DELETE');
                req.setHeader('Host','s3.amazonaws.com');
                req.setEndpoint('https://s3.amazonaws.com'+'/'+bucketName+'/'+path);
                req.setHeader('Date',formattedDateString);
                req.setHeader('Authorization', createAuthHeader('DELETE', cvs[0].FileExtension, path, formattedDateString, bucketName, clientKey, secretKey));
                req.setBodyAsBlob(data);
                req.setHeader('Content-Length', String.valueOf((EncodingUtil.base64Encode(data)).length()));

                try{
                    HTTPResponse res = http.send(req);

                    System.debug('MYDEBUG: ' + cvs[0].Title + ' RESPONSE STRING: ' + res.toString());
                    System.debug('MYDEBUG: ' + cvs[0].Title + ' RESPONSE STATUS: '+res.getStatus());
                    System.debug('MYDEBUG: ' + cvs[0].Title + ' STATUS_CODE:'+res.getStatusCode());

                } catch(System.CalloutException e) {
                    System.debug('AWS Callout Exception on ' + cvs[0].Title + 'ERROR: ' + e.getMessage());
                }
            } else if (coList[0].File_Saved__c== false) {
                 delete coList;
            }
        }
    }

    public static string createAuthHeader(String method,String contentType,String filename,String formattedDateString,String bucket,String client,String secret){
        string auth;
        String stringToSign = method+'\n\n'+contentType+'\n'+formattedDateString+'\n/'+bucket+'/'+filename;
        Blob mac = Crypto.generateMac('HMACSHA1', blob.valueof(stringToSign),blob.valueof(secret));
        String sig = EncodingUtil.base64Encode(mac);
        auth = 'AWS' + ' ' + client + ':' + sig;
        return auth;
    }
}

Trigger:

trigger DocumentTrigger on ContentDocument (before delete) {
    Set<Id> fileIds = new Set<Id>();
    fileIds = Trigger.oldMap.keySet();
    FileDeleteHandler.fileDeleteMethod(fileIds);
}
2
  • Please edit your post to ask a specific question. (See How to Ask). It's impossible for the community to determine by itself what "right" means for this code, so we need you to help us understand what support you need.
    – David Reed
    Commented Jul 27, 2019 at 18:53
  • Hi @DavidReed, I've edited my question, sorry for confusion.
    – Almond
    Commented Jul 29, 2019 at 2:32

1 Answer 1

0

If the Trigger is on document deletion, it is possible that the ContentVersion you are querying is also deleted? Therefore it will return zero rows and your list will be empty, giving you a ListException. This can be prevented by using a BeforeDelete trigger, or gathering the necessary data from the Trigger context itself if available, instead of querying the database.

This depends whether you are running this method via anonymous block, via a class, or via a trigger which is currently unclear.

To further troubleshoot, could you please specify if it is running via a trigger to produce this exact error, and what trigger event are you using.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .