APEX – Code Samples

  1. A sample Code Uses Batch class using callout and statefull receiving the respose in xml. trying to show how to read the xml response.
global class BatchToEquipmentGETCall implements Database.Batchable<sObject>,   Database.AllowsCallouts , Database.Stateful{
    public String setOfRegIdParam ;
    public String query;
    public String strDSPAccessToken;
    public String strPassed = Label.Passed;
    public String strAccept = Label.Accept;
    global BatchToEquipmentGETCall(String strRecordIds,String strDSPAccessToken) {
        this.setOfRegIdParam = strRecordIds;
        this.strDSPAccessToken = strDSPAccessToken;
    }
    
     map<Id , Boolean> mapStoreResult = new map<Id , Boolean>();
     map<Id , String> mapStoreEDResponse = new map<Id , String>();
                      
     global Database.QueryLocator start(Database.BatchableContext BC) {
     query = 'SELECT Name,Id,'+
                       'Result__c FROM Registration_History__c WHERE Id IN (\''+ setOfRegIdParam+'\') AND PO_DailyTelematics__c =  \''+strAccept + '\' AND Result__c = \'' +strPassed + '\' AND PO_Telematics_FinalRegistration_Status__c != \'' +strPassed + '\'';
      system.debug('***ED'+ query);
        return Database.getQueryLocator(query);
     }

     global void execute(Database.BatchableContext BC, List<Registration_History__c> lstRegHistory) {         
        String strHttpRequestBody ='';
        //List<Registration_History__c> lstRegHistoryToUpdate = new List<Registration_History__c>();
        String strEDResponse = '';
        for ( Registration_History__c objRegHistory: lstRegHistory){
         try{
            //EquipmentDataAPI objED = new EquipmentDataAPI();
            //strEDResponse = EquipmentDataAPI.makeEquipmentDataGetCall(objRegHistory.Name);
            //Call ED GET API

            //String strEDResponse = '';
            HttpRequest req = new HttpRequest();
            String str_clientId = label.EquipmentDataUserName;
            String str_ClientSecret = label.EquipmentDataPwd;
            Blob headerValue = Blob.valueOf(str_clientId + ':' + str_ClientSecret);
            String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
            req.setHeader('Authorization', authorizationHeader);
            string strEndpointParam = label.EquipmentDataEndPoint+objRegHistory.Name;
            system.debug('Endpoint :::' + strEndpointParam);
            req.setEndpoint(strEndpointParam);
            req.setMethod('GET');
            Http http = new Http();
            HTTPResponse res = http.send(req);
            system.debug('ED GET>>'+ res.getBody());
            system.debug('>>'+ res.getStatusCode());
            if(res.getStatusCode() == 200){
                Dom.Document xmlDOC = new Dom.Document();
                xmlDOC.load(res.getBody());   
                Dom.XMLNode node= xmlDOC.getRootElement();
                for (Dom.XMLNode child1: node.getChildElements()) {  
                    system.debug(child1.getName());
                    if (child1.getName()=='equipmentInfo') {                 
                        for (Dom.XMLNode child2: child1.getChildElements()) { 
                            system.debug(child1.getName());
                            if(child2.getName()=='equipmentOwnerList'){
                                system.debug(child2.getName());
                              for (Dom.XMLNode child3: child2.getChildElements()) { 
                                    system.debug(child3.getName());
                                    if(child3.getName()=='equipmentOwner'){
                                        for (Dom.XMLNode child4: child3.getChildElements()) {
                                          system.debug(child4.getName());
                                          if(child4.getName()=='ownershipStatus'){
                                            system.debug('child4::::'+child4.getText());
                                            if(child4.getText() == 'A'){
                                                strEDResponse = 'Record Exists';
                                            }
                                          }  
                                      }
                                  }
                              }
                          }
                      }
                  }
                }
            }

            mapStoreEDResponse.put(objRegHistory.Id, strEDResponse);     
            system.debug ('mapStoreEDResponse:::' + mapStoreEDResponse);    
          }
          catch (Exception e) {         
            System.debug('Error:' + e.getMessage() + 'LN:' + e.getLineNumber() );           
            mapStoreEDResponse.put(objRegHistory.Id,e.getMessage() ); //Added as part of US #110762
          }
       }
    }   

    global void finish(Database.BatchableContext BC){  
        
       List<String> lstRegHistoryId = new List<String>();
       List<Registration_History__c> lstRegHistoryToUpdate = new List<Registration_History__c>();
       List<Registration_History__c> lstRegHistory =  new List<Registration_History__c>();
       lstRegHistory = [SELECT Name,Id,PO_ExistingEquipment__c,PO_ED_GET_Status__c FROM Registration_History__c WHERE Id IN : mapStoreEDResponse.keySet() ];
       for(Registration_History__c objRH : lstRegHistory) {
           if(mapStoreEDResponse.get(objRH.Id) != 'Record Exists'){
             
              objRH.PO_ED_GET_Status__c = Label.Failed;
              objRH.Telematics_Error_Message__c = mapStoreEDResponse.get(objRH.Id);
              objRH.PO_ExistingEquipment__c = false;
           }else{
              objRH.PO_ED_GET_Status__c = Label.Passed;
              objRH.PO_ExistingEquipment__c = true;
              objRH.Telematics_Error_Message__c = Label.ED_GET_active_owner;
           }
            lstRegHistoryId.add(objRH.Id);
            lstRegHistoryToUpdate.add(objRH);

       }
       update lstRegHistoryToUpdate;
       String strRecordIds = String.join(lstRegHistoryId,'\',\'');
       Database.executeBatch(new BatchToEquipmentPOSTCall(strRecordIds, strDSPAccessToken),1);
    }
}

Leave a comment