Friday 6 July 2012

Rule your Apex Governor Limits through actionFunction


Recently I ran into an issue where I had to make more than 10 HTTP Callouts from my Apex code. Immediate solution we would think would be batch apex or future calls, but this was not a great idea as user would have to wait till the whole process is complete and also due to the number of apex job limits.

Finally we came up this solution – use actionFunction and split Apex callouts. Since Limit of 10 API Callouts is for single execution, we can always make multiple executes with smaller number of callouts. For example – If originally I had to make 20 callouts on click of a button, What if I click 4 different buttons with 5 Callouts each – We will not hit the Limit here…!

Here is the sample code for the same.

/*
Controller for Demo Page
*/
public with sharing class DemoPageControler {

//Declare vars...
List objAccounts;
public String currentStatus {get;set;}

//Constructor
public DemoPageControler(){

objAccounts = new List();
}

//main method...
public void processRecords(){
//This method when called will throw exception
process1();
process2();
process3();
process4();
}

public void process1(){

//This function makes 5 Callouts
callHTTP();
callHTTP();
callHTTP();
callHTTP();
callHTTP();

currentStatus = 'Process 1 completed';
}

public void process2(){


//This function makes 5 Callouts
callHTTP();
callHTTP();
callHTTP();
callHTTP();
callHTTP();

currentStatus = 'Process 2 completed';
}

public void process3(){

//This function makes 5 Callouts
callHTTP();
callHTTP();
callHTTP();
callHTTP();
callHTTP();

currentStatus = 'Process 3 completed';
}

public void process4(){

//This function makes 5 Callouts
callHTTP();
callHTTP();
callHTTP();
callHTTP();
callHTTP();

currentStatus = 'Process completed';
}

public void blankFunction(){


}

public void callHTTP() {

String strurl='http://maps.googleapis.com/maps/api/geocode/xml?address=92618&sensor=false';
HttpRequest req=new HttpRequest();
req.setEndpoint(strurl);
req.setMethod('POST');
string strbody='hi';
req.setBody(strbody);
req.setCompressed(true);
Http http=new Http();
HTTPResponse res=http.send(req);
string strRes=res.getbody();
system.debug('**** Response XML Data is *****'+strRes);

}
}



VisualForce Page code:























We can use the same process to get around other similar exceptions like too many DML operations, too many script statements.