-
ChatterFeed
-
0Best Answers
-
0Likes Received
-
0Likes Given
-
5Questions
-
5Replies
Apex Code: Help me in solving 70% test coverage for following test class.
Help me in getting 70 % test coverage for following code.
Apex Code:
Apex Code:
global class BatchUpdateContactRole implements Database.Batchable<sObject>
{
global Database.QueryLocator start(Database.BatchableContext BC)
{
String str = '001q000001Ob8yxAAB';
String query = 'SELECT Id, RoleProcessed__c, Name FROM Account Where id =:str';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<Account> scope)
{
try{
List<Contact> conToUpdate = new List<Contact>();
List<Account> accToUpdate = new List<Account>();
Set<string> allAccountIds = new set<string>();
Map<string, list<Contact>> AccountIdContactMap = new Map<string, list<Contact>>();
Map<Id,Account> AccountData = new Map<Id,Account>();
Map<String, DominantRolePatternm__mdt> mapEd = DominantRolePatternm__mdt.getAll();
for(Account a: scope){
allAccountIds.add(a.Id);
AccountData.put(a.id,a);
}
system.debug('All AccountIds'+allAccountIds);
for(Contact con : [SELECT Id, rdcc__Role__c, FirstName, LastName, accountId from Contact where accountId IN :allAccountIds]){
if(AccountIdContactMap.containsKey(con.accountId) && AccountIdContactMap.get(con.accountId)!=null){
AccountIdContactMap.get(con.accountId).add(con);
}else{
AccountIdContactMap.put(con.accountId, new list<contact>{con});
}
}
system.debug('AccountIdContactMap'+AccountIdContactMap);
for(string accId : AccountIdContactMap.keyset()){
boolean roleEmpty = false;
boolean allroleEmpty = false;
Integer countContact = 0;
Integer countNull = 0;
String roleToUpdate = '';
Map<string,Integer> roleMap = new Map<string,Integer>();
if(accId!=null){
system.debug('account Id'+accId);
for(Contact cont : AccountIdContactMap.get(accId)){
system.debug('Contact to be processed'+cont.Id);
if(cont.rdcc__Role__c == null){
//atleast one empty role is found within contacts of Account
roleEmpty = true;
++countNull;
system.debug('empty role found');
//break;
}
// system.debug('sizeee--'+AccountIdContactMap.get(accId).size()+'--- count--'+countNull);
if(countNull == AccountIdContactMap.get(accId).size())
{
allroleEmpty = true;
}
}
system.debug('sizeee--'+AccountIdContactMap.get(accId).size()+'--- count--'+countNull);
if(roleEmpty && allroleEmpty)
{
Account AccData = AccountData.get(accId);
for(String nameEmailDomain : mapEd.keySet()){
System.debug('----->'+mapEd.get(nameEmailDomain).Name_Combination__c);
List<String> lsttest= mapEd.get(nameEmailDomain).Name_Combination__c.split(';');
for(String roleStr : lsttest)
{
system.debug('inside contains111--'+roleStr);
if(AccData.Name.contains(roleStr))
{
system.debug('inside contains222-'+roleStr);
for(Contact cont : AccountIdContactMap.get(accId)){
cont.MatchingRole__c = mapEd.get(nameEmailDomain).RoleMatched__c;
conToUpdate.add(cont);
}
}
}
}
}
else if(roleEmpty && !allroleEmpty)
{
system.debug('Inside If Condition');
Integer prevValue = 0;
Integer num = 1;
for(Contact cont : AccountIdContactMap.get(accId)){
system.debug('Contact to be processed'+cont.Id);
if(cont.rdcc__Role__c != null){
system.debug('roleMap'+roleMap);
if(roleMap.containsKey(cont.rdcc__Role__c)){
num = roleMap.get(cont.rdcc__Role__c);
roleMap.put(cont.rdcc__Role__c,num+1);
}else{
roleMap.put(cont.rdcc__Role__c,num);
}
}
}
system.debug('Role Map'+roleMap);
List<Integer> mapValues = new List<Integer>();
//Check the maximum count to find Dominant
Integer maxValue = 0;
Integer secondHighestValue = 0;
if(roleMap.size() > 0){
mapValues = roleMap.values();
mapValues.sort();
maxValue = mapvalues[mapvalues.size()-1];
if(mapValues.size()>1){
secondHighestValue = mapvalues[mapValues.size()-2];
}
system.debug('max Values'+maxValue);
system.debug('second highest value'+secondHighestValue);
if(maxValue != secondHighestValue){ //dominant role not clashing
for(String s : roleMap.keySet()){
Integer pattern_value = roleMap.get(s);
if((pattern_value == maxValue) && (maxValue > 0)){
system.debug(' Dominant Role for contacts with accountId'+accId+' is ' + s + ' with value' + pattern_value);
roleToUpdate = s;
}
}
}
else if(maxValue == secondHighestValue){ //dominant role not clashing
for(String s : roleMap.keySet()){
system.debug('s'+s);
Integer pattern_value = roleMap.get(s);
if((pattern_value == maxValue) && (maxValue > 0) ||(pattern_value == secondHighestValue) && (secondHighestValue > 0) ){
system.debug(' Dominant Role for contacts with accountId'+accId+' is ' + s + ' with value' + pattern_value);
for (String St : System.Label.Significant_Role.split(','))
{
if(st.equalsIgnoreCase(s))
roleToUpdate = s;
}
}
}
}
}
system.debug('AccountIdContactMap'+AccountIdContactMap);
//Updating Role in contact with dominant role
for(Contact cont : AccountIdContactMap.get(accId)){
if(cont.rdcc__Role__c == null){
system.debug('roleToUpdate'+roleToUpdate);
if(roleToUpdate != ''){
cont.MatchingRole__c = roleToUpdate;
cont.rdcc__Role__c = roleToUpdate;
}
}
conToUpdate.add(cont);
}
}
}
//acc.RoleProcessed__c = true;
Account acc = new Account();
acc.Id = accId;
acc.RoleProcessed__c = True;
accToUpdate.add(acc);
}
system.debug('Con To Update'+conToUpdate);
if(conToUpdate.size()>0 && conToUpdate!=null){
update conToUpdate;
}
system.debug('Acc To Update'+accToUpdate);
if(accToUpdate.size()>0 && accToUpdate!=null){
update accToUpdate;
}
}catch(exception e){
system.debug('e--'+e);
}
}
global void finish(Database.BatchableContext BC)
{
}
}
Test Class:
@isTest
private class BatchUpdateContactRoleTest {
@testSetup
static void setup() {
List<Account> accounts = new List<Account>();
List<Contact> contacts = new List<Contact>();
// insert 10 accounts and add test fields as per your need.
Account acc=new Account(name='Account ',
billingcity='Chennai',billingcountry='India');
insert acc;
// find the account just inserted. add contact for each & test data required.
Contact con1=new Contact(firstname='first',
lastname='last',rdcc__Role__c='Test0', accountId=acc.id);
insert con1;
Contact con2=new Contact(firstname='first',
lastname='last',rdcc__Role__c='Test1', accountId=acc.id);
insert con2;
Contact con3=new Contact(firstname='first',
lastname='last',rdcc__Role__c='', accountId=acc.id);
insert con3;
}
static testmethod void testMethod2(){
Test.startTest();
BatchUpdateContactRole tb = new BatchUpdateContactRole();
Id batchId = Database.executeBatch(tb,50);
Test.stopTest();
}
}
-
- Aqua Matrix
- October 28, 2021
- Like
- 0
I want help in writing trigger.
Hi,
I had created data in the custom metadata for city and zipcode...
I want to write the apex trigger to autopopulate the cityname If I select the zipcode which s present in the custom metadata...
Could you please help me to write the trigger for the above scenario...
I had written the apex code to fetch the custom metadata
And now I want to write the trigger to autopopulate the city name if we choose the zipcode.
I had created data in the custom metadata for city and zipcode...
I want to write the apex trigger to autopopulate the cityname If I select the zipcode which s present in the custom metadata...
Could you please help me to write the trigger for the above scenario...
I had written the apex code to fetch the custom metadata
And now I want to write the trigger to autopopulate the city name if we choose the zipcode.
trigger Autopopulate on Contact (after insert) {
// When a new account is created, fill in the city and state based on zip code
if (trigger.isAfter && trigger.isInsert) {
zipcodemetda.fetchAllMetadata();
}
}
-
- Aqua Matrix
- October 19, 2021
- Like
- 0
I want a help to cover code coverage for below apex class
Hi,
I have code coverage of 44% for below apex batch class,help me in covering code coverage of 75% for below Apex class.
Apex code:
I have code coverage of 44% for below apex batch class,help me in covering code coverage of 75% for below Apex class.
Apex code:
Global class BatchValidateEmailDominantPattern Implements Database.Batchable<sObject>,Database.AllowsCallouts, Database.stateful{
Public boolean noCredit = false;
Public string key;
List<EmailValidationApiKey__mdt> apiKeys = [SELECT APIKey__c from EmailValidationApiKey__mdt];
Global Database.QueryLocator Start(Database.BatchableContext BC){
String query = '';
Set<String> accIds = new Set<String>();
//accIds.add('001q000001OZhiPAAT');
//accIds.add('001q000001Ll1puAAB');
//accIds.add('001q000001OJZxpAAH');
//accIds.add('001q000001Ll1puAAB');
try{
system.debug('Validate Email Pattern start!');
//Callout
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
for(EmailValidationApiKey__mdt record: apiKeys){
key = record.APIKey__c;
}
//Checking credits
String apiURL = 'https://api.zerobounce.net/v2/getcredits?api_key='+key;
req.setEndpoint(apiURL);
req.setHeader('Content-Type', 'application/json');
req.setMethod('GET');
String defaultAcc = 'Test Email';
if (!Test.isRunningTest()) {
res = http.send(req);
system.debug('--res.getBody--'+res.getBody());
if(res.getStatusCode() == 200){
system.debug('success status');
Map<String, Object> docData = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
string credits =(string)docData.get('Credits');
Integer cred = Integer.valueOf(credits);
if(cred >= 1){
system.debug('Credits'+cred);
query = 'SELECT Id, Name FROM Account where DominantEmailPattern__c != null and EmailBatchProcessed__c = true AND ID IN :accIds';
}else{
query = 'Select Id,Name From Account where Name =: defaultAcc';
noCredit = true;
}
}
}else{
query='Select Id,Name From Account where Name =: defaultAcc';
}
}catch (Exception e) {
System.debug('Error:' + e.getMessage() + 'LN:' + e.getLineNumber() );
}
return Database.getQueryLocator(query);
}
Global void execute(Database.BatchableContext BC, List<Account> scope) {
system.debug('scope'+scope);
String endpoint;
Map<Id,String> DominantEmailContactMap = new Map<Id,String>();
List<String> ListemailList = new List<String>();
List<List<String>> listWrapper = new List<List<String>>();
Set<string> allAccountIds = new set<string>();
Map<string, list<Contact>> AccountIdContactMap = new Map<string, list<Contact>>();
List<Contact> conToUpdate = new List<Contact>();
List<Contact> allConToUpdate = new List<Contact>();
Set<string> conIds = new set<string>();
Set<string> catchAllConIds = new set<string>();
try {
if((scope.size() > 0)&& (scope!=null)){
system.debug('scope size greater than 0');
for(Account a: scope){
allAccountIds.add(a.Id);
}
system.debug('allAccountIds'+allAccountIds);
for(Contact con : [SELECT Id, Email, FirstName, LastName, MatchingEmail1__c, MatchingEmail2__c, accountId from Contact where accountId IN :allAccountIds and EmailValidateFlag__c = False]){
if(AccountIdContactMap.containsKey(con.accountId) && AccountIdContactMap.get(con.accountId)!=null){
AccountIdContactMap.get(con.accountId).add(con);
}else{
AccountIdContactMap.put(con.accountId, new list<contact>{con});
}
}
system.debug('AccountIdcontactmap'+AccountIdContactMap);
for(string accId : AccountIdContactMap.keyset()){
system.debug('Inside loop');
if(accId!=null){
for(Contact cont : AccountIdContactMap.get(accId)){
if(cont.MatchingEmail1__c != null)
{
if( DominantEmailContactMap.containsKey(cont.Id))
{
String mapEmail = DominantEmailContactMap.get(cont.Id);
mapEmail = cont.MatchingEmail1__c;
DominantEmailContactMap.put(cont.Id,mapEmail);
}else{
DominantEmailContactMap.put(cont.Id, cont.MatchingEmail1__c);
}
}
}
}
}
system.debug('DominantEmailContactMap'+DominantEmailContactMap);
if(DominantEmailContactMap!=null){
List<String> FinalEmailList = new List<String>();
ListemailList = DominantEmailContactMap.values();
for(String emailString : ListemailList )
{
FinalEmailList.add(emailString);
}
for(Integer i = 0 ; i < (FinalEmailList.size()/3)+1 ; i++){
List<String> lstTemp = new List<String>();
for(Integer j=(i*3);(j<(i*3)+3) && j<FinalEmailList.size() ; j++){
lstTemp.add(FinalEmailList.get(j));
}
if(lstTemp!=null && lstTemp.size()>0){
listWrapper.add(lstTemp);
}
}
}
String firstPart = '{\"api_key\":\"'+key+'\",';
String reqPart = '\"email_batch\":[';
system.debug('listwrapper'+listWrapper);
for(List<String> emailTempList: listWrapper){
String emailRequest = '';
String matchingEmail = '';
if(emailTempList.size() == 1){
for(Integer i=0; i<emailTempList.size(); i++){
matchingEmail = emailTempList[i];
if(matchingEmail != ''){
emailRequest += '{\"email_address\": '+'\"'+matchingEmail+'\"'+'}';
}
}
}
else if(emailTempList.size()> 1){
for(Integer i=0; i<emailTempList.size(); i++){
matchingEmail = emailTempList[i];
if(matchingEmail != ''){
emailRequest += '{\"email_address\": '+'\"'+matchingEmail+'\"'+'},';
}
}
}
String lastPart = ']}';
if (emailRequest.right(1) == ',')
emailRequest = emailRequest.removeEnd(',');
String request = firstPart + reqPart + emailRequest +lastPart;
system.debug('Request'+request);
if(request != null)
{
system.debug('Inside if');
HttpRequest req1 = new HttpRequest();
HttpResponse res1 = new HttpResponse();
Http http1 = new Http();
req1.setHeader('Content-Type', 'application/json');
req1.setEndpoint('https://bulkapi.zerobounce.net/v2/validatebatch');
req1.setMethod('POST');
req1.setBody(request);
if (!Test.isRunningTest()) {
res1 = http1.send(req1);
System.debug('Response Validating email' + res1.getBody());
if(res1.getStatusCode() == 200){
EmailValidationBatchJsonParser emailParserResponse = new EmailValidationBatchJsonParser();
emailParserResponse = (EmailValidationBatchJsonParser) JSON.deserialize(res1.getBody(), EmailValidationBatchJsonParser.class);
List<EmailValidationBatchJsonParser.email_batch> etList = emailParserResponse.email_batch;
for(EmailValidationBatchJsonParser.email_batch etObj : etList){
system.debug('etObj.status'+etObj.status);
if(etObj.status == 'Valid'){
system.debug('Email Status Valid');
for(Id conId : DominantEmailContactMap.keySet()){
if(DominantEmailContactMap.get(conId) == etObj.address){
conIds.add(conId);
}
}
}else if(etObj.status == 'catch-all'){
for(Id conId : DominantEmailContactMap.keySet()){
if(DominantEmailContactMap.get(conId) == etObj.address){
catchAllConIds.add(conId);
}
}
}else{
system.debug('Not Valid status');
}
}
}else{
system.debug('Response Failure!!');
}
}else{
system.debug('status code: error');
}
}
}
//Update Contacts Email
system.debug('conIds'+conIds);
if(conIds!=null){
system.debug('Inside');
for(Contact con : [SELECT Id, Email, MatchingEmail1__c from Contact where Id IN:conIds]){
if(con.MatchingEmail1__c!=null){
system.debug('con'+con.Id);
con.ValidEmail__c = con.MatchingEmail1__c;
system.debug('con updated email'+con.ValidEmail__c);
}
conToUpdate.add(con);
}
}
if(catchAllConIds!=null){
for(Contact cont: [SELECT Id, catchAllEmail__c from Contact where Id IN:catchAllConIds]){
cont.catchAllEmail__c = True;
conToUpdate.add(cont);
}
}
for(Id conId : DominantEmailContactMap.keySet()){
Contact cn = new Contact();
cn.Id = conId;
cn.EmailValidateFlag__c = True;
allConToUpdate.add(cn);
}
if(conToUpdate!=null && conToUpdate.size()>0){
update conToUpdate;
}
if(allConToUpdate!=null && allConToUpdate.size()>0){
update allConToUpdate;
}
}
}catch (Exception e) {
System.debug('Error:' + e.getMessage() + 'LN:' + e.getLineNumber() );
}
}
Global void finish(Database.BatchableContext BC) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {'shweta.lal@nagarro.com','aditya.pandey@nagarro.com'};
mail.setToAddresses(toAddresses);
if(nocredit){
mail.setSubject('No Credits Found!');
mail.setPlainTextBody('Credits are not available on this API key');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}else{
AsyncApexJob a = [Select Id, Status,ExtendedStatus,NumberOfErrors,JobItemsProcessed,TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =: BC.getJobId()];
mail.setSubject('Dominant Email Pattern Batch ' + a.Status);
mail.setPlainTextBody('records processed ' + a.TotalJobItems + 'with '+ a.NumberOfErrors + ' failures.');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
}
test class:
@isTest(SeeAllData=true)
public class TestBatchValidate {
@istest
public static void testmet(){
List<Contact> clist = new List<Contact>();
List<Account> accounts = new List<Account>();
Account acc=new Account(name='Account ',SecDomEmailPattern__c = 'FinitialLastName@va.gov',
billingcity='Chennai',billingcountry='India',EmailBatchProcessed__c = true,DominantEmailPattern__c='FirstName.LastName@aec.com',RoleProcessed__c=True);
accounts.add(acc);
contact c = new contact(LastName='sample name',MatchingEmail1__c='samplename@gmail.com',Accountid=acc.Id);
clist.add(c);
contact c1 = new contact(LastName='sample' ,MatchingEmail1__c='sample@gah.com',FirstName='sample',Accountid=acc.Id);
clist.add(c1);
contact c2 = new contact(LastName='sample',MatchingEmail1__c='',Accountid=acc.Id);
clist.add(c2);
contact c3 = new contact(LastName='sample' ,MatchingEmail1__c='sample5@gmail.com',Accountid=acc.Id);
clist.add(c3);
contact c4 = new contact(LastName='sample',MatchingEmail1__c='sample6@gmail.com' ,Accountid=acc.Id);
clist.add(c4);
contact c5 = new contact(LastName='sample' ,MatchingEmail1__c='sample7@gmail.com',Accountid=acc.Id);
clist.add(c5);
insert(clist);
}
@istest
public static void testmet2(){
Test.startTest();
BatchValidateEmailDominantPattern obj = new BatchValidateEmailDominantPattern();
DataBase.executeBatch(obj);
Test.stopTest();
}
}
-
- Aqua Matrix
- September 22, 2021
- Like
- 0
I want help in writing test class for below Apex Batch Class
Hi,
I want to write a test class which covers code coverage of 75% for below Apex Batch class
I want to write a test class which covers code coverage of 75% for below Apex Batch class
Global class BatchValidateSecondDominantEmail Implements Database.Batchable<sObject>,Database.AllowsCallouts,Database.stateful{
Public boolean noCredit = false;
Public string key;
List<EmailValidationApiKey__mdt> apiKeys = [SELECT APIKey__c from EmailValidationApiKey__mdt];
Global Database.QueryLocator Start(Database.BatchableContext BC){
system.debug('Start!!!');
String query = '';
try{
//Callout
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
for(EmailValidationApiKey__mdt record: apiKeys){
key = record.APIKey__c;
}
//Checking credits
String apiURL = 'https://api.zerobounce.net/v2/getcredits?api_key='+key;
req.setEndpoint(apiURL);
req.setHeader('Content-Type', 'application/json');
req.setMethod('GET');
if (!Test.isRunningTest()) {
res = http.send(req);
system.debug('--res.getBody--'+res.getBody());
if(res.getStatusCode() == 200){
Map<String, Object> docData = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
system.debug('===docData==='+docData);
string credits =(string)docData.get('Credits');
Integer cred = Integer.valueOf(credits);
system.debug('credits'+cred);
if(cred >= 1){
system.debug('Credits'+cred);
query = 'SELECT Id, Name FROM Account where EmailBatchProcessed__c = true';
}else{
noCredit = true;
}
}
}
/* String accId = '001q000001Ll27sAAB';
String query = 'SELECT Id, Name FROM Account where EmailBatchProcessed__c = true AND Id =: accId';
*/
}catch (Exception e) {
System.debug('Error:' + e.getMessage() + 'LN:' + e.getLineNumber() );
}
system.debug('query fired');
return Database.getQueryLocator(query);
}
Global void execute(Database.BatchableContext BC, List<Account> scope) {
system.debug('inside execute');
system.debug('scope'+scope);
String endpoint;
Map<Id,String> SecondDominantEmailContactMap = new Map<Id,String>();
List<String> ListemailList = new List<String>();
List<List<String>> listWrapper = new List<List<String>>();
Set<string> allAccountIds = new set<string>();
Map<string, list<Contact>> AccountIdContactMap = new Map<string, list<Contact>>();
List<Contact> conToUpdate = new List<Contact>();
List<Contact> allConToUpdate = new List<Contact>();
Set<string> conIds = new set<string>();
Set<string> catchAllConIds = new set<string>();
try {
if((scope.size() > 0)&& (scope!=null)){
for(Account a: scope){
allAccountIds.add(a.Id);
}
for(Contact con : [SELECT Id, Email, FirstName, LastName, MatchingEmail2__c, accountId from Contact where accountId IN :allAccountIds AND MatchingEmail2__c!=null AND MatchingEmail1__c!=null AND EmailValidateFlag__c = True AND EmailValidateFlag2__c = False AND Email=null]){
if(AccountIdContactMap.containsKey(con.accountId) && AccountIdContactMap.get(con.accountId)!=null){
AccountIdContactMap.get(con.accountId).add(con);
}else{
AccountIdContactMap.put(con.accountId, new list<contact>{con});
}
}
for(string accId : AccountIdContactMap.keyset()){
if(accId!=null){
for(Contact cont : AccountIdContactMap.get(accId)){
if(cont.MatchingEmail2__c != null)
{
if( SecondDominantEmailContactMap.containsKey(cont.Id))
{
String mapEmail = SecondDominantEmailContactMap.get(cont.Id);
mapEmail = cont.MatchingEmail2__c;
SecondDominantEmailContactMap.put(cont.Id,mapEmail);
}else{
SecondDominantEmailContactMap.put(cont.Id, cont.MatchingEmail2__c);
}
}
}
}
}
if(SecondDominantEmailContactMap!=null){
List<String> FinalEmailList = new List<String>();
ListemailList = SecondDominantEmailContactMap.values();
for(String emailString : ListemailList )
{
FinalEmailList.add(emailString);
}
system.debug('FinalEmailList'+FinalEmailList);
for(Integer i = 0 ; i < (FinalEmailList.size()/3)+1 ; i++){
List<String> lstTemp = new List<String>();
for(Integer j=(i*3);(j<(i*3)+3) && j<FinalEmailList.size() ; j++){
system.debug('value of counter'+j);
lstTemp.add(FinalEmailList.get(j));
system.debug('lstTemp'+lstTemp);
}
if(lstTemp!=null && lstTemp.size()>0){
listWrapper.add(lstTemp);
}
}
}
system.debug('listWrapper'+listWrapper);
String firstPart = '{\"api_key\":\"'+key+'\",';
String reqPart = '\"email_batch\":[';
for(List<String> emailTempList: listWrapper){
String emailRequest = '';
String matchingEmail = '';
if(emailTempList.size() == 1){
for(Integer i=0; i<emailTempList.size(); i++){
matchingEmail = emailTempList[i];
if(matchingEmail != ''){
emailRequest += '{\"email_address\": '+'\"'+matchingEmail+'\"'+'}';
}
}
}
else if(emailTempList.size()> 1){
for(Integer i=0; i<emailTempList.size(); i++){
matchingEmail = emailTempList[i];
if(matchingEmail != ''){
emailRequest += '{\"email_address\": '+'\"'+matchingEmail+'\"'+'},';
}
}
}
String lastPart = ']}';
if (emailRequest.right(1) == ',')
emailRequest = emailRequest.removeEnd(',');
String request = firstPart + reqPart + emailRequest +lastPart;
if(request != null)
{
HttpRequest req1 = new HttpRequest();
HttpResponse res1 = new HttpResponse();
Http http1 = new Http();
req1.setHeader('Content-Type', 'application/json');
req1.setEndpoint('https://bulkapi.zerobounce.net/v2/validatebatch');
req1.setMethod('POST');
req1.setBody(request);
if (!Test.isRunningTest()) {
res1 = http1.send(req1);
System.debug('Response Validating email' + res1.getBody());
if(res1.getStatusCode() == 200){
system.debug('success');
EmailValidationBatchJsonParser emailParserResponse = new EmailValidationBatchJsonParser();
emailParserResponse = (EmailValidationBatchJsonParser) JSON.deserialize(res1.getBody(), EmailValidationBatchJsonParser.class);
List<EmailValidationBatchJsonParser.email_batch> etList = emailParserResponse.email_batch;
system.debug('list'+etList);
for(EmailValidationBatchJsonParser.email_batch etObj : etList){
if(etObj.status == 'Valid'){
system.debug('Status Valid!!');
for(Id conId : SecondDominantEmailContactMap.keySet()){
if(SecondDominantEmailContactMap.get(conId) == etObj.address){
system.debug('Email status valid for conId'+conId);
conIds.add(conId);
}
}
}else if(etObj.status == 'catch-all'){
system.debug('Catch all status');
for(Id conId : SecondDominantEmailContactMap.keySet()){
if(SecondDominantEmailContactMap.get(conId) == etObj.address){
catchAllConIds.add(conId);
}
}
}else{
system.debug('Not Valid status');
}
}
}
}else{
system.debug('status code: error');
}
}
}
//Update Contacts Email
if(conIds!=null){
for(Contact con : [SELECT Id, Email, MatchingEmail2__c from Contact where Id IN:conIds]){
if(con.MatchingEmail2__c!=null){
con.Email = con.MatchingEmail2__c;
}
conToUpdate.add(con);
}
}
if(catchAllConIds!=null){
for(Contact cont: [SELECT Id, catchAllEmail__c from Contact where Id IN:catchAllConIds]){
cont.catchAllEmail__c = True;
conToUpdate.add(cont);
}
}
for(Id conId : SecondDominantEmailContactMap.keySet()){
Contact cn = new Contact();
cn.Id = conId;
cn.EmailValidateFlag2__c = True;
allConToUpdate.add(cn);
}
if(conToUpdate!=null && conToUpdate.size()>0){
update conToUpdate;
}
if(allConToUpdate!=null && allConToUpdate.size()>0){
update allConToUpdate;
}
}
}catch (Exception e) {
System.debug('Error:' + e.getMessage() + 'LN:' + e.getLineNumber() );
}
}
Global void finish(Database.BatchableContext BC) {
system.debug('Inside finish'+noCredit);
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {'shweta.lal@nagarro.com'};
mail.setToAddresses(toAddresses);
if(nocredit){
mail.setSubject('No Credits Found!');
mail.setPlainTextBody('Credits are not available on this API key');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}else{
AsyncApexJob a = [Select Id, Status,ExtendedStatus,NumberOfErrors,JobItemsProcessed,TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =: BC.getJobId()];
mail.setSubject('Dominant Email Pattern Batch ' + a.Status);
mail.setPlainTextBody('records processed ' + a.TotalJobItems + 'with '+ a.NumberOfErrors + ' failures.');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
}
-
- Aqua Matrix
- September 15, 2021
- Like
- 0
i want to write a test class for below apex batch class
hii,
i want to write a test class for below apex batch class which covers 75% code coverage.
Apex code:
i want to write a test class for below apex batch class which covers 75% code coverage.
Apex code:
global class BatchUpdateContactEmail implements Database.Batchable<sObject>
{
global Database.QueryLocator start(Database.BatchableContext BC)
{
String accId = '001q000001Ll27sAAB';
String query = 'SELECT Id,EmailBatchProcessed__c, Name,(SELECT Id, Email, FirstName, LastName FROM Contacts) FROM Account Where Id =: accId';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<Account> scope)
{
try{
system.debug('scope'+scope);
List<Contact> conToUpdate = new List<Contact>();
List<Account> accToUpdate = new List<Account>();
List<String> patternList = new List <String>();
List<String> genericPattern = new List<String>();
List<EmailPattern__mdt> listEmailPattern = [SELECT Id, Pattern__c from EmailPattern__mdt];
List<GenericEmailPattern__mdt> genericPatternList = [SELECT Id, GenericPattern__c from GenericEmailPattern__mdt];
for(EmailPattern__mdt record: listEmailPattern){
patternList.add(record.Pattern__c);
}
for(GenericEmailPattern__mdt record: genericPatternList){
genericPattern.add(record.GenericPattern__c);
}
for(Account acc : scope){
Map<string,Integer> counterMap = new Map<string,Integer>();
Map<Id,string> emailConMap = new Map<Id,string>();
Map<Id,string> accountDomainMap = new Map<Id,string>();
Map<string,Integer> emailDomainMap = new Map<string,Integer>();
boolean emailEmpty = false;
Integer countContact = 0;
String dominantPattern = '';
String secondDominantPattern = '';
String maxDomain = '';
for(string s1:patternList){
counterMap.put(s1,0);
}
if(acc.Id!=null && acc.EmailBatchProcessed__c!=true){
countContact = acc.contacts.size();
if(countContact > 1){
for(Contact cont : acc.contacts)
{
if(emailEmpty == false){
if(cont.Email == null){
system.debug('one empty email found');
//atleast one empty email is found within contacts of Account
emailEmpty = true;
break;
}
}
}
}
//if atleast one blank email found
if(emailEmpty == true){
Integer domainCount = 0;
boolean validDomain = false;
String domainName = '';
Map<string,integer> emailMap = new Map<string,integer>();
boolean noMatch = false;
boolean patternFound = false;
for(Contact cont : acc.contacts){
system.debug('contact to be processed'+cont.Id);
Map<string,string> conMap = new Map<string,string>();
String temps = '';
String emailDomain = '';
Integer num = 0;
if(cont.Email !=null && cont.Email!=''){
temps = cont.Email.split('@')[0];
emailDomain = cont.Email.split('@')[1];
Integer prevValue = 0;
boolean validEmail = true;
boolean genericPatternFound = false;
system.debug('genericPattern List'+genericPattern);
for(String s: genericPattern){
if(cont.Email.contains(s)){
genericPatternFound=true;
break;
}
}
//Finding Maximum repeated Domain
if(!genericPatternFound){
system.debug('Not generic pattern');
if(emailDomain != ''){
prevValue = emailDomainMap.get(emailDomain);
if(prevValue != null){
num = num + 1;
}
emailDomainMap.put(emailDomain,num);
}
string firstName = '';
string lastName = '';
if(cont.FirstName != ''){
firstName = cont.FirstName.toLowercase();
}
if(cont.LastName != ''){
lastName = cont.LastName.toLowercase();
String middleName = '';
if (lastName.containsWhitespace()){
List<String> names = lastName.split('');
for(String name :names){
middleName = names.get(0);
}
}
}
system.debug('firstname'+firstName);
system.debug('lastname'+lastName);
conMap.put(firstName+'.'+lastName,'FirstName.LastName');
conMap.put(firstName,'FirstName');
conMap.put(firstName+lastName,'FirstNameLastName');
conMap.put(firstName.substring(0,1)+lastName,'FinitialLastName');
conMap.put(firstName+lastName.substring(0,1),'FirstNameLastinitial');
conMap.put(firstName.substring(0,1)+'.'+lastName,'Finitial.LastName');
conMap.put(firstName+'_'+lastName,'FirstName_LastName');
conMap.put(firstName+'-'+lastName,'FirstName-LastName');
conMap.put(firstName.substring(0,1)+'_'+lastName,'Finitial_LastName');
//replace it with temps
system.debug('temps'+temps);
string pattern = conMap.get(temps);
system.debug('conMap'+conMap);
system.debug('Pattern'+pattern);
if(pattern != null)
{
if(patternFound!= true){
patternFound = true;
}
integer count = counterMap.get(pattern);
count = count + 1;
counterMap.put(pattern,count);
}else{
noMatch = true;
}
}
}
}
//Check the maximum count to find Dominant pattern in an Account
if(patternFound){
Integer maxValue = 0;
Integer secondHighestValue = 0;
List<Integer> mapValues = new List<Integer>();
List<String> patternKeyList = new List<String>();
if(counterMap != null){
mapValues = counterMap.values();
mapValues.sort();
maxValue = mapvalues[mapvalues.size()-1];
secondHighestValue = mapvalues[mapValues.size()-2];
string secondPartEmail = '';
boolean dominantPatternFound = false;
for(String s : counterMap.keySet())
{
Integer pattern_value = counterMap.get(s);
if((pattern_value == maxValue) && (maxValue > 0))
{
if(!dominantPatternFound){
system.debug(' Dominant Pattern Email for contacts with accountId'+acc.Id+' is ' + s + ' with value' + pattern_value);
dominantPattern = s;
dominantPatternFound = true;
}
}
if((pattern_value == secondHighestValue) && (secondHighestValue > 0)){
system.debug(' Second Dominant Pattern Email for contacts with accountId'+acc.Id+' is ' + s + ' with value' + pattern_value);
secondDominantPattern = s;
}
}
}
//Checking Max Domain Name
Integer highestNum = 0;
List<Integer> domainList = new List<Integer>();
if(emailDomainMap != null){
domainList = emailDomainMap.values();
domainList.sort();
if(domainList.size()>0){
highestNum = domainList[domainList.size()-1];
}
}
for(String domain : emailDomainMap.keySet()){
Integer num = emailDomainMap.get(domain);
if(num == highestNum){
maxDomain = domain;
system.debug('Max Domain for contacts with accountId'+acc.Id+' is ' + maxDomain);
}
}
//Updating fields in contact with pattern formed email
for(Contact cont : acc.contacts){
// cont.MatchingEmail1__c = '';
// cont.MatchingEmail2__c = '';
string patternString = '';
string emailDomain = '';
List<String> domPatternList = new List<String>();
domPatternList.add(dominantPattern);
domPatternList.add(secondDominantPattern);
if(cont.Email == null){
cont.MatchingEmail1__c = '';
cont.MatchingEmail2__c = '';
string firstName = '';
string lastName = '';
string middleName = '';
if(cont.FirstName != null && cont.FirstName != ''){
firstName = cont.FirstName.toLowercase();
}
if(cont.LastName != null && cont.LastName != ''){
lastName = cont.LastName.toLowercase();
List<String> names = new List<string>();
if (lastName.containsWhitespace()){
names = lastName.split('');
}else if(lastName.contains('.')){
names = lastName.split('.');
}
for(String name :names){
middleName = names.get(0);
}
}
if(middleName != ''){
lastName = middleName;
}
for(string s2:domPatternList){
switch on s2{
when 'FirstName.LastName' {
patternString = firstName+'.'+lastName;
}when 'FirstName' {
patternString = firstName;
}when 'FirstNameLastName' {
patternString = firstName+lastName;
}when 'FinitialLastName' {
patternString = firstName.substring(0,1)+lastName;
}when 'FirstNameLastinitial' {
patternString = firstName+lastName.substring(0,1);
}when 'Finitial.LastName' {
patternString = firstName.substring(0,1)+'.'+lastName;
}when 'FirstName_LastName' {
patternString = firstName+'_'+lastName;
}when 'FirstName-LastName' {
patternString = firstName+'-'+lastName;
}when 'Finitial_LastName' {
patternString = firstName.substring(0,1)+'_'+lastName;
}when else{
system.debug('No Match found');
}
}
if(s2.equals(dominantPattern)){
if(dominantPattern != ''){
cont.MatchingEmail1__c = patternString+'@'+maxDomain;
}
}else if (s2.equals(secondDominantPattern)){
if(secondDominantPattern != ''){
cont.MatchingEmail2__c = patternString+'@'+maxDomain;
}
}
}
}
conToUpdate.add(cont);
}
}
}
}
acc.EmailBatchProcessed__c = true;
if(dominantPattern != ''){
acc.DominantEmailPattern__c = dominantPattern+'@'+maxDomain;
}
accToUpdate.add(acc);
}
system.debug('Contact List........ '+conToUpdate);
if(conToUpdate.size()>0 && conToUpdate!=null){
update conToUpdate;
}
if(accToUpdate.size()>0 && accToUpdate!=null){
update accToUpdate;
}
}catch(exception e){
system.debug('e--'+e);
}
}
global void finish(Database.BatchableContext BC)
{
}
}
-
- Aqua Matrix
- September 13, 2021
- Like
- 0
Apex Code: Help me in solving 70% test coverage for following test class.
Help me in getting 70 % test coverage for following code.
Apex Code:
Apex Code:
global class BatchUpdateContactRole implements Database.Batchable<sObject>
{
global Database.QueryLocator start(Database.BatchableContext BC)
{
String str = '001q000001Ob8yxAAB';
String query = 'SELECT Id, RoleProcessed__c, Name FROM Account Where id =:str';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<Account> scope)
{
try{
List<Contact> conToUpdate = new List<Contact>();
List<Account> accToUpdate = new List<Account>();
Set<string> allAccountIds = new set<string>();
Map<string, list<Contact>> AccountIdContactMap = new Map<string, list<Contact>>();
Map<Id,Account> AccountData = new Map<Id,Account>();
Map<String, DominantRolePatternm__mdt> mapEd = DominantRolePatternm__mdt.getAll();
for(Account a: scope){
allAccountIds.add(a.Id);
AccountData.put(a.id,a);
}
system.debug('All AccountIds'+allAccountIds);
for(Contact con : [SELECT Id, rdcc__Role__c, FirstName, LastName, accountId from Contact where accountId IN :allAccountIds]){
if(AccountIdContactMap.containsKey(con.accountId) && AccountIdContactMap.get(con.accountId)!=null){
AccountIdContactMap.get(con.accountId).add(con);
}else{
AccountIdContactMap.put(con.accountId, new list<contact>{con});
}
}
system.debug('AccountIdContactMap'+AccountIdContactMap);
for(string accId : AccountIdContactMap.keyset()){
boolean roleEmpty = false;
boolean allroleEmpty = false;
Integer countContact = 0;
Integer countNull = 0;
String roleToUpdate = '';
Map<string,Integer> roleMap = new Map<string,Integer>();
if(accId!=null){
system.debug('account Id'+accId);
for(Contact cont : AccountIdContactMap.get(accId)){
system.debug('Contact to be processed'+cont.Id);
if(cont.rdcc__Role__c == null){
//atleast one empty role is found within contacts of Account
roleEmpty = true;
++countNull;
system.debug('empty role found');
//break;
}
// system.debug('sizeee--'+AccountIdContactMap.get(accId).size()+'--- count--'+countNull);
if(countNull == AccountIdContactMap.get(accId).size())
{
allroleEmpty = true;
}
}
system.debug('sizeee--'+AccountIdContactMap.get(accId).size()+'--- count--'+countNull);
if(roleEmpty && allroleEmpty)
{
Account AccData = AccountData.get(accId);
for(String nameEmailDomain : mapEd.keySet()){
System.debug('----->'+mapEd.get(nameEmailDomain).Name_Combination__c);
List<String> lsttest= mapEd.get(nameEmailDomain).Name_Combination__c.split(';');
for(String roleStr : lsttest)
{
system.debug('inside contains111--'+roleStr);
if(AccData.Name.contains(roleStr))
{
system.debug('inside contains222-'+roleStr);
for(Contact cont : AccountIdContactMap.get(accId)){
cont.MatchingRole__c = mapEd.get(nameEmailDomain).RoleMatched__c;
conToUpdate.add(cont);
}
}
}
}
}
else if(roleEmpty && !allroleEmpty)
{
system.debug('Inside If Condition');
Integer prevValue = 0;
Integer num = 1;
for(Contact cont : AccountIdContactMap.get(accId)){
system.debug('Contact to be processed'+cont.Id);
if(cont.rdcc__Role__c != null){
system.debug('roleMap'+roleMap);
if(roleMap.containsKey(cont.rdcc__Role__c)){
num = roleMap.get(cont.rdcc__Role__c);
roleMap.put(cont.rdcc__Role__c,num+1);
}else{
roleMap.put(cont.rdcc__Role__c,num);
}
}
}
system.debug('Role Map'+roleMap);
List<Integer> mapValues = new List<Integer>();
//Check the maximum count to find Dominant
Integer maxValue = 0;
Integer secondHighestValue = 0;
if(roleMap.size() > 0){
mapValues = roleMap.values();
mapValues.sort();
maxValue = mapvalues[mapvalues.size()-1];
if(mapValues.size()>1){
secondHighestValue = mapvalues[mapValues.size()-2];
}
system.debug('max Values'+maxValue);
system.debug('second highest value'+secondHighestValue);
if(maxValue != secondHighestValue){ //dominant role not clashing
for(String s : roleMap.keySet()){
Integer pattern_value = roleMap.get(s);
if((pattern_value == maxValue) && (maxValue > 0)){
system.debug(' Dominant Role for contacts with accountId'+accId+' is ' + s + ' with value' + pattern_value);
roleToUpdate = s;
}
}
}
else if(maxValue == secondHighestValue){ //dominant role not clashing
for(String s : roleMap.keySet()){
system.debug('s'+s);
Integer pattern_value = roleMap.get(s);
if((pattern_value == maxValue) && (maxValue > 0) ||(pattern_value == secondHighestValue) && (secondHighestValue > 0) ){
system.debug(' Dominant Role for contacts with accountId'+accId+' is ' + s + ' with value' + pattern_value);
for (String St : System.Label.Significant_Role.split(','))
{
if(st.equalsIgnoreCase(s))
roleToUpdate = s;
}
}
}
}
}
system.debug('AccountIdContactMap'+AccountIdContactMap);
//Updating Role in contact with dominant role
for(Contact cont : AccountIdContactMap.get(accId)){
if(cont.rdcc__Role__c == null){
system.debug('roleToUpdate'+roleToUpdate);
if(roleToUpdate != ''){
cont.MatchingRole__c = roleToUpdate;
cont.rdcc__Role__c = roleToUpdate;
}
}
conToUpdate.add(cont);
}
}
}
//acc.RoleProcessed__c = true;
Account acc = new Account();
acc.Id = accId;
acc.RoleProcessed__c = True;
accToUpdate.add(acc);
}
system.debug('Con To Update'+conToUpdate);
if(conToUpdate.size()>0 && conToUpdate!=null){
update conToUpdate;
}
system.debug('Acc To Update'+accToUpdate);
if(accToUpdate.size()>0 && accToUpdate!=null){
update accToUpdate;
}
}catch(exception e){
system.debug('e--'+e);
}
}
global void finish(Database.BatchableContext BC)
{
}
}
Test Class:
@isTest
private class BatchUpdateContactRoleTest {
@testSetup
static void setup() {
List<Account> accounts = new List<Account>();
List<Contact> contacts = new List<Contact>();
// insert 10 accounts and add test fields as per your need.
Account acc=new Account(name='Account ',
billingcity='Chennai',billingcountry='India');
insert acc;
// find the account just inserted. add contact for each & test data required.
Contact con1=new Contact(firstname='first',
lastname='last',rdcc__Role__c='Test0', accountId=acc.id);
insert con1;
Contact con2=new Contact(firstname='first',
lastname='last',rdcc__Role__c='Test1', accountId=acc.id);
insert con2;
Contact con3=new Contact(firstname='first',
lastname='last',rdcc__Role__c='', accountId=acc.id);
insert con3;
}
static testmethod void testMethod2(){
Test.startTest();
BatchUpdateContactRole tb = new BatchUpdateContactRole();
Id batchId = Database.executeBatch(tb,50);
Test.stopTest();
}
}

- Aqua Matrix
- October 28, 2021
- Like
- 0
I want help in writing trigger.
Hi,
I had created data in the custom metadata for city and zipcode...
I want to write the apex trigger to autopopulate the cityname If I select the zipcode which s present in the custom metadata...
Could you please help me to write the trigger for the above scenario...
I had written the apex code to fetch the custom metadata
And now I want to write the trigger to autopopulate the city name if we choose the zipcode.
I had created data in the custom metadata for city and zipcode...
I want to write the apex trigger to autopopulate the cityname If I select the zipcode which s present in the custom metadata...
Could you please help me to write the trigger for the above scenario...
I had written the apex code to fetch the custom metadata
And now I want to write the trigger to autopopulate the city name if we choose the zipcode.
trigger Autopopulate on Contact (after insert) {
// When a new account is created, fill in the city and state based on zip code
if (trigger.isAfter && trigger.isInsert) {
zipcodemetda.fetchAllMetadata();
}
}

- Aqua Matrix
- October 19, 2021
- Like
- 0
I want a help to cover code coverage for below apex class
Hi,
I have code coverage of 44% for below apex batch class,help me in covering code coverage of 75% for below Apex class.
Apex code:
I have code coverage of 44% for below apex batch class,help me in covering code coverage of 75% for below Apex class.
Apex code:
Global class BatchValidateEmailDominantPattern Implements Database.Batchable<sObject>,Database.AllowsCallouts, Database.stateful{
Public boolean noCredit = false;
Public string key;
List<EmailValidationApiKey__mdt> apiKeys = [SELECT APIKey__c from EmailValidationApiKey__mdt];
Global Database.QueryLocator Start(Database.BatchableContext BC){
String query = '';
Set<String> accIds = new Set<String>();
//accIds.add('001q000001OZhiPAAT');
//accIds.add('001q000001Ll1puAAB');
//accIds.add('001q000001OJZxpAAH');
//accIds.add('001q000001Ll1puAAB');
try{
system.debug('Validate Email Pattern start!');
//Callout
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
for(EmailValidationApiKey__mdt record: apiKeys){
key = record.APIKey__c;
}
//Checking credits
String apiURL = 'https://api.zerobounce.net/v2/getcredits?api_key='+key;
req.setEndpoint(apiURL);
req.setHeader('Content-Type', 'application/json');
req.setMethod('GET');
String defaultAcc = 'Test Email';
if (!Test.isRunningTest()) {
res = http.send(req);
system.debug('--res.getBody--'+res.getBody());
if(res.getStatusCode() == 200){
system.debug('success status');
Map<String, Object> docData = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
string credits =(string)docData.get('Credits');
Integer cred = Integer.valueOf(credits);
if(cred >= 1){
system.debug('Credits'+cred);
query = 'SELECT Id, Name FROM Account where DominantEmailPattern__c != null and EmailBatchProcessed__c = true AND ID IN :accIds';
}else{
query = 'Select Id,Name From Account where Name =: defaultAcc';
noCredit = true;
}
}
}else{
query='Select Id,Name From Account where Name =: defaultAcc';
}
}catch (Exception e) {
System.debug('Error:' + e.getMessage() + 'LN:' + e.getLineNumber() );
}
return Database.getQueryLocator(query);
}
Global void execute(Database.BatchableContext BC, List<Account> scope) {
system.debug('scope'+scope);
String endpoint;
Map<Id,String> DominantEmailContactMap = new Map<Id,String>();
List<String> ListemailList = new List<String>();
List<List<String>> listWrapper = new List<List<String>>();
Set<string> allAccountIds = new set<string>();
Map<string, list<Contact>> AccountIdContactMap = new Map<string, list<Contact>>();
List<Contact> conToUpdate = new List<Contact>();
List<Contact> allConToUpdate = new List<Contact>();
Set<string> conIds = new set<string>();
Set<string> catchAllConIds = new set<string>();
try {
if((scope.size() > 0)&& (scope!=null)){
system.debug('scope size greater than 0');
for(Account a: scope){
allAccountIds.add(a.Id);
}
system.debug('allAccountIds'+allAccountIds);
for(Contact con : [SELECT Id, Email, FirstName, LastName, MatchingEmail1__c, MatchingEmail2__c, accountId from Contact where accountId IN :allAccountIds and EmailValidateFlag__c = False]){
if(AccountIdContactMap.containsKey(con.accountId) && AccountIdContactMap.get(con.accountId)!=null){
AccountIdContactMap.get(con.accountId).add(con);
}else{
AccountIdContactMap.put(con.accountId, new list<contact>{con});
}
}
system.debug('AccountIdcontactmap'+AccountIdContactMap);
for(string accId : AccountIdContactMap.keyset()){
system.debug('Inside loop');
if(accId!=null){
for(Contact cont : AccountIdContactMap.get(accId)){
if(cont.MatchingEmail1__c != null)
{
if( DominantEmailContactMap.containsKey(cont.Id))
{
String mapEmail = DominantEmailContactMap.get(cont.Id);
mapEmail = cont.MatchingEmail1__c;
DominantEmailContactMap.put(cont.Id,mapEmail);
}else{
DominantEmailContactMap.put(cont.Id, cont.MatchingEmail1__c);
}
}
}
}
}
system.debug('DominantEmailContactMap'+DominantEmailContactMap);
if(DominantEmailContactMap!=null){
List<String> FinalEmailList = new List<String>();
ListemailList = DominantEmailContactMap.values();
for(String emailString : ListemailList )
{
FinalEmailList.add(emailString);
}
for(Integer i = 0 ; i < (FinalEmailList.size()/3)+1 ; i++){
List<String> lstTemp = new List<String>();
for(Integer j=(i*3);(j<(i*3)+3) && j<FinalEmailList.size() ; j++){
lstTemp.add(FinalEmailList.get(j));
}
if(lstTemp!=null && lstTemp.size()>0){
listWrapper.add(lstTemp);
}
}
}
String firstPart = '{\"api_key\":\"'+key+'\",';
String reqPart = '\"email_batch\":[';
system.debug('listwrapper'+listWrapper);
for(List<String> emailTempList: listWrapper){
String emailRequest = '';
String matchingEmail = '';
if(emailTempList.size() == 1){
for(Integer i=0; i<emailTempList.size(); i++){
matchingEmail = emailTempList[i];
if(matchingEmail != ''){
emailRequest += '{\"email_address\": '+'\"'+matchingEmail+'\"'+'}';
}
}
}
else if(emailTempList.size()> 1){
for(Integer i=0; i<emailTempList.size(); i++){
matchingEmail = emailTempList[i];
if(matchingEmail != ''){
emailRequest += '{\"email_address\": '+'\"'+matchingEmail+'\"'+'},';
}
}
}
String lastPart = ']}';
if (emailRequest.right(1) == ',')
emailRequest = emailRequest.removeEnd(',');
String request = firstPart + reqPart + emailRequest +lastPart;
system.debug('Request'+request);
if(request != null)
{
system.debug('Inside if');
HttpRequest req1 = new HttpRequest();
HttpResponse res1 = new HttpResponse();
Http http1 = new Http();
req1.setHeader('Content-Type', 'application/json');
req1.setEndpoint('https://bulkapi.zerobounce.net/v2/validatebatch');
req1.setMethod('POST');
req1.setBody(request);
if (!Test.isRunningTest()) {
res1 = http1.send(req1);
System.debug('Response Validating email' + res1.getBody());
if(res1.getStatusCode() == 200){
EmailValidationBatchJsonParser emailParserResponse = new EmailValidationBatchJsonParser();
emailParserResponse = (EmailValidationBatchJsonParser) JSON.deserialize(res1.getBody(), EmailValidationBatchJsonParser.class);
List<EmailValidationBatchJsonParser.email_batch> etList = emailParserResponse.email_batch;
for(EmailValidationBatchJsonParser.email_batch etObj : etList){
system.debug('etObj.status'+etObj.status);
if(etObj.status == 'Valid'){
system.debug('Email Status Valid');
for(Id conId : DominantEmailContactMap.keySet()){
if(DominantEmailContactMap.get(conId) == etObj.address){
conIds.add(conId);
}
}
}else if(etObj.status == 'catch-all'){
for(Id conId : DominantEmailContactMap.keySet()){
if(DominantEmailContactMap.get(conId) == etObj.address){
catchAllConIds.add(conId);
}
}
}else{
system.debug('Not Valid status');
}
}
}else{
system.debug('Response Failure!!');
}
}else{
system.debug('status code: error');
}
}
}
//Update Contacts Email
system.debug('conIds'+conIds);
if(conIds!=null){
system.debug('Inside');
for(Contact con : [SELECT Id, Email, MatchingEmail1__c from Contact where Id IN:conIds]){
if(con.MatchingEmail1__c!=null){
system.debug('con'+con.Id);
con.ValidEmail__c = con.MatchingEmail1__c;
system.debug('con updated email'+con.ValidEmail__c);
}
conToUpdate.add(con);
}
}
if(catchAllConIds!=null){
for(Contact cont: [SELECT Id, catchAllEmail__c from Contact where Id IN:catchAllConIds]){
cont.catchAllEmail__c = True;
conToUpdate.add(cont);
}
}
for(Id conId : DominantEmailContactMap.keySet()){
Contact cn = new Contact();
cn.Id = conId;
cn.EmailValidateFlag__c = True;
allConToUpdate.add(cn);
}
if(conToUpdate!=null && conToUpdate.size()>0){
update conToUpdate;
}
if(allConToUpdate!=null && allConToUpdate.size()>0){
update allConToUpdate;
}
}
}catch (Exception e) {
System.debug('Error:' + e.getMessage() + 'LN:' + e.getLineNumber() );
}
}
Global void finish(Database.BatchableContext BC) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {'shweta.lal@nagarro.com','aditya.pandey@nagarro.com'};
mail.setToAddresses(toAddresses);
if(nocredit){
mail.setSubject('No Credits Found!');
mail.setPlainTextBody('Credits are not available on this API key');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}else{
AsyncApexJob a = [Select Id, Status,ExtendedStatus,NumberOfErrors,JobItemsProcessed,TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =: BC.getJobId()];
mail.setSubject('Dominant Email Pattern Batch ' + a.Status);
mail.setPlainTextBody('records processed ' + a.TotalJobItems + 'with '+ a.NumberOfErrors + ' failures.');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
}
test class:
@isTest(SeeAllData=true)
public class TestBatchValidate {
@istest
public static void testmet(){
List<Contact> clist = new List<Contact>();
List<Account> accounts = new List<Account>();
Account acc=new Account(name='Account ',SecDomEmailPattern__c = 'FinitialLastName@va.gov',
billingcity='Chennai',billingcountry='India',EmailBatchProcessed__c = true,DominantEmailPattern__c='FirstName.LastName@aec.com',RoleProcessed__c=True);
accounts.add(acc);
contact c = new contact(LastName='sample name',MatchingEmail1__c='samplename@gmail.com',Accountid=acc.Id);
clist.add(c);
contact c1 = new contact(LastName='sample' ,MatchingEmail1__c='sample@gah.com',FirstName='sample',Accountid=acc.Id);
clist.add(c1);
contact c2 = new contact(LastName='sample',MatchingEmail1__c='',Accountid=acc.Id);
clist.add(c2);
contact c3 = new contact(LastName='sample' ,MatchingEmail1__c='sample5@gmail.com',Accountid=acc.Id);
clist.add(c3);
contact c4 = new contact(LastName='sample',MatchingEmail1__c='sample6@gmail.com' ,Accountid=acc.Id);
clist.add(c4);
contact c5 = new contact(LastName='sample' ,MatchingEmail1__c='sample7@gmail.com',Accountid=acc.Id);
clist.add(c5);
insert(clist);
}
@istest
public static void testmet2(){
Test.startTest();
BatchValidateEmailDominantPattern obj = new BatchValidateEmailDominantPattern();
DataBase.executeBatch(obj);
Test.stopTest();
}
}

- Aqua Matrix
- September 22, 2021
- Like
- 0
i want to write a test class for below apex batch class
hii,
i want to write a test class for below apex batch class which covers 75% code coverage.
Apex code:
i want to write a test class for below apex batch class which covers 75% code coverage.
Apex code:
global class BatchUpdateContactEmail implements Database.Batchable<sObject>
{
global Database.QueryLocator start(Database.BatchableContext BC)
{
String accId = '001q000001Ll27sAAB';
String query = 'SELECT Id,EmailBatchProcessed__c, Name,(SELECT Id, Email, FirstName, LastName FROM Contacts) FROM Account Where Id =: accId';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<Account> scope)
{
try{
system.debug('scope'+scope);
List<Contact> conToUpdate = new List<Contact>();
List<Account> accToUpdate = new List<Account>();
List<String> patternList = new List <String>();
List<String> genericPattern = new List<String>();
List<EmailPattern__mdt> listEmailPattern = [SELECT Id, Pattern__c from EmailPattern__mdt];
List<GenericEmailPattern__mdt> genericPatternList = [SELECT Id, GenericPattern__c from GenericEmailPattern__mdt];
for(EmailPattern__mdt record: listEmailPattern){
patternList.add(record.Pattern__c);
}
for(GenericEmailPattern__mdt record: genericPatternList){
genericPattern.add(record.GenericPattern__c);
}
for(Account acc : scope){
Map<string,Integer> counterMap = new Map<string,Integer>();
Map<Id,string> emailConMap = new Map<Id,string>();
Map<Id,string> accountDomainMap = new Map<Id,string>();
Map<string,Integer> emailDomainMap = new Map<string,Integer>();
boolean emailEmpty = false;
Integer countContact = 0;
String dominantPattern = '';
String secondDominantPattern = '';
String maxDomain = '';
for(string s1:patternList){
counterMap.put(s1,0);
}
if(acc.Id!=null && acc.EmailBatchProcessed__c!=true){
countContact = acc.contacts.size();
if(countContact > 1){
for(Contact cont : acc.contacts)
{
if(emailEmpty == false){
if(cont.Email == null){
system.debug('one empty email found');
//atleast one empty email is found within contacts of Account
emailEmpty = true;
break;
}
}
}
}
//if atleast one blank email found
if(emailEmpty == true){
Integer domainCount = 0;
boolean validDomain = false;
String domainName = '';
Map<string,integer> emailMap = new Map<string,integer>();
boolean noMatch = false;
boolean patternFound = false;
for(Contact cont : acc.contacts){
system.debug('contact to be processed'+cont.Id);
Map<string,string> conMap = new Map<string,string>();
String temps = '';
String emailDomain = '';
Integer num = 0;
if(cont.Email !=null && cont.Email!=''){
temps = cont.Email.split('@')[0];
emailDomain = cont.Email.split('@')[1];
Integer prevValue = 0;
boolean validEmail = true;
boolean genericPatternFound = false;
system.debug('genericPattern List'+genericPattern);
for(String s: genericPattern){
if(cont.Email.contains(s)){
genericPatternFound=true;
break;
}
}
//Finding Maximum repeated Domain
if(!genericPatternFound){
system.debug('Not generic pattern');
if(emailDomain != ''){
prevValue = emailDomainMap.get(emailDomain);
if(prevValue != null){
num = num + 1;
}
emailDomainMap.put(emailDomain,num);
}
string firstName = '';
string lastName = '';
if(cont.FirstName != ''){
firstName = cont.FirstName.toLowercase();
}
if(cont.LastName != ''){
lastName = cont.LastName.toLowercase();
String middleName = '';
if (lastName.containsWhitespace()){
List<String> names = lastName.split('');
for(String name :names){
middleName = names.get(0);
}
}
}
system.debug('firstname'+firstName);
system.debug('lastname'+lastName);
conMap.put(firstName+'.'+lastName,'FirstName.LastName');
conMap.put(firstName,'FirstName');
conMap.put(firstName+lastName,'FirstNameLastName');
conMap.put(firstName.substring(0,1)+lastName,'FinitialLastName');
conMap.put(firstName+lastName.substring(0,1),'FirstNameLastinitial');
conMap.put(firstName.substring(0,1)+'.'+lastName,'Finitial.LastName');
conMap.put(firstName+'_'+lastName,'FirstName_LastName');
conMap.put(firstName+'-'+lastName,'FirstName-LastName');
conMap.put(firstName.substring(0,1)+'_'+lastName,'Finitial_LastName');
//replace it with temps
system.debug('temps'+temps);
string pattern = conMap.get(temps);
system.debug('conMap'+conMap);
system.debug('Pattern'+pattern);
if(pattern != null)
{
if(patternFound!= true){
patternFound = true;
}
integer count = counterMap.get(pattern);
count = count + 1;
counterMap.put(pattern,count);
}else{
noMatch = true;
}
}
}
}
//Check the maximum count to find Dominant pattern in an Account
if(patternFound){
Integer maxValue = 0;
Integer secondHighestValue = 0;
List<Integer> mapValues = new List<Integer>();
List<String> patternKeyList = new List<String>();
if(counterMap != null){
mapValues = counterMap.values();
mapValues.sort();
maxValue = mapvalues[mapvalues.size()-1];
secondHighestValue = mapvalues[mapValues.size()-2];
string secondPartEmail = '';
boolean dominantPatternFound = false;
for(String s : counterMap.keySet())
{
Integer pattern_value = counterMap.get(s);
if((pattern_value == maxValue) && (maxValue > 0))
{
if(!dominantPatternFound){
system.debug(' Dominant Pattern Email for contacts with accountId'+acc.Id+' is ' + s + ' with value' + pattern_value);
dominantPattern = s;
dominantPatternFound = true;
}
}
if((pattern_value == secondHighestValue) && (secondHighestValue > 0)){
system.debug(' Second Dominant Pattern Email for contacts with accountId'+acc.Id+' is ' + s + ' with value' + pattern_value);
secondDominantPattern = s;
}
}
}
//Checking Max Domain Name
Integer highestNum = 0;
List<Integer> domainList = new List<Integer>();
if(emailDomainMap != null){
domainList = emailDomainMap.values();
domainList.sort();
if(domainList.size()>0){
highestNum = domainList[domainList.size()-1];
}
}
for(String domain : emailDomainMap.keySet()){
Integer num = emailDomainMap.get(domain);
if(num == highestNum){
maxDomain = domain;
system.debug('Max Domain for contacts with accountId'+acc.Id+' is ' + maxDomain);
}
}
//Updating fields in contact with pattern formed email
for(Contact cont : acc.contacts){
// cont.MatchingEmail1__c = '';
// cont.MatchingEmail2__c = '';
string patternString = '';
string emailDomain = '';
List<String> domPatternList = new List<String>();
domPatternList.add(dominantPattern);
domPatternList.add(secondDominantPattern);
if(cont.Email == null){
cont.MatchingEmail1__c = '';
cont.MatchingEmail2__c = '';
string firstName = '';
string lastName = '';
string middleName = '';
if(cont.FirstName != null && cont.FirstName != ''){
firstName = cont.FirstName.toLowercase();
}
if(cont.LastName != null && cont.LastName != ''){
lastName = cont.LastName.toLowercase();
List<String> names = new List<string>();
if (lastName.containsWhitespace()){
names = lastName.split('');
}else if(lastName.contains('.')){
names = lastName.split('.');
}
for(String name :names){
middleName = names.get(0);
}
}
if(middleName != ''){
lastName = middleName;
}
for(string s2:domPatternList){
switch on s2{
when 'FirstName.LastName' {
patternString = firstName+'.'+lastName;
}when 'FirstName' {
patternString = firstName;
}when 'FirstNameLastName' {
patternString = firstName+lastName;
}when 'FinitialLastName' {
patternString = firstName.substring(0,1)+lastName;
}when 'FirstNameLastinitial' {
patternString = firstName+lastName.substring(0,1);
}when 'Finitial.LastName' {
patternString = firstName.substring(0,1)+'.'+lastName;
}when 'FirstName_LastName' {
patternString = firstName+'_'+lastName;
}when 'FirstName-LastName' {
patternString = firstName+'-'+lastName;
}when 'Finitial_LastName' {
patternString = firstName.substring(0,1)+'_'+lastName;
}when else{
system.debug('No Match found');
}
}
if(s2.equals(dominantPattern)){
if(dominantPattern != ''){
cont.MatchingEmail1__c = patternString+'@'+maxDomain;
}
}else if (s2.equals(secondDominantPattern)){
if(secondDominantPattern != ''){
cont.MatchingEmail2__c = patternString+'@'+maxDomain;
}
}
}
}
conToUpdate.add(cont);
}
}
}
}
acc.EmailBatchProcessed__c = true;
if(dominantPattern != ''){
acc.DominantEmailPattern__c = dominantPattern+'@'+maxDomain;
}
accToUpdate.add(acc);
}
system.debug('Contact List........ '+conToUpdate);
if(conToUpdate.size()>0 && conToUpdate!=null){
update conToUpdate;
}
if(accToUpdate.size()>0 && accToUpdate!=null){
update accToUpdate;
}
}catch(exception e){
system.debug('e--'+e);
}
}
global void finish(Database.BatchableContext BC)
{
}
}

- Aqua Matrix
- September 13, 2021
- Like
- 0