Sunday 23 October 2022

Apex Triggers Scenarios

//1. Before Insert Trigger: Apex trigger to update account description with Account Name and  Account Number.


trigger BeforeInsertTrigger1 on Account (before insert, before update, before delete,                                     

                                         after insert, after update, after delete, after undelete) 


{

    /*

    if(Trigger.isInsert){

        if(Trigger.isBefore){            

            for(Account acc: Trigger.new){

                if(String.isBlank(acc.Description)){

                   // acc.Description = acc.Name + ' '+acc.AccountNumber;

                }

            }

        }

    }

*/

}

=================

trigger BeforeInsertTrigger2 on Account (before insert, before update, before delete,


                                        after insert, after update, after delete, after undelete) 


{

/*

    if(Trigger.isInsert || Trigger.isUpdate){


        if(Trigger.isBefore){


            for(Account acc: Trigger.new){


                if(String.isNotBlank(acc.Industry)){


                    if(acc.Industry == 'Banking'){


                        acc.Rating = 'Hot';


                    }  


                    else if(acc.Industry == 'Agriculture'){


                        acc.Rating = 'Warm';


                    }


                    else


                        acc.Rating = 'Cold';


                }


            }


        }


    }


*/

}

===========================

trigger BeforeInsertTrigger3 on Account (before insert, before update) {

   /*

    Set<String> accountNameSet = new Set<String>();

    

    for(Account acc: [SELECT Name FROM Account]){

        

        accountNameSet.add(acc.Name);

        

        System.debug('accountNameSet @@ '+accountNameSet);

        

    }

    

    for(Account acc: trigger.new){

        

        if(accountNameSet.contains(acc.Name)){

            

            System.debug('accountNameSet.contains(acc.Name) '+acc.Name);

            

            acc.Name.addError('An Account exists with same name ! ');

            

        }

        

    }*/

    

}

==========================

trigger BeforeInsertTrigger4 on Contact (before insert,before update) {

 /* Set < Id > accountIdSet = new Set < id > ();

  Map < Id, List < Contact >> accountIdContactMap = new Map < Id, List < Contact >> ();

  Account acc = new Account();

  for (Contact con: Trigger.New) {

   accountIdSet.add(con.AccountId);

  }

  for (Contact con: [SELECT Id, Primary__c, AccountId FROM Contact

    WHERE AccountId =: accountIdSet AND Primary__c = TRUE

   ]) {

   if (accountIdContactMap.containsKey(con.AccountId)) {

    accountIdContactMap.get(con.AccountId).add(con);

   } else {

    accountIdContactMap.put(con.AccountId, new List < Contact > ());

    accountIdContactMap.get(con.AccountId).add(con);

   }

  }

  for (Contact con: Trigger.New) {

   if ((accountIdContactMap.containsKey(con.AccountId)) &&

    (con.AccountId != NULL) && (con.Primary__c == TRUE)) {

    {

     con.Primary__c.addError('Primary Contact already exists');

     con.addError('Primary Contact already exists');

    }

   }

  } */

 }

========================

trigger AfterInsertTrigger5 on Account (after insert) {

    

    List<Contact> listCon = new List<Contact>();

    

    for(Account acc: Trigger.new){

        

        Contact con = new Contact();

        

        con.LastName = acc.Name + ' Contact';

        con.Description = acc.Description;

        

        con.AccountId = acc.Id;

        

        listCon.add(con);

        

    }

    

    if(!listCon.isEmpty()){

        

        try {

            

            Database.insert(listCon, false);

            

        }

        

        catch(Exception ex){

            

            System.debug('Exception occurred '+ex);

            

        }

        

    } 

    

    

}

====================

trigger BeforeUpdateTrigger6 on Account (before update) {

/*

      for(Account acc: Trigger.new){

          

          if(Trigger.oldMap.get(acc.Id).AccountNumber != null){

               if(acc.AccountNumber != Trigger.oldMap.get(acc.Id).AccountNumber){


                    acc.addError('Cannot change the Account Number');


                }

          }

         

      }*/

}

====================

trigger AfterUpdateTrigger7 on Account (after update) {

   /*

    Map < Id, Account > mapAccount = new Map < Id, Account > ();

    

    List < Contact > listContact = new List < Contact > ();

    

    

    

    for (Account acct: Trigger.new)

        

        mapAccount.put(acct.Id, acct);

    

    

    

    listContact = [SELECT Description, AccountId FROM Contact

                   

                   WHERE AccountId IN: mapAccount.keySet()];

    

    

    

    if (listContact.size() > 0) {

        

        for (Contact con: listContact) {

            

            con.Description = mapAccount.get(con.AccountId).Description;

            

        }

        

        update listContact;

        

    } */

    

}

===============================

trigger AfterUpdateTrigger8 on Contact (after update) {

 /*

    Map < ID, Account > accIdMap = new Map < ID, Account > (); 

  //Making it a map instead of list for easier lookup

  

  List < Id > accIdSet = new List < Id > ();

  for (Contact childObj: Trigger.new) {

    accIdSet.add(childObj.AccountId);

   }


   accIdMap = new Map < Id, Account > ([SELECT id, Description,

    (SELECT ID, Description FROM Contacts) FROM Account WHERE ID IN: accIdSet]);


   for (Contact con: Trigger.new) {

    Account myParentOpp = accIdMap.get(con.AccountId);

    myParentOpp.Description = con.Description;

   }

   update accIdMap.values();

    */

  }

=====================

trigger BeforeDeleteTrigger9 on Account (before delete) {

    /*

    for (Account acc: [SELECT ID From Account WHERE ID IN: Trigger.old AND 

                       

                       ID IN(SELECT AccountId from Contact)]) 

        

    {

        

        trigger.oldMap.get(acc.Id).addError('Cannot delete Account with contacts');

        

    }

*/

}

===================

trigger BeforeDeleteTrigger10 on Contact (before delete) {

    /*

    for(Contact con: Trigger.old){

        

        if(con.Primary__c){

            

            con.Primary__c.addError('Primary contact cannot be deleted.');

            

        }

        

    } */

}

=======================

trigger AfterDeleteTrigger11 on Contact (after delete) {

/*

     List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();


            for (Contact con : Trigger.old) {


                if (con.Email != null) {


                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();


                    List<String> sendTo = new List<String>();


                    sendTo.add(con.Email);


                    mail.setToAddresses(sendTo);


                    mail.setSubject('Your Contact is deleted');


                    String body = 'Dear ' + con.LastName + ', '; 


                    body += 'Your Contact is deleted successfully in Salesforce org.';


                    mail.setHtmlBody(body);


                    mails.add(mail);


                }


            }


            Messaging.sendEmail(mails);

*/

}

=========================

trigger AfterUnDeleteTrigger12 on Account (after undelete) {

    /*

     List<Account> listAccount = new List<Account>();


            for(Account acc : [SELECT ID, Name, Description from Account where Id IN : trigger.new]){ 


                acc.Name = 'Restored Account: ' + acc.Name;


                acc.Description = 'This Account is restored by Trigger';


                listAccount.add(acc);


            } 


            update listAccount;

*/

        }

===============================

trigger AfterInsertUpdateTrigger13 on Contact (after insert) {

/*

Map < Id, Id > accConMap = new Map < Id, Id > ();

    List < Contact > conList = new List < Contact > ();

    

    for (Contact cont: Trigger.New) {

        if (cont.AccountId != null && cont.Primary__c && 

            (Trigger.isInsert || (Trigger.isUpdate && 

            !Trigger.oldMap.get(cont.Id).Primary__c))) {

                accConMap.put(cont.AccountId, cont.Id);

            }

    }

    if(!accConMap.isEmpty())

    {

        for (Contact con: [select Id, Primary__c from contact

                           where accountid IN: accConMap.keyset() AND 

                           Id NOT IN: accConMap.values()

                           AND Primary__c = true

                          ]) 

        {

            con.Primary__c = false;

            conList.add(con);

        }

        if(!conList.isEmpty()) {

            update conList;

        }

    }

*/

}

=======================

trigger AfterInsertTrigger14 on Opportunity (after insert) {

    /*

    List<Task> listTask = new List<Task>();

    

    for(Opportunity opp: Trigger.new)

        

    {

        if(opp.StageName == 'Closed Won' ){

            Task t = new Task();

            

            t.Subject = 'Follow up task';

            

            t.WhatId = opp.Id;

            

            listTask.add(t);

            

        }

    }

    

    if(!listTask.isEmpty()){

        

        try{

            

            Database.insert(listTask, false);

            

        }

        

        catch(Exception ex){

            

            System.debug('Exception '+ex);

            

        }

        

    }

    */

}

==============================

trigger AfterInsertUpdateTrigger15 on Contact (after insert) {

  /*  Set<Id> accountIdSet = new Set<Id>();

    Map<Id, Account> accountMap = new Map<Id, Account>();

    for(Contact con: Trigger.new){

        if(con.AccountId != null){

            accountIdSet.add(con.AccountId);

        }

    }

    if(accountIdSet != null){

        for(AggregateResult ar: [SELECT count(Id) contactCount, sum(Amount__c) sumAmount, 

                                 avg(Amount__c) avgAmount, Max(Amount__c) maxAmount,

                                 min(Amount__c) minAmount, AccountId FROM Contact 

                                 WHERE AccountId in: accountIdSet GROUP BY AccountId ])

        {

            Account acc = new Account();

            acc.Id = (Id)ar.get('AccountId');

            acc.Count_of_Contacts__c = (Integer)ar.get('contactCount');

            acc.Sum_of_Contacts_Amount__c = (Decimal)ar.get('sumAmount');

            acc.Max_of_Contacts_Amount__c = (Decimal)ar.get('maxAmount');

            acc.Min_of_Contacts_Amount__c = (Decimal)ar.get('minAmount');

            acc.Average_Of_Contacts_Amount__c = (Decimal)ar.get('avgAmount');                    

            accountMap.put(acc.Id, acc);

        }

    }

    if(accountMap != null){

        update accountMap.values();

    }

*/

}

============================

Trigger AfterInsertUpdateTrigger16 on Contact(After insert, After Delete, After Undelete, After Update) {

 /*

    Set < Id > setAccountIds = new Set < Id > ();

  if (Trigger.isInsert || Trigger.isUndelete || Trigger.IsUpdate) {

   for (Contact con: Trigger.new) {

    setAccountIds.add(con.AccountId);

   }

  }

  if (Trigger.isDelete) {

   for (Contact con: Trigger.old) {

    setAccountIds.add(con.AccountId);

   }

  }

  List < Account > listAccs = [Select id, name, number_of_contacts__c,

   (Select id from contacts) from Account

   where Id in: setAccountIds

  ];

  for (Account acc: listAccs) {

   acc.number_of_contacts__c = acc.contacts.size();

  }

  update listAccs;

*/

 }

=======================

trigger ContentDocumentTrigger17 on ContentDocument (before insert) {


    for(ContentDocument cd : trigger.new) {


        if(cd.Title == 'Test1') {

            cd.addError('Name should not be Test');

            cd.Title.addError('Name should not be Test');


        }

    }

}

===================

18. Create Task For Closed Opp

trigger Trigger10_CreateTaskForClosedOpp on Opportunity (after insert) {

    List<Task> listTask = new List<Task>();

    for(Opportunity opp: [SELECT Id, StageName FROM Opportunity 

                         WHERE StageName = 'Closed Won' AND ID IN: Trigger.new])

    {

        Task t = new Task();

        t.Subject = 'Follow up task';

        t.WhatId = opp.Id;

        listTask.add(t);

    }

    if(!listTask.isEmpty()){

        try{

            Database.insert(listTask, false);

        }

        catch(Exception ex){

            System.debug('Exception '+ex);

        }

    }

}


19. Duplicate Lead ContactEmail

trigger Trigger13_DuplicateLeadContactEmail on Lead (before insert) {

  

    /*

    Set<String> leadEmailSet = new Set<String>();

    for(Lead l: Trigger.new){

        leadEmailSet.add(l.Email);

    }

    

    Map<String, Lead> leadMap = new Map<String, Lead>();

    for(Lead l: [SELECT Id, Email FROM Lead WHERE Email in: leadEmailSet ]){

        leadMap.put(l.Email, l);

    }

    

    for(Lead l: Trigger.new){

        if(leadMap.containsKey(l.Email)){

            l.addError(' Lead is already existed with this Email');

        }

    }

    

    Map<String, Contact> conMap = new Map<String, Contact>();

    for(Contact con: [SELECT Id, Email FROM Contact WHERE Email in: leadEmailSet]){

        conMap.put(con.Email, con);

    }

    

    for(Lead l: Trigger.new){

        if(conMap.containsKey(l.Email)){

            l.addError('Contact is already existed with this Email');

        }

    }

    */

}

==================
20. Trigger to create contacts based on given number whenever Account is created.


Trigger:

trigger AccountTrigger1 on Account (after insert) {
    
   AccountTrigger1Handler.createContacts(Trigger.new);
}

Trigger Handler:

public class AccountTrigger1Handler {
    public static void createContacts(List<Account> listAccount){
        List<Contact> listContact = new List<Contact>();
        for(Account acc: listAccount){
            for(Integer i=0; i < acc.Number_of_Contacts__c; i++ ){
                Contact con = new Contact();
                con.AccountId = acc.Id;
                con.LastName = acc.Name + 'Contact '+i;
                listContact.add(con);
            }
        }
        
        if(listContact.size() > 0 && !listContact.isEmpty()){
            try{
                Database.insert(listContact, false);
            }
            catch(Exception e){
                System.debug('Error occurred '+e);
            }
        }
    }
}

========================

21. Trigger to fetch values from Custom Metadata type and update in ISO__c field of Account:


Trigger updateIsoCode on Contact(before insert) {
  List < Country_ISO_Code__mdt > countryIsoCodeMetadata = [SELECT Id,
  Country__c, ISO_Code__c FROM Country_ISO_Code__mdt
  ];
  Map < String, String > countryIsoCodeMap = new Map < String, String > ();
  if (countryIsoCodeMetadata != null && countryIsoCodeMetadata.size() > 0) {
   for (Country_ISO_Code__mdt cmd: countryIsoCodeMetadata) {
    countryIsoCodeMap.put(cmd.Country__c, cmd.ISO_Code__c);
   }
  }
  for (Contact con: Trigger.new) {
   if (countryIsoCodeMap.containsKey(con.Country__c)) {
    System.debug('inside Contact loop @@@ ' + countryIsoCodeMap);
    con.ISO_Code__c = countryIsoCodeMap.get(con.Country__c);
   }
  }
 }

========================

22. Cant delete attachment for completed Case

trigger ContentDocumentLinkTriggerDelete on ContentDocumentLink (before delete) {
    System.debug('ContentDocumentLinkTriggerDelete');
    if(trigger.isBefore) {
        if(trigger.isDelete) {
            System.debug('inside before delete @@@ ');
            Map<Id, Case> closedCasesMap = new Map<Id, Case>();
            for(Case cs: [Select Id from Case  where Status = 'Completed'  ]){
                closedCasesMap.put(cs.Id, cs);
                System.debug('closedCasesMap ==> ' +closedCasesMap);
            }
            for(ContentDocumentLink a : Trigger.old) {
                System.debug('ContentDocumentLink parent id: ' +a.Id);
                if(closedCasesMap.containsKey(a.LinkedEntityId)){
                    a.addError('Cant delete attachment for completed Case');
                }
            } 
        }
    }  /*
    for(ContentDocumentLink a : Trigger.old) {
        a.addError('cant delete @@@');
    }
    */
}

23. Submit for approval.

trigger accountApprovalSubmit on Account(after insert, after update) {
   List < Approval.ProcessSubmitRequest > recordsToBeSubmitted = 
   new List < Approval.ProcessSubmitRequest > ();
   
   for (Account acc: trigger.new) {
    if (acc.Usage_Exclusion__c && (Trigger.isInsert ||
      trigger.newMap.get(acc.id).Usage_Exclusion__c != 
      trigger.oldMap.get(acc.id).Usage_Exclusion__c)) {
      
     Approval.ProcessSubmitRequest request = new Approval.ProcessSubmitRequest();
     request.setComments('Submitting request for approval.');
     request.setObjectId(acc.Id);
     recordsToBeSubmitted.add(request);
    }
   }
   if (!recordsToBeSubmitted.isEmpty())
    Approval.ProcessResult[] results = Approval.process(recordsToBeSubmitted, False);
   //You can loop over the above results list and debug the result if you want.
  }

24. Apex trigger to update Account Owner name in Account's Description. 
 Trigger updateOwnerName on Account(before insert, before update) {
  Set < id > ownerIds = new Set < id > ();
  for (Account a: Trigger.new)
   ownerIds.add(a.OwnerId);
  Map < id, User > owners = new Map < id, User > ([Select FirstName from User
   Where Id in: ownerIds
  ]);
  for (Account a: accList) {
   a.Description = owners.get(a.OwnerId).FirstName;
  }
 }

============================
25. Send email with pdf after contact is created.

trigger sendEmail on Employee__c (after insert, after update)  {   
    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    for(Employee__c e : trigger.new) {  
        Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
        attach.setContentType(‘application/pdf’);
        attach.setFileName(‘Employee.pdf’);
       
        String body;
       
        body = ‘<html><h1 style=”text-align:center;”>Employee Information</h1><br/><br/><table align=”center”><tr><td>Employee Name</td><td>’ + e.Name + ‘</td></tr><tr><td>Age</td><td>’ + e.Age__c + ‘</td></tr><tr><td>State</td><td>’ + e.State__c + ‘</td></tr><tr><td>City</td><td>’ + e.City__c + ‘</td></tr></table></html>’;
        System.debug(‘HTML is ‘ + body);
       
        attach.Body = Blob.toPDF(body);
               
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] { e.Email__c });
        mail.setSubject(‘PDF Generation’);
        mail.setHtmlBody(‘PFA’);
        mail.setFileAttachments(new Messaging.EmailFileAttachment[] { attach });    
       
        mails.add(mail); 
    }
    if(!mails.isEmpty()) {
        Messaging.SendEmail(mails);
    }
}

============================
26. Basically you need to create the ContentDocumentLink to link it to both the ContentNote and the sObject.
trigger AddNote on Lead (after insert) {
    List<ContentNote> nte = new List<ContentNote>();
    List<ContentDocumentLink> lnk = new List<ContentDocumentLink>();
    for(Lead lds : Trigger.new){
        ContentNote cnt = new ContentNote();
        cnt.Content = Blob.valueof(lds.Sales_Notes__c);
        cnt.Title = 'Creation Note';
        nte.add(cnt);
    }
    
    if(nte.size()>0){
        insert nte;
    }
    for(Lead lds : Trigger.new){
        ContentDocumentLink clnk = new ContentDocumentLink();
        clnk.LinkedEntityId = lds.Id;
        clnk.ContentDocumentId = nte[0].Id;
        clnk.ShareType = 'I';
        lnk.add(clnk);
    }
    
    if(nte.size()>0){
        insert lnk;
    }
}

Thursday 13 October 2022

SOAP & REST Inbound/Outbound integration

SOAP Inbound and Outbound:

=================

Login into Org1 Destination org: sfdc338@gmail.com


Step 1: Create SOAP inbound web service:

global class SoapInboundWebService {    

    webservice static String createAccount(String accountName, String accountNumber, 

                                           String accountPhone, String accountDescription)

    {

        Account acc = new Account();

        acc.Name = accountName;

        acc.AccountNumber = accountNumber;

        acc.Phone = accountPhone;

        acc.Description = accountDescription;

        insert acc;

        return acc.Name;

    }

}

Step 2: Generate Partner wsdl and SoapInboundWebService wsdl files.

Go to setup ==> Quick Find ==>  APIs ==>

Generate Partner wsdl.

Generate wsdl for "SoapInboundWebService" class. ==> Go to Apex class "SoapInboundWebService" ==> click on "Generate WSDL" button and save file.


Step 3: Now go to source org and generate apex classes for Partner WSDL and SoapInboundWebService wsdl.


When we generate apex classes using SoapInboundWebService wsdl, salesforce will generate two apex classes.

They are 

soapSforceComSchemasClassSoapinboun

AsyncSoapSforceComSchemasClassSoapinboun


Now go to class "soapSforceComSchemasClassSoapinboun" and get the elements to create Soap outbound call.

Before making a callout ==> we need to create remote site settings and store url of target org in client org(from here making callout).


Remote Site Settings: Remote Site Name SOHELSFDC338

Remote Site URL: https://ap24.salesforce.com


Below is Soap outbound call: Go to developer console and execute below from anonymous block. An account will be created in target org.


partnerSoapSforceCom.Soap sp = new partnerSoapSforceCom.Soap();

partnerSoapSforceCom.LoginResult log = sp.login('sfdc338@gmail.com', 'sohel42011BW2rEx55O33yFxYkfc8QLOv2'); 


soapSforceComSchemasClassSoapinboun.SessionHeader_element SessionHeader = new soapSforceComSchemasClassSoapinboun.SessionHeader_element();

SessionHeader.sessionId = log.sessionId;

soapSforceComSchemasClassSoapinboun.SoapInboundWebService ws = new soapSforceComSchemasClassSoapinboun.SoapInboundWebService();

ws.SessionHeader = SessionHeader;

ws.createAccount('SA1','1111','9999999999','SA1 Description');


Now let's call this logic from Trigger.:


trigger SoapInboundWebServiceTrigger on Account (before insert) {

    for(Account acc: Trigger.new){

        SoapInboundWebServiceTriggerHandler.createAccountMethod(acc.Name, acc.AccountNumber, acc.Phone, acc.Description);

    }

}

==========

public class SoapInboundWebServiceTriggerHandler {

    @future(callout=true)

    public static void createAccountMethod(String accName, String accNumber, String accPhone, String accDescription){

        

        partnerSoapSforceCom.Soap sp = new partnerSoapSforceCom.Soap();

        partnerSoapSforceCom.LoginResult log = sp.login('sfdc338@gmail.com', 'sohel42011BW2rEx55O33yFxYkfc8QLOv2'); 

        soapSforceComSchemasClassSoapinboun.SessionHeader_element SessionHeader = new soapSforceComSchemasClassSoapinboun.SessionHeader_element();

        SessionHeader.sessionId = log.sessionId;

        soapSforceComSchemasClassSoapinboun.SoapInboundWebService ws = new soapSforceComSchemasClassSoapinboun.SoapInboundWebService();

        ws.SessionHeader = SessionHeader;

        ws.createAccount(accName, accNumber, accPhone, accDescription);

    }

}


Created an Account record from source and account has been created in target org successfully.

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Rest Inbound Web Service:

==> Login into Salesforce 1 org - Destination org - SFDC338@gmail.com

Created below class:

@RestResource(urlMapping='/Account10/*')
global with sharing class RestInboundWebService {
    
    @HttpPost
    global static String doPost(String name, String phone, String website) 
    {
        Account account = new Account();
        account.Name = name;
        account.phone = phone;
        account.website = website;
        insert account;
        return 'Congrats... New Account has been created in SF1 instance. Here is Account Id :' +account.Id;
    }
}

Create Connected App with below details:

Name: SFDC338

Callback URL: https://sohel-sf-dev-ed.my.salesforce.com/services/oauth2/callback

After creation of Connected App, Consumer Key and Consumer Secret will be generated by Salesforce.

Consumer Key: 3MVG9fe4g9fhX0E7RnFaHALdmsbgONcNa1sfLPMUbW10tKIzxjcto8McjyvJx0bPlUMqoeh7P8ZAUc7LNgtNY
Consumer Secret: F20C3C0347E54A07C7E3A989266535821607E3CB43B6BA216934D9E31030E620
 
==================================================

Rest Outbound Web Service:

==> Login into Salesforce 2 org - Source org - sohel@sfdc2.com


Create "Remote Site Settings"

Remote Site Name: SOHELSFDC338
Remote Site URL: https://sohel-sf-dev-ed.my.salesforce.com


Create below classes:

public class RestAccessToken{
    
    
    String clientId = '3MVG9fe4g9fhX0E7RnFaHALdmsbgONcNa1sfLPMUbW10tKIzxjcto8McjyvJx0bPlUMqoeh7P8ZAUc7LNgtNY';
    
    //Use your Client Secret
    String clientsecret='F20C3C0347E54A07C7E3A989266535821607E3CB43B6BA216934D9E31030E620';
    
    //Your Destination org username
    String username='sfdc338@gmail.com';
    
    //Your Destination orgPassword+Security Token
    String password='sohel42011BW2rEx55O33yFxYkfc8QLOv2';
    
    String accesstoken_url='https://login.salesforce.com/services/oauth2/token';
    String authurl='https://login.salesforce.com/services/oauth2/authorize';
    
    public class deserializeResponse {
        public String id;
        public String access_token;
    }
    public String ReturnAccessToken(RestAccessToken Acc){
        String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password;
        Http h= new Http();
        HttpRequest req= new HttpRequest();
        req.setBody(reqbody);
        req.setMethod('POST');
        //Change "ap4" in url to your Destination Org Instance
        req.setEndpoint('https://sohel-sf-dev-ed.my.salesforce.com/services/oauth2/token');
        HttpResponse res=h.send(req);
        System.debug(res.getBody()+'By-AP-1986-Response');
        deserializeResponse resp1= (deserializeResponse)JSON.deserialize(res.getBody(),deserializeResponse.class);
        System.debug(resp1+'By-AP-deserializeresponse');
        System.debug(resp1.access_token+'Access token');
        return resp1.access_token;
    }
    
}

////////////

public class CalloutForRestInboundWebService {

    @future(callout=true)
    public static void createAccount(String accName, String accPhone, String accWebsite){
           RestAccessToken acc1= new RestAccessToken();
    String accessToken=acc1.ReturnAccessToken(acc1);
        Httprequest req=new httprequest();
         Http http = new Http();
        String endPointURL='https://sohel-sf-dev-ed.my.salesforce.com/services/apexrest/Account10/';
        req.setendpoint(endPointURL);
        req.setHeader('Content-Type', 'application/xml; charset=utf-8');
        req.setBody('<?xml version="1.0" encoding="UTF-8" ?><request><name>'+accName+'</name><phone>'+accPhone+'</phone><website >'+accWebsite+'</website > </request>');
        req.setmethod('POST');
       
        req.setHeader('Authorization','Authorization: Bearer '+accessToken);
       system.debug('Access token @@@@@@@------->'+accessToken);
        String response;
        HTTPResponse res = http.send(req);
        response=res.getbody();
        System.debug('****************res.getStatusCode();'+res.getStatusCode());
        System.debug('****************res.getbody();'+res.getbody());
        //return null;
    }
}

///////////////

trigger CalloutForRestInboundWebService_Trigger on Account (before insert) {

    for(Account acc: Trigger.new){
        CalloutForRestInboundWebService.createAccount(acc.Name, acc.Phone, acc.Website);
    }
}