0

enter image description hereenter image description hereI recieve this error when testing the bulk uploading that we have implemented on our SF environment

Apex Class:

public class CarrierUpdateController {

  public transient Blob fileContent {get;set;}  // The uploaded File.
  public transient string fileName {get;set;}   // The FileName of the File.
  public transient string fileData{get;set;}    // The Data within the File.
  public transient Integer fileSize {get;set;}  // The File Size of the File.

  public boolean displayPopup {get; set;}  // Displays the PopUp form with Field Mapping
  public Id batchId {get; set;}  // The Job Id of the Scheduled Batch

  public Boolean batchStatusBool {get;set;}
  public String batchStatus {get;set;}
  public String batchStatusDetail {get;set;}
  public Boolean pollerBool {get;set;}
  public Integer batchTotalBatches {get; set;}
  public Integer batchProcessedBatches {get; set;}
  public Integer batchFailures {get; set;}

  public CarrierUpdate__c newCarrierUpdate {get;set;}
  public List<CarrierUpdateDetail__c> cudToInsert {get;set;}
  public Boolean processData {get;set;}
  public List<CarrierUpdateFileMapping__c> fieldMapping {get;set;}
  public Map<String, CarrierUpdateFileMapping__c> carrierUploadFileMap {get;set;}
  public Map<String, Integer> fieldHeaderMap = new Map<String, Integer>();

  transient String[] fileRows = new String[]{};
  transient String fieldValue;
  transient Integer fieldNumber;

  public CarrierUpdateController() {

    batchStatusBool = false;
    pollerBool = false;

    cudToInsert = new List<CarrierUpdateDetail__c>();
    processData = false;

    // Make sure the "CarrierUpdateFileMapping__c" Custom Setting is populated.
    carrierUploadFileMap = CarrierUpdateFileMapping__c.getAll();
    fieldMapping = new List<CarrierUpdateFileMapping__c>([SELECT Id, ColumnHeader__c, FieldLabel__c 
                                                            FROM CarrierUpdateFileMapping__c 
                                                            ORDER BY ColumnHeader__c ASC]);
  }


  /**
  * @description Method to read and import the CSV File into CarrierUpdate__c Object
  */
  public Pagereference readCSVFile(){

    // Make sure a File has been chosen.
    if(fileContent == null){
      ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.WARNING,'Please select a CSV File to Upload.');
      ApexPages.addMessage(errormsg);
      return null;
    }

    // Only accept CSV Files.
    if(!fileName.toUpperCase().contains('.CSV')){
      ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.WARNING,'Please select a CSV File to Upload.');
      ApexPages.addMessage(errormsg);
      return null;
    }  

    // Make sure the "CarrierUpdateFileMapping__c" Custom Setting is populated.
    if(carrierUploadFileMap == null){
      ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.WARNING,'The "Carrier Update File Mapping" Custom Setting is missing. Please contact your Salesforce Admin');
      ApexPages.addMessage(errormsg);
      return null;
    }

    try{      

      // Convert the uploaded file from BLOB format into a string.
      fileData = blobToString(fileContent,'ISO-8859-1');

      // Now sepatate every row of the CSV file.
      fileRows = fileData.split('\n');

      // Get the position and header value for the first row in the fileRows Array.
      String[] fileColumnHeader = fileRows[0].split(',');
      for (Integer i = 0; i < fileColumnHeader.size(); i++) {
        fieldHeaderMap.put(fileColumnHeader[i], i);
      }
      //System.debug('****** fieldHeaderMap: '+fieldHeaderMap);

      // Get the Number of rows within the File.
      fileSize = fileRows.Size();

      // Map collection of the file row data.
      Map<Integer,String[]> mapOfRows = new Map<Integer,String[]>();

      for(Integer i = 1; i < fileRows.size(); i++) {
        string[] rowValues = fileRows[i].split(',');
        System.debug('****** Row: '+ i + ' |  rowValues: '+rowValues);

        for(String fieldName: fileColumnHeader) {
          fieldNumber = fieldHeaderMap.get(fieldName);
          //System.debug('****** fieldNumber: '+fieldNumber);
          //System.Debug('***** carrierUploadFileMap.containsKey: '+carrierUploadFileMap.containsKey(String.valueOf(fieldNumber)));
          if(carrierUploadFileMap.containsKey(String.valueOf(fieldNumber))){
            fieldValue = rowValues[fieldNumber].trim();

            if(!mapOfRows.containsKey(i)){
              mapOfRows.put(i,new String[]{fieldValue});
            }
            else{
              mapOfRows.get(i).add(fieldValue);
            }
          }
        }
      }

      if(!mapOfRows.isEmpty()){
        try{
          newCarrierUpdate = new CarrierUpdate__c();
          newCarrierUpdate.FileSize__c = String.valueOf(mapOfRows.Size());
          newCarrierUpdate.FileName__c = fileName;
          newCarrierUpdate.UploadedBy__c = Userinfo.getUserId();
          newCarrierUpdate.UploadDate__c = System.today();
          Insert newCarrierUpdate;
        } catch(DMLException e){
          ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured whilst trying to insert a Carrier Update Record'+e.getMessage());
          ApexPages.addMessage(errormsg);
        }

        for(Integer i : mapOfRows.keySet()){
          // Get the Row date from the Map mapOfRows.
          String[] fields = mapOfRows.get(i);    

          // Create a new Carrier Update Detail record for each row in the Map.
          CarrierUpdateDetail__c cud = new CarrierUpdateDetail__c();
          cud.CarrierUpdateId__c = newCarrierUpdate.Id;
          cud.CaseNumber__c = String.isBlank(fields[0]) ? null : fields[0].leftPad(8,'0');
          cud.CarrierOrderReference__c = String.isBlank(fields[1]) ? null : fields[1];
          cud.OrderAccepted__c = String.isBlank(fields[2]) ? null : Date.valueOf(fields[2]); 
          cud.SiteSurveyDate__c = String.isBlank(fields[3]) ? null : Date.valueOf(fields[3]);
          cud.SiteSurveyTime__c = String.isBlank(fields[4]) ? null : fields[4];
          cud.Category__c = String.isBlank(fields[5]) ? null : fields[5];
          cud.KCI3ReceivedDate__c = String.isBlank(fields[6]) ? null : Date.valueOf(fields[6]);
          cud.ConfirmedDeliveryDate__c = String.isBlank(fields[7]) ? null : Date.valueOf(fields[7]);
          cud.InstallationDate__c = String.isBlank(fields[8]) ? null : Date.valueOf(fields[8]);
          cud.EndToEndTestDate__c = String.isBlank(fields[9]) ? null : Date.valueOf(fields[9]);
          cud.EndToEndTestTime__c = String.isBlank(fields[10]) ? null : fields[10];
          cud.NextUpdateDue__c = String.isBlank(fields[11]) ? null : Date.valueOf(fields[11]);
          cud.InternalComment__c = String.isBlank(fields[12]) ? null : fields[12]; 
          cud.PartnerComment__c = String.isBlank(fields[13]) ? null : fields[13];
          cud.Router_Required_Date__c = String.isBlank(fields[14]) ? null : Date.valueOf(fields[14]);
          cud.CaseId__c = String.isBlank(fields[15]) ? null : fields[15];
          cud.Case_Owner__c = String.isBlank(fields[16]) ? null : fields[16];

          cudToInsert.add(cud);
        }
      }
    }
    catch(Exception e){
      ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured reading the CSV file'+e.getMessage());
      ApexPages.addMessage(errormsg);
    }       

    // Finally, insert the collected records
    try{
      insert cudToInsert;
        processData = true;
    }
    catch (Exception e){
      ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured inserting the records'+e.getMessage());
      ApexPages.addMessage(errormsg);
    }    
    return null;
  }


  /**
  * @description Method to 
  * @param input - The CSV file being uploaded.
  * @param inCharset - The character used.
  */
   public static String blobToString(Blob input, String inCharset){

    String hex = EncodingUtil.convertToHex(input);
    System.assertEquals(0, hex.length() & 1);
    final Integer bytesCount = hex.length() >> 1;
    String[] bytes = new String[bytesCount];

    for(Integer i = 0; i < bytesCount; ++i){
      bytes[i] =  hex.mid(i << 1, 2);
    }
    return EncodingUtil.urlDecode('%' + String.join(bytes, '%'), inCharset);
  } 


  /**
  * @description Method used to display the imported data in the CarrierUpdateDetail__c Object.
  */
  public CarrierUpdateDetail__c[] getCarrierUpdateDetails(){

    if(cudToInsert!= NULL){
      if(cudToInsert.size() > 0){
        return [SELECT Id, CarrierUpdateId__c, CaseNumber__c, CarrierOrderReference__c, OrderAccepted__c, SiteSurveyDate__c, SiteSurveyTime__c, Category__c, KCI3ReceivedDate__c, ConfirmedDeliveryDate__c, InstallationDate__c, EndToEndTestDate__c, EndToEndTestTime__c, NextUpdateDue__c, InternalComment__c, PartnerComment__c
                FROM CarrierUpdateDetail__c
                WHERE CarrierUpdateId__c =: newCarrierUpdate.Id
                LIMIT 1000];
      }else{
        return null;                    
      }
    }else{
      return null;
    }
  }  


  /**
  * @description Method to process the import data inserted in the CarrierUpdateDetail__c object.
  */
  //public Pagereference processData(){
  public void processData(){    

    batchStatusBool = true;

    Map<String, CarrierUpdateDetail__c> carrierUpdateDetailMap = new Map<String, CarrierUpdateDetail__c>();
    for(CarrierUpdateDetail__c cud: [SELECT Id, CaseId__c, CaseNumber__c, CarrierOrderReference__c ,Category__c, InternalComment__c, PartnerComment__c, NextUpdateDue__c, ConfirmedDeliveryDate__c, 
                                      EndToEndTestDate__c, EndToEndTestTime__c, InstallationDate__c, KCI3ReceivedDate__c, OrderAccepted__c, SiteSurveyDate__c, SiteSurveyTime__c
                                      FROM CarrierUpdateDetail__c WHERE CarrierUpdateId__c =: newCarrierUpdate.Id]){
      carrierUpdateDetailMap.put(cud.CaseNumber__c, cud);
    }

    // CALL THE BATCH APEX CLASS BatchCarrierUpdate.cls TO PROCESS THE DATA UPDATE.
    BatchCarrierUpdate b = new BatchCarrierUpdate(carrierUpdateDetailMap);
    batchId = Database.executeBatch(b,5);
    checkBatchStatus();

    //return new PageReference('/' + newCarrierUpdate.Id); 
    //return new PageReference('/apex/CarrierUpdate'); 
  }

  public void checkBatchStatus() {
    AsyncApexJob job = [SELECT Id, TotalJobItems, Status, NumberOfErrors, ExtendedStatus, JobItemsProcessed, JobType, ApexClassId, CreatedDate FROM AsyncApexJob WHERE Id =: batchId LIMIT 1];
    batchStatus = job.Status;
    batchStatusDetail = job.ExtendedStatus;
    batchTotalBatches = job.TotalJobItems;
    batchProcessedBatches = job.JobItemsProcessed;
    batchFailures = job.NumberOfErrors;

    if(batchStatus == 'Completed') {
        pollerBool = false;
    } else {
        pollerBool = true;
    }
  }


  /**
  * @description Method to Cancel the Carrier Update import.
  */
  public PageReference cancelUpdate() {

    if(newCarrierUpdate != null) {
      try {
        List<CarrierUpdate__c> toDelete = [SELECT Id FROM CarrierUpdate__c WHERE Id =: newCarrierUpdate.Id];
        delete toDelete;
      } catch(Exception e) {
          ApexPages.addMessages(e);
      }
    }
    return new PageReference('/a0a'); 
  }   


  /**
  * @description Method to Close the Carrier Update import.
  */
  public PageReference Close() {
    return new PageReference('/' + newCarrierUpdate.Id); 
  }   

  public void closePopup() {        
      displayPopup = false;    
  }     
  public void showPopup() {        
      displayPopup = true;    
  }   

}

Here is the test class to go with it:

@isTest
private class CarrierUpdateControllerTest {

    static {

        insert new CarrierUpdateFileMapping__c(Name='0',ColumnHeader__c='A',FieldLabel__c='Partner Ref',APIName__c='CaseNumber__c');
        insert new CarrierUpdateFileMapping__c(Name='5',ColumnHeader__c='F',FieldLabel__c=' Order Accepted Date KCI1 Date)',APIName__c='OrderAccepted__c');
        insert new CarrierUpdateFileMapping__c(Name='6',ColumnHeader__c='G',FieldLabel__c=' Site Survey Date (B End)',APIName__c='SiteSurveyDate__c');
        insert new CarrierUpdateFileMapping__c(Name='7',ColumnHeader__c='H',FieldLabel__c=' Site Survey Time (B End)',APIName__c='SiteSurveyTime__c');
        insert new CarrierUpdateFileMapping__c(Name='11',ColumnHeader__c='L',FieldLabel__c='Category',APIName__c='Category__c');
        insert new CarrierUpdateFileMapping__c(Name='12',ColumnHeader__c='M',FieldLabel__c='KCI-3 Received Date',APIName__c='KCI3ReceivedDate__c');
        insert new CarrierUpdateFileMapping__c(Name='13',ColumnHeader__c='N',FieldLabel__c='Confirmed Delivery Date (CDD)',APIName__c='ConfirmedDeliveryDate__c');
        insert new CarrierUpdateFileMapping__c(Name='14',ColumnHeader__c='O',FieldLabel__c='Installation Date (B End)',APIName__c='InstallationDate__c');                                                   
        insert new CarrierUpdateFileMapping__c(Name='15',ColumnHeader__c='P',FieldLabel__c='End to End Test Date (B End)',APIName__c='EndToEndTestDate__c');
        insert new CarrierUpdateFileMapping__c(Name='17',ColumnHeader__c='R',FieldLabel__c='Internal Comment',APIName__c='InternalComment__c');
        insert new CarrierUpdateFileMapping__c(Name='18',ColumnHeader__c='S',FieldLabel__c='Partner Comment',APIName__c='PartnerComment__c');
        insert new CarrierUpdateFileMapping__c(Name='19',ColumnHeader__c='T',FieldLabel__c='Router Required Date',APIName__c='Router_Required_Date__c');
        insert new CarrierUpdateFileMapping__c(Name='20',ColumnHeader__c='U',FieldLabel__c='Case ID',APIName__c='CaseId__c');
        insert new CarrierUpdateFileMapping__c(Name='21',ColumnHeader__c='V',FieldLabel__c='Case Owner',APIName__c='Case_Owner__c');
        insert new CarrierUpdateFileMapping__c(Name='22',ColumnHeader__c='W',FieldLabel__c='Case Number',APIName__c='CaseNumber__c');

        insert new CaseToCarrierUpdatedMap__c(Name='Category__c',CarrierUpdateField__c='Category__c');        
        insert new CaseToCarrierUpdatedMap__c(Name='Confirmed_Delivery_Date__c',CarrierUpdateField__c='ConfirmedDeliveryDate__c');        
        insert new CaseToCarrierUpdatedMap__c(Name='End_to_End_Test_Date__c',CarrierUpdateField__c='EndToEndTestDate__c');        
        insert new CaseToCarrierUpdatedMap__c(Name='Installation_Date__c',CarrierUpdateField__c='InstallationDate__c');        
        insert new CaseToCarrierUpdatedMap__c(Name='KCI_3_Received_Date__c',CarrierUpdateField__c='KCI3ReceivedDate__c');        
        insert new CaseToCarrierUpdatedMap__c(Name='Order_Accepted__c',CarrierUpdateField__c='OrderAccepted__c');        
        insert new CaseToCarrierUpdatedMap__c(Name='Site_Survey_Date__c',CarrierUpdateField__c='SiteSurveyDate__c');        
        insert new CaseToCarrierUpdatedMap__c(Name='Site_Survey_Time__c',CarrierUpdateField__c='SiteSurveyTime__c');                                
   }

    @istest
    public static void uploadMissingFileNegativeTest() {  

        PageReference pageref = Page.CarrierUpdate;
        Test.setCurrentPage(pageref);

        CarrierUpdateController controller = new CarrierUpdateController();
        controller = new CarrierUpdateController();
        controller.fileName = 'CarrierUpdate.csv';

        Test.startTest();  // Start the test, this changes limit context back to test from trigger.
        controller.readCSVFile();
        Test.stopTest();  // Stop the test, this changes limit context back to test from trigger. 

        // get the list of ApexPages.Message
        List<ApexPages.Message> msgList = ApexPages.getMessages();
        for(ApexPages.Message msg :  ApexPages.getMessages()) {
            System.assertEquals('Please select a CSV File to Upload.', msg.getSummary());
            System.assertEquals(ApexPages.Severity.WARNING, msg.getSeverity());
        }             
    }

    @istest
    public static void uploadUnknownFileTypeNegativeTest() {  

        String fieldHeader = 'Partner Reference,TTB Reference,Date order placed with OR,VLAN,NNI,KCI1 Date,Survey Date,Survey Time,KCI2 Received Date,ECCs Applicable,Wayleave Required,Category of Works,KCI3 Received Date,CDD,Fibre Date,F&T Date,Next Update Due,Comment';
        String csvLine1 = '00557591,TTB0725036,2017-04-10,1053,nge001.loh-10XE-11/2/2,2017-04-11,2017-04-12,AM,2017-04-13,Null,Null,2,2017-04-14,2017-04-15,2017-04-16,2017-04-17,2017-04-18,InternalComment,PartnerComment';
        String csvLine2 = '00557592,TTB0725036,2017-04-10,1053,nge001.loh-10XE-11/2/2,2017-04-11,2017-04-12,AM,2017-04-13,Null,Null,2,2017-04-14,2017-04-15,2017-04-16,2017-04-17,2017-04-18,InternalComment,PartnerComment';
        String csvLine3 = '00557593,TTB0725036,2017-04-10,1053,nge001.loh-10XE-11/2/2,2017-04-11,2017-04-12,AM,2017-04-13,Null,Null,2,2017-04-14,2017-04-15,2017-04-16,2017-04-17,2017-04-18,InternalComment,PartnerComment';
        String blobCreator = fieldHeader + '\r\n' + csvLine1 + '\r\n' + csvLine2 + '\r\n' + csvLine3;     

        PageReference pageref = Page.CarrierUpdate;
        Test.setCurrentPage(pageref);

        CarrierUpdateController controller = new CarrierUpdateController();
        controller = new CarrierUpdateController();
        controller.fileName = 'CarrierUpdate.txt';
        controller.fileContent = Blob.valueOf(blobCreator);

        Test.startTest();  // Start the test, this changes limit context back to test from trigger.
        controller.readCSVFile();
        Test.stopTest();  // Stop the test, this changes limit context back to test from trigger. 

        // get the list of ApexPages.Message
        List<ApexPages.Message> msgList = ApexPages.getMessages();
        for(ApexPages.Message msg :  ApexPages.getMessages()) {
            System.assertEquals('Please select a CSV File to Upload.', msg.getSummary());
            System.assertEquals(ApexPages.Severity.WARNING, msg.getSeverity());
        }             
    }   

    @istest
    public static void uploadMissingCustomSettingNegativeTest() {  

        String fieldHeader = 'Partner Reference,TTB Reference,Date order placed with OR,VLAN,NNI,KCI1 Date,Survey Date,Survey Time,KCI2 Received Date,ECCs Applicable,Wayleave Required,Category of Works,KCI3 Received Date,CDD,Fibre Date,F&T Date,Next Update Due,Comment';
        String csvLine1 = '00557591,TTB0725036,2017-04-10,1053,nge001.loh-10XE-11/2/2,2017-04-11,2017-04-12,AM,2017-04-13,Null,Null,2,2017-04-14,2017-04-15,2017-04-16,2017-04-17,2017-04-18,InternalComment,PartnerComment';
        String csvLine2 = '00557592,TTB0725036,2017-04-10,1053,nge001.loh-10XE-11/2/2,2017-04-11,2017-04-12,AM,2017-04-13,Null,Null,2,2017-04-14,2017-04-15,2017-04-16,2017-04-17,2017-04-18,InternalComment,PartnerComment';
        String csvLine3 = '00557593,TTB0725036,2017-04-10,1053,nge001.loh-10XE-11/2/2,2017-04-11,2017-04-12,AM,2017-04-13,Null,Null,2,2017-04-14,2017-04-15,2017-04-16,2017-04-17,2017-04-18,InternalComment,PartnerComment';
        String blobCreator = fieldHeader + '\r\n' + csvLine1 + '\r\n' + csvLine2 + '\r\n' + csvLine3;     

        PageReference pageref = Page.CarrierUpdate;
        Test.setCurrentPage(pageref);

        CarrierUpdateController controller = new CarrierUpdateController();
        controller = new CarrierUpdateController();
        controller.fileName = 'CarrierUpdate.csv';
        controller.fileContent = Blob.valueOf(blobCreator);
        controller.carrierUploadFileMap = null;

        Test.startTest();  // Start the test, this changes limit context back to test from trigger.
        controller.readCSVFile();
        Test.stopTest();  // Stop the test, this changes limit context back to test from trigger. 

        System.assertEquals('CarrierUpdate.csv', controller.fileName);

        // get the list of ApexPages.Message
        List<ApexPages.Message> msgList = ApexPages.getMessages();
        for(ApexPages.Message msg :  ApexPages.getMessages()) {
            System.assertEquals('The "Carrier Update File Mapping" Custom Setting is missing. Please contact your Salesforce Admin', msg.getSummary());
            System.assertEquals(ApexPages.Severity.WARNING, msg.getSeverity());
        }             
    }   

    @istest
    public static void ProcessDataTest() {  

        String fieldHeader = 'Partner Reference,TTB Reference,Date order placed with OR,VLAN,NNI,KCI1 Date,Survey Date,Survey Time,KCI2 Received Date,ECCs Applicable,Wayleave Required,Category of Works,KCI3 Received Date,CDD,Fibre Date,F&T Date,Next Update Due,Comment';
        String csvLine1 = '00557591,TTB0725036,2017-04-10,1053,nge001.loh-10XE-11/2/2,2017-04-11,2017-04-12,AM,2017-04-13,Null,Null,2,2017-04-14,2017-04-15,2017-04-16,2017-04-17,2017-04-18,InternalComment,PartnerComment';
        String csvLine2 = '00557592,TTB0725036,2017-04-10,1053,nge001.loh-10XE-11/2/2,2017-04-11,2017-04-12,AM,2017-04-13,Null,Null,2,2017-04-14,2017-04-15,2017-04-16,2017-04-17,2017-04-18,InternalComment,PartnerComment';
        String csvLine3 = '00557593,TTB0725036,2017-04-10,1053,nge001.loh-10XE-11/2/2,2017-04-11,2017-04-12,AM,2017-04-13,Null,Null,2,2017-04-14,2017-04-15,2017-04-16,2017-04-17,2017-04-18,InternalComment,PartnerComment';
        String blobCreator = fieldHeader + '\r\n' + csvLine1 + '\r\n' + csvLine2 + '\r\n' + csvLine3;     

        PageReference pageref = Page.CarrierUpdate;
        Test.setCurrentPage(pageref);

        CarrierUpdateController controller = new CarrierUpdateController();
        controller = new CarrierUpdateController();
        controller.fileName = 'CarrierUpdate.csv';
        controller.fileContent = Blob.valueOf(blobCreator);

        Test.startTest();  // Start the test, this changes limit context back to test from trigger.
        controller.readCSVFile();
        Test.stopTest();  // Stop the test, this changes limit context back to test from trigger. 

        System.assertEquals('CarrierUpdate.csv', controller.fileName);

        List<CarrierUpdate__c> cupd = [SELECT Id,FileSize__c,FileName__c FROM CarrierUpdate__c];
        System.assertEquals(1, cupd.Size());
        System.assertEquals('3', cupd[0].FileSize__c);
        System.assertEquals('CarrierUpdate.csv', cupd[0].FileName__c);

        controller.getCarrierUpdateDetails();
        controller.processData();
        controller.closePopup();
        controller.showPopup();
    }

    @istest
    public static void CancelImportTest() {  

        String fieldHeader = 'Partner Reference,TTB Reference,Date order placed with OR,VLAN,NNI,KCI1 Date,Survey Date,Survey Time,KCI2 Received Date,ECCs Applicable,Wayleave Required,Category of Works,KCI3 Received Date,CDD,Fibre Date,F&T Date,Next Update Due,Comment';
        String csvLine1 = '00557591,TTB0725036,2017-04-10,1053,nge001.loh-10XE-11/2/2,2017-04-11,2017-04-12,AM,2017-04-13,Null,Null,2,2017-04-14,2017-04-15,2017-04-16,2017-04-17,2017-04-18,InternalComment,PartnerComment';
        String csvLine2 = '00557592,TTB0725036,2017-04-10,1053,nge001.loh-10XE-11/2/2,2017-04-11,2017-04-12,AM,2017-04-13,Null,Null,2,2017-04-14,2017-04-15,2017-04-16,2017-04-17,2017-04-18,InternalComment,PartnerComment';
        String csvLine3 = '00557593,TTB0725036,2017-04-10,1053,nge001.loh-10XE-11/2/2,2017-04-11,2017-04-12,AM,2017-04-13,Null,Null,2,2017-04-14,2017-04-15,2017-04-16,2017-04-17,2017-04-18,InternalComment,PartnerComment';
        String blobCreator = fieldHeader + '\r\n' + csvLine1 + '\r\n' + csvLine2 + '\r\n' + csvLine3;     

        PageReference pageref = Page.CarrierUpdate;
        Test.setCurrentPage(pageref);

        CarrierUpdateController controller = new CarrierUpdateController();
        controller = new CarrierUpdateController();
        controller.fileName = 'CarrierUpdate.csv';
        controller.fileContent = Blob.valueOf(blobCreator);

        Test.startTest();  // Start the test, this changes limit context back to test from trigger.
        controller.readCSVFile();
        Test.stopTest();  // Stop the test, this changes limit context back to test from trigger. 

        System.assertEquals('CarrierUpdate.csv', controller.fileName);

        List<CarrierUpdate__c> cupd = [SELECT Id,FileSize__c,FileName__c FROM CarrierUpdate__c];
        System.assertEquals(1, cupd.Size());
        System.assertEquals('3', cupd[0].FileSize__c);
        System.assertEquals('CarrierUpdate.csv', cupd[0].FileName__c);

        controller.getCarrierUpdateDetails();
        controller.cancelUpdate();

        List<CarrierUpdate__c> cupd1 = [SELECT Id FROM CarrierUpdate__c];
        System.assertEquals(0, cupd1.Size());

        List<CarrierUpdateDetail__c> cupdet = [SELECT Id FROM CarrierUpdateDetail__c];
        System.assertEquals(0, cupdet.Size());
    }

}
  • 3
    Can you reduce your code down to the minimum code required to demonstrate your issue. This does a few things: 1) saves us time and effort in trying to help you as we don't have as much code to go through and 2) can actually help you find your own mistake before you ask your question as you will weed out code that cannot possibly be your issue. – gNerb Mar 6 at 16:46
  • I don't know where the error is this is the reason for all of the code, wouldn't it be easier if you did what 99% of SF Devs do and look only at the relevant code? Secondly, I don't understand your English in the second part, can you try and make it more readable so I can answer your question? – Harry Smith Mar 6 at 16:55
  • can you post the sample csv file as well – Pranay Jaiswal Mar 6 at 17:02
  • The CSV was just for testing but i'll add it now for you – Harry Smith Mar 6 at 17:07
  • I've provided a screenshot as SE wont let you upload files – Harry Smith Mar 6 at 17:10
1

You need to trace this error in your code to discover the underlying issue and location, since you're using exception handlers to display errors in a "friendly" fashion.

As a side note, it is often better to use narrow exception handlers, to trap only specific, expected issues that can be handled, rather than to do catch (Exception e). The latter make debugging more difficult, and production code should not throw unexpected catchable exceptions anyway.

In any case, your error message shows the problem is in the try block for this handler:

catch(Exception e){
  ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured reading the CSV file'+e.getMessage());
  ApexPages.addMessage(errormsg);
}       

Since you are seeing an

List index out of bounds: 2

exception, we know exactly which line the issue falls upon:

cud.OrderAccepted__c = String.isBlank(fields[2]) ? null : Date.valueOf(fields[2]); 

Since the previous two lines don't throw an exception, you know the problem is that your code is receiving a line that (it thinks) contains only two elements.

So one of two things is happening: either your data is bad, or the code you're using to ingest CSV lines and convert them into your internal data structures is broken. You have some debug logs being generated that should help you pin down the ultimate issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.