3

I am currently working on creating a scheduled apex to query an external json case objects and insert these objects in salesforce. I am quite new to this framework and quite stuck. The below is a how far i got so far.

global class PublicStuffBatchApex implements Database.Batchable<sObject>, Database.AllowsCallouts{

public String query = 'SELECT Id, Name, Description, SuppliedEmail, SuppliedName, SuppliedPhone, SuppliedTargetAddress__c, SuppliedAddress__c FROM Case';
private static final boolean LOG_THIS_CLASS = true;

global Database.QueryLocator start(Database.BatchableContext BC) {
    return Database.getQueryLocator(query);
}

global void execute(Database.BatchableContext BC, List<Case> records) {

    String endpoint;

    for (Integer i = 0; i < records.size(); i++)
    {
        try
        {
            Date d = Date.today();
            HttpRequest req = new HttpRequest();
            HttpResponse res = new HttpResponse();
            Http http = new Http();
            req.setMethod('GET');

            String strEndPoint = 'https://www.publicstuff.com/api/2.0/requesttypes_list?client_id=1376';
            req.setEndpoint(strEndPoint);
            req.setHeader('Content-Type', 'application/json');
            req.setMethod('POST');
            String json = res.getBody();
            req.setBody(json);
            //req.setCompressed(true);

            //String json = res.getBody().replace('\n', '');

            if (!Test.isRunningTest()) {      
            res = http.send(req);
            System.debug('Str:' + res.getBody());
      }
        } catch(Exception e){
            System.debug('Error:' + e.getMessage());
        }

    }



    //parseJSON(json); //TODO
}

public class WrapperClass {
    public String Id{get; set;}
    public String Name{get; set;}
    public String decription{get; set;}
    public String requst_type_id{get; set;}


}


/*
** The finish method is called after all batches are processed. Use this method to send confirmation emails or execute post-processing operations.
*/
global void finish(Database.BatchableContext BC) {

}

I also have the schedule class:

global class PublicStuffRequestScheduler implements Schedulable {
    global void execute(SchedulableContext sc) {
    PublicStuffBatchApex  uab = new PublicStuffBatchApex(); 
    database.executebatch(uab);
    }
}

Any input would be much appreciated and just to point me in the right direction. My returned json object is posted here: Json returned object

3
  • 1
    What Issues are you having? For starters, your start method is being executed and you never set the query value
    – Eric
    Nov 27 '14 at 20:20
  • Look at simplifying your PublicStuffBatchApex class by not implementing Schedulable and Messaging.InboundEmailHandler. Instead just focus on being a batching class. Then, as Eric suggests, you need to define a base SOQL query for cases in the constructor and assign it the the query member. The cases returned by this query will be passed to the execute method and result in HTTP requests. Nov 28 '14 at 1:29
  • @DanielBallinger, how would i do this? I actually need to do a Http request in order to get json object, deserialize the object and insert the content as a new Case object. I dont see a reson to do a SOQL on cases in the constructor but I think I need to SOQL the Json object/response. Pls point me in the right direction. thx
    – codeSlayer
    Nov 28 '14 at 9:13
2

I see you have revised your batch class. I'm not sure it have gone in the correct direction if you want it to run on a schedule. You could have probably stayed with implementing Schedulable and dropped the batch implementation.

I assume you were using batches to allow for the callout to occur. Since there isn't anything to batch over you could just uses a future method.

E.g.

global class PublicStuffApex implements Schedulable {

    private static final boolean LOG_THIS_CLASS = true;

    global void execute(SchedulableContext sc){
        createNewCases();
    }

    // Note the callout=true that will switch to an async context that allows callouts.
    @future(callout=true)
    public static void createNewCases() {

        // Callout code verbatim from the question
        if (LOG_THIS_CLASS) System.debug('<Arcus> In the execute body');
        Date d = Date.today();
        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        req.setMethod('GET');

        String strEndPoint = 'https://www.publicstuff.com/api/2.0/requesttypes_list?client_id=1376';
        req.setEndpoint(strEndPoint);
        req.setHeader('Content-Type', 'application/json');
        req.setMethod('POST');
        String json = res.getBody();
        req.setBody(json);
        //req.setCompressed(true);

        //String json = res.getBody().replace('\n', '');
        if (LOG_THIS_CLASS) System.debug('<Arcus> The body of the response is ' + json);

        if (!Test.isRunningTest()) {      
        res = http.send(req);
        System.debug('Str:' + res.getBody());
    }
}
4
  • The method works fine. But i will potentially have more than 200 records that needs to be inserted at every call. then it needs to implement the Batchable right?
    – codeSlayer
    Dec 2 '14 at 13:45
  • @codeSlayer You can insert up to 10,000 records in one transaction. See Per-Transaction Apex Limits. If the response exceeds that then, yes, you will need to use an iterable batch. Just how many records are you expecting to process? Is there any way to do paging of the results against the API? Dec 2 '14 at 18:23
  • I dont expect more than 1000 a day. But after looking at the Transaction Apex Limit page, the Total number of SOQL queries issued1 is 200 for the Async Limit.
    – codeSlayer
    Dec 3 '14 at 12:04
  • @codeSlayer The "Total number of SOQL queries issued" limit is per transaction. So in the future method createNewCases() you could do any combination of SOQL queries or insert/update/upsert/delete (DML) statements up to a total of 200. Each DML statement can take a collection of records. So you should have no problem staying within this limit if you insert all 1000 records in one call. Dec 3 '14 at 18:26

Your Answer

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

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