• Tom Simmons
  • NEWBIE
  • 85 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 15
    Questions
  • 22
    Replies
All, below is my code coverage. It allows me update hierarchy of records at one time. Code works fine however I`m not currently able to get full 100 % code coverage. What I have right now is about 92 % and I dont understand what`s missing? Can someone of you pls point it out? or maybe give me a sample test class that would work?

Wrapper Class:
public with sharing class TaskKeyWrapper 
{
	public Integer key {get; set;}
	public Task comment {get; set;}
		
	public TaskKeyWrapper(Integer inKey, Task inComment)
	{
		key=inKey;
		comment=inComment;
	}
}
Wrapper Class:
public with sharing class CaseKeyWrapper 
{
	public Integer key {get; set;}
	public Case cs {get; set;}
	public List<CaseCommentKeyWrapper> comments {get; set;}
	private Integer commentKey=1;
		
	public CaseKeyWrapper(Integer inKey, Case inCs, List<CaseComment> inComments)
	{
		cs=inCs;
		key=inKey;
		comments=new List<CaseCommentKeyWrapper>();
		if (null!=inComments)
		{
			for (CaseComment cc : inComments)
			{
				comments.add(new CaseCommentKeyWrapper(commentKey++, cc));
			}
		}
	}
	public void addComment()
	{
		comments.add(new CaseCommentKeyWrapper(commentKey++, new CaseComment(ParentId=cs.id)));

	}
}

Extension:
 
public with sharing class AccountCasesCommentsEditExt 
{
    public List<CaseKeyWrapper> caseWrappers {get; set;}
    public ApexPages.StandardController stdCtrl {get; set;}
    public Integer key=1;	  
    public String caseToDel {get; set;}  
    public String ccToDel {get; set;}
    public String caseToAddCC {get; set;}  
    public List<Case> casesToDelete=new List<Case>();
    public List<CaseComment> commentsToDelete=new List<CaseComment>();
    
    public AccountCasesCommentsEditExt(ApexPages.StandardController std)
    {
        stdCtrl=std;
        List<Case> cases=[select id, Status, Subject, 
                          (select id, CommentBody, IsPublished, ParentId from CaseComments) 
                          from Case
                          where AccountId=:stdCtrl.getId()];	
        
        caseWrappers=new list<CaseKeyWrapper>();
        for (Case cs : cases)
        {
            caseWrappers.add(new CaseKeyWrapper(key++, cs, cs.CaseComments));
        }
    }
    
    public Integer getCaseWrapperPos(String keyStr)
    {
        Integer key=Integer.valueOf(keyStr.substring(2));
        Integer result=-1;
        Integer index=0;
        for (CaseKeyWrapper cand : caseWrappers)
        {
            if (cand.key==key)
            {
                result=index;
                break;
            }
            else
            {
                index++;
            }
        }
        return result;
    }
    
    public CaseKeyWrapper getCaseWrapper(String keyStr)
    {
        CaseKeyWrapper wrapper=null;
        Integer pos=getCaseWrapperPos(keyStr);
        if (-1!=pos)
        {
            wrapper=caseWrappers.get(pos);
        }
        
        return wrapper;
    }
    
    public Integer getCaseCommentWrapperPos(String keyStr, CaseKeyWrapper wrapper)
    {
        Integer key=Integer.valueOf(keyStr.substring(2));
        Integer result=-1;
        Integer index=0;
        for (CaseCommentKeyWrapper cand : wrapper.comments)
        {
            if (cand.key==key)
            {
                result=index;
                break;
            }
            else
            {
                index++;
            }
        }
        
        return result;
    }
    
    public CaseCommentKeyWrapper getCaseCommentWrapper(String keyStr, CaseKeyWrapper caseWrapper)
    {
        CaseCommentKeyWrapper wrapper=null;
        Integer pos=getCaseCommentWrapperPos(keyStr, caseWrapper);
        if (-1!=pos)
        {
            wrapper=caseWrapper.comments.get(pos);
        }
        return wrapper;
    }
    
    public PageReference deleteCase()
    {
        Integer pos=getCaseWrapperPos(caseToDel);
        if (-1!=pos)	
        {
            CaseKeyWrapper wrapper=caseWrappers.get(pos);
            if (null!=wrapper.cs.Id)
            {
                casesToDelete.add(wrapper.cs);
            }
            caseWrappers.remove(pos);
        }
        return null;
    }
    
    
    public PageReference deleteCaseComment()
    {
        String[] keyComps=ccToDel.split(':');
        
        Integer pos=getCaseWrapperPos(keyComps[0]);
        if (-1!=pos)	
        {
            CaseKeyWrapper wrapper=caseWrappers.get(pos);
            Integer commentPos=getCaseCommentWrapperPos(keyComps[1], wrapper);
            if (-1!=commentPos)	
            {
                CaseCommentKeyWrapper comWrap=wrapper.comments.get(commentPos);
                
                if (null!=comWrap.comment.Id)
                {
                    commentsToDelete.add(comWrap.comment);
                }
                wrapper.comments.remove(commentPos);
            }
        }
        
        return null;
    }
    
    public PageReference addCase()
    {
        caseWrappers.add(
            new CaseKeyWrapper(key++, 
                               new Case(AccountId=stdCtrl.getId()),
                               null));
        return null;
    }
    
    public PageReference addCaseComment()
    {
        CaseKeyWrapper wrapper=getCaseWrapper(caseToAddCC);
        if (null!=wrapper)
        {
            wrapper.addComment();
        }
        return null;
    }
    
    public PageReference save()
    {
        List<Case> cases=new List<Case>();
        for (CaseKeyWrapper wrapper : caseWrappers)
        {
            cases.add(wrapper.cs);
        }
        
        upsert cases;
        
        List<CaseComment> caseComments=new List<CaseComment>();
        for (CaseKeyWrapper wrapper : caseWrappers)
        {
            for (CaseCommentKeywrapper ccWrapper : wrapper.comments)
            {	
                CaseComment comment=ccWrapper.comment;
                if (null==comment.ParentId)
                {
                    comment.parentId=wrapper.cs.id;
                }
                caseComments.add(comment);
            }	
        }
            try {
        upsert caseComments;
        
        delete casesToDelete; 
        delete commentsToDelete; 
    } catch(exception e) {
    }
        return stdCtrl.save();
        
    } 
  }

Test Class:
@isTest
public class addMultpleTestClass2 {

      public static testMethod void testMyController() {
    Account A = new Account (Name='Account Test');    
    insert A;
    Case c1 = New Case (Accountid = A.id);
    insert c1;
    Case c2 = New Case (Accountid = A.id);    
     insert c2;
 
                CaseComment cc1 = New CaseComment (CommentBody='test',Parentid=c1.id);
        		insert cc1;
          
                CaseComment cc2 = New CaseComment (CommentBody='test',Parentid=c1.id); 
   			 insert cc2;
  
    List<CaseComment> Casecomments = New   List <CaseComment>  () ;
        Casecomments.add(cc1);
        Casecomments.add(cc2);
          Test.StartTest();

    PageReference pageRef = Page.AccountCasesCommentsEdit;
    Test.setCurrentPage(pageRef);
        
    ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(A);
    ApexPages.currentPage().getParameters().put('Id',A.Id);

    AccountCasesCommentsEditExt  controller = new AccountCasesCommentsEditExt (sc);

    TaskKeyWrapper Agendas = New TaskKeyWrapper (1, new Task(Whatid=c1.id));
    CaseKeyWrapper caseWrapper = new CaseKeyWrapper(1,c1, Casecomments);
    controller.key  = 2; 
    controller.addCase();
    controller.caseToAddCC = 'CS1';
    controller.caseToDel = 'CS2';
    controller.ccToDel='CS2:CC1'  ; 
    controller.ccToDel='CS2:CC1'  ;
    String Key ='CS1';

    controller.addCaseComment();
    controller.deleteCase();
   controller.deleteCaseComment();
     controller.getCaseWrapperPos (key);
    controller.getCaseCommentWrapperPos(Key,caseWrapper);
    controller.getCaseCommentWrapper(Key,caseWrapper);
                controller.save();
        
        Key ='CS2';
       controller.getCaseCommentWrapperPos(Key,caseWrapper);
		        controller.save();

    Test.stopTest();

}
}


Lines not being covered,

User-added image
User-added image
All, Im working on writing a test class for below controller however it keeps failing. This VF page allows to enter hierarchy of records in one click. When Im trying to test this, it keep failing and Im getting below error message when Im trying to call addAgendaComment () method. How should I increase my test coverage? Can some please help point me in right direction or give me an example?

Error: System.NullPointerException: Attempt to de-reference a null object
Class.AccountCasesCommentsEditExt.getCaseWrapperPos: line 36, column 1
Class.AccountCasesCommentsEditExt.getCaseWrapper: line 59, column 1
Class.AccountCasesCommentsEditExt.addCaseComment: line 154, column 1
Class.addMultpleTestClass2.testMyController: line 36, column 1

Wrapper 1
public with sharing class CaseCommentKeyWrapper 
{
    public Integer key {get; set;}
    public CaseComment comment {get; set;}

    public CaseCommentKeyWrapper(Integer inKey, CaseComment inComment)
    {
        key=inKey;
        comment=inComment;
    }
}

Wrapper 2:
public with sharing class CaseKeyWrapper 
{
    public Integer key {get; set;}
    public Case cs {get; set;}
    public List<CaseCommentKeyWrapper> comments {get; set;}
    private Integer commentKey=1;

    public CaseKeyWrapper(Integer inKey, Case inCs, List<CaseComment> inComments)
    {
        cs=inCs;
        key=inKey;
        comments=new List<CaseCommentKeyWrapper>();
        if (null!=inComments)
        {
            for (CaseComment cc : inComments)
            {
                comments.add(new CaseCommentKeyWrapper(commentKey++, cc));
            }
        }
    }
    public void addComment()
    {
        comments.add(new CaseCommentKeyWrapper(commentKey++, new CaseComment(ParentId=cs.id)));
    }
}

Controller Extension:
public with sharing class AccountCasesCommentsEditExt 
{
    public List<CaseKeyWrapper> caseWrappers {get; set;}

    public ApexPages.StandardController stdCtrl {get; set;}

    public Integer key=1;   

    public String caseToDel {get; set;}

    public String ccToDel {get; set;}

    public String caseToAddCC {get; set;}

    public List<Case> casesToDelete=new List<Case>();

    public List<CaseComment> commentsToDelete=new List<CaseComment>();

    public AccountCasesCommentsEditExt(ApexPages.StandardController std)
    {
        stdCtrl=std;
        List<Case> cases=[select id, Status, Subject, 
                          (select id, CommentBody, IsPublished, ParentId from CaseComments) 
                          from Case
                          where AccountId=:stdCtrl.getId()];    

        caseWrappers=new list<CaseKeyWrapper>();
        for (Case cs : cases)
        {
            caseWrappers.add(new CaseKeyWrapper(key++, cs, cs.CaseComments));
        }
    }

    public Integer getCaseWrapperPos(String keyStr)
    {
        Integer key=Integer.valueOf(keyStr.substring(2));
        Integer result=-1;

        Integer index=0;
        for (CaseKeyWrapper cand : caseWrappers)
        {
            if (cand.key==key)
            {
                result=index;
                break;
            }
            else
            {
                index++;
            }
        }

        return result;
    }

    public CaseKeyWrapper getCaseWrapper(String keyStr)
    {
        CaseKeyWrapper wrapper=null;
        Integer pos=getCaseWrapperPos(keyStr);
        if (-1!=pos)
        {
            wrapper=caseWrappers.get(pos);
        }

        return wrapper;
    }

    public Integer getCaseCommentWrapperPos(String keyStr, CaseKeyWrapper wrapper)
    {
        Integer key=Integer.valueOf(keyStr.substring(2));
        Integer result=-1;

        Integer index=0;
        for (CaseCommentKeyWrapper cand : wrapper.comments)
        {
            if (cand.key==key)
            {
                result=index;
                break;
            }
            else
            {
                index++;
            }
        }

        return result;
    }

    public CaseCommentKeyWrapper getCaseCommentWrapper(String keyStr, CaseKeyWrapper caseWrapper)
    {
        CaseCommentKeyWrapper wrapper=null;
        Integer pos=getCaseCommentWrapperPos(keyStr, caseWrapper);
        if (-1!=pos)
        {
            wrapper=caseWrapper.comments.get(pos);
        }

        return wrapper;
    }

    public PageReference deleteCase()
    {
        Integer pos=getCaseWrapperPos(caseToDel);
        if (-1!=pos)    
        {
            CaseKeyWrapper wrapper=caseWrappers.get(pos);
            if (null!=wrapper.cs.Id)
            {
                casesToDelete.add(wrapper.cs);
            }
            caseWrappers.remove(pos);
        }
        return null;
    }


    public PageReference deleteCaseComment()
    {
        String[] keyComps=ccToDel.split(':');

        Integer pos=getCaseWrapperPos(keyComps[0]);
        if (-1!=pos)    
        {
            CaseKeyWrapper wrapper=caseWrappers.get(pos);
            Integer commentPos=getCaseCommentWrapperPos(keyComps[1], wrapper);
            if (-1!=commentPos) 
            {
                CaseCommentKeyWrapper comWrap=wrapper.comments.get(commentPos);

                if (null!=comWrap.comment.Id)
                {
                    commentsToDelete.add(comWrap.comment);
                }
                wrapper.comments.remove(commentPos);
            }
        }

        return null;
    }

    public PageReference addCase()
    {
        caseWrappers.add(
            new CaseKeyWrapper(key++, 
                               new Case(AccountId=stdCtrl.getId()),
                               null));

        return null;
    }

    public PageReference addCaseComment()
    {
        CaseKeyWrapper wrapper=getCaseWrapper(caseToAddCC);
        if (null!=wrapper)
        {
            wrapper.addComment();
        }
        return null;
    }

    public PageReference save()
    {
        List<Case> cases=new List<Case>();
        for (CaseKeyWrapper wrapper : caseWrappers)
        {
            cases.add(wrapper.cs);
        }

        upsert cases;

        List<CaseComment> caseComments=new List<CaseComment>();
        for (CaseKeyWrapper wrapper : caseWrappers)
        {
            for (CaseCommentKeywrapper ccWrapper : wrapper.comments)
            {   
                CaseComment comment=ccWrapper.comment;
                if (null==comment.ParentId)
                {
                    comment.parentId=wrapper.cs.id;
                }
                caseComments.add(comment);
            }   
        }

        upsert caseComments;

        delete casesToDelete; 
        delete commentsToDelete; 

        return stdCtrl.save();
    }

}
My test class:
@isTest
public class addMultpleTestClass2 {

    public static testMethod void testMyController() {
        PageReference pageRef = Page.AccountCasesCommentsEdit;
        Test.setCurrentPage(pageRef);

        Account A = new Account ();    
        A.Name='Account Test'; 
        insert A;

        Case c = New Case ();
        c.Accountid = A.id;
        insert c;


        List<CaseComment> Casecomments = New   List <CaseComment>  ()    ;
        Casecomments.add(new CaseComment(CommentBody='test', Parentid=c.id));
        Casecomments.add(new CaseComment(CommentBody='test', Parentid=c.id));
        insert Casecomments;

        ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(c);
        ApexPages.currentPage().getParameters().put('Id',c.Id);

        AccountCasesCommentsEditExt  controller = new AccountCasesCommentsEditExt (sc);

        controller.key  = 2; 
        controller.addCase();

        //I`m getting error at below line... 
        controller.addCaseComment();

    }
}


 
All, here is my trigger and I want to convert this trigger into a batch class. I have 3 objects on this trigger. Account, Margin__C and commission__c.
Use case: This trigger currently run on Margin__C Object. When Margin__C is updated or inserted, it looks at date range between yr_StartDate__c and yr_endDate__c and compares it with object 'commission__c's field ‘Final_Date__c’. If ‘Final_Date__c’ falls between any of these dates, it sums the amount in ‘Gross_Commission__c’ field and updates it on Account record under Gross__C. The trigger runs well however when I try to convert it to batch class, it calculate all the amount in the  commission__c and puts it on the Account record. I only need it calculate when Gross_Commission__c falls between yr_StartDate__c and yr_endDate__c. Can someone pls help me batch class for trigger below?

 
trigger CalculateMargins on Margin__c (before update, before insert) {
    
    Map <id,commission__c> AdvMap = New Map  <id,commission__c>  ();
      Map <id,Account> AccMap = New Map  <id,Account>  ();
  
    Set <id> MarginSets = New Set <id> ();
    For (Margin__c Pay : Trigger.New) {
        MarginSets.add(Pay.Id);
     	
    }
    
    List <commission__c> CommsList = [SELECT ID, Gross_Commission__c,Margin__c,Accounts__c FROM commission__c WHERE Margin__c IN : MarginSets];
			  system.debug('list of CommsList: '+ CommsList);
    

            Map<Id, Account> c= new Map<Id, Account>();
        
        for (commission__c ps : CommsList)
        { 
            Account Acc = new Account(Id = ps.Accounts__c);
            Acc.Gross__C = 0;
            AccountMap.put(ps.Accounts__c, Acc);
        }
            
             
                For (Margin__c Margin : Trigger.New) {
                    
                    Date Startdate = Margin.yr_StartDate__c;
                    Date enddate = Margin.yr_EndDate__c;

                    system.debug(Startdate + '@@@' +  enddate);

            
        for (commission__c     ps : [select Accounts__c, Gross_Commission__c, Margin__c
                                     from commission__c
                                     where    Final_Date__c >= :Startdate  
                                              AND Final_Date__c <= :enddate])
        {
            Account accs = AccountMap.get(ps.Accounts__c);

            if (ps.Gross_Commission__c != null && ps.Accounts__c != null && ps.Margin__c != null)
            {
                accs.Gross__C += ps.Gross_Commission__c;
                
            }
        }
       
       update AccountMap.values();
      
       
    }    
}

 
All, need help. Below is my callout class which makes two different callouts to external system. In callout 1, it gets a token. In Callout 2, it uses that token to retrieve the actual data. For some reason, I`m not getting a complete test coverage on this class. After line " deserializeResults3 = (accountParser)System.JSON.deserialize(fieldValue, accountParser.class);", nothing is being covered. Can someone please help? Any help is much appreciated.
 
global class CalloutsAccounts1 implements Database.Batchable<sObject>,Database.AllowsCallouts{
   global Database.QueryLocator start(Database.BatchableContext BC){
        String query =  'SELECT Id FROM Account';
        return Database.getQueryLocator(query); 
   }

   global void execute(Database.BatchableContext BC, List<Account> scope){
        HttpRequest obj = new HttpRequest(); 
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        String reqBody = '{ "user": "sales_user", "password": "sales_password" }';
        obj.setMethod('POST');
        obj.setHeader('Content-Type','application/json');
        obj.setEndPoint('https://test.samplepoint.com/api/UserSrvs.svc/Login');
        obj.setBody(reqBody);
        obj.getheader('Auth-Token');
        res = http.send(obj);
                                system.debug('Oauth Response: '+res.getbody());
                               system.debug('Header Auth-Token Response: '+res.getHeader('Auth-Token'));

                authtoken objAuthenticationInfo = (authtoken)JSON.deserialize(res.getbody(), authtoken.class);
                System.debug('objAuthenticationInfo: '+objAuthenticationInfo);


                                String token = res.getHeader('Auth-Token');
                                system.debug('token: '+token);    


        Http h1 = new Http();
        HttpRequest req1 = new HttpRequest();
        String reqBody2 = '{"Accountype" : "workforce"}'; 
        req1.setHeader('Auth-Token', token);
        req1.setHeader('Content-Type','application/json');
        req1.setMethod('POST');
         req1.setBody(reqBody2);

        req1.setEndpoint('https://test.samplepoint.com/api/accservices.svc/accountfeed');
        system.debug('======req1========'+req1);
        HttpResponse res1 = h1.send(req1);
        system.debug('==========res1============'+res1.getBody());



                   JSONParser parser = JSON.createParser(res1.getBody());
                    parser.nextToken();
                     parser.nextValue();
                            system.debug('==========parser============'+parser);

                    String fieldName = parser.getCurrentName();
                    String fieldValue = parser.getText(); 
        system.debug('==========fieldValue============'+fieldValue);
    accountParser deserializeResults3 =  new accountParser();
    deserializeResults3 = (accountParser)System.JSON.deserialize(fieldValue, accountParser.class);

     List <accountParser.cls_account> advisorList = new List<accountParser.cls_account>();
    advisorList = deserializeResults3.root.accounts.account;

           Map <Decimal,Id> AdvisorMap = New Map  <Decimal,Id>   ();

        List <Account> advisorAccList = [SELECT Id, Fact_Finder_Client_ID__c, RecordTypeID FROM Account WHERE RecordTypeid = '012410000009tw6[![enter image description here][1]][1]'];

        For (Account Acs : advisorAccList) {
            If (Acs.Fact_Finder_Client_ID__c != null)
            AdvisorMap.put(Acs.Fact_Finder_Client_ID__c, Acs.ID);
            system.debug('@@@'+AdvisorMap);
                }
             Map <String,Id> HouseholdMap = New Map  <String,Id>   ();

        List <Account> advisorAccList1 = [SELECT Id, SSN__c, RecordTypeID FROM Account WHERE RecordTypeid = '012410000009Yr4'];

        For (Account Acs1 : advisorAccList1) {
            If (Acs1.SSN__c != null)
            HouseholdMap.put(Acs1.SSN__c, Acs1.ID);
                }

List<Financial_Account__c> lstAccount = new List<Financial_Account__c>();
for(accountParser.cls_account cand : advisorList){
    Financial_Account__c PFA = New Financial_Account__c();
    //PFA.Cirrus_Unique_ID__c =  cand.account_id;

    //Map Advisor Lookup
   PFA._Advisor_ID__c = cand.advisor_id; 
   PFA.Advisor__c = AdvisorMap.get(PFA._Advisor_ID__c );  

    //Map Household Client Lookup
    PFA._Household_ID2__c = cand.household_id;
   if (HouseholdMap.get(PFA._Household_ID2__c) == null) {
       PFA.Client__c = '0013C000003wagf'; 
} else if (PFA._Household_ID2__c != null) {
         PFA.Client__c = HouseholdMap.get(PFA._Household_ID2__c);  
}


    PFA._Unique_ID__c =  cand.account_id;
    PFA.Financial_Account_Number__c =  cand.account_num;
    PFA.Account_Type__c =  cand.account_type;
    PFA.Tax_Status__c=  cand.taxable_flg;
    PFA.Investment_Objective__c =  cand.objective;
    if (cand.inception_date != null) {
    PFA.Account_Opening__c = date.parse(cand.inception_date);
        }
        if (cand.perf_begin_date != null) {
    PFA._perf_begin_date__c = date.parse(cand.perf_begin_date);
        }
     }
    PFA.Account_Type__c =  cand.account_type;
    PFA.compute_flg__c = cand.compute_flg;
    PFA.Account_Description__c = cand.description;
    PFA.fwc_hh_id__c = cand.fwc_hh_id;


    lstAccount.add(PFA);
}


Boolean isUpsertfirstTime = true;
try {
    upsert lstAccount Financial_Account_Number__c;
}catch (DMLException e) {
                System.debug('Re-trying');
                if(isUpsertfirstTime){
                        upsert lstAccount Financial_Account_Number__c;
                                isUpsertfirstTime = false;
              }
}


   }       

   global void finish(Database.BatchableContext BC){
              CalloutsAccounts2 myContactBatch = new CalloutsAccounts2();
      Id batchProcessId = Database.executeBatch(myContactBatch);

   }
Mock:
 
@isTest
global class Example1_HttpCalloutMock implements HttpCalloutMock {

    //  Implement this interface method
    global HttpResponse respond(HttpRequest req) {

        //  Prepare a response to return
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');

        //  Can use the HttpRequest details to shape the response
        if (req.getMethod() == 'POST' && req.getEndpoint() == 'https://test.samplepoint.com/api/UserSrvs.svc/Login') { 

            //  Provide a response for this endpoint
        res.setBody('{"User":{"indenty":250751503,"GroupID":0,"IdentityProviderID":0,"IdentityProviderUserID":"test","FirstName":"test","LastName":"Services","Email":"test@test.com","AffiliateId":111,"Type":14,"SubType":1,"Gender":"M","InUseFlg":false},"AffiliatePreferences":null}');
     res.setHeader('Auth-Token', '6VIitOCHBJfSA7lZIlgdNLpxw+v5AvcksXlVjtnjg34qwLYHwDTHlFZYj2xC7X0nTU6djaWruJa03+FgN8cet3kwuu4N5HaAhEbldu5t8+gDH9siTt/wO58O+6872sG8=');
        res.setStatusCode(200);                  
        }


          if (req.getMethod() == 'POST' && req.getEndpoint() == 'https://test.samplepoint.com/api/accservices.svc/accountfeed') { 
                        res.setHeader('Content-Type', 'application/json');
            //  Provide a response for this endpoint
        res1.setHeader('Content-Type', 'application/json');
res1.setBody('{  "d": "{\"root\":{\"pagination\":{\"accounts\":{\"pages\":\"111\"},\"page\":\"1\",\"pageSize\":\"2\"},\"accounts\":{\"account\":[{\"account_id\":\"512\",\"account_num\":\"35111516\",\"account_type\":\" Remainder Trust\",\"taxable_flg\":\"1\",\"compute \":\"0\",\"description\":\"ZZ-test, dave B\",\"add_id\":\"57\",\"fwc_id\":\"test-test\",\" begin_date\":\"07/10/2003\",\"inc_date\":\"07/09/2003\",\"termination_date\":\"02/24/2014\",\"last_date\":\"04/30/2008\",\"test_id\":\"18\",\"planning_id\":\"1175\",\"account_num\":\"20696291\",\"objective\":\"WCM \"},{\"account_id\":\"513\",\"account_num\":\"1515661\",\"account_type\":\"Individual Account\",\"taxable_flg\":\"1\",\" compute\":\"0\",\"description\":\"ZZ-tst, dave B\",\"add_id\":\"57\",\"fwc _id\":\"NWCP - test\",\" begin_date\":\"06/30/2003\",\" inc_date\":\"07/09/2006\",\"termination_date\":\"02/24/2014\",\"last_date\":\"04/30/2008\",\"test_id\":\"18\",\"planning_id\":\"175\",\" account_num\":\"1251515\",\"objective\":\"test\"}]}}}"}');
     res1.setHeader('Auth-Token', '6VIitOCHBJfSA7lZIlgdNLpxw+v5AvcksXlVjtnjg34qwLYHwDTHlFZYj2xC7X0nTU6djaWruJa03+FgN8cet3kwuu4N5HaAhEbldu5t8+gDH9siTt/wO58O+6872sG8=');
        res1.setStatusCode(200);              
        }


        return res;
    }
}
Test class:
 
@isTest
private class CalloutClassTest {
     @isTest static void testCallout() {
      Test.startTest();
       Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
       CalloutsAccounts1 CA= new CalloutsAccounts1 ();
       Account acc = new Account( Name = 'My Test Account' );
       Insert acc;
        Database.executeBatch(new CalloutsAccounts1 (), 100);
       Test.stopTest();

    }
}
User-added image


 

All, need help with test class on Batch apex. Below is batch apex code which make 2 callouts (for Token and actual data) however i`m not able to get test coverege on this class. All I have is 7% coverage. Can someone please help?
 
global class CalloutsAccounts implements Database.Batchable<sObject>,Database.AllowsCallouts{


   global Database.QueryLocator start(Database.BatchableContext BC){
        String query =  'SELECT Id FROM Account LIMIT 1';
        return Database.getQueryLocator(query); 
   }

   global void execute(Database.BatchableContext BC, List<Account> scope){
        HttpRequest obj = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        String reqBody = '{ "user": "Username", "passwd": "user_password" }';
        obj.setMethod('POST');
        obj.setHeader('Content-Type','application/json');
        obj.setEndPoint('https://test.samplepoint.com/api/UserSrvs.svc/Login');
        obj.setBody(reqBody);
        obj.getheader('Auth-Token');
        res = http.send(obj);

                authtoken objAuthenticationInfo = (authtoken)JSON.deserialize(res.getbody(), authtoken.class);
String token = res.getHeader('Auth-Token');


        Http h1 = new Http();
        HttpRequest req1 = new HttpRequest();
        String reqBody2 = ' {"Accountype" : "workforce"}'; 
        req1.setHeader('Auth-Token', token);
        req1.setHeader('Content-Type','application/json');
        req1.setMethod('POST');
         req1.setBody(reqBody2);

        req1.setEndpoint('https://test.samplepoint.com/api/accservices.svc/accountfeed');
        HttpResponse res1 = h1.send(req1);



                   JSONParser parser = JSON.createParser(res1.getBody());
                    parser.nextToken();
                     parser.nextValue();

                    String fieldName = parser.getCurrentName();
                    String fieldValue = parser.getText(); 

    accParser deserializeResults3 =  new accParser ();
    deserializeResults3 = (accParser)System.JSON.deserialize(fieldValue, accParser.class);
     List < accParser.cls_account> advisorList = new List< accParser.cls_account>();
    advisorList = deserializeResults3.root.accounts.account;

           Map <Decimal,Id> AdvisorMap = New Map  <Decimal,Id>   ();

        List <Account> advisorAccList = [SELECT Id, Fact_ID__c, RecordTypeID FROM Account WHERE RecordTypeid = '0124100000091Ho'];

        For (Account Acs : advisorAccList) {
            If (Acs.Fact_ID__c != null)
            AdvisorMap.put(Acs.Fact_ID__c, Acs.ID);
                }


             Map <String,Id> HouseholdMap = New Map  <String,Id>   ();

        List <Account> advisorAccList1 = [SELECT Id, SSCN__c, RecordTypeID FROM Account WHERE RecordTypeid = '012410000009Il6'];

        For (Account Acs1 : advisorAccList1) {
            If (Acs1.SSCN__c != null)
            HouseholdMap.put(Acs1.SSCN__c, Acs1.ID);
            system.debug('@@@'+HouseholdMap);
                }



List<Financial_Account__c> lstAccount = new List<Financial_Account__c>();
for(accountParser.cls_account cand : advisorList){
    Financial_Account__c PFA = New Financial_Account__c();
    //PFA.Cirrus_Unique_ID__c =  cand.account_id;

    //Map Advisor Lookup
   PFA.Advisor_ID__c = cand.advisor_id; 
   PFA.Advisor__c = AdvisorMap.get(PFA.Advisor_ID__c );  

    //Map Household Client Lookup
    PFA.Household_ID2__c = cand.household_id;
   if (HouseholdMap.get(PFA.Household_ID2__c) == null) {
       PFA.Client__c = '0013C000003Ywet'; 
} else if (PFA.Household_ID2__c != null) {
         PFA.Client__c = HouseholdMap.get(PFA.Household_ID2__c);  
}




    PFA.Unique_ID__c =  cand.account_id;
    PFA.Financial_Account_Number__c =  cand.accountnum;
    PFA.Account_Type__c =  cand.account;
    PFA.Tax_Status__c=  cand.taxablestatus;
    PFA.Investment_Objective__c =  cand.objective;
    if (cand.inception_date != null) {
    PFA.Account_Opening__c = date.parse(cand.inception);
        }
        if (cand.perf_begin_date != null) {
    PFA.perf_begin_date__c = date.parse(cand.perfdate);
        }
    // if (cand.household_id != null) {
  //  PFA.Household_ID__c = cand.housedate_id;
  //      }
    PFA.Account_Type__c =  cand.account_type;
   // PFA.Client__c =  '0013C000003CRTr'; LOOKUP TO ACCOUNTS
    PFA.compute_flg__c = cand.compute_flg;
    PFA.Account_Description__c = cand.description;
    PFA.fwc_hh_id__c = cand.fwc_hh_id;
        if (cand.termination_date != null) {
    PFA.termination_date__C = date.parse(cand.termination_date);
        }
        if (cand.last_date != null) {
    PFA.last_date__c = date.parse(cand.last_date);
        }
    PFA.Custodian_Id__c = cand.custodian_id;
    PFA.billing_account_num__c = cand.billing_account_num;
    PFA.rebal_method__c = cand.rebal_method;




    lstAccount.add(PFA);
}


Boolean isUpsertfirstTime = true;
try {
    upsert lstAccount Financial_Account_Number__c;
}catch (DMLException e) {
                System.debug('Re-trying');
                if(isUpsertfirstTime){
                        upsert lstAccount Financial_Account_Number__c;
                                isUpsertfirstTime = false;
              }
}


   }       

   global void finish(Database.BatchableContext BC){
              CalloutsAccounts2 myaccBatch = new CalloutsAccounts2();
      Id batchProcessId = Database.executeBatch(myacctBatch);

   }
}

Mock:
 
@isTest
global class MockHttpResponseGenerator implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
        // Optionally, only send a mock response for a specific endpoint
        // and method.
               System.assertEquals('https://test.samplepoint.com/api/UserSrvs.svc/', req.getEndpoint());
        System.assertEquals('POST', req.getMethod()); 

        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
res.setBody(''{ "user": "Username", "passwd": "user_password" }');
        res.setHeader('Auth-Token', '3+yV8B+7iSTu7Oj4alK4/fJPY1a5VRhAre6jG5vx6kDTXMOENFWJqAIQpuYE8nOdLwDmQBdo=');
 res.setStatusCode(200);         
        return res;
    }
}

Test class:
@isTest
private class CalloutClassTest {
     @isTest static void testCallout() {
        // Set mock callout class 

        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        Test.startTest();
  Account acc = new Account(  Name = 'My Test Account' );

  		  upsert acc;

        Database.executeBatch(new CalloutsAccounts(), 100);
        Test.stopTest();

    }


 
Need help. Im new to Apex (with decent exp on Java) and Im working on callout class to get data from external system. Below code works fine, however while making a callout to larger data set, I get "Error: System.LimitException: Too many DML rows: 10001". Im assuming this is due to large data being returned from webservice. Is there a way to process this data in batches? I know Batch class is used for operations like this however I`m not able to get it work. How can I process JSON reponse in batches? Can someone please give me a working example?

 
HttpRequest obj = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        String reqBody = '{ "user": "user_name", "pswd": "user_password" }';
        obj.setMethod('POST');
        obj.setHeader('Content-Type','application/json');
        obj.setEndPoint('https://test.samplepoint.com/api/UserSrvs.svc/Login');
        obj.setBody(reqBody);
        obj.getheader('Auth-Token');
        res = http.send(obj);

                authtoken objAuthenticationInfo = (authtoken)JSON.deserialize(res.getbody(), authtoken.class);
                System.debug('objAuthenticationInfo: '+objAuthenticationInfo);


                                String token = res.getHeader('Auth-Token');
                                system.debug('token: '+token);    


        Http h1 = new Http();
        HttpRequest req1 = new HttpRequest();
        String reqBody2 = '{"Accountype" : "workforce"}'; 
        req1.setHeader('Auth-Token', token);
        req1.setHeader('Content-Type','application/json');
        req1.setMethod('POST');
         req1.setBody(reqBody2);

        req1.setEndpoint('https://test.samplepoint.com/api/accservices.svc/accountfeed');
        system.debug('======req1========'+req1);
        HttpResponse res1 = h1.send(req1);
        system.debug('==========res1============'+res1.getBody());



    DataParser deserializeRes =  new DataParser();
    deserializeRes = (DataParser)System.JSON.deserialize(replaceJson, DataParser.class);
     List <DataParser.cls_account> advisorList = new List<DataParser.cls_account>();
    advisorList = deserializeRes.rut.accounts.account;



List<Funtional_Account__c> lstAccount = new List<Funtional_Account__c>();
for(DataParser.cls_account c : advisorList){
    Funtional_Account__c PFA = New Funtional_Account__c();
    PFA.payment_Unique_ID__c =  c.account_id;
   PFA.Advisor_ID__c = c.advisor_id;   
    PFA.Unique_ID__c =  c.account_id;
    PFA.Financial_Account_Number__c =  c.account_num;
    PFA.Account_Type__c =  c.account_type;
    PFA.Client__c =  '0015C000003VqWh';

    lstAccount.add(PFA);
}


Boolean isUpsertfirstTime = true;
try {
    upsert lstAccount Financial_Account_Number__c;
}catch (DMLException e) {
                System.debug('Re-trying');
                if(isUpsertfirstTime){
                        upsert lstAccount Financial_Account_Number__c;
                                isUpsertfirstTime = false;
              }
}

 
Need help. Using Class below, I have deserialized JSON response however I`m not able to figure out how should I create an account in Salesforce using this deserialized data. Can someone please help?
 
public class candidateParser{
public cls_rut rut;
public class cls_rut {
    public cls_candidates candidates;
}
public class cls_ candidates {
    public cls_candidate [] candidate;
}
public class cls_candidate {
    public String candidate_id; //3
    public String candidate_code;   //AA12
    public String description;  // Steven S.
}
public static candidateParser parse(String json){
    return (candidateParser) System.JSON.deserialize(json, candidateParser.class);
}}

Deserialized JSON:
11:11:02:208 USER_DEBUG [69]|DEBUG|deserializeResults====: candidateParser:[rut=cls_rut:[candidates=cls_candidates:[candidate=(cls_candidate:[candidate_code=AA12, candidate_id=3, description=Steven S.], cls_candidate:[candidate_code= AA13, candidate_id=4, description= Brad Hess], cls_candidate:[candidate_code= AA14, candidate_id=5, description=Brad Jones], cls_candidate:[candidate_code= AA14, candidate_id=6, description=Sample candidate], cls_candidate:[candidate_code= AA16, candidate_id=7, description=ross. k],...)]]]


I`m trying below but I keep getting null response on account name. Please help -
 
candidateParser.cls_candidate deserializeResults2 =     (candidateParser.cls_candidate)JSON.deserialize(replaceJson, candidateParser.cls_candidate.class);    
System.debug('deserializeResults2====: '+deserializeResults2);

Account Acc = New Account ();
Acc.Name =  deserializeResults2.candidate_code;
Insert Acc;

 
All, below is my code. While trying to make callout to an external API, I`m getting an error “System.CalloutException: Exceeded max size limit of 6000000” synchronously. I believe this is happening since payload that is being received is very large. I was wondering if there is a way to work across these limits. I tried using @future too however its giving me an error too "System.LimitException: Apex heap size too large: 12649268". Can someone please suggest a better way to get data in Salesforce?
 
HttpRequest obj = new HttpRequest();
    HttpResponse res = new HttpResponse();
    Http http = new Http();
    String reqBody = '{ "user": "test_user", "passwd": "2gbwefgnaiognawgona12" }';
    obj.setMethod('POST');
    obj.setHeader('Content-Type','application/json');
    obj.setEndPoint('https://test.samplepoint.com/api/UserSrvs.svc/Login');
    obj.setBody(reqBody);
    obj.getheader('Auth-Token');
    res = http.send(obj);
                            system.debug('Oauth Response: '+res.getbody());
                           system.debug('Header Auth-Token Response: '+res.getHeader('Auth-Token'));

            authtoken objAuthenticationInfo = (authtoken)JSON.deserialize(res.getbody(), authtoken.class);
            System.debug('objAuthenticationInfo: '+objAuthenticationInfo);


      Http h1 = new Http();
    HttpRequest req1 = new HttpRequest();
    String reqBody2 = '{ "Accountype" : "workforce"}';
    req1.setHeader('Auth-Token', res.getHeader('Auth-Token'));
    req1.setHeader('Content-Type','application/json');
    req1.setMethod('POST');
     req1.setBody(reqBody2);

    req1.setEndpoint('https://test.samplepoint.com/api/accservices.svc/accountfeed');//URL will be your Salesforce REST API end point where you will do POST,PUT,DELETE orGET
    system.debug('======req1========'+req1);
    HttpResponse res1 = h1.send(req1);
    system.debug('==========res1============'+res1.getBody());

 
All, below is my code. While trying to make callout to an external API, I`m getting an error “System.CalloutException: Exceeded max size limit of 6000000”. Can someone please explain why this is happening ? I tried using cURL and POSTMAN and they are working fine however JSON response that is received with these tools is very large. Could this be the reason why I`m getting this error? Is SF not capable of handing large JSON response?       

 
HttpRequest obj = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        String reqBody = '{ "user": "test_user", "passwd": "2gbwefgnaiognawgona12" }';
        obj.setMethod('POST');
        obj.setHeader('Content-Type','application/json');
        obj.setEndPoint('https://test.samplepoint.com/api/UserSrvs.svc/Login');
        obj.setBody(reqBody);
        obj.getheader('Auth-Token');
        res = http.send(obj);
                                system.debug('Oauth Response: '+res.getbody());
                               system.debug('Header Auth-Token Response: '+res.getHeader('Auth-Token'));
        
                authtoken objAuthenticationInfo = (authtoken)JSON.deserialize(res.getbody(), authtoken.class);
                System.debug('objAuthenticationInfo: '+objAuthenticationInfo);
			
        
		  Http h1 = new Http();
        HttpRequest req1 = new HttpRequest();
        String reqBody2 = '{ "Accountype" : "workforce"}';
        req1.setHeader('Auth-Token', res.getHeader('Auth-Token'));
        req1.setHeader('Content-Type','application/json');
        req1.setMethod('POST');
         req1.setBody(reqBody2);

        req1.setEndpoint('https://test.samplepoint.com/api/accservices.svc/accountfeed');//URL will be your Salesforce REST API end point where you will do POST,PUT,DELETE orGET
        system.debug('======req1========'+req1);
        HttpResponse res1 = h1.send(req1);
        system.debug('==========res1============'+res1.getBody());

 
Dear all,
Below is my callout code which is getting data from other Salesforce instance. Code work fine, however instead of @future, I want this code to run on daily basis (once a day) to get all the records from other Salesforce instance. Since I`m new to salesforce, can someone please help me in converting this code to batchable class? Also, is there any other best way to accomplish daily callouts? Please suggest... 
 
public class SampleIntegration
{
        @future (callout=true)
    public static void integration()
    {
        HttpRequest obj = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        String username = 'tom.simmons@hotmail.com';
        String pwd = 'Welcome123rwnYJye3ZaZlxCCq9UJ7sD0AE';
        String reqBody = 'grant_type=password&client_id=3MVG9Y6d_Btp4xp4D3Z8GAwN6wIbOw3vQabsximESJjFoCgpNad5tVtSnQIZN7xAyCekd0tyknn95VTImvYJ2&client_secret=817876896827445493&username='+username+'&password='+pwd;
        obj.setMethod('POST');
        obj.setEndPoint('https://login.salesforce.com/services/oauth2/token');
        obj.setBody(reqBody);
        res = http.send(obj);
                                system.debug('Oauth Response: '+res.getbody());
        OAuth2 objAuthenticationInfo = (OAuth2)JSON.deserialize(res.getbody(), OAuth2.class);
                     system.debug(objAuthenticationInfo);   
                System.debug('objAuthenticationInfo'+objAuthenticationInfo);


        Http h1 = new Http();
        HttpRequest req1 = new HttpRequest();
        req1.setHeader('Authorization','Bearer '+objAuthenticationInfo.access_token);
        req1.setHeader('Content-Type','application/json');
        req1.setHeader('accept','application/json');
        req1.setMethod('GET');
        String strName = 'Hello 3';
        req1.setEndpoint('https://na1.salesforce.com/services/apexrest/Dev_tom/Account1');//URL will be your Salesforce REST API end point where you will do POST,PUT,DELETE orGET
        system.debug('======req1========'+req1);
        HttpResponse res1 = h1.send(req1);
        system.debug('==========res1============'+res1.getBody());

                        JSON2Apex Jsondes = (JSON2Apex)JSON.deserialize(res1.getbody(), JSON2Apex.class);
                                                                System.debug('Jsondes'+Jsondes);

                                                Account A = New Account ();
                                                A.Name = Jsondes.Name;
                                                A.Site = Jsondes.ID;
                                                insert A;


    }

                }


 
Dear all, I need help with getting started with Webservices. We have a customer who would like to integrate their webservices in Salesforce. Webservices return XML format and customer would like to push data to Salesforce on daily basis (Approx 10,00 to 15,000 records daily). How can we acheive this?
  1. Will I need a WSDL document generated for customer`s webservices to get started and consume the webserivces? If yes, can someone please suggest me standard practices (maybe step by step) and give me a sample code to make daily callouts.
  2. Does all Webservices support JSON or does that depend upon type of Webservices we are interacting with?
Since I`m new to Webservices, any help is much appricated. 
 
All, need help. I`m getting an error at line 17 unexpected token: ')' and I cant figure out why. Can someone please help?
 
public class callout {


Settings__c ts = [SELECT Name, Client_Secret__c, ConsumerKey__c, Password__c, SecurityToken__c,Username__c from Settings__c];



String clientId = ts.ConsumerKey__c;
String clientSecret = ts.Client_Secret__c;
String username=ts.Username__c;
String password=ts.Password__c+ts.SecurityToken__c; 

String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password;

Http h = new Http ();
HttpRequest req = new HttpRequest ();
req.setBody(reqbody);
req.setMethod('POST');
req.setEndpoint(ts.URL__c+'/services/oauth2/token');

HttpResponse res = h.send(req);
OAuth2 objAuthenticationInfo = (OAuth2)JSON.deserialize(res.getbody(), OAuth2.class);
RequestWrapper reqst=new RequestWrapper();
if(objAuthenticationInfo.access_token!=null){
Http h1 = new Http();
HttpRequest req1 = new HttpRequest();

req1.setHeader('Authorization','Bearer '+objAuthenticationInfo.access_token);
req1.setHeader('Content-Type','application/json');
req1.setHeader('accept','application/json');
req1.setBody(jsonstr);//Send JSON body
req1.setMethod('POST');
req1.setEndpoint(ts.URL__c+URL);
HttpResponse res1 = h1.send(req1);
system.debug('RESPONSE_BODY'+res1 .getbody());
}
}

 
All, I`m new to Apex REST web services world and I`m struggling with a project of integration. What I have is a API documentation from our customer which contains cURL examples, fields and sample JSON response. At this point, all I have is a documentation. How can I make a call out to their api system to exchange data? Do I need to ask them userid and password to thier system to authenticate?

Error: Everytime I try to access the API from CURL, I get "curl: (6) Could not resolve host ".
All, I want to pull and send real time data from external third party API system. (For example, if Account is created or update, some custom fields on the account should get updated from external data). How can i acheive this? Can someone pls share a sample REST/SOAP code (with authentication) which I can refer to? Any help is greatly appreciated.
Dear all, I`m new to Apex REST/SOAP web services world and I`m struggling with a project of integration. What I have a API documentation from client which contains cURL examples, fields and sample JSON response. My questions,
1) How should I start and how can I call this API data inside Salesforce? I need ability to pull and push the data into Salesforce.
2) Are there any changes that need to do in external API system or can I call web services directly in Salesforce if I have login ID and Password of API?
3) In integration projects like this, what should be first step? What information will I need from client to start the integration?
 
I have read few articles online on REST but none of the article provide real time examples. Can you Apex Gurus please help? Any help is much appreciated.
 

All, need help with test class on Batch apex. Below is batch apex code which make 2 callouts (for Token and actual data) however i`m not able to get test coverege on this class. All I have is 7% coverage. Can someone please help?
 
global class CalloutsAccounts implements Database.Batchable<sObject>,Database.AllowsCallouts{


   global Database.QueryLocator start(Database.BatchableContext BC){
        String query =  'SELECT Id FROM Account LIMIT 1';
        return Database.getQueryLocator(query); 
   }

   global void execute(Database.BatchableContext BC, List<Account> scope){
        HttpRequest obj = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        String reqBody = '{ "user": "Username", "passwd": "user_password" }';
        obj.setMethod('POST');
        obj.setHeader('Content-Type','application/json');
        obj.setEndPoint('https://test.samplepoint.com/api/UserSrvs.svc/Login');
        obj.setBody(reqBody);
        obj.getheader('Auth-Token');
        res = http.send(obj);

                authtoken objAuthenticationInfo = (authtoken)JSON.deserialize(res.getbody(), authtoken.class);
String token = res.getHeader('Auth-Token');


        Http h1 = new Http();
        HttpRequest req1 = new HttpRequest();
        String reqBody2 = ' {"Accountype" : "workforce"}'; 
        req1.setHeader('Auth-Token', token);
        req1.setHeader('Content-Type','application/json');
        req1.setMethod('POST');
         req1.setBody(reqBody2);

        req1.setEndpoint('https://test.samplepoint.com/api/accservices.svc/accountfeed');
        HttpResponse res1 = h1.send(req1);



                   JSONParser parser = JSON.createParser(res1.getBody());
                    parser.nextToken();
                     parser.nextValue();

                    String fieldName = parser.getCurrentName();
                    String fieldValue = parser.getText(); 

    accParser deserializeResults3 =  new accParser ();
    deserializeResults3 = (accParser)System.JSON.deserialize(fieldValue, accParser.class);
     List < accParser.cls_account> advisorList = new List< accParser.cls_account>();
    advisorList = deserializeResults3.root.accounts.account;

           Map <Decimal,Id> AdvisorMap = New Map  <Decimal,Id>   ();

        List <Account> advisorAccList = [SELECT Id, Fact_ID__c, RecordTypeID FROM Account WHERE RecordTypeid = '0124100000091Ho'];

        For (Account Acs : advisorAccList) {
            If (Acs.Fact_ID__c != null)
            AdvisorMap.put(Acs.Fact_ID__c, Acs.ID);
                }


             Map <String,Id> HouseholdMap = New Map  <String,Id>   ();

        List <Account> advisorAccList1 = [SELECT Id, SSCN__c, RecordTypeID FROM Account WHERE RecordTypeid = '012410000009Il6'];

        For (Account Acs1 : advisorAccList1) {
            If (Acs1.SSCN__c != null)
            HouseholdMap.put(Acs1.SSCN__c, Acs1.ID);
            system.debug('@@@'+HouseholdMap);
                }



List<Financial_Account__c> lstAccount = new List<Financial_Account__c>();
for(accountParser.cls_account cand : advisorList){
    Financial_Account__c PFA = New Financial_Account__c();
    //PFA.Cirrus_Unique_ID__c =  cand.account_id;

    //Map Advisor Lookup
   PFA.Advisor_ID__c = cand.advisor_id; 
   PFA.Advisor__c = AdvisorMap.get(PFA.Advisor_ID__c );  

    //Map Household Client Lookup
    PFA.Household_ID2__c = cand.household_id;
   if (HouseholdMap.get(PFA.Household_ID2__c) == null) {
       PFA.Client__c = '0013C000003Ywet'; 
} else if (PFA.Household_ID2__c != null) {
         PFA.Client__c = HouseholdMap.get(PFA.Household_ID2__c);  
}




    PFA.Unique_ID__c =  cand.account_id;
    PFA.Financial_Account_Number__c =  cand.accountnum;
    PFA.Account_Type__c =  cand.account;
    PFA.Tax_Status__c=  cand.taxablestatus;
    PFA.Investment_Objective__c =  cand.objective;
    if (cand.inception_date != null) {
    PFA.Account_Opening__c = date.parse(cand.inception);
        }
        if (cand.perf_begin_date != null) {
    PFA.perf_begin_date__c = date.parse(cand.perfdate);
        }
    // if (cand.household_id != null) {
  //  PFA.Household_ID__c = cand.housedate_id;
  //      }
    PFA.Account_Type__c =  cand.account_type;
   // PFA.Client__c =  '0013C000003CRTr'; LOOKUP TO ACCOUNTS
    PFA.compute_flg__c = cand.compute_flg;
    PFA.Account_Description__c = cand.description;
    PFA.fwc_hh_id__c = cand.fwc_hh_id;
        if (cand.termination_date != null) {
    PFA.termination_date__C = date.parse(cand.termination_date);
        }
        if (cand.last_date != null) {
    PFA.last_date__c = date.parse(cand.last_date);
        }
    PFA.Custodian_Id__c = cand.custodian_id;
    PFA.billing_account_num__c = cand.billing_account_num;
    PFA.rebal_method__c = cand.rebal_method;




    lstAccount.add(PFA);
}


Boolean isUpsertfirstTime = true;
try {
    upsert lstAccount Financial_Account_Number__c;
}catch (DMLException e) {
                System.debug('Re-trying');
                if(isUpsertfirstTime){
                        upsert lstAccount Financial_Account_Number__c;
                                isUpsertfirstTime = false;
              }
}


   }       

   global void finish(Database.BatchableContext BC){
              CalloutsAccounts2 myaccBatch = new CalloutsAccounts2();
      Id batchProcessId = Database.executeBatch(myacctBatch);

   }
}

Mock:
 
@isTest
global class MockHttpResponseGenerator implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
        // Optionally, only send a mock response for a specific endpoint
        // and method.
               System.assertEquals('https://test.samplepoint.com/api/UserSrvs.svc/', req.getEndpoint());
        System.assertEquals('POST', req.getMethod()); 

        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
res.setBody(''{ "user": "Username", "passwd": "user_password" }');
        res.setHeader('Auth-Token', '3+yV8B+7iSTu7Oj4alK4/fJPY1a5VRhAre6jG5vx6kDTXMOENFWJqAIQpuYE8nOdLwDmQBdo=');
 res.setStatusCode(200);         
        return res;
    }
}

Test class:
@isTest
private class CalloutClassTest {
     @isTest static void testCallout() {
        // Set mock callout class 

        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        Test.startTest();
  Account acc = new Account(  Name = 'My Test Account' );

  		  upsert acc;

        Database.executeBatch(new CalloutsAccounts(), 100);
        Test.stopTest();

    }


 
Dear all, I need help with getting started with Webservices. We have a customer who would like to integrate their webservices in Salesforce. Webservices return XML format and customer would like to push data to Salesforce on daily basis (Approx 10,00 to 15,000 records daily). How can we acheive this?
  1. Will I need a WSDL document generated for customer`s webservices to get started and consume the webserivces? If yes, can someone please suggest me standard practices (maybe step by step) and give me a sample code to make daily callouts.
  2. Does all Webservices support JSON or does that depend upon type of Webservices we are interacting with?
Since I`m new to Webservices, any help is much appricated. 
 
All, below is my code coverage. It allows me update hierarchy of records at one time. Code works fine however I`m not currently able to get full 100 % code coverage. What I have right now is about 92 % and I dont understand what`s missing? Can someone of you pls point it out? or maybe give me a sample test class that would work?

Wrapper Class:
public with sharing class TaskKeyWrapper 
{
	public Integer key {get; set;}
	public Task comment {get; set;}
		
	public TaskKeyWrapper(Integer inKey, Task inComment)
	{
		key=inKey;
		comment=inComment;
	}
}
Wrapper Class:
public with sharing class CaseKeyWrapper 
{
	public Integer key {get; set;}
	public Case cs {get; set;}
	public List<CaseCommentKeyWrapper> comments {get; set;}
	private Integer commentKey=1;
		
	public CaseKeyWrapper(Integer inKey, Case inCs, List<CaseComment> inComments)
	{
		cs=inCs;
		key=inKey;
		comments=new List<CaseCommentKeyWrapper>();
		if (null!=inComments)
		{
			for (CaseComment cc : inComments)
			{
				comments.add(new CaseCommentKeyWrapper(commentKey++, cc));
			}
		}
	}
	public void addComment()
	{
		comments.add(new CaseCommentKeyWrapper(commentKey++, new CaseComment(ParentId=cs.id)));

	}
}

Extension:
 
public with sharing class AccountCasesCommentsEditExt 
{
    public List<CaseKeyWrapper> caseWrappers {get; set;}
    public ApexPages.StandardController stdCtrl {get; set;}
    public Integer key=1;	  
    public String caseToDel {get; set;}  
    public String ccToDel {get; set;}
    public String caseToAddCC {get; set;}  
    public List<Case> casesToDelete=new List<Case>();
    public List<CaseComment> commentsToDelete=new List<CaseComment>();
    
    public AccountCasesCommentsEditExt(ApexPages.StandardController std)
    {
        stdCtrl=std;
        List<Case> cases=[select id, Status, Subject, 
                          (select id, CommentBody, IsPublished, ParentId from CaseComments) 
                          from Case
                          where AccountId=:stdCtrl.getId()];	
        
        caseWrappers=new list<CaseKeyWrapper>();
        for (Case cs : cases)
        {
            caseWrappers.add(new CaseKeyWrapper(key++, cs, cs.CaseComments));
        }
    }
    
    public Integer getCaseWrapperPos(String keyStr)
    {
        Integer key=Integer.valueOf(keyStr.substring(2));
        Integer result=-1;
        Integer index=0;
        for (CaseKeyWrapper cand : caseWrappers)
        {
            if (cand.key==key)
            {
                result=index;
                break;
            }
            else
            {
                index++;
            }
        }
        return result;
    }
    
    public CaseKeyWrapper getCaseWrapper(String keyStr)
    {
        CaseKeyWrapper wrapper=null;
        Integer pos=getCaseWrapperPos(keyStr);
        if (-1!=pos)
        {
            wrapper=caseWrappers.get(pos);
        }
        
        return wrapper;
    }
    
    public Integer getCaseCommentWrapperPos(String keyStr, CaseKeyWrapper wrapper)
    {
        Integer key=Integer.valueOf(keyStr.substring(2));
        Integer result=-1;
        Integer index=0;
        for (CaseCommentKeyWrapper cand : wrapper.comments)
        {
            if (cand.key==key)
            {
                result=index;
                break;
            }
            else
            {
                index++;
            }
        }
        
        return result;
    }
    
    public CaseCommentKeyWrapper getCaseCommentWrapper(String keyStr, CaseKeyWrapper caseWrapper)
    {
        CaseCommentKeyWrapper wrapper=null;
        Integer pos=getCaseCommentWrapperPos(keyStr, caseWrapper);
        if (-1!=pos)
        {
            wrapper=caseWrapper.comments.get(pos);
        }
        return wrapper;
    }
    
    public PageReference deleteCase()
    {
        Integer pos=getCaseWrapperPos(caseToDel);
        if (-1!=pos)	
        {
            CaseKeyWrapper wrapper=caseWrappers.get(pos);
            if (null!=wrapper.cs.Id)
            {
                casesToDelete.add(wrapper.cs);
            }
            caseWrappers.remove(pos);
        }
        return null;
    }
    
    
    public PageReference deleteCaseComment()
    {
        String[] keyComps=ccToDel.split(':');
        
        Integer pos=getCaseWrapperPos(keyComps[0]);
        if (-1!=pos)	
        {
            CaseKeyWrapper wrapper=caseWrappers.get(pos);
            Integer commentPos=getCaseCommentWrapperPos(keyComps[1], wrapper);
            if (-1!=commentPos)	
            {
                CaseCommentKeyWrapper comWrap=wrapper.comments.get(commentPos);
                
                if (null!=comWrap.comment.Id)
                {
                    commentsToDelete.add(comWrap.comment);
                }
                wrapper.comments.remove(commentPos);
            }
        }
        
        return null;
    }
    
    public PageReference addCase()
    {
        caseWrappers.add(
            new CaseKeyWrapper(key++, 
                               new Case(AccountId=stdCtrl.getId()),
                               null));
        return null;
    }
    
    public PageReference addCaseComment()
    {
        CaseKeyWrapper wrapper=getCaseWrapper(caseToAddCC);
        if (null!=wrapper)
        {
            wrapper.addComment();
        }
        return null;
    }
    
    public PageReference save()
    {
        List<Case> cases=new List<Case>();
        for (CaseKeyWrapper wrapper : caseWrappers)
        {
            cases.add(wrapper.cs);
        }
        
        upsert cases;
        
        List<CaseComment> caseComments=new List<CaseComment>();
        for (CaseKeyWrapper wrapper : caseWrappers)
        {
            for (CaseCommentKeywrapper ccWrapper : wrapper.comments)
            {	
                CaseComment comment=ccWrapper.comment;
                if (null==comment.ParentId)
                {
                    comment.parentId=wrapper.cs.id;
                }
                caseComments.add(comment);
            }	
        }
            try {
        upsert caseComments;
        
        delete casesToDelete; 
        delete commentsToDelete; 
    } catch(exception e) {
    }
        return stdCtrl.save();
        
    } 
  }

Test Class:
@isTest
public class addMultpleTestClass2 {

      public static testMethod void testMyController() {
    Account A = new Account (Name='Account Test');    
    insert A;
    Case c1 = New Case (Accountid = A.id);
    insert c1;
    Case c2 = New Case (Accountid = A.id);    
     insert c2;
 
                CaseComment cc1 = New CaseComment (CommentBody='test',Parentid=c1.id);
        		insert cc1;
          
                CaseComment cc2 = New CaseComment (CommentBody='test',Parentid=c1.id); 
   			 insert cc2;
  
    List<CaseComment> Casecomments = New   List <CaseComment>  () ;
        Casecomments.add(cc1);
        Casecomments.add(cc2);
          Test.StartTest();

    PageReference pageRef = Page.AccountCasesCommentsEdit;
    Test.setCurrentPage(pageRef);
        
    ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(A);
    ApexPages.currentPage().getParameters().put('Id',A.Id);

    AccountCasesCommentsEditExt  controller = new AccountCasesCommentsEditExt (sc);

    TaskKeyWrapper Agendas = New TaskKeyWrapper (1, new Task(Whatid=c1.id));
    CaseKeyWrapper caseWrapper = new CaseKeyWrapper(1,c1, Casecomments);
    controller.key  = 2; 
    controller.addCase();
    controller.caseToAddCC = 'CS1';
    controller.caseToDel = 'CS2';
    controller.ccToDel='CS2:CC1'  ; 
    controller.ccToDel='CS2:CC1'  ;
    String Key ='CS1';

    controller.addCaseComment();
    controller.deleteCase();
   controller.deleteCaseComment();
     controller.getCaseWrapperPos (key);
    controller.getCaseCommentWrapperPos(Key,caseWrapper);
    controller.getCaseCommentWrapper(Key,caseWrapper);
                controller.save();
        
        Key ='CS2';
       controller.getCaseCommentWrapperPos(Key,caseWrapper);
		        controller.save();

    Test.stopTest();

}
}


Lines not being covered,

User-added image
User-added image
All, Im working on writing a test class for below controller however it keeps failing. This VF page allows to enter hierarchy of records in one click. When Im trying to test this, it keep failing and Im getting below error message when Im trying to call addAgendaComment () method. How should I increase my test coverage? Can some please help point me in right direction or give me an example?

Error: System.NullPointerException: Attempt to de-reference a null object
Class.AccountCasesCommentsEditExt.getCaseWrapperPos: line 36, column 1
Class.AccountCasesCommentsEditExt.getCaseWrapper: line 59, column 1
Class.AccountCasesCommentsEditExt.addCaseComment: line 154, column 1
Class.addMultpleTestClass2.testMyController: line 36, column 1

Wrapper 1
public with sharing class CaseCommentKeyWrapper 
{
    public Integer key {get; set;}
    public CaseComment comment {get; set;}

    public CaseCommentKeyWrapper(Integer inKey, CaseComment inComment)
    {
        key=inKey;
        comment=inComment;
    }
}

Wrapper 2:
public with sharing class CaseKeyWrapper 
{
    public Integer key {get; set;}
    public Case cs {get; set;}
    public List<CaseCommentKeyWrapper> comments {get; set;}
    private Integer commentKey=1;

    public CaseKeyWrapper(Integer inKey, Case inCs, List<CaseComment> inComments)
    {
        cs=inCs;
        key=inKey;
        comments=new List<CaseCommentKeyWrapper>();
        if (null!=inComments)
        {
            for (CaseComment cc : inComments)
            {
                comments.add(new CaseCommentKeyWrapper(commentKey++, cc));
            }
        }
    }
    public void addComment()
    {
        comments.add(new CaseCommentKeyWrapper(commentKey++, new CaseComment(ParentId=cs.id)));
    }
}

Controller Extension:
public with sharing class AccountCasesCommentsEditExt 
{
    public List<CaseKeyWrapper> caseWrappers {get; set;}

    public ApexPages.StandardController stdCtrl {get; set;}

    public Integer key=1;   

    public String caseToDel {get; set;}

    public String ccToDel {get; set;}

    public String caseToAddCC {get; set;}

    public List<Case> casesToDelete=new List<Case>();

    public List<CaseComment> commentsToDelete=new List<CaseComment>();

    public AccountCasesCommentsEditExt(ApexPages.StandardController std)
    {
        stdCtrl=std;
        List<Case> cases=[select id, Status, Subject, 
                          (select id, CommentBody, IsPublished, ParentId from CaseComments) 
                          from Case
                          where AccountId=:stdCtrl.getId()];    

        caseWrappers=new list<CaseKeyWrapper>();
        for (Case cs : cases)
        {
            caseWrappers.add(new CaseKeyWrapper(key++, cs, cs.CaseComments));
        }
    }

    public Integer getCaseWrapperPos(String keyStr)
    {
        Integer key=Integer.valueOf(keyStr.substring(2));
        Integer result=-1;

        Integer index=0;
        for (CaseKeyWrapper cand : caseWrappers)
        {
            if (cand.key==key)
            {
                result=index;
                break;
            }
            else
            {
                index++;
            }
        }

        return result;
    }

    public CaseKeyWrapper getCaseWrapper(String keyStr)
    {
        CaseKeyWrapper wrapper=null;
        Integer pos=getCaseWrapperPos(keyStr);
        if (-1!=pos)
        {
            wrapper=caseWrappers.get(pos);
        }

        return wrapper;
    }

    public Integer getCaseCommentWrapperPos(String keyStr, CaseKeyWrapper wrapper)
    {
        Integer key=Integer.valueOf(keyStr.substring(2));
        Integer result=-1;

        Integer index=0;
        for (CaseCommentKeyWrapper cand : wrapper.comments)
        {
            if (cand.key==key)
            {
                result=index;
                break;
            }
            else
            {
                index++;
            }
        }

        return result;
    }

    public CaseCommentKeyWrapper getCaseCommentWrapper(String keyStr, CaseKeyWrapper caseWrapper)
    {
        CaseCommentKeyWrapper wrapper=null;
        Integer pos=getCaseCommentWrapperPos(keyStr, caseWrapper);
        if (-1!=pos)
        {
            wrapper=caseWrapper.comments.get(pos);
        }

        return wrapper;
    }

    public PageReference deleteCase()
    {
        Integer pos=getCaseWrapperPos(caseToDel);
        if (-1!=pos)    
        {
            CaseKeyWrapper wrapper=caseWrappers.get(pos);
            if (null!=wrapper.cs.Id)
            {
                casesToDelete.add(wrapper.cs);
            }
            caseWrappers.remove(pos);
        }
        return null;
    }


    public PageReference deleteCaseComment()
    {
        String[] keyComps=ccToDel.split(':');

        Integer pos=getCaseWrapperPos(keyComps[0]);
        if (-1!=pos)    
        {
            CaseKeyWrapper wrapper=caseWrappers.get(pos);
            Integer commentPos=getCaseCommentWrapperPos(keyComps[1], wrapper);
            if (-1!=commentPos) 
            {
                CaseCommentKeyWrapper comWrap=wrapper.comments.get(commentPos);

                if (null!=comWrap.comment.Id)
                {
                    commentsToDelete.add(comWrap.comment);
                }
                wrapper.comments.remove(commentPos);
            }
        }

        return null;
    }

    public PageReference addCase()
    {
        caseWrappers.add(
            new CaseKeyWrapper(key++, 
                               new Case(AccountId=stdCtrl.getId()),
                               null));

        return null;
    }

    public PageReference addCaseComment()
    {
        CaseKeyWrapper wrapper=getCaseWrapper(caseToAddCC);
        if (null!=wrapper)
        {
            wrapper.addComment();
        }
        return null;
    }

    public PageReference save()
    {
        List<Case> cases=new List<Case>();
        for (CaseKeyWrapper wrapper : caseWrappers)
        {
            cases.add(wrapper.cs);
        }

        upsert cases;

        List<CaseComment> caseComments=new List<CaseComment>();
        for (CaseKeyWrapper wrapper : caseWrappers)
        {
            for (CaseCommentKeywrapper ccWrapper : wrapper.comments)
            {   
                CaseComment comment=ccWrapper.comment;
                if (null==comment.ParentId)
                {
                    comment.parentId=wrapper.cs.id;
                }
                caseComments.add(comment);
            }   
        }

        upsert caseComments;

        delete casesToDelete; 
        delete commentsToDelete; 

        return stdCtrl.save();
    }

}
My test class:
@isTest
public class addMultpleTestClass2 {

    public static testMethod void testMyController() {
        PageReference pageRef = Page.AccountCasesCommentsEdit;
        Test.setCurrentPage(pageRef);

        Account A = new Account ();    
        A.Name='Account Test'; 
        insert A;

        Case c = New Case ();
        c.Accountid = A.id;
        insert c;


        List<CaseComment> Casecomments = New   List <CaseComment>  ()    ;
        Casecomments.add(new CaseComment(CommentBody='test', Parentid=c.id));
        Casecomments.add(new CaseComment(CommentBody='test', Parentid=c.id));
        insert Casecomments;

        ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(c);
        ApexPages.currentPage().getParameters().put('Id',c.Id);

        AccountCasesCommentsEditExt  controller = new AccountCasesCommentsEditExt (sc);

        controller.key  = 2; 
        controller.addCase();

        //I`m getting error at below line... 
        controller.addCaseComment();

    }
}


 
All, need help. Below is my callout class which makes two different callouts to external system. In callout 1, it gets a token. In Callout 2, it uses that token to retrieve the actual data. For some reason, I`m not getting a complete test coverage on this class. After line " deserializeResults3 = (accountParser)System.JSON.deserialize(fieldValue, accountParser.class);", nothing is being covered. Can someone please help? Any help is much appreciated.
 
global class CalloutsAccounts1 implements Database.Batchable<sObject>,Database.AllowsCallouts{
   global Database.QueryLocator start(Database.BatchableContext BC){
        String query =  'SELECT Id FROM Account';
        return Database.getQueryLocator(query); 
   }

   global void execute(Database.BatchableContext BC, List<Account> scope){
        HttpRequest obj = new HttpRequest(); 
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        String reqBody = '{ "user": "sales_user", "password": "sales_password" }';
        obj.setMethod('POST');
        obj.setHeader('Content-Type','application/json');
        obj.setEndPoint('https://test.samplepoint.com/api/UserSrvs.svc/Login');
        obj.setBody(reqBody);
        obj.getheader('Auth-Token');
        res = http.send(obj);
                                system.debug('Oauth Response: '+res.getbody());
                               system.debug('Header Auth-Token Response: '+res.getHeader('Auth-Token'));

                authtoken objAuthenticationInfo = (authtoken)JSON.deserialize(res.getbody(), authtoken.class);
                System.debug('objAuthenticationInfo: '+objAuthenticationInfo);


                                String token = res.getHeader('Auth-Token');
                                system.debug('token: '+token);    


        Http h1 = new Http();
        HttpRequest req1 = new HttpRequest();
        String reqBody2 = '{"Accountype" : "workforce"}'; 
        req1.setHeader('Auth-Token', token);
        req1.setHeader('Content-Type','application/json');
        req1.setMethod('POST');
         req1.setBody(reqBody2);

        req1.setEndpoint('https://test.samplepoint.com/api/accservices.svc/accountfeed');
        system.debug('======req1========'+req1);
        HttpResponse res1 = h1.send(req1);
        system.debug('==========res1============'+res1.getBody());



                   JSONParser parser = JSON.createParser(res1.getBody());
                    parser.nextToken();
                     parser.nextValue();
                            system.debug('==========parser============'+parser);

                    String fieldName = parser.getCurrentName();
                    String fieldValue = parser.getText(); 
        system.debug('==========fieldValue============'+fieldValue);
    accountParser deserializeResults3 =  new accountParser();
    deserializeResults3 = (accountParser)System.JSON.deserialize(fieldValue, accountParser.class);

     List <accountParser.cls_account> advisorList = new List<accountParser.cls_account>();
    advisorList = deserializeResults3.root.accounts.account;

           Map <Decimal,Id> AdvisorMap = New Map  <Decimal,Id>   ();

        List <Account> advisorAccList = [SELECT Id, Fact_Finder_Client_ID__c, RecordTypeID FROM Account WHERE RecordTypeid = '012410000009tw6[![enter image description here][1]][1]'];

        For (Account Acs : advisorAccList) {
            If (Acs.Fact_Finder_Client_ID__c != null)
            AdvisorMap.put(Acs.Fact_Finder_Client_ID__c, Acs.ID);
            system.debug('@@@'+AdvisorMap);
                }
             Map <String,Id> HouseholdMap = New Map  <String,Id>   ();

        List <Account> advisorAccList1 = [SELECT Id, SSN__c, RecordTypeID FROM Account WHERE RecordTypeid = '012410000009Yr4'];

        For (Account Acs1 : advisorAccList1) {
            If (Acs1.SSN__c != null)
            HouseholdMap.put(Acs1.SSN__c, Acs1.ID);
                }

List<Financial_Account__c> lstAccount = new List<Financial_Account__c>();
for(accountParser.cls_account cand : advisorList){
    Financial_Account__c PFA = New Financial_Account__c();
    //PFA.Cirrus_Unique_ID__c =  cand.account_id;

    //Map Advisor Lookup
   PFA._Advisor_ID__c = cand.advisor_id; 
   PFA.Advisor__c = AdvisorMap.get(PFA._Advisor_ID__c );  

    //Map Household Client Lookup
    PFA._Household_ID2__c = cand.household_id;
   if (HouseholdMap.get(PFA._Household_ID2__c) == null) {
       PFA.Client__c = '0013C000003wagf'; 
} else if (PFA._Household_ID2__c != null) {
         PFA.Client__c = HouseholdMap.get(PFA._Household_ID2__c);  
}


    PFA._Unique_ID__c =  cand.account_id;
    PFA.Financial_Account_Number__c =  cand.account_num;
    PFA.Account_Type__c =  cand.account_type;
    PFA.Tax_Status__c=  cand.taxable_flg;
    PFA.Investment_Objective__c =  cand.objective;
    if (cand.inception_date != null) {
    PFA.Account_Opening__c = date.parse(cand.inception_date);
        }
        if (cand.perf_begin_date != null) {
    PFA._perf_begin_date__c = date.parse(cand.perf_begin_date);
        }
     }
    PFA.Account_Type__c =  cand.account_type;
    PFA.compute_flg__c = cand.compute_flg;
    PFA.Account_Description__c = cand.description;
    PFA.fwc_hh_id__c = cand.fwc_hh_id;


    lstAccount.add(PFA);
}


Boolean isUpsertfirstTime = true;
try {
    upsert lstAccount Financial_Account_Number__c;
}catch (DMLException e) {
                System.debug('Re-trying');
                if(isUpsertfirstTime){
                        upsert lstAccount Financial_Account_Number__c;
                                isUpsertfirstTime = false;
              }
}


   }       

   global void finish(Database.BatchableContext BC){
              CalloutsAccounts2 myContactBatch = new CalloutsAccounts2();
      Id batchProcessId = Database.executeBatch(myContactBatch);

   }
Mock:
 
@isTest
global class Example1_HttpCalloutMock implements HttpCalloutMock {

    //  Implement this interface method
    global HttpResponse respond(HttpRequest req) {

        //  Prepare a response to return
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');

        //  Can use the HttpRequest details to shape the response
        if (req.getMethod() == 'POST' && req.getEndpoint() == 'https://test.samplepoint.com/api/UserSrvs.svc/Login') { 

            //  Provide a response for this endpoint
        res.setBody('{"User":{"indenty":250751503,"GroupID":0,"IdentityProviderID":0,"IdentityProviderUserID":"test","FirstName":"test","LastName":"Services","Email":"test@test.com","AffiliateId":111,"Type":14,"SubType":1,"Gender":"M","InUseFlg":false},"AffiliatePreferences":null}');
     res.setHeader('Auth-Token', '6VIitOCHBJfSA7lZIlgdNLpxw+v5AvcksXlVjtnjg34qwLYHwDTHlFZYj2xC7X0nTU6djaWruJa03+FgN8cet3kwuu4N5HaAhEbldu5t8+gDH9siTt/wO58O+6872sG8=');
        res.setStatusCode(200);                  
        }


          if (req.getMethod() == 'POST' && req.getEndpoint() == 'https://test.samplepoint.com/api/accservices.svc/accountfeed') { 
                        res.setHeader('Content-Type', 'application/json');
            //  Provide a response for this endpoint
        res1.setHeader('Content-Type', 'application/json');
res1.setBody('{  "d": "{\"root\":{\"pagination\":{\"accounts\":{\"pages\":\"111\"},\"page\":\"1\",\"pageSize\":\"2\"},\"accounts\":{\"account\":[{\"account_id\":\"512\",\"account_num\":\"35111516\",\"account_type\":\" Remainder Trust\",\"taxable_flg\":\"1\",\"compute \":\"0\",\"description\":\"ZZ-test, dave B\",\"add_id\":\"57\",\"fwc_id\":\"test-test\",\" begin_date\":\"07/10/2003\",\"inc_date\":\"07/09/2003\",\"termination_date\":\"02/24/2014\",\"last_date\":\"04/30/2008\",\"test_id\":\"18\",\"planning_id\":\"1175\",\"account_num\":\"20696291\",\"objective\":\"WCM \"},{\"account_id\":\"513\",\"account_num\":\"1515661\",\"account_type\":\"Individual Account\",\"taxable_flg\":\"1\",\" compute\":\"0\",\"description\":\"ZZ-tst, dave B\",\"add_id\":\"57\",\"fwc _id\":\"NWCP - test\",\" begin_date\":\"06/30/2003\",\" inc_date\":\"07/09/2006\",\"termination_date\":\"02/24/2014\",\"last_date\":\"04/30/2008\",\"test_id\":\"18\",\"planning_id\":\"175\",\" account_num\":\"1251515\",\"objective\":\"test\"}]}}}"}');
     res1.setHeader('Auth-Token', '6VIitOCHBJfSA7lZIlgdNLpxw+v5AvcksXlVjtnjg34qwLYHwDTHlFZYj2xC7X0nTU6djaWruJa03+FgN8cet3kwuu4N5HaAhEbldu5t8+gDH9siTt/wO58O+6872sG8=');
        res1.setStatusCode(200);              
        }


        return res;
    }
}
Test class:
 
@isTest
private class CalloutClassTest {
     @isTest static void testCallout() {
      Test.startTest();
       Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
       CalloutsAccounts1 CA= new CalloutsAccounts1 ();
       Account acc = new Account( Name = 'My Test Account' );
       Insert acc;
        Database.executeBatch(new CalloutsAccounts1 (), 100);
       Test.stopTest();

    }
}
User-added image


 

All, need help with test class on Batch apex. Below is batch apex code which make 2 callouts (for Token and actual data) however i`m not able to get test coverege on this class. All I have is 7% coverage. Can someone please help?
 
global class CalloutsAccounts implements Database.Batchable<sObject>,Database.AllowsCallouts{


   global Database.QueryLocator start(Database.BatchableContext BC){
        String query =  'SELECT Id FROM Account LIMIT 1';
        return Database.getQueryLocator(query); 
   }

   global void execute(Database.BatchableContext BC, List<Account> scope){
        HttpRequest obj = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        String reqBody = '{ "user": "Username", "passwd": "user_password" }';
        obj.setMethod('POST');
        obj.setHeader('Content-Type','application/json');
        obj.setEndPoint('https://test.samplepoint.com/api/UserSrvs.svc/Login');
        obj.setBody(reqBody);
        obj.getheader('Auth-Token');
        res = http.send(obj);

                authtoken objAuthenticationInfo = (authtoken)JSON.deserialize(res.getbody(), authtoken.class);
String token = res.getHeader('Auth-Token');


        Http h1 = new Http();
        HttpRequest req1 = new HttpRequest();
        String reqBody2 = ' {"Accountype" : "workforce"}'; 
        req1.setHeader('Auth-Token', token);
        req1.setHeader('Content-Type','application/json');
        req1.setMethod('POST');
         req1.setBody(reqBody2);

        req1.setEndpoint('https://test.samplepoint.com/api/accservices.svc/accountfeed');
        HttpResponse res1 = h1.send(req1);



                   JSONParser parser = JSON.createParser(res1.getBody());
                    parser.nextToken();
                     parser.nextValue();

                    String fieldName = parser.getCurrentName();
                    String fieldValue = parser.getText(); 

    accParser deserializeResults3 =  new accParser ();
    deserializeResults3 = (accParser)System.JSON.deserialize(fieldValue, accParser.class);
     List < accParser.cls_account> advisorList = new List< accParser.cls_account>();
    advisorList = deserializeResults3.root.accounts.account;

           Map <Decimal,Id> AdvisorMap = New Map  <Decimal,Id>   ();

        List <Account> advisorAccList = [SELECT Id, Fact_ID__c, RecordTypeID FROM Account WHERE RecordTypeid = '0124100000091Ho'];

        For (Account Acs : advisorAccList) {
            If (Acs.Fact_ID__c != null)
            AdvisorMap.put(Acs.Fact_ID__c, Acs.ID);
                }


             Map <String,Id> HouseholdMap = New Map  <String,Id>   ();

        List <Account> advisorAccList1 = [SELECT Id, SSCN__c, RecordTypeID FROM Account WHERE RecordTypeid = '012410000009Il6'];

        For (Account Acs1 : advisorAccList1) {
            If (Acs1.SSCN__c != null)
            HouseholdMap.put(Acs1.SSCN__c, Acs1.ID);
            system.debug('@@@'+HouseholdMap);
                }



List<Financial_Account__c> lstAccount = new List<Financial_Account__c>();
for(accountParser.cls_account cand : advisorList){
    Financial_Account__c PFA = New Financial_Account__c();
    //PFA.Cirrus_Unique_ID__c =  cand.account_id;

    //Map Advisor Lookup
   PFA.Advisor_ID__c = cand.advisor_id; 
   PFA.Advisor__c = AdvisorMap.get(PFA.Advisor_ID__c );  

    //Map Household Client Lookup
    PFA.Household_ID2__c = cand.household_id;
   if (HouseholdMap.get(PFA.Household_ID2__c) == null) {
       PFA.Client__c = '0013C000003Ywet'; 
} else if (PFA.Household_ID2__c != null) {
         PFA.Client__c = HouseholdMap.get(PFA.Household_ID2__c);  
}




    PFA.Unique_ID__c =  cand.account_id;
    PFA.Financial_Account_Number__c =  cand.accountnum;
    PFA.Account_Type__c =  cand.account;
    PFA.Tax_Status__c=  cand.taxablestatus;
    PFA.Investment_Objective__c =  cand.objective;
    if (cand.inception_date != null) {
    PFA.Account_Opening__c = date.parse(cand.inception);
        }
        if (cand.perf_begin_date != null) {
    PFA.perf_begin_date__c = date.parse(cand.perfdate);
        }
    // if (cand.household_id != null) {
  //  PFA.Household_ID__c = cand.housedate_id;
  //      }
    PFA.Account_Type__c =  cand.account_type;
   // PFA.Client__c =  '0013C000003CRTr'; LOOKUP TO ACCOUNTS
    PFA.compute_flg__c = cand.compute_flg;
    PFA.Account_Description__c = cand.description;
    PFA.fwc_hh_id__c = cand.fwc_hh_id;
        if (cand.termination_date != null) {
    PFA.termination_date__C = date.parse(cand.termination_date);
        }
        if (cand.last_date != null) {
    PFA.last_date__c = date.parse(cand.last_date);
        }
    PFA.Custodian_Id__c = cand.custodian_id;
    PFA.billing_account_num__c = cand.billing_account_num;
    PFA.rebal_method__c = cand.rebal_method;




    lstAccount.add(PFA);
}


Boolean isUpsertfirstTime = true;
try {
    upsert lstAccount Financial_Account_Number__c;
}catch (DMLException e) {
                System.debug('Re-trying');
                if(isUpsertfirstTime){
                        upsert lstAccount Financial_Account_Number__c;
                                isUpsertfirstTime = false;
              }
}


   }       

   global void finish(Database.BatchableContext BC){
              CalloutsAccounts2 myaccBatch = new CalloutsAccounts2();
      Id batchProcessId = Database.executeBatch(myacctBatch);

   }
}

Mock:
 
@isTest
global class MockHttpResponseGenerator implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
        // Optionally, only send a mock response for a specific endpoint
        // and method.
               System.assertEquals('https://test.samplepoint.com/api/UserSrvs.svc/', req.getEndpoint());
        System.assertEquals('POST', req.getMethod()); 

        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
res.setBody(''{ "user": "Username", "passwd": "user_password" }');
        res.setHeader('Auth-Token', '3+yV8B+7iSTu7Oj4alK4/fJPY1a5VRhAre6jG5vx6kDTXMOENFWJqAIQpuYE8nOdLwDmQBdo=');
 res.setStatusCode(200);         
        return res;
    }
}

Test class:
@isTest
private class CalloutClassTest {
     @isTest static void testCallout() {
        // Set mock callout class 

        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        Test.startTest();
  Account acc = new Account(  Name = 'My Test Account' );

  		  upsert acc;

        Database.executeBatch(new CalloutsAccounts(), 100);
        Test.stopTest();

    }


 
Need help. Im new to Apex (with decent exp on Java) and Im working on callout class to get data from external system. Below code works fine, however while making a callout to larger data set, I get "Error: System.LimitException: Too many DML rows: 10001". Im assuming this is due to large data being returned from webservice. Is there a way to process this data in batches? I know Batch class is used for operations like this however I`m not able to get it work. How can I process JSON reponse in batches? Can someone please give me a working example?

 
HttpRequest obj = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        String reqBody = '{ "user": "user_name", "pswd": "user_password" }';
        obj.setMethod('POST');
        obj.setHeader('Content-Type','application/json');
        obj.setEndPoint('https://test.samplepoint.com/api/UserSrvs.svc/Login');
        obj.setBody(reqBody);
        obj.getheader('Auth-Token');
        res = http.send(obj);

                authtoken objAuthenticationInfo = (authtoken)JSON.deserialize(res.getbody(), authtoken.class);
                System.debug('objAuthenticationInfo: '+objAuthenticationInfo);


                                String token = res.getHeader('Auth-Token');
                                system.debug('token: '+token);    


        Http h1 = new Http();
        HttpRequest req1 = new HttpRequest();
        String reqBody2 = '{"Accountype" : "workforce"}'; 
        req1.setHeader('Auth-Token', token);
        req1.setHeader('Content-Type','application/json');
        req1.setMethod('POST');
         req1.setBody(reqBody2);

        req1.setEndpoint('https://test.samplepoint.com/api/accservices.svc/accountfeed');
        system.debug('======req1========'+req1);
        HttpResponse res1 = h1.send(req1);
        system.debug('==========res1============'+res1.getBody());



    DataParser deserializeRes =  new DataParser();
    deserializeRes = (DataParser)System.JSON.deserialize(replaceJson, DataParser.class);
     List <DataParser.cls_account> advisorList = new List<DataParser.cls_account>();
    advisorList = deserializeRes.rut.accounts.account;



List<Funtional_Account__c> lstAccount = new List<Funtional_Account__c>();
for(DataParser.cls_account c : advisorList){
    Funtional_Account__c PFA = New Funtional_Account__c();
    PFA.payment_Unique_ID__c =  c.account_id;
   PFA.Advisor_ID__c = c.advisor_id;   
    PFA.Unique_ID__c =  c.account_id;
    PFA.Financial_Account_Number__c =  c.account_num;
    PFA.Account_Type__c =  c.account_type;
    PFA.Client__c =  '0015C000003VqWh';

    lstAccount.add(PFA);
}


Boolean isUpsertfirstTime = true;
try {
    upsert lstAccount Financial_Account_Number__c;
}catch (DMLException e) {
                System.debug('Re-trying');
                if(isUpsertfirstTime){
                        upsert lstAccount Financial_Account_Number__c;
                                isUpsertfirstTime = false;
              }
}

 
Need help. Using Class below, I have deserialized JSON response however I`m not able to figure out how should I create an account in Salesforce using this deserialized data. Can someone please help?
 
public class candidateParser{
public cls_rut rut;
public class cls_rut {
    public cls_candidates candidates;
}
public class cls_ candidates {
    public cls_candidate [] candidate;
}
public class cls_candidate {
    public String candidate_id; //3
    public String candidate_code;   //AA12
    public String description;  // Steven S.
}
public static candidateParser parse(String json){
    return (candidateParser) System.JSON.deserialize(json, candidateParser.class);
}}

Deserialized JSON:
11:11:02:208 USER_DEBUG [69]|DEBUG|deserializeResults====: candidateParser:[rut=cls_rut:[candidates=cls_candidates:[candidate=(cls_candidate:[candidate_code=AA12, candidate_id=3, description=Steven S.], cls_candidate:[candidate_code= AA13, candidate_id=4, description= Brad Hess], cls_candidate:[candidate_code= AA14, candidate_id=5, description=Brad Jones], cls_candidate:[candidate_code= AA14, candidate_id=6, description=Sample candidate], cls_candidate:[candidate_code= AA16, candidate_id=7, description=ross. k],...)]]]


I`m trying below but I keep getting null response on account name. Please help -
 
candidateParser.cls_candidate deserializeResults2 =     (candidateParser.cls_candidate)JSON.deserialize(replaceJson, candidateParser.cls_candidate.class);    
System.debug('deserializeResults2====: '+deserializeResults2);

Account Acc = New Account ();
Acc.Name =  deserializeResults2.candidate_code;
Insert Acc;

 
All, below is my code. While trying to make callout to an external API, I`m getting an error “System.CalloutException: Exceeded max size limit of 6000000” synchronously. I believe this is happening since payload that is being received is very large. I was wondering if there is a way to work across these limits. I tried using @future too however its giving me an error too "System.LimitException: Apex heap size too large: 12649268". Can someone please suggest a better way to get data in Salesforce?
 
HttpRequest obj = new HttpRequest();
    HttpResponse res = new HttpResponse();
    Http http = new Http();
    String reqBody = '{ "user": "test_user", "passwd": "2gbwefgnaiognawgona12" }';
    obj.setMethod('POST');
    obj.setHeader('Content-Type','application/json');
    obj.setEndPoint('https://test.samplepoint.com/api/UserSrvs.svc/Login');
    obj.setBody(reqBody);
    obj.getheader('Auth-Token');
    res = http.send(obj);
                            system.debug('Oauth Response: '+res.getbody());
                           system.debug('Header Auth-Token Response: '+res.getHeader('Auth-Token'));

            authtoken objAuthenticationInfo = (authtoken)JSON.deserialize(res.getbody(), authtoken.class);
            System.debug('objAuthenticationInfo: '+objAuthenticationInfo);


      Http h1 = new Http();
    HttpRequest req1 = new HttpRequest();
    String reqBody2 = '{ "Accountype" : "workforce"}';
    req1.setHeader('Auth-Token', res.getHeader('Auth-Token'));
    req1.setHeader('Content-Type','application/json');
    req1.setMethod('POST');
     req1.setBody(reqBody2);

    req1.setEndpoint('https://test.samplepoint.com/api/accservices.svc/accountfeed');//URL will be your Salesforce REST API end point where you will do POST,PUT,DELETE orGET
    system.debug('======req1========'+req1);
    HttpResponse res1 = h1.send(req1);
    system.debug('==========res1============'+res1.getBody());

 
All, below is my code. While trying to make callout to an external API, I`m getting an error “System.CalloutException: Exceeded max size limit of 6000000”. Can someone please explain why this is happening ? I tried using cURL and POSTMAN and they are working fine however JSON response that is received with these tools is very large. Could this be the reason why I`m getting this error? Is SF not capable of handing large JSON response?       

 
HttpRequest obj = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        String reqBody = '{ "user": "test_user", "passwd": "2gbwefgnaiognawgona12" }';
        obj.setMethod('POST');
        obj.setHeader('Content-Type','application/json');
        obj.setEndPoint('https://test.samplepoint.com/api/UserSrvs.svc/Login');
        obj.setBody(reqBody);
        obj.getheader('Auth-Token');
        res = http.send(obj);
                                system.debug('Oauth Response: '+res.getbody());
                               system.debug('Header Auth-Token Response: '+res.getHeader('Auth-Token'));
        
                authtoken objAuthenticationInfo = (authtoken)JSON.deserialize(res.getbody(), authtoken.class);
                System.debug('objAuthenticationInfo: '+objAuthenticationInfo);
			
        
		  Http h1 = new Http();
        HttpRequest req1 = new HttpRequest();
        String reqBody2 = '{ "Accountype" : "workforce"}';
        req1.setHeader('Auth-Token', res.getHeader('Auth-Token'));
        req1.setHeader('Content-Type','application/json');
        req1.setMethod('POST');
         req1.setBody(reqBody2);

        req1.setEndpoint('https://test.samplepoint.com/api/accservices.svc/accountfeed');//URL will be your Salesforce REST API end point where you will do POST,PUT,DELETE orGET
        system.debug('======req1========'+req1);
        HttpResponse res1 = h1.send(req1);
        system.debug('==========res1============'+res1.getBody());

 
Dear all,
Below is my callout code which is getting data from other Salesforce instance. Code work fine, however instead of @future, I want this code to run on daily basis (once a day) to get all the records from other Salesforce instance. Since I`m new to salesforce, can someone please help me in converting this code to batchable class? Also, is there any other best way to accomplish daily callouts? Please suggest... 
 
public class SampleIntegration
{
        @future (callout=true)
    public static void integration()
    {
        HttpRequest obj = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        String username = 'tom.simmons@hotmail.com';
        String pwd = 'Welcome123rwnYJye3ZaZlxCCq9UJ7sD0AE';
        String reqBody = 'grant_type=password&client_id=3MVG9Y6d_Btp4xp4D3Z8GAwN6wIbOw3vQabsximESJjFoCgpNad5tVtSnQIZN7xAyCekd0tyknn95VTImvYJ2&client_secret=817876896827445493&username='+username+'&password='+pwd;
        obj.setMethod('POST');
        obj.setEndPoint('https://login.salesforce.com/services/oauth2/token');
        obj.setBody(reqBody);
        res = http.send(obj);
                                system.debug('Oauth Response: '+res.getbody());
        OAuth2 objAuthenticationInfo = (OAuth2)JSON.deserialize(res.getbody(), OAuth2.class);
                     system.debug(objAuthenticationInfo);   
                System.debug('objAuthenticationInfo'+objAuthenticationInfo);


        Http h1 = new Http();
        HttpRequest req1 = new HttpRequest();
        req1.setHeader('Authorization','Bearer '+objAuthenticationInfo.access_token);
        req1.setHeader('Content-Type','application/json');
        req1.setHeader('accept','application/json');
        req1.setMethod('GET');
        String strName = 'Hello 3';
        req1.setEndpoint('https://na1.salesforce.com/services/apexrest/Dev_tom/Account1');//URL will be your Salesforce REST API end point where you will do POST,PUT,DELETE orGET
        system.debug('======req1========'+req1);
        HttpResponse res1 = h1.send(req1);
        system.debug('==========res1============'+res1.getBody());

                        JSON2Apex Jsondes = (JSON2Apex)JSON.deserialize(res1.getbody(), JSON2Apex.class);
                                                                System.debug('Jsondes'+Jsondes);

                                                Account A = New Account ();
                                                A.Name = Jsondes.Name;
                                                A.Site = Jsondes.ID;
                                                insert A;


    }

                }