• Abhiram Sheshadri 9
  • NEWBIE
  • 105 Points
  • Member since 2015

  • Chatter
    Feed
  • 1
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 5
    Questions
  • 11
    Replies
In the Trailhead Apex Web Services Unit, my class has 100% test coverage and using the Workbench: REST Explorer, responds correctly to existing accounts with or without associated contacts. If an invalid Id is passed in, I return an empty account.

However, when I Check the challenge, I get "System.ListException: List index out of bounds: 0" problem in response. I'm not sure what's wrong - any pointers?
Hi,

I have a scheduler class which is scheduled to run every 5 min which calls a batch class. This batch class calls a method from another class which adds multiple jobs to a queue. When it's scheduled I am getting System.LimitException: Too many queueable jobs added to the queue: 2.
But if I don't schedule and run the code from Ananymous block or from VF button it works just fine. Below I am attaching the code sample for the same.
Scheduler Class
global with sharing class getSocialPostsScheduleBatch implements Schedulable {
global void execute(SchedulableContext sc) {
  ID BatchId = Database.executeBatch(new getPostsBatch(), 200);
}
}

Batch class:
global class getPostsBatch implements Database.Batchable<sObject>, Database.AllowsCallouts,Database.Stateful{

global Database.QueryLocator start(Database.BatchableContext BC)
{
    String query='Select Id from User Limit 1';
    return Database.getQueryLocator(query);
}

global void execute(Database.BatchableContext BC, List<Object> scope)
{
   getSocialPosts.getPosts();

}   
global void finish(Database.BatchableContext BC)
{
   
}
}

Callout Class:
public class getSocialPosts{
	public static void getPosts() {
		   String auth_token = oauthLogin();
		   
		   DateTime endTime = dateTime.now();
		   String unixendTime = ''+endTime.getTime()/1000;
		   System.debug('Unix time-stamp: '+unixendTime);
		   
		   DateTime startTime = dateTime.now().addHours(-24);
		   String unixStartTime = ''+startTime.getTime()/1000;
		   System.debug('Unix time-stamp: '+unixStartTime);
		   
		   SocialPostsCustomSetting__c customSet = SocialPostsCustomSetting__c.getInstance('Record');
		   String custId=customSet.SocialPostId__c;
		   System.debug('ID from Custom Settings='+custId);

		   HttpRequest req = new HttpRequest(); 
		   req.setMethod('GET');
		   req.setEndpoint('https://api.socialstudio.radian6.com/v3/posts?topics=1135172&limit=5&sinceId='+custId+'&sortBy=publishedDate');
		   req.setHeader('access_token',auth_token);
		   Http http = new Http();
		   HTTPResponse res = http.send(req);
		   System.debug('BODY: '+res.getBody());
		   System.debug('STATUS:'+res.getStatus());
		   System.debug('STATUS_CODE:'+res.getStatusCode());
		   //fromJSON jsonObj = fromJSON.parse(res.getBody());
		   string jsonstr = res.getBody();
		   system.debug('JSON Body='+jsonstr);
		   if((jsonstr.containsIgnoreCase('Comment from')||jsonstr.containsIgnoreCase('Reply From'))&&jsonstr.containsIgnoreCase('Post from')){
			   JsonParser5 jsonobj;
			   //fromJSON jsonobj;
			   try{
					  jsonobj = (JsonParser5)JSON.deserialize(res.getBody(),JsonParser5.class);
					  //jsonobj= fromJSON.parse(res.getBody());
					  System.debug('Parsed Data='+jsonobj);
				   }catch(Exception e){
					   
						   system.debug('Exception in deserialize '+e.getMessage());
						   
				   }
			   system.debug('JSONOBJ inside if='+jsonobj );
			   
			   List<JsonParser5.data> jsonList =new List<JsonParser5.data>();
			   if(jsonobj!=null){
					   if(jsonobj.data!=null){
						   jsonList = jsonobj.data;
					   }
			   }
			   system.debug('JSONLIST5='+jsonList );
			   List<String> idSet = new List<String>();
			   Map<String,Map<String,String>> socialIdUrlMap = new Map<String,Map<String,String>>();
			   if(jsonList.size()>0){
				   for(JsonParser5.data obj : jsonList){
					   
					   if(obj.title.containsIgnoreCase('Comment from')){
						   if(!obj.title.containsIgnoreCase('Comment From: Lopples')){
							   
							   postToFacebook.postReplytoComment(obj.externalId);
						   }
					   }
					   else{
						   if(!obj.title.contains('Lopples')){
							   System.debug('Id='+obj.id);
							   idSet.add(obj.id);
							   Map<String,String> contentMap = new Map<String,String>();
							   contentMap.put(obj.entities.media[0].media_url,obj.content);
							   socialIdUrlMap.put(obj.externalId,contentMap );
						  
						   }  
					   }
				   }
				   if(socialIdUrlMap.size()>0){
					   saveImages(socialIdUrlMap);
				   }
				   customSet.SocialPostId__c=idSet[0];
				   update customSet;
			   }
				
		   }
		}
	public static void saveImages(Map<String,Map<String,String>> socialIdUrlMap){
        List<ContentVersion> cvList = new List<ContentVersion>();
        Integer count=0;
        for (String socialId : socialIdUrlMap.keySet()){
            Map<String,String> data= new Map<String,String>();
            data = socialIdUrlMap.get(socialId);
            for(String url: data.keySet()){
                if(!url.contains('https://www.facebook.com')){
                count++;
                Http h = new Http();
                HttpRequest req = new HttpRequest();
                req.setMethod('GET');
                req.setEndpoint(url);
                if(url.contains('png')){
                    system.debug('Inside PNG'+url);
                    req.setHeader('Content-Type', 'image/png');
                }
                else if(url.contains('jpg')){
                    system.debug('Inside JPEG'+url);
                    req.setHeader('Content-Type', 'image/jpeg');
                }
                HttpResponse res = null;
                string responseValue = '';
                try{
                    res = h.send(req);
                }catch (System.CalloutException e){
                     System.debug('ERROR:' + e.getMessage());
                }
                blob image = res.getBodyAsBlob();
                ContentVersion cv = new ContentVersion();
                cv.VersionData = image;
                String finalurl = url.split('\\?').get(0);
                cv.PathOnClient = finalurl;
                cv.title = socialId;
                cv.Description = data.get(url);
                cvList.add(cv);
                }
            }
        }
        
        insert cvList;
       
			if(!cvList.isEmpty()){
				for(ContentVersion cv : cvList){
					System.Queueable job = new DeferredHandler(cv.Id);
					System.enqueueJob(job);
				}
			}
		}
	}

The last snippt where I am adding multiple jobs to the queue is causing the issue.
Please let me know if if I am doing wrong here and any workaround to fix the issue​
Hi,

I have written the below classes as part of the trailhead challenge for Apex REST callouts.

The class -

public class AnimalLocator {
  
  public static String getAnimalNameById(Integer id) {
    
    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/'+id);
    request.setMethod('GET');
    
    HttpResponse response = http.send(request);
    List<Object> animals; 
    String returnValue; 
    
    // parse the JSON response
    if (response.getStatusCode() == 200) {
      Map<String, Object> result = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
      animals = (List<Object>) result.get('animals');
      System.debug(animals);
    }
    
    if (animals.size() > 0 && animals != NULL && id < animals.size()) {
      returnValue = (String) animals.get(id);
    }
    
    return returnValue;
  } 
    
}

Mock Response Class - 

@isTest
global class AnimalLocatorMock implements HttpCalloutMock {
     // Implement this interface method
    global HTTPResponse respond(HTTPRequest request) {
        // Create a fake response
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody('{"animals": ["majestic badger", "fluffy bunny", "scary bear", "chicken", "mighty moose"]}');
        response.setStatusCode(200);
        return response; 
    }
}

Test Class - 

@isTest
private class AnimalLocatorTest{
    @isTest static void AnimalLocatorMock1() {
        Test.setMock(HttpCalloutMock.class, new AnimalLocatorMock());
        string result = AnimalLocator.getAnimalNameById(3);
        String expectedResult = 'chicken';
        System.assertEquals(result,expectedResult );
    }
}

I have got 100% code coverage for the main class. But when I check the challenge I get 

Challenge Not yet complete... here's what's wrong: 
There was an unexpected error in your org which is preventing this assessment check from completing: System.NullPointerException: Attempt to de-reference a null object

Please tell me if any changes to the code is required. It's really frustrating as I am stuck from past 3-4 days with this unit.

Thanks & Regards,

Abhiram Sheshadri
Hi,

For the Apex web services challenge, I have written the following class

@RestResource(urlMapping='/Accounts/*/contacts')
global with sharing class AccountManager {
     @HttpGet
    global static Account getAccount(){
        RestRequest request = RestContext.request;
        String Accountid = request.requestURI.substring(10,25);
        Account result = [SELECT id,name ,(SELECT id,name from contacts) from Account where id=:Accountid];
        return result;
    }
}

When I test this with passing the account ID in Workbench REST Explorer I am able to fetch both the account details as well as it's associated contact details.

But when I check the challenge I get the below error.

There was an unexpected error in your org which is preventing this assessment check from completing: System.QueryException: List has no rows for assignment to SObject

Any Help?

Thanks & Regards,
Abhiram Sheshadri
Class : Standard stuff from salesforce

@isTest
private class AnimalsCalloutsTest {

    @isTest static  void testGetCallout() {
        // Create the mock response based on a static resource
        StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
        mock.setStaticResource('GetAnimalResource');
        mock.setStatusCode(200);
        mock.setHeader('Content-Type', 'application/json;charset=UTF-8');
        // Associate the callout with a mock response
        Test.setMock(HttpCalloutMock.class, mock);
        // Call method to test
        HttpResponse result = AnimalsCallouts.makeGetCallout();
        // Verify mock response is not null
        System.assertNotEquals(null,result,
            'The callout returned a null response.');
        // Verify status code
        System.assertEquals(200,result.getStatusCode(),
          'The status code is not 200.');
        // Verify content type   
        System.assertEquals('application/json;charset=UTF-8',
          result.getHeader('Content-Type'),
          'The content type value is not expected.');  
        // Verify the array contains 3 items     
        Map<String, Object> results = (Map<String, Object>) 
            JSON.deserializeUntyped(result.getBody());
        List<Object> animals = (List<Object>) results.get('animals');
        System.assertEquals(3, animals.size(),
          'The array should only contain 3 items.');          
    }   

}

While saving getting 

Error: Compile Error: Method does not exist or incorrect signature: [StaticResourceCalloutMock].setStaticResource(String) at line 7 column 9
The formula should be on the Case object.
The formula should be of return type Number.
The formula should be named 'Days Since Last Update' and have a resulting API Name of 'Days_Since_Last_Update__c'.
The formula should return the number of days between the account’s Last Activity Date and today.

This is the requirement

My formula field is 

TODAY() - Account.LastActivityDate with return type number.

The error is :

There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Delete failed. First exception on row 0 with id 00128000009zGneAAE; first error: DELETE_FAILED, Your attempt to delete Test Account could not be completed because it is associated with the following entitlements.: Test AccountEntitlement : []

Please help me in completing the challenge as I am unable to understand the error.
Hi,

I have written the below classes as part of the trailhead challenge for Apex REST callouts.

The class -

public class AnimalLocator {
  
  public static String getAnimalNameById(Integer id) {
    
    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/'+id);
    request.setMethod('GET');
    
    HttpResponse response = http.send(request);
    List<Object> animals; 
    String returnValue; 
    
    // parse the JSON response
    if (response.getStatusCode() == 200) {
      Map<String, Object> result = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
      animals = (List<Object>) result.get('animals');
      System.debug(animals);
    }
    
    if (animals.size() > 0 && animals != NULL && id < animals.size()) {
      returnValue = (String) animals.get(id);
    }
    
    return returnValue;
  } 
    
}

Mock Response Class - 

@isTest
global class AnimalLocatorMock implements HttpCalloutMock {
     // Implement this interface method
    global HTTPResponse respond(HTTPRequest request) {
        // Create a fake response
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody('{"animals": ["majestic badger", "fluffy bunny", "scary bear", "chicken", "mighty moose"]}');
        response.setStatusCode(200);
        return response; 
    }
}

Test Class - 

@isTest
private class AnimalLocatorTest{
    @isTest static void AnimalLocatorMock1() {
        Test.setMock(HttpCalloutMock.class, new AnimalLocatorMock());
        string result = AnimalLocator.getAnimalNameById(3);
        String expectedResult = 'chicken';
        System.assertEquals(result,expectedResult );
    }
}

I have got 100% code coverage for the main class. But when I check the challenge I get 

Challenge Not yet complete... here's what's wrong: 
There was an unexpected error in your org which is preventing this assessment check from completing: System.NullPointerException: Attempt to de-reference a null object

Please tell me if any changes to the code is required. It's really frustrating as I am stuck from past 3-4 days with this unit.

Thanks & Regards,

Abhiram Sheshadri
Hi,

I have written the below classes as part of the trailhead challenge for Apex REST callouts.

The class -

public class AnimalLocator {
  
  public static String getAnimalNameById(Integer id) {
    
    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/'+id);
    request.setMethod('GET');
    
    HttpResponse response = http.send(request);
    List<Object> animals; 
    String returnValue; 
    
    // parse the JSON response
    if (response.getStatusCode() == 200) {
      Map<String, Object> result = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
      animals = (List<Object>) result.get('animals');
      System.debug(animals);
    }
    
    if (animals.size() > 0 && animals != NULL && id < animals.size()) {
      returnValue = (String) animals.get(id);
    }
    
    return returnValue;
  } 
    
}

Mock Response Class - 

@isTest
global class AnimalLocatorMock implements HttpCalloutMock {
     // Implement this interface method
    global HTTPResponse respond(HTTPRequest request) {
        // Create a fake response
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody('{"animals": ["majestic badger", "fluffy bunny", "scary bear", "chicken", "mighty moose"]}');
        response.setStatusCode(200);
        return response; 
    }
}

Test Class - 

@isTest
private class AnimalLocatorTest{
    @isTest static void AnimalLocatorMock1() {
        Test.setMock(HttpCalloutMock.class, new AnimalLocatorMock());
        string result = AnimalLocator.getAnimalNameById(3);
        String expectedResult = 'chicken';
        System.assertEquals(result,expectedResult );
    }
}

I have got 100% code coverage for the main class. But when I check the challenge I get 

Challenge Not yet complete... here's what's wrong: 
There was an unexpected error in your org which is preventing this assessment check from completing: System.NullPointerException: Attempt to de-reference a null object

Please tell me if any changes to the code is required. It's really frustrating as I am stuck from past 3-4 days with this unit.

Thanks & Regards,

Abhiram Sheshadri
In the Trailhead Apex Web Services Unit, my class has 100% test coverage and using the Workbench: REST Explorer, responds correctly to existing accounts with or without associated contacts. If an invalid Id is passed in, I return an empty account.

However, when I Check the challenge, I get "System.ListException: List index out of bounds: 0" problem in response. I'm not sure what's wrong - any pointers?
Hi,

For the Apex web services challenge, I have written the following class

@RestResource(urlMapping='/Accounts/*/contacts')
global with sharing class AccountManager {
     @HttpGet
    global static Account getAccount(){
        RestRequest request = RestContext.request;
        String Accountid = request.requestURI.substring(10,25);
        Account result = [SELECT id,name ,(SELECT id,name from contacts) from Account where id=:Accountid];
        return result;
    }
}

When I test this with passing the account ID in Workbench REST Explorer I am able to fetch both the account details as well as it's associated contact details.

But when I check the challenge I get the below error.

There was an unexpected error in your org which is preventing this assessment check from completing: System.QueryException: List has no rows for assignment to SObject

Any Help?

Thanks & Regards,
Abhiram Sheshadri
Class : Standard stuff from salesforce

@isTest
private class AnimalsCalloutsTest {

    @isTest static  void testGetCallout() {
        // Create the mock response based on a static resource
        StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
        mock.setStaticResource('GetAnimalResource');
        mock.setStatusCode(200);
        mock.setHeader('Content-Type', 'application/json;charset=UTF-8');
        // Associate the callout with a mock response
        Test.setMock(HttpCalloutMock.class, mock);
        // Call method to test
        HttpResponse result = AnimalsCallouts.makeGetCallout();
        // Verify mock response is not null
        System.assertNotEquals(null,result,
            'The callout returned a null response.');
        // Verify status code
        System.assertEquals(200,result.getStatusCode(),
          'The status code is not 200.');
        // Verify content type   
        System.assertEquals('application/json;charset=UTF-8',
          result.getHeader('Content-Type'),
          'The content type value is not expected.');  
        // Verify the array contains 3 items     
        Map<String, Object> results = (Map<String, Object>) 
            JSON.deserializeUntyped(result.getBody());
        List<Object> animals = (List<Object>) results.get('animals');
        System.assertEquals(3, animals.size(),
          'The array should only contain 3 items.');          
    }   

}

While saving getting 

Error: Compile Error: Method does not exist or incorrect signature: [StaticResourceCalloutMock].setStaticResource(String) at line 7 column 9
I have a requirement where I need to dynamically get the RecordId in a VF page which is launched on click of a global action in sObject's detail page. As this sObject will be dynamic, I can't use a standard controller. The VF page opens up in an iFrame which doesn't get the Id from the detail page link. I tried URL methods for JavaScript call but with no success.

Does anyone have any idea upon how to retrieve this in Lightning Experience?
This functionality was completed well in SF classic via a button.
RecordId doesn't come in the iFrame.
In the Trailhead Apex Web Services Unit, my class has 100% test coverage and using the Workbench: REST Explorer, responds correctly to existing accounts with or without associated contacts. If an invalid Id is passed in, I return an empty account.

However, when I Check the challenge, I get "System.ListException: List index out of bounds: 0" problem in response. I'm not sure what's wrong - any pointers?