Monday, August 10, 2015

Convert Salesforce time into 24 hour clock time

Before passing the parameter check wheather the parameter contains 'PM' or not.
You can use String.valueOf(date).contains('PM')
    public static String getPMTime(String timeToConvertToPm)
{
    System.debug('>>>>>>>>>><><><><><><><><><><><>timeToConvertToPm'+timeToConvertToPm);
    decimal x= decimal.valueOf((timeToConvertToPm.subStringBefore(' ')).replace(':','.'));
    if(!timeToConvertToPm.subStringBefore(':').contains('12')){
      x=x+12;
    }
    String newTime=String.valueOf(x);
     newTime=newTime.replace('.',':');
    System.debug('>>>>>>>>>><><><><><><><><><><><>newTime'+newTime);
    return newTime;
  }


Wednesday, August 5, 2015

TurboBridge integration with salesforce

Requirements :

The client wanted to add a member to campaign and when this happens the contact who's addedas a campainMember should create a dial-in-pin for a conference bridge so that a contact can dial in the bridge number and join a conference 


Step 1 : The Trigger

This trigger calls the helper class method 
/* 
* Name          : TriggerOnCampainMember
* Author        : 
* Description   : Trigger to update CampaignMember.
*
* Maintenance History: 
* 03/06/2015 - Piyush Singhal - 2.0 - Created  
* 
*/
trigger TriggerOnCampainMember on CampaignMember (after update,after insert,before insert) {
 if(trigger.isAfter){
     // Version 2.0 Start
     if(trigger.isInsert){
         TriggerHelper.createBridgePinForValidCampainMenmbers(trigger.newmap);
     }
     // Version 2.0 End
     
 }
 
}

Step 2 : The Helper Class 

The Helper class method createBridgePinForValidCampainMenmbers(trigger.newmap);
    /* 
        * Description   : Method to run batch class when campain members are inserted in a campain.
        * Param 1       : mapOfCampainMembers(map of inserted campain records)
        * Created       : Created with version 2.0
        */
        public static void createBridgePinForValidCampainMenmbers(map<id,CampaignMember> mapOfCampainMembers){
            list<CampaignMember> listOfCampainMembers = new list<CampaignMember>();
            listOfCampainMembers = [SELECT Id,Contact.Dial_in_Unique_PIN__c,Campaign.RecordTypeID FROM CampaignMember WHERE id IN:mapOfCampainMembers.keyset()];
            RecordType RecordTypeId = [SELECT id,name,SobjectType from RecordType WHERE SobjectType ='Campaign' AND name = ' Events' Limit 1];
            list<string> listOfContactId = new list<string>();
            for(CampaignMember eachCM:listOfCampainMembers){
                system.debug('eachCM11111111'+eachCM);
                if((eachCM.Contact.Dial_in_Unique_PIN__c ==null||eachCM.Contact.Dial_in_Unique_PIN__c =='') && eachCM.Campaign.RecordTypeID == RecordTypeId.id){
                    listOfContactId.add(eachCM.ContactId);
                } 
            }
            if(listOfContactId.size()>0){
                Database.executeBatch(new BatchClassToGetTurboBridgePin(listOfContactId),1);
            }
        }

Step 3 : The Batch Class 

The batch Class method BatchClassToGetTurboBridgePin(listOfContactId)
We are passing list of contactId to the constructor of the batch class
    /* 
* Name          : BatchClassToGetTurboBridgePin
* Author        : 
* Description   : Batch class to get TurboBridge pin for each contact.
* Test Class    : BatchClassGetTurboBridgePin_Test
* Maintenance History: 
* 10/06/2015 - Piyush Singhal - 1.0 - Created 
*/
global with sharing class BatchClassToGetTurboBridgePin implements Database.Batchable<sObject>,Database.AllowsCallouts,Database.stateful{
    global list<id> listOfContactId = new list<id>();
    global list<Contact> listOfContactToUpdate = new list <Contact>();
    global BatchClassToGetTurboBridgePin(List<id> listOfContact){
        listOfContactId = listOfContact       ;  
    }

    global Database.QueryLocator start(Database.BatchableContext BC){
        return DataBase.getQueryLocator([SELECT Id,FirstName,LastName,Title,name,Dial_in_Unique_PIN__c,RecordTypeId,Account.name,TB_ToUpdateNameInTB__c FROM Contact WHERE Id IN: listOfContactId]);
    }
    
    global void execute(Database.BatchableContext BC,List<sObject> scope){
        system.debug('Batch Class Execute');
        system.debug('Batch Class Execute'+scope);
        
        for(sObject Eachscope:scope){
            listOfContactToUpdate.add(TriggerHelper.insertUpdatePinInTurboBridge1((Contact)Eachscope));
            
        }
        
    }
    
    global void finish(Database.BatchableContext BC){
            try{
                update listOfContactToUpdate;
            }catch(Exception ex){
                System.debug('*****Excetion in batch class******'+ex);
            }
            system.debug('Batch Class Finish');
        }
}

Step 3 : The Callout method 1 - Getting last Inserted PIN

    /* 
    * Description   : Does a callout on turbobridge to get the last inserted pin.
    * Exception     : Handeling by try & catch
    * Created       : Created with version 2.0
    * Modification : Version 3.0 - updated the method to get the maximum number of inserted pin then
    *      do a callout again with a parameter offst to get the last inserted pin
    * Callouts      : 2
    * API Doc       : https://api.turbobridge.com/3.0/
    * Return        : Returns the last pin inserted on turbobridge as a string
    */
    public static string getLastInsertedPin(){
        
        AlgoWorks_TurboBridgeIntegration__c TB_variable = AlgoWorks_TurboBridgeIntegration__c.getValues('Value');
        System.debug('TB_variable'+TB_variable);
        String body = 'outputFormat=json';
        Integer offSetValue = 0 ;
        list<integer> listOfUserIdFromTB = new list<integer>();
        if(TB_variable != null){
         body = body +'&authAccountEmail='+TB_variable.TB_username__c;
         body = body +'&authAccountPassword='+TB_variable.TB_password__c;
         body = body +'&authAccountPartnerID=turbobridge';
         body = body +'&authAccountAccountID='+TB_variable.TB_accountId__c;
         body = body +'&requestType=getBridgeUserIDs';
         body = body +'&conferenceID='+TB_variable.TB_conferenceIdA__c;
        }
        
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://api.turbobridge.com/Bridge');
        req.setMethod('GET');    
        req.setBody(body);
        
        Http h = new Http();
        HttpResponse res;
        if(test.isRunningTest()){
         req.setEndpoint('https://www.google.com');
         res =new Httpresponse();
        }
        try{
            res = h.send(req);
        }catch(Exception ex){
            System.debug('*************Exception in callout*************'+ex);
        }
        if(!test.isRunningTest()){
         //System.debug('values'+res.getBody());
        }
        
        try{
            AlgoWorks_TurboBrigeResponse response = (AlgoWorks_TurboBrigeResponse)JSON.deserialize(string.valueOf(res.getBody()), AlgoWorks_TurboBrigeResponse.class);
            for (AlgoWorks_TurboBrigeResponse.requestItem ri : response.responseList.requestItem) {
               System.debug('Piyush Result'+ri.result.totalResults);
               offSetValue = ri.result.totalResults;
            }
        }catch(Exception ex){
            System.debug('**********Exception in deserializing the pin******** '+ex);
        }
        //Start Verion 3.0 Callout with offset
        body = body+'&startOffset='+string.valueOf(offSetValue-1)+'&';
        body = body+'resultCount=1000';
        system.debug('Piyush Body'+body);
        HttpRequest req2 = new HttpRequest();
        req2.setEndpoint('https://api.turbobridge.com/Bridge');
        req2.setMethod('GET');    
        req2.setBody(body);
        
        Http y = new Http();
        HttpResponse res2;
        if(test.isRunningTest()){
         req2.setEndpoint('https://www.google.com');
         res2 =new Httpresponse();
        }
        try{
            res2 = y.send(req2); 
        }catch(Exception ex){
            System.debug('*************Exception in callout*************'+ex);
        }
        if(!test.isRunningTest()){
         //System.debug('values'+res2.getBody());
        }
        try{
            AlgoWorks_TurboBrigeResponse response = (AlgoWorks_TurboBrigeResponse)JSON.deserialize(string.valueOf(res2.getBody()), AlgoWorks_TurboBrigeResponse.class);
            for (AlgoWorks_TurboBrigeResponse.requestItem ri : response.responseList.requestItem) {
               for (AlgoWorks_TurboBrigeResponse.bridgeUserID u : ri.result.bridgeUserID) {
                    listOfUserIdFromTB.add(integer.valueOf(u.userID));
                }
            }
        }catch(Exception ex){
            System.debug('**********Exception in deserializing the pin******** '+ex);
        }
        //End Version 3.0 Callout with offset
        
        
        listOfUserIdFromTB.sort();
        system.debug('listOfUserIdFromTB'+listOfUserIdFromTB);
        if(listOfUserIdFromTB.size()>0){
         return string.valueOf((listOfUserIdFromTB.get(listOfUserIdFromTB.size()-1))+1);
        }
        else{
         return null;
        }
         
    }

Step 3 : The Callout method 2 - Creating a pin for a bridge  

    /* 
    * Description   : Method to update ranking on campain members from Contacts.
    * Param 1       : contactToUpdate(list of contacts to add to turbobridge and update Pin)
    * Exception     : Handeling by try & catch
    * Created       : Created with version 1.0
    * Callouts      : 1
    * API Doc       : https://api.turbobridge.com/3.0/
    * Return        : returns the updated contact with the pin
    */
    public static Contact insertUpdatePinInTurboBridge1(Contact contactToUpdate){
            Contact con = contactToUpdate;
            system.debug('***TriggerClass**up*'+con.Dial_in_Unique_PIN__c+'>>>>>>>>>>>>>>>'+contactToUpdate);
            Database.SaveResult results ;
            RecordType contactRecordType = [SELECT id,name,SobjectType from RecordType WHERE SobjectType ='Contact' AND name = 'Industry Participant' Limit 1];
            AlgoWorks_TurboBridgeIntegration__c TB_variable = AlgoWorks_TurboBridgeIntegration__c.getValues('Value');
            if(!con.TB_ToUpdateNameInTB__c || con.Dial_in_Unique_PIN__c==null || con.Dial_in_Unique_PIN__c == ''){
                con.Dial_in_Unique_PIN__c = getLastInsertedPin();
            }
            else{
                con.TB_ToUpdateNameInTB__c = false;
            }
            JSONGenerator gen = JSON.createGenerator(true);
            
            gen.writeStartObject();
                
            gen.writeFieldName('request');
            
            gen.writeStartObject();
                
            gen.writeFieldName('authAccount');
            
            gen.writeStartObject();
           
            System.debug('>>>>>>>>>>>>>>>TB_variable'+TB_variable);
             System.debug('>>>>>>>>>>>>>>>TB_variable.TB_username__c'+TB_variable.TB_username__c);
             gen.writeStringField('email', TB_variable.TB_username__c);
             gen.writeStringField('password', TB_variable.TB_password__c);
             gen.writeStringField('partnerID', 'turbobridge');
             gen.writeStringField('accountID', TB_variable.TB_accountId__c);
             gen.writeEndObject();
             
             gen.writeFieldName('requestList');
             gen.writeStartArray();
             
             gen.writeStartObject();
             gen.writeFieldName('setBridgeUserID');
             gen.writeStartObject();
             gen.writeStringField('conferenceID',TB_variable.TB_conferenceIdA__c);
             System.debug('>>>>>>>>>>>>>>>>>>>>>>>>>>contactToUpdate'+contactToUpdate);
             if(test.isRunningTest()){
              contactToUpdate.Dial_in_Unique_PIN__c='1';
             }
             gen.writeStringField('userID', contactToUpdate.Dial_in_Unique_PIN__c);
             gen.writeStringField('name', getValidNameForTurboBridgePin(contactToUpdate));
             gen.writeStringField('hostFlag',(contactToUpdate.RecordTypeId==contactRecordType.id?'1':'0'));
             gen.writeEndObject();
             gen.writeEndObject();
              
             gen.writeStartObject();
             gen.writeFieldName('setBridgeUserID');
             gen.writeStartObject();
             gen.writeStringField('conferenceID',TB_variable.TB__c);
             gen.writeStringField('userID', contactToUpdate.Dial_in_Unique_PIN__c);
             gen.writeStringField('name', getValidNameForTurboBridgePin(contactToUpdate));
             gen.writeStringField('hostFlag',(contactToUpdate.RecordTypeId==contactRecordType.id?'1':'0'));
             gen.writeEndObject();
             gen.writeEndObject();
             
             //setBridge
             gen.writeEndArray();
             
             gen.writeEndObject();
             gen.writeEndObject();  
            String generate = gen.getAsString(); 
            HttpRequest req = new HttpRequest();
            req.setEndpoint('https://api.turbobridge.com/Bridge');
            req.setHeader('Content-Type', 'application/json');
            req.setMethod('POST');    
            req.setBody(generate);
            Http h = new Http();
            HttpResponse res ;
            try{
                res = h.send(req);
            }catch(exception ex){
                System.debug('********Exception in callout************'+ex);
            }
            if(!test.isRunningTest()){
             System.debug(res.getBody());
            }
            system.debug('***TriggerClass***'+contactToUpdate.Dial_in_Unique_PIN__c);
            con.TB_ToUpdateNameInTB__c = false;
            return con;
        }
        
        /* 
        * Description   : Method to generate a name to be inserted in turbobridge.
        * Param 1       : contactVariable contact to be inserted in turbobridge.
        * Created       : Created with version 2.0
        * Return        : Returns the name to be inserted as string.
        */
        public static string getValidNameForTurboBridgePin(Contact contactVariable){
           return contactVariable.FirstName+' '+contactVariable.LastName+' '+' ('+contactVariable.Account.name+' - '+contactVariable.Title+')';
        }