• ismyhc
  • NEWBIE
  • 25 Points
  • Member since 2011

  • Chatter
    Feed
  • 1
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 11
    Questions
  • 23
    Replies

Im trying to return the text of multiple xml elements with the same name. Im using Xmlnode.

 

Heres part of the code that handles the response:

 

// Get xml body from response
dom.Document docx = res.getBodyDocument();
dom.Xmlnode xroot = docx.getRootElement();
dom.Xmlnode xrec = xroot.getChildElement('error', null);

// Setup email for exception
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();            
String[] toAddress = new String[] {ownerEmail};
mail.setToAddresses(toAddress);
mail.setSenderDisplayName('Salesforce');
mail.setSubject('A problem has occured with creating the Proposal');
mail.setPlainTextBody('The following error occured when trying to create the Proposal: \n\n"Proposal ' + newError + '"\n\nPlease correct the errors above and try again.');    
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

 

The reponse would look something like:

 

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<errors>
    <error>advertiser can't be blank</error>
    <error>name can't be blank</error>
    <error>campaign_type can't be blank</error>
    <error>start_date can't be blank</error>
</errors>

 

Right now it only returns the text from the first "error" element.

 

Ive looked at the xmlnode docs, but Im having a hard time understanding how to get the text from all of the nodes.

 

Any help would be much appreciated!!


Thanks!

  • August 15, 2012
  • Like
  • 0

I have one more test at the moment that I am trying to setup correctly. I think the issue is that the opportunity relies on a few custom fields and Im not quite sure exactly how I would create those in my test?

 

I can provide more info if nessesary.

 

Any insight would be much appreciated!

 

System.DmlException: Update failed. First exception on row 0 with id 006U0000007zk5DIAQ; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, aiMatch.aimatchOpportunityGrabTrigger: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.aiMatch.aimatchOpportunityGrabTrigger: line 22, column 1: []

 

private static testmethod void aimatchOpportunityGrabTest() {
        
        Profile p = [select id from profile where name='System Administrator']; 
        User u = new User(alias = 'standt', email='sysadmin@testorg.com', 
            emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US', 
            localesidkey='en_US', profileid = p.Id, 
            timezonesidkey='America/Los_Angeles', username='aimatchtest@testorg.com');


        System.runAs(u) {
            
            List<Opportunity> listOpportunity = new List<Opportunity>();
                    
            // Create Opportunity test data
            Opportunity o = new Opportunity (name = 'test', campaign_created_in_aimatch__c = true, ownerid = '005U0000000gvRnIAI',
                                                        stagename = 'Renew', closedate = system.today(), aimatch_advertiser__c = 'a00U00000016hLW',
                                                        campaign_start_date__c = Date.today(), campaign_end_date__c = Date.today() + 30);
            insert o;                                                                                                  
            
            test.startTest();
                listOpportunity.add(o);
                update listOpportunity;
            test.stopTest();    
        
        }
}

 

  • August 09, 2012
  • Like
  • 0

So I've just started to work on an app that I wrote a year ago, which was using the api version 22. I havent touched this app in quite sometime, but we are now wanting to use it and there are some modifications that I need to make. I ran my tests and got 76% coverage. Well I thought it maybe a good idea to update the api version from 22 to the latest at 25. 

 

Heres what I get. I can update all classes and triggers except test class to 25 with no problems. When I update my test class to api version 24 or above I get:

 

4 errors of:

 

System.NullPointerException: Attempt to de-reference a null object

 

Stack traces for each of the above errors are:

Class.aiMatch.aimatchEditSettingsController.getApiUrlValue: line 10, column 1 Class.aiMatch.testaimatchOpportunityGrab.testEditSettingsControllerPos: line 106, column 1

 

 

Class.aiMatch.aimatchXmlApiCall.buildWebServiceRequest: line 10, column 1 Class.aiMatch.testaimatchOpportunityGrab.testXmlApiCall: line 44, column 1

 

Class.aiMatch.aimatchGetAdvertisersXmlApiCall.buildWebServiceRequest: line 17, column 1 Class.aiMatch.testaimatchOpportunityGrab.testGetAdvertisersXmlApiCall: line 63, column 1

 

 

Class.aiMatch.aimatchEditSettingsController.getApiUrlValue: line 10, column 1 Class.aiMatch.testaimatchOpportunityGrab.testEditSettingsControllerNeg: line 147, column 1

 

1 error of:

 

System.DmlException: Update failed. First exception on row 0 with id 006U0000007zk5DIAQ; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, aiMatch.aimatchOpportunityGrabTrigger: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.aiMatch.aimatchOpportunityGrabTrigger: line 22, column 1: []

 

Stack trace of above error:

Class.aiMatch.testaimatchOpportunityGrab.aimatchOpportunityGrabTest: line 25, column 1

 

 

 

The app works as expected. I've just gotten back into working with Apex after a year or so. Been working on Ruby and Javascript projects all year so I quite a bit rusty... :(

 

Any help is much appreciated!

 

 Here is my test class:

 

public class testaimatchOpportunityGrab {

    private static testmethod void aimatchOpportunityGrabTest() {
        
        Profile p = [select id from profile where name='System Administrator']; 
        User u = new User(alias = 'standt', email='sysadmin@testorg.com', 
            emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US', 
            localesidkey='en_US', profileid = p.Id, 
            timezonesidkey='America/Los_Angeles', username='aimatchtest@testorg.com');


        System.runAs(u) {
            
            List<Opportunity> listOpportunity = new List<Opportunity>();
                    
            // Create Opportunity test data
            Opportunity o = new Opportunity (name = 'test', campaign_created_in_aimatch__c = true, ownerid = '005U0000000gvRnIAI',
                                                        stagename = 'Renew', closedate = system.today(), aimatch_advertiser__c = 'a00U00000016hLW',
                                                        campaign_start_date__c = Date.today(), campaign_end_date__c = Date.today() + 30);
            insert o;                                                                                                  
            
            test.startTest();
            listOpportunity.add(o);
            
            update listOpportunity;


            test.stopTest();    
        
        }

    }    
    
    private static testMethod void testXmlApiCall() {
        //First, build the http request
        aimatchXmlApiCall testWebCallout = new aimatchXmlApiCall();
        String campName = 'Testcamp';
        String ownerName = 'testMe';
        String ownerEmail = 'test@email.com';
        String advertiserID = '12';
        String sDate = '2011-02-08';
        String eDate = '2011-02-09';
        
        HttpRequest req = testWebCallout.buildWebServiceRequest(campName, ownerName, ownerEmail, advertiserID, sDate, eDate);
   
        //NOTE - WE DO NOT EXECUTE THE METHOD, invokeWebService.  
        //Now, since we can't execute the actual web service, 
        //write apex code to build a sample HttpResponse object
      
        String xmlRes = '<advertisers type="array"><advertiser><id type="integer">7</id><name>ABC Telecom</name></advertiser></advertisers>';
      
        HttpResponse res = new HttpResponse();
        res.setBody(xmlRes);
        
        //Apply test data and attributes to the HttpResponse object as needed
        testWebCallout.handleWebServiceResponse(res, ownerEmail);
  
    }

    private static testMethod void testGetAdvertisersXmlApiCall() {
      //First, build the http request
        aimatchGetAdvertisersXmlApiCall testWebCallout  = new aimatchGetAdvertisersXmlApiCall();
        HttpRequest req = testWebCallout.buildWebServiceRequest();
   
      //NOTE - WE DO NOT EXECUTE THE METHOD, invokeWebService.       
      //Now, since we can't execute the actual web service, 
      //write apex code to build a sample HttpResponse object
      
      String xmlRes = '<advertisers type="array"><advertiser><id type="integer">7</id><name>ABC Telecom</name></advertiser></advertisers>';
      
      HttpResponse res = new HttpResponse();
      res.setBody(xmlRes);
      
      //Apply test data and attributes to the HttpResponse object as needed
      testWebCallout.handleWebServiceResponse(res);
  
    }

    private static testmethod void testEditSettingsControllerPos() {
        
        Profile p = [select id from profile where name='System Administrator']; 
        User u = new User(alias = 'standt', email='sysadmin@testorg.com', 
            emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US', 
            localesidkey='en_US', profileid = p.Id, 
            timezonesidkey='America/Los_Angeles', username='aimatchtest@testorg.com');
            
            list<aimatch_conf__c> theConf = [select id, name from aimatch_conf__c where name = 'settings' limit 1];
            list<aimatch_conf__c> updateConf = new list<aimatch_conf__c>();
            
            for(aimatch_conf__c con : theConf) {

                aimatch_conf__c thisConfVal = new aimatch_conf__c(Id=con.id);
                
                thisConfVal.name = 'settings';
                thisConfVal.aimatch_api_url__c = 'http://url.com';
                thisConfVal.aimatch_api_key__c = '123424351';
                thisConfVal.aimatch_schedule__c = '0 56 10 * * ?';
                thisConfVal.campaign_start_date_field_name__c = 'campaign_Start_Date__c';
                thisConfVal.campaign_end_date_field_name__c = 'campaign_End_Date__c';
                updateConf.add(thisConfVal);
            }
            upsert updateConf;

        System.runAs(u) {
                        
            aimatchEditSettingsController.getApiUrlValue();
            aimatchEditSettingsController.getApiKeyValue();
            aimatchEditSettingsController.getAdvSchValue();
            aimatchEditSettingsController.getCampStartDateFieldNameValue();
            aimatchEditSettingsController.getCampEndDateFieldNameValue();
            
            aimatchEditSettingsController editSettingsController = new aimatchEditSettingsController();
            editSettingsController.schAdv();
            editSettingsController.save();
        
        }
            
    }

    private static testmethod void testEditSettingsControllerNeg() {
        
        Profile p = [select id from profile where name='System Administrator']; 
        User u = new User(alias = 'standt', email='sysadmin@testorg.com', 
            emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US', 
            localesidkey='en_US', profileid = p.Id, 
            timezonesidkey='America/Los_Angeles', username='aimatchtest@testorg.com');
            
            list<aimatch_conf__c> theConf = [select id, name from aimatch_conf__c where name = 'settings' limit 1];
            list<aimatch_conf__c> updateConf = new list<aimatch_conf__c>();
            
            for(aimatch_conf__c con : theConf) {

                aimatch_conf__c thisConfVal = new aimatch_conf__c(Id=con.id);
                
                thisConfVal.name = 'settings';
                thisConfVal.aimatch_api_url__c = '';
                thisConfVal.aimatch_api_key__c = '';
                thisConfVal.aimatch_schedule__c = '';
                thisConfVal.campaign_start_date_field_name__c = '';
                thisConfVal.campaign_end_date_field_name__c = '';
                updateConf.add(thisConfVal);
            }
            upsert updateConf;

        System.runAs(u) {
            
            aimatchEditSettingsController.getApiUrlValue();
            aimatchEditSettingsController.getApiKeyValue();
            aimatchEditSettingsController.getAdvSchValue();
            aimatchEditSettingsController.getCampStartDateFieldNameValue();
            aimatchEditSettingsController.getCampEndDateFieldNameValue();
            
            aimatchEditSettingsController editSettingsController = new aimatchEditSettingsController();
            editSettingsController.schAdv();
            editSettingsController.save();
        
        }
    }
     
}

 

 

 

  • August 08, 2012
  • Like
  • 0

I must be missing something..

 

The date is always 1 day behind when formating like so:

 

datetime xDate = o.campaign_start_date__c;
			
String xxDate = xDate.format('yyyy-dd-MM');
system.debug('sdate :' +xxDate);

 

I set the above field to 8/16/2011

 

and in debug it shows up as: 2011-15-08

 

Everytime I change it the debug value is shown as 1 day behind.. Im sure I could to +1, but could someone help me understand why this is happening?

 

Thanks!
Jacob Davis

  • August 18, 2011
  • Like
  • 1

Ive searched around to find that reflection isnt avaible in Apex. Now Im pretty sure thats what I need to accomplish what I am going ask, but if there is another way to accomplish this, any help would be appreciated!

 

My app creates two custom fields on opportunity.

 

campaign_start_date__c

campaign_end_date__c

 

If in the case that a customer that installs my app already has two custom date fields on opportunity I would like them to be able to specify using thier custom fields.

 

Ive setup a custom setting that allows them to input the name of the custom fields.

 

I would like to pull from that custom setting and use their custom fields. So.... something like this...

 

 // Get customer Campaign start date and end date field names from Custom Setting x_conf__c 
 x_conf__c getConf = x_conf__c.getInstance('settings'); 
            
 // Get start date field name
 string campStartDateFieldName = string.valueOf(getConf.campaign_start_date_field_name__c);
 string csd = campStartDateFieldName;


// Get start date field name
 string campEndDateFieldName = string.valueOf(getConf.campaign_start_date_field_name__c);
 string esd = campEndDateFieldName;

string xCampaignStartDate = o.+csd;
string xCampaignStartDate = o.+esd;

 

Now I realize this doesnt work... But is there a way to accomplish what I am trying to do here?

 

Thanks!

  • August 17, 2011
  • Like
  • 0

Im in the process of packaging our code so that a client of ours can start testing our app. One of the processes invloved in our app is a scheduled job that happens once a day. Ive been just setting up cron through the "system log" so far while in development mode... like soo...

 

       

system.schedule('Advertiser Batch Job', sch, m);
scheduleAdvertiserBatch m = new scheduleAdvertiserBatch();
String sch = '0 56 10 * * ?';

 

 

How would I package something like this? Or will the client have to schedule the batch job manually?

 

Thanks!
Jacob Davis 

  • August 15, 2011
  • Like
  • 0

Im having trouble getting any test coverage on my trigger. I am getting 85% on the first class thats executed by my trigger, but I just cant seem to get any coverage at all on the actuall trigger.

 

Im thinking that part of the reason is since I am checking the users accessability to a custom object that I may need to create a user in the test? Not sure..

 

Im assuming I shouldnt be referencing an exsiting record to my custom object x_advertiser__c as well, instead creating that object and inserting it?

 

Anyways, any insight would be much appreciated.  The help here on the forums have been really great.

 

Heres the testmethod:

public class testxOpportunityGrab {

    private static testmethod void xOpportunityGrabTest() {
                
        Opportunity opportunity = new Opportunity (name = 'test', campaign_created_in_x__c = false,
                                                    stagename = 'Renew', closedate = system.today(), x_advertiser__c = 'a00U000000161iQIAQ',
                                                    campaign_start_date__c = Date.today(), campaign_end_date__c = Date.today() + 30);
        insert Opportunity;

        List<Opportunity> listOpportunity = new List<Opportunity>();
        listOpportunity.add(Opportunity);
        xOpportunityGrab.addOpportunityGrab(listOpportunity);
                
    }       
}

 

Hers the trigger:

trigger xCheckAdvertiserTrigger on Opportunity (before update) {
		
	for (Opportunity o:Trigger.new) {
		
		// Check to see if user has access to custom object x_advertiser__c
		Schema.DescribeFieldResult d = Opportunity.x_advertiser__c.getDescribe();
		Boolean usr = d.isAccessible();

	
		// If usr does, then continue through the process of executing the trigger
		if (usr == true) {
				
			// Instantiate passVarification vars
			Boolean passedVarification1;
			Boolean passedVarification2;
			Boolean passedVarification3;
			
			// Validate fields
			if (o.campaign_created_in_x__c == true && o.x_Advertiser__c == null) {
				o.campaign_created_in_x__c = false;
				o.x_Advertiser__c.addError('You must select an x Advertiser.');
			} else {
				passedVarification1 = true;
			}
			
			// Validate fields
			if (o.campaign_created_in_x__c == true && o.Campaign_Start_Date__c == null) {
				o.campaign_created_in_x__c = false;
				o.Campaign_Start_Date__c.addError('You must select a campaign start date before you can create the campaign in x.');
			} else {
				passedVarification2 = true;
			}
			
			if (o.campaign_created_in_x__c == true && passedVarification1 == true && passedVarification2 == true) {
				passedVarification3 = true;
			} else {
				passedVarification3 = false;
			}
			
			// If all validation passed then run the create campaign process
			if (passedVarification1 == true && passedVarification2 == true && passedVarification3 == true) {
				Opportunity[] opps = Trigger.new;
				//Call main x method
				xOpportunityGrab.addOpportunityGrab(opps);		
			}
			
			//System.debug(' passedVarification1 :::: '+passedVarification1);
			//System.debug(' passedVarification2 :::: '+passedVarification2);
			//System.debug(' passedVarification3 :::: '+passedVarification3);
			
		} else {
		
		}
		 
	}	

}

 

And heres the main class called by the trigger:

public class xOpportunityGrab {
             
    public static void addOpportunityGrab(Opportunity[] opps) {
    
        for (Opportunity o: opps) {
                                  
            // Set campaign checkbox to true if flase
            o.campaign_created_in_x__c = true;
            
            // Use Opportunity name as campaign name
            String xCampaignName = string.valueOf(o.name);
            
            // Grab saleforce Id to use for query
            ID sf_xAdvertiserId = o.x_Advertiser__c;
            
            // Query to determine the value of Opportunity x advertiser Id
            string query = 'Select x_advertiserId__c from x_advertiser__c where id =\'' +sf_xAdvertiserId+'\' ';
            
            // Create object to hold Id Value
            sObject advIdObject = Database.query(query);
            
            // Extract Id from object
            String xAdvertiserID = string.valueof(advIdObject.get(x_Advertiser__c.x_AdvertiserId__c));
            
            // Get opportunity owner Full name
            Opportunity oo = [Select oo.Owner.name, oo.OwnerId From Opportunity oo where oo.Id = :opps];
			String ownerName = String.valueOf(oo.Owner.name);
            
            // Campaign start date from custom field
            String xCampaignStartDate;
            
            // Check for missing Start date, if true campaign start date is today
            if (string.valueOf(o.campaign_Start_Date__c) == null) {
                xCampaignStartDate = String.valueOf(system.today());
            	} else {
            	xCampaignStartDate = String.valueOf(o.campaign_start_date__c);
            }
            
            // Campaign end date from custom field
            String xCampaignEndDate;
            
            if (string.valueOf(o.campaign_End_Date__c) == null) {
            	xCampaignEndDate = '';
            	} else {
            	xCampaignEndDate = String.valueOf(o.campaign_end_date__c);
            }
                   
            // Callout to xml api process
            if (!Test.isRunningTest()) {
                xXmlApiCall.sendRequest(xCampaignName, ownerName, xAdvertiserID, xCampaignStartDate, xCampaignEndDate);
            }            
            
        }        
    }
}

 

 

  • August 11, 2011
  • Like
  • 0

Hey Guys,

 

Im struggling abit with figuring out how to parse some xml into a custom object. Ive been working with the xmlstreamreader example, but I cant quite wrap my head around how step through the xml elements values that I want to insert into my custom object....

 

The xml response Im getting back from my webcallout looks like this:

 

<advertisers type="array">
  <advertiser>
    <id type="integer">7</id>
    <name>ABC Telecom</name>
  </advertiser>
  <advertiser>
    <id type="integer">106</id>
    <name>ABC_Ozone</name>
  </advertiser><advertiser>
    <id type="integer">13</id>
    <name>Acme Corp</name>
  </advertiser>
</advertisers>

 

My goal is loop through this and extract the value of id and name of each advertiser. I would then like to insert the id and name of each advertiser into a custom object. I would use the name field for the name of the advertiser and I have a custom field realationship setup to store the id value.

 

Any help is much appreciated.

  • August 05, 2011
  • Like
  • 0

Hi All,

 

Ive created a custom object (advertiser__c) that I want to use to hold the name of an Avertiser as well as an Advertiser ID. I realize that by default when you create a custom object that you get a name field and an ID field but that ID field is saleforce specific. My quesiton is what do I need to do to be able to tie Advertiser name and its Advertiser ID together? (Advertiser ID would just be an integer which is determed by another system) .

 

The advertiser__c custom object is represented on a standard opportunity page with a lookup field. I would like the availble options to be presented to the user as the advertiser name, but on the backend when the user selects an advertiser, my process will use its associated advertiser ID.

 

Any insight on the best way to accomplish this would be much appreciated!

Thanks!

  • August 04, 2011
  • Like
  • 0

Hi all,

 

I've created a a cutsom field for opportunites which is the datatype picklist. I would like to be able to setup a batch class that will periodically do a web callout that returns a list of names which I would then like to use to update the picklist values available for the custom field. 

 

How would I insert these values into the custom field so that all opportunites have access to them?

 

Thanks!

 

 

  • August 01, 2011
  • Like
  • 0

Im new to Apex coding and programing in general. Im having a hard time figureing out the test coverage etc.. Ive been succsefull in getting salesforce to do everything I want, but when it comes to code coverage and testing, I am having a terrible time. Ive looked around at the various documents, but Im just having a hard time grasping how to test what I am doing from the examples Ive seen. Any help would be much appreciated.


Here is the class that gets triggered. It also calls out to another class.

 

public class xOpportunityGrab {
             
    public static void addOpportunityGrab(Opportunity[] opps) {
                 
        for (Opportunity o: opps) {
            if (o.Probability >= 90 && o.campaign_created_in_x__c != true) {
                
                // Set campaign checkbox to true if flase
                o.campaign_created_in_x__c = true;
                
                // Use Opportunity name as campaign name
                String xCampaignName = o.name;
                
                // Use Opportunity owner as campaign salesperson
                String xCampaignSalesperson = String.valueOf(o.owner);
                
                // Campaign start date from custom field
                String xCampaignStartDate = String.valueOf(o.campaign_start_date__c);
                
                // Campaign end date from custom field
                String xCampaignEndDate = String.valueOf(o.campaign_end_date__c);
                
                // Callout to xml api process
                xXmlApiCall.sendRequest(xCampaignName, xCampaignSalesperson, xCampaignStartDate, xCampaignEndDate);
                
            }
        }
    }
}

 

I must be missing something..

 

The date is always 1 day behind when formating like so:

 

datetime xDate = o.campaign_start_date__c;
			
String xxDate = xDate.format('yyyy-dd-MM');
system.debug('sdate :' +xxDate);

 

I set the above field to 8/16/2011

 

and in debug it shows up as: 2011-15-08

 

Everytime I change it the debug value is shown as 1 day behind.. Im sure I could to +1, but could someone help me understand why this is happening?

 

Thanks!
Jacob Davis

  • August 18, 2011
  • Like
  • 1

Im trying to return the text of multiple xml elements with the same name. Im using Xmlnode.

 

Heres part of the code that handles the response:

 

// Get xml body from response
dom.Document docx = res.getBodyDocument();
dom.Xmlnode xroot = docx.getRootElement();
dom.Xmlnode xrec = xroot.getChildElement('error', null);

// Setup email for exception
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();            
String[] toAddress = new String[] {ownerEmail};
mail.setToAddresses(toAddress);
mail.setSenderDisplayName('Salesforce');
mail.setSubject('A problem has occured with creating the Proposal');
mail.setPlainTextBody('The following error occured when trying to create the Proposal: \n\n"Proposal ' + newError + '"\n\nPlease correct the errors above and try again.');    
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

 

The reponse would look something like:

 

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<errors>
    <error>advertiser can't be blank</error>
    <error>name can't be blank</error>
    <error>campaign_type can't be blank</error>
    <error>start_date can't be blank</error>
</errors>

 

Right now it only returns the text from the first "error" element.

 

Ive looked at the xmlnode docs, but Im having a hard time understanding how to get the text from all of the nodes.

 

Any help would be much appreciated!!


Thanks!

  • August 15, 2012
  • Like
  • 0

I have one more test at the moment that I am trying to setup correctly. I think the issue is that the opportunity relies on a few custom fields and Im not quite sure exactly how I would create those in my test?

 

I can provide more info if nessesary.

 

Any insight would be much appreciated!

 

System.DmlException: Update failed. First exception on row 0 with id 006U0000007zk5DIAQ; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, aiMatch.aimatchOpportunityGrabTrigger: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.aiMatch.aimatchOpportunityGrabTrigger: line 22, column 1: []

 

private static testmethod void aimatchOpportunityGrabTest() {
        
        Profile p = [select id from profile where name='System Administrator']; 
        User u = new User(alias = 'standt', email='sysadmin@testorg.com', 
            emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US', 
            localesidkey='en_US', profileid = p.Id, 
            timezonesidkey='America/Los_Angeles', username='aimatchtest@testorg.com');


        System.runAs(u) {
            
            List<Opportunity> listOpportunity = new List<Opportunity>();
                    
            // Create Opportunity test data
            Opportunity o = new Opportunity (name = 'test', campaign_created_in_aimatch__c = true, ownerid = '005U0000000gvRnIAI',
                                                        stagename = 'Renew', closedate = system.today(), aimatch_advertiser__c = 'a00U00000016hLW',
                                                        campaign_start_date__c = Date.today(), campaign_end_date__c = Date.today() + 30);
            insert o;                                                                                                  
            
            test.startTest();
                listOpportunity.add(o);
                update listOpportunity;
            test.stopTest();    
        
        }
}

 

  • August 09, 2012
  • Like
  • 0

So I've just started to work on an app that I wrote a year ago, which was using the api version 22. I havent touched this app in quite sometime, but we are now wanting to use it and there are some modifications that I need to make. I ran my tests and got 76% coverage. Well I thought it maybe a good idea to update the api version from 22 to the latest at 25. 

 

Heres what I get. I can update all classes and triggers except test class to 25 with no problems. When I update my test class to api version 24 or above I get:

 

4 errors of:

 

System.NullPointerException: Attempt to de-reference a null object

 

Stack traces for each of the above errors are:

Class.aiMatch.aimatchEditSettingsController.getApiUrlValue: line 10, column 1 Class.aiMatch.testaimatchOpportunityGrab.testEditSettingsControllerPos: line 106, column 1

 

 

Class.aiMatch.aimatchXmlApiCall.buildWebServiceRequest: line 10, column 1 Class.aiMatch.testaimatchOpportunityGrab.testXmlApiCall: line 44, column 1

 

Class.aiMatch.aimatchGetAdvertisersXmlApiCall.buildWebServiceRequest: line 17, column 1 Class.aiMatch.testaimatchOpportunityGrab.testGetAdvertisersXmlApiCall: line 63, column 1

 

 

Class.aiMatch.aimatchEditSettingsController.getApiUrlValue: line 10, column 1 Class.aiMatch.testaimatchOpportunityGrab.testEditSettingsControllerNeg: line 147, column 1

 

1 error of:

 

System.DmlException: Update failed. First exception on row 0 with id 006U0000007zk5DIAQ; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, aiMatch.aimatchOpportunityGrabTrigger: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.aiMatch.aimatchOpportunityGrabTrigger: line 22, column 1: []

 

Stack trace of above error:

Class.aiMatch.testaimatchOpportunityGrab.aimatchOpportunityGrabTest: line 25, column 1

 

 

 

The app works as expected. I've just gotten back into working with Apex after a year or so. Been working on Ruby and Javascript projects all year so I quite a bit rusty... :(

 

Any help is much appreciated!

 

 Here is my test class:

 

public class testaimatchOpportunityGrab {

    private static testmethod void aimatchOpportunityGrabTest() {
        
        Profile p = [select id from profile where name='System Administrator']; 
        User u = new User(alias = 'standt', email='sysadmin@testorg.com', 
            emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US', 
            localesidkey='en_US', profileid = p.Id, 
            timezonesidkey='America/Los_Angeles', username='aimatchtest@testorg.com');


        System.runAs(u) {
            
            List<Opportunity> listOpportunity = new List<Opportunity>();
                    
            // Create Opportunity test data
            Opportunity o = new Opportunity (name = 'test', campaign_created_in_aimatch__c = true, ownerid = '005U0000000gvRnIAI',
                                                        stagename = 'Renew', closedate = system.today(), aimatch_advertiser__c = 'a00U00000016hLW',
                                                        campaign_start_date__c = Date.today(), campaign_end_date__c = Date.today() + 30);
            insert o;                                                                                                  
            
            test.startTest();
            listOpportunity.add(o);
            
            update listOpportunity;


            test.stopTest();    
        
        }

    }    
    
    private static testMethod void testXmlApiCall() {
        //First, build the http request
        aimatchXmlApiCall testWebCallout = new aimatchXmlApiCall();
        String campName = 'Testcamp';
        String ownerName = 'testMe';
        String ownerEmail = 'test@email.com';
        String advertiserID = '12';
        String sDate = '2011-02-08';
        String eDate = '2011-02-09';
        
        HttpRequest req = testWebCallout.buildWebServiceRequest(campName, ownerName, ownerEmail, advertiserID, sDate, eDate);
   
        //NOTE - WE DO NOT EXECUTE THE METHOD, invokeWebService.  
        //Now, since we can't execute the actual web service, 
        //write apex code to build a sample HttpResponse object
      
        String xmlRes = '<advertisers type="array"><advertiser><id type="integer">7</id><name>ABC Telecom</name></advertiser></advertisers>';
      
        HttpResponse res = new HttpResponse();
        res.setBody(xmlRes);
        
        //Apply test data and attributes to the HttpResponse object as needed
        testWebCallout.handleWebServiceResponse(res, ownerEmail);
  
    }

    private static testMethod void testGetAdvertisersXmlApiCall() {
      //First, build the http request
        aimatchGetAdvertisersXmlApiCall testWebCallout  = new aimatchGetAdvertisersXmlApiCall();
        HttpRequest req = testWebCallout.buildWebServiceRequest();
   
      //NOTE - WE DO NOT EXECUTE THE METHOD, invokeWebService.       
      //Now, since we can't execute the actual web service, 
      //write apex code to build a sample HttpResponse object
      
      String xmlRes = '<advertisers type="array"><advertiser><id type="integer">7</id><name>ABC Telecom</name></advertiser></advertisers>';
      
      HttpResponse res = new HttpResponse();
      res.setBody(xmlRes);
      
      //Apply test data and attributes to the HttpResponse object as needed
      testWebCallout.handleWebServiceResponse(res);
  
    }

    private static testmethod void testEditSettingsControllerPos() {
        
        Profile p = [select id from profile where name='System Administrator']; 
        User u = new User(alias = 'standt', email='sysadmin@testorg.com', 
            emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US', 
            localesidkey='en_US', profileid = p.Id, 
            timezonesidkey='America/Los_Angeles', username='aimatchtest@testorg.com');
            
            list<aimatch_conf__c> theConf = [select id, name from aimatch_conf__c where name = 'settings' limit 1];
            list<aimatch_conf__c> updateConf = new list<aimatch_conf__c>();
            
            for(aimatch_conf__c con : theConf) {

                aimatch_conf__c thisConfVal = new aimatch_conf__c(Id=con.id);
                
                thisConfVal.name = 'settings';
                thisConfVal.aimatch_api_url__c = 'http://url.com';
                thisConfVal.aimatch_api_key__c = '123424351';
                thisConfVal.aimatch_schedule__c = '0 56 10 * * ?';
                thisConfVal.campaign_start_date_field_name__c = 'campaign_Start_Date__c';
                thisConfVal.campaign_end_date_field_name__c = 'campaign_End_Date__c';
                updateConf.add(thisConfVal);
            }
            upsert updateConf;

        System.runAs(u) {
                        
            aimatchEditSettingsController.getApiUrlValue();
            aimatchEditSettingsController.getApiKeyValue();
            aimatchEditSettingsController.getAdvSchValue();
            aimatchEditSettingsController.getCampStartDateFieldNameValue();
            aimatchEditSettingsController.getCampEndDateFieldNameValue();
            
            aimatchEditSettingsController editSettingsController = new aimatchEditSettingsController();
            editSettingsController.schAdv();
            editSettingsController.save();
        
        }
            
    }

    private static testmethod void testEditSettingsControllerNeg() {
        
        Profile p = [select id from profile where name='System Administrator']; 
        User u = new User(alias = 'standt', email='sysadmin@testorg.com', 
            emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US', 
            localesidkey='en_US', profileid = p.Id, 
            timezonesidkey='America/Los_Angeles', username='aimatchtest@testorg.com');
            
            list<aimatch_conf__c> theConf = [select id, name from aimatch_conf__c where name = 'settings' limit 1];
            list<aimatch_conf__c> updateConf = new list<aimatch_conf__c>();
            
            for(aimatch_conf__c con : theConf) {

                aimatch_conf__c thisConfVal = new aimatch_conf__c(Id=con.id);
                
                thisConfVal.name = 'settings';
                thisConfVal.aimatch_api_url__c = '';
                thisConfVal.aimatch_api_key__c = '';
                thisConfVal.aimatch_schedule__c = '';
                thisConfVal.campaign_start_date_field_name__c = '';
                thisConfVal.campaign_end_date_field_name__c = '';
                updateConf.add(thisConfVal);
            }
            upsert updateConf;

        System.runAs(u) {
            
            aimatchEditSettingsController.getApiUrlValue();
            aimatchEditSettingsController.getApiKeyValue();
            aimatchEditSettingsController.getAdvSchValue();
            aimatchEditSettingsController.getCampStartDateFieldNameValue();
            aimatchEditSettingsController.getCampEndDateFieldNameValue();
            
            aimatchEditSettingsController editSettingsController = new aimatchEditSettingsController();
            editSettingsController.schAdv();
            editSettingsController.save();
        
        }
    }
     
}

 

 

 

  • August 08, 2012
  • Like
  • 0

I must be missing something..

 

The date is always 1 day behind when formating like so:

 

datetime xDate = o.campaign_start_date__c;
			
String xxDate = xDate.format('yyyy-dd-MM');
system.debug('sdate :' +xxDate);

 

I set the above field to 8/16/2011

 

and in debug it shows up as: 2011-15-08

 

Everytime I change it the debug value is shown as 1 day behind.. Im sure I could to +1, but could someone help me understand why this is happening?

 

Thanks!
Jacob Davis

  • August 18, 2011
  • Like
  • 1

Ive searched around to find that reflection isnt avaible in Apex. Now Im pretty sure thats what I need to accomplish what I am going ask, but if there is another way to accomplish this, any help would be appreciated!

 

My app creates two custom fields on opportunity.

 

campaign_start_date__c

campaign_end_date__c

 

If in the case that a customer that installs my app already has two custom date fields on opportunity I would like them to be able to specify using thier custom fields.

 

Ive setup a custom setting that allows them to input the name of the custom fields.

 

I would like to pull from that custom setting and use their custom fields. So.... something like this...

 

 // Get customer Campaign start date and end date field names from Custom Setting x_conf__c 
 x_conf__c getConf = x_conf__c.getInstance('settings'); 
            
 // Get start date field name
 string campStartDateFieldName = string.valueOf(getConf.campaign_start_date_field_name__c);
 string csd = campStartDateFieldName;


// Get start date field name
 string campEndDateFieldName = string.valueOf(getConf.campaign_start_date_field_name__c);
 string esd = campEndDateFieldName;

string xCampaignStartDate = o.+csd;
string xCampaignStartDate = o.+esd;

 

Now I realize this doesnt work... But is there a way to accomplish what I am trying to do here?

 

Thanks!

  • August 17, 2011
  • Like
  • 0

Im in the process of packaging our code so that a client of ours can start testing our app. One of the processes invloved in our app is a scheduled job that happens once a day. Ive been just setting up cron through the "system log" so far while in development mode... like soo...

 

       

system.schedule('Advertiser Batch Job', sch, m);
scheduleAdvertiserBatch m = new scheduleAdvertiserBatch();
String sch = '0 56 10 * * ?';

 

 

How would I package something like this? Or will the client have to schedule the batch job manually?

 

Thanks!
Jacob Davis 

  • August 15, 2011
  • Like
  • 0

Im having trouble getting any test coverage on my trigger. I am getting 85% on the first class thats executed by my trigger, but I just cant seem to get any coverage at all on the actuall trigger.

 

Im thinking that part of the reason is since I am checking the users accessability to a custom object that I may need to create a user in the test? Not sure..

 

Im assuming I shouldnt be referencing an exsiting record to my custom object x_advertiser__c as well, instead creating that object and inserting it?

 

Anyways, any insight would be much appreciated.  The help here on the forums have been really great.

 

Heres the testmethod:

public class testxOpportunityGrab {

    private static testmethod void xOpportunityGrabTest() {
                
        Opportunity opportunity = new Opportunity (name = 'test', campaign_created_in_x__c = false,
                                                    stagename = 'Renew', closedate = system.today(), x_advertiser__c = 'a00U000000161iQIAQ',
                                                    campaign_start_date__c = Date.today(), campaign_end_date__c = Date.today() + 30);
        insert Opportunity;

        List<Opportunity> listOpportunity = new List<Opportunity>();
        listOpportunity.add(Opportunity);
        xOpportunityGrab.addOpportunityGrab(listOpportunity);
                
    }       
}

 

Hers the trigger:

trigger xCheckAdvertiserTrigger on Opportunity (before update) {
		
	for (Opportunity o:Trigger.new) {
		
		// Check to see if user has access to custom object x_advertiser__c
		Schema.DescribeFieldResult d = Opportunity.x_advertiser__c.getDescribe();
		Boolean usr = d.isAccessible();

	
		// If usr does, then continue through the process of executing the trigger
		if (usr == true) {
				
			// Instantiate passVarification vars
			Boolean passedVarification1;
			Boolean passedVarification2;
			Boolean passedVarification3;
			
			// Validate fields
			if (o.campaign_created_in_x__c == true && o.x_Advertiser__c == null) {
				o.campaign_created_in_x__c = false;
				o.x_Advertiser__c.addError('You must select an x Advertiser.');
			} else {
				passedVarification1 = true;
			}
			
			// Validate fields
			if (o.campaign_created_in_x__c == true && o.Campaign_Start_Date__c == null) {
				o.campaign_created_in_x__c = false;
				o.Campaign_Start_Date__c.addError('You must select a campaign start date before you can create the campaign in x.');
			} else {
				passedVarification2 = true;
			}
			
			if (o.campaign_created_in_x__c == true && passedVarification1 == true && passedVarification2 == true) {
				passedVarification3 = true;
			} else {
				passedVarification3 = false;
			}
			
			// If all validation passed then run the create campaign process
			if (passedVarification1 == true && passedVarification2 == true && passedVarification3 == true) {
				Opportunity[] opps = Trigger.new;
				//Call main x method
				xOpportunityGrab.addOpportunityGrab(opps);		
			}
			
			//System.debug(' passedVarification1 :::: '+passedVarification1);
			//System.debug(' passedVarification2 :::: '+passedVarification2);
			//System.debug(' passedVarification3 :::: '+passedVarification3);
			
		} else {
		
		}
		 
	}	

}

 

And heres the main class called by the trigger:

public class xOpportunityGrab {
             
    public static void addOpportunityGrab(Opportunity[] opps) {
    
        for (Opportunity o: opps) {
                                  
            // Set campaign checkbox to true if flase
            o.campaign_created_in_x__c = true;
            
            // Use Opportunity name as campaign name
            String xCampaignName = string.valueOf(o.name);
            
            // Grab saleforce Id to use for query
            ID sf_xAdvertiserId = o.x_Advertiser__c;
            
            // Query to determine the value of Opportunity x advertiser Id
            string query = 'Select x_advertiserId__c from x_advertiser__c where id =\'' +sf_xAdvertiserId+'\' ';
            
            // Create object to hold Id Value
            sObject advIdObject = Database.query(query);
            
            // Extract Id from object
            String xAdvertiserID = string.valueof(advIdObject.get(x_Advertiser__c.x_AdvertiserId__c));
            
            // Get opportunity owner Full name
            Opportunity oo = [Select oo.Owner.name, oo.OwnerId From Opportunity oo where oo.Id = :opps];
			String ownerName = String.valueOf(oo.Owner.name);
            
            // Campaign start date from custom field
            String xCampaignStartDate;
            
            // Check for missing Start date, if true campaign start date is today
            if (string.valueOf(o.campaign_Start_Date__c) == null) {
                xCampaignStartDate = String.valueOf(system.today());
            	} else {
            	xCampaignStartDate = String.valueOf(o.campaign_start_date__c);
            }
            
            // Campaign end date from custom field
            String xCampaignEndDate;
            
            if (string.valueOf(o.campaign_End_Date__c) == null) {
            	xCampaignEndDate = '';
            	} else {
            	xCampaignEndDate = String.valueOf(o.campaign_end_date__c);
            }
                   
            // Callout to xml api process
            if (!Test.isRunningTest()) {
                xXmlApiCall.sendRequest(xCampaignName, ownerName, xAdvertiserID, xCampaignStartDate, xCampaignEndDate);
            }            
            
        }        
    }
}

 

 

  • August 11, 2011
  • Like
  • 0

Hey Guys,

 

Im struggling abit with figuring out how to parse some xml into a custom object. Ive been working with the xmlstreamreader example, but I cant quite wrap my head around how step through the xml elements values that I want to insert into my custom object....

 

The xml response Im getting back from my webcallout looks like this:

 

<advertisers type="array">
  <advertiser>
    <id type="integer">7</id>
    <name>ABC Telecom</name>
  </advertiser>
  <advertiser>
    <id type="integer">106</id>
    <name>ABC_Ozone</name>
  </advertiser><advertiser>
    <id type="integer">13</id>
    <name>Acme Corp</name>
  </advertiser>
</advertisers>

 

My goal is loop through this and extract the value of id and name of each advertiser. I would then like to insert the id and name of each advertiser into a custom object. I would use the name field for the name of the advertiser and I have a custom field realationship setup to store the id value.

 

Any help is much appreciated.

  • August 05, 2011
  • Like
  • 0

Hi All,

 

Ive created a custom object (advertiser__c) that I want to use to hold the name of an Avertiser as well as an Advertiser ID. I realize that by default when you create a custom object that you get a name field and an ID field but that ID field is saleforce specific. My quesiton is what do I need to do to be able to tie Advertiser name and its Advertiser ID together? (Advertiser ID would just be an integer which is determed by another system) .

 

The advertiser__c custom object is represented on a standard opportunity page with a lookup field. I would like the availble options to be presented to the user as the advertiser name, but on the backend when the user selects an advertiser, my process will use its associated advertiser ID.

 

Any insight on the best way to accomplish this would be much appreciated!

Thanks!

  • August 04, 2011
  • Like
  • 0

Hi all,

 

I've created a a cutsom field for opportunites which is the datatype picklist. I would like to be able to setup a batch class that will periodically do a web callout that returns a list of names which I would then like to use to update the picklist values available for the custom field. 

 

How would I insert these values into the custom field so that all opportunites have access to them?

 

Thanks!

 

 

  • August 01, 2011
  • Like
  • 0