function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Rst123Rst123 

Test class coverage Issue...

 I have written a test class for my class but its not covering the class....i'm new to it.can you help me in test class i have written

@isTest
private class TestABC {

    static testMethod void specialReplaceAmpersandTest() {
        String testString = 'test&replacement';
        String resultString = 'test%26replacement';
        System.assertEquals(Utility.specialReplaceAmpersand(testString),resultString);
       
    }
   
    static testMethod void urlEncodeTest()
    {
        String testString = 'test&url%encode%test';
        String resultString = 'test%26url%25encode%25test';
       
        System.assertEquals(Utility.urlEncode(testString),resultString);
    }
   
    static testMethod void differentiateListsTest()
    {
        List<String> masterList = new List<String>();
        masterList.add('Element1');
        masterList.add('Element2');
        masterList.add('Element3');
        List<String> childList = new List<String>();
        childList.add('Element2');
        List<String> resultList = new List<String>();
        resultList.add('Element1');
        resultList.add('Element3');
       
        System.assertEquals(Utility.differentiateLists(masterList,childList),resultList);
       
    }
   
    static testMethod void substractSetTest()
    {
        Set<String> set1 = new Set<String>();
        set1.add('Element1');
        set1.add('Element2');
        set1.add('Element3');
        Set<String> set2 = new Set<String>();
        set2.add('Element2');
        Set<String> resultSet = new Set<String>();
        resultSet.add('Element1');
        resultSet.add('Element3');
        System.assertEquals(Utility.SubstractSet(set1,set2), resultSet);
    }
  
    Static testMethod void checkForNullTest()
    {
        String str1 = 'testStr1';
        String str2 = 'testStr2';
        String str3;
        Decimal decVal1 = 10.0;
        Decimal decVal2 = 11.0;
        Decimal decVal3;
        Integer intVal1 = 10;
        Integer intVal2 = 11;
        Integer intVal3;
        Boolean bool1 = true;
        Boolean bool2 = false;
        String str4 = 'T' ;
        Date dt1 = system.today();
        Date dt2 = system.today() + 1;
        Date dt3;
        DateTime datTime1 = DateTime.now();
        DateTime datTime2 = DateTime.now() + 1;
        DateTime datTime3;
       
        system.assertEquals(Utility.checkForNull(str1,str2),str2);
        system.assertEquals(Utility.checkForNull(str1,str3),str1);
        system.assertEquals(Utility.checkForNull(decVal1,decVal2),decVal2);
        system.assertEquals(Utility.checkForNull(decVal1,decVal3),decVal1);
        system.assertEquals(Utility.checkForNull(intVal1,intVal2),intVal2);
        system.assertEquals(Utility.checkForNull(intVal1,intVal3),intVal1);
        system.assertEquals(Utility.checkForNull(bool1,bool2),bool2);
        system.assertEquals(Utility.checkForNull(bool1,str4),bool1);
        system.assertEquals(Utility.checkForNull(dt1,dt2),dt2);
        system.assertEquals(Utility.checkForNull(dt1,dt3),dt1);
        system.assertEquals(Utility.checkForNull(datTime1,datTime2),datTime2);
        system.assertEquals(Utility.checkForNull(datTime1,datTime3),datTime1);
       
    }
   
   static testMethod void getPhoneEscapedTest()
   {
    String FullNumber = '203-000-007x2345';
    String phoneNumber = '203000007';
    String extension = '2345';
    System.assertEquals(Utility.getPhoneEscaped(FullNumber,true),phoneNumber);
    System.assertEquals(Utility.getPhoneEscaped(FullNumber,false),extension);
   }
  
   static testMethod void testEncrypt()
   {
    String Value = '003M0000008tN30';
    String Test = 'JiW2d9ABjkbJ15c0jFQg7g%3D%3D'; 
    System.assertEquals(Utility.EncryptId(Value),Test);
   }
  
   static testMethod void testEncryptIdB64()
   {   
    String Value = '003M0000008tN30';
    String Test = 'JiW2d9ABjkbJ15c0jFQg7g==';
    System.assertEquals(Utility.EncryptIdB64(Value),Test);
   }
  
   static testMethod void testsaveMultipleLogsToDataStore()
   {   
         integer TEST_SIZE = 5 ;
         String [] idList = new String[0] ;
         String [] strList = new String[0] ;
         List<Account> aList = new List<Account>() ;
         for (integer i=0 ;i < TEST_SIZE ;i++){
            Account testAccount = new Account(Name='Test Account',Request_Merge__c = TRUE,Account_Merge_Details__c='Test Detail');
            aList.add(testAccount) ;
         }
         insert aList;
        
         for (Account a:aList)
            idList.add(a.Id) ;
        
         for (integer i=0 ;i < TEST_SIZE ;i++){
            String str = '' ;
            for (integer k=0 ; k < 700;k++)
                 str+='AAAAAAAAAAAA ' ;
            System.debug('--- ' + str.length());    
            strList.add(str) ;
         }
        Test.startTest() ;
        System.debug('ID List size : ' + idList.size() + '  StringList size:  ' + strList.size());
        Utility.saveMultipleLogsToDataStore(idList, 'Test', strList) ;
        Integer count = [select count() from Data_Store__c where Parent_Object__c = 'Test'] ;
        System.assertEquals(TEST_SIZE*2, count) ; // String is going to be split into 2
        Test.stopTest();
       
   }
  
   static testMethod void testcheckLimits(){
         integer TEST_SIZE = 1 ;
         List<Account> aList = new List<Account>() ;
         for (integer i=0 ;i < TEST_SIZE ;i++){
            Account testAccount = new Account(Name='Test Account'+i,Request_Merge__c = TRUE,Account_Merge_Details__c='Test Detail'+i);
            aList.add(testAccount) ;
         }
         insert aList;
        
         String debugX = '******* Test log' ;
        
         debugX = Utility.checkLimits(debugX) ;
                 
         System.assertEquals(debugX.indexof('RESOURCE USAGE')>0, true) ;
               
   }
}

Rst123Rst123
=============CLASS PArt-1 ==========================


public with sharing class ABC{

    public static boolean isOwnerUpdate;
    public static boolean IsStageChange;
   
    public static string debuglog='';
    public static Map<String,String> ConstextVariables=new Map<String,String>();
   
    public static void log(string classname, String str){
        debuglog += System.now().format('[yyyy-MM-dd HH:mm:ss.SSS]')+'('+classname+') '+ str + '\n';
        system.debug(logginglevel.info,'('+classname+') '+ str);       
    }
    public static String getDebugLog(){
        return debuglog;
    }
   
   
    //Replaces & in string with the special character %26. Required while displaying picklist values with &
    public static String specialReplaceAmpersand(String normalString){
       
      if (normalString.contains('&')){
        normalString = normalString.ReplaceAll( '&', '%26' );
      }
     
      return normalString;
   
    }
   
    public static String urlEncode(String normalString){
      if(normalString==null){
          return null;
      }
     //conversion of % to url code should always happen first  
      if (normalString.contains('%')){
        normalString = normalString.ReplaceAll( '%', '%25' );
      }     
     //--------------------------------------------------------
      if (normalString.contains('&')){
        normalString = normalString.ReplaceAll( '&', '%26' );
      }
       
      return normalString;
   
    }
   
    /*This utility method returns the items which are present in list master list but not in child list*/
    public static list<String> differentiateLists(list<String> masterList, list<String> childList){
        list<String> onlyInL1=new list<String>();
        String l2elementString='';
       
        if(childList.size()>0){
            for(String l2element:childList){
                l2elementString+=l2element+';';
            }
        }else{
            return masterList;
        }
       
        system.debug('Elements in second list='+l2elementString);
       
        if(masterList.size()>0){
            for(String l1element:masterList){
                if(!l2elementString.contains(l1element)){
                    system.debug(l1element+' from first list argument not in second list argument');
                    onlyInL1.add(l1element);                   
                }          
            }
        }else{
            return null;
        }
       
        return onlyInL1;       
    }
   
    public static Set<String> SubstractSet(set<String> setA,set<String> setB){
        set<String> result=new set<String>();
        for(String e:setA){
            if(!setB.contains(e) && e!=null){
                result.add(e);
            }
        }
        return result;     
    }
   
    public static String checkForNull(String fieldVal, String tagVal){
        if(tagVal==null){
            return fieldVal;
        }
        return tagVal;
    }
   
     public static Decimal checkForNull(Decimal fieldVal, Decimal tagVal){
        if(tagVal==null){
            return fieldVal;
        }
        return tagVal;
    }
   
     public static Integer checkForNull(Integer fieldVal, Integer tagVal){
        if(tagVal==null){
            return fieldVal;
        }
        return tagVal;
    }
   
     public static Date checkForNull(Date fieldVal, Date tagVal){
        if(tagVal==null){
            return fieldVal;
        }
        return tagVal;
    }
     public static Datetime checkForNull(Datetime fieldVal, Datetime tagVal){
        if(tagVal==null){
            return fieldVal;
        }
        return tagVal;
    }

    public static boolean checkForNull(Boolean fieldVal, String tagVal){
        return tagVal!=null && (tagVal=='Y' || tagVal=='1' || tagVal=='T');
    }

    public static boolean checkForNull(Boolean fieldVal, Boolean tagVal){
        return tagVal!=null && tagVal;
    }
   
    public static string getPhoneEscaped(String FullNumber, boolean getMain){
        system.debug('Full Number='+FullNumber);
        if(FullNumber==null){
            return null;
        }
       
        FullNumber=FullNumber.replaceAll('-','');
        FullNumber=FullNumber.replaceAll(' ','');
        FullNumber=FullNumber.replaceAll('\\)','');
        FullNumber=FullNumber.replaceAll('\\(','');
        FullNumber=FullNumber.replaceAll('\\+','');
       
       
        String mainNumber=null;
        String extension=null;

        String extensionMarker1='extn';
        String extensionMarker2='x';
       
        String[] splits=FullNumber.split(extensionMarker1);
        if(splits.size()==2){
            mainNumber=splits[0];
            extension=splits[1];
        }else{
            splits=FullNumber.split(extensionMarker2);
            if(splits.size()==2){
                mainNumber=splits[0];
                extension=splits[1];
            }else{
                mainNumber=FullNumber;
            }
        }
        if(mainNumber!=null){
            system.debug('Main phone number:'+mainNumber);
        }
        if(extension!=null){
            system.debug('Extension number:'+extension);
        }
       
        if(getMain){
            return mainNumber;
        }else{
            return extension;
        }
    }
  
   public static String encrypt(String value){
        String retValue = null;
        if(value!=null){    
             retValue = EncodingUtil.base64Encode(Blob.valueOf(value));
        }
        return retValue;
   }
  
   public static String decrypt(String value){
       String retValue = null;
       if(value!=null){
             try{
                retValue = EncodingUtil.base64Decode(value).toString();
             } catch(Exception e){
               System.debug('Exception in decoding '+e);
               retValue = null;
             }
       }
       return retValue;
   }
  
   public static String removeValueforTag(String xml,String tag){
         String removedString = xml;
         if(xml!=null && xml!=''){
           Integer startPoint = 0;
           String startTag='<'+tag+'>';
           String endTag='</'+tag+'>';
           while(removedString.indexOf(startTag, startPoint)>-1){
            
             Integer startReplace = removedString.indexOf(startTag, startPoint);
             Integer endReplace = removedString.indexOf(endTag, startPoint);
             String replaceStr=removedString.substring(startReplace + startTag.length(), endReplace);
             removedString = removedString.replace(replaceStr, '**REMOVED**');
             startPoint=endReplace+endTag.length();
           }
         }
         return removedString;
   }
  
   public static String removeValueforTags(String xml,String tags){
         String workedXml = xml;
         if(tags!=null && tags!=''){
             for(String tag:tags.split('#')){
              workedXml = removeValueforTag(workedXml,tag);
             }
         }
         return workedXml;
   }
  
   public static String removeValueforTags(String xml,String tags, String namespace){
        String workedXml = xml;
        if(tags!=null && tags!=''){
            for(String tag:tags.split('#')){
               workedXml = removeValueforTag(workedXml,namespace+':'+tag);
            }
        }
       
        return workedXml;
   }
  
   //Splits traget strings on the delimiter and returns a list of those values
   public static list<String> getValList(String valString, String delimiter){
        system.debug('String='+valString);
        system.debug('Delimiter='+delimiter);
       
        list<String> valList=new List<String>();   
   
        if(valString!=''||valString!=null){
            valList=valString.split(delimiter);
        }
       
        system.debug(valList.size()+' values extracted from string');
        return valList;    
   }
  
   // Calculates the distance between 2 points.. Inputs in signed decimal degrees with '-' indicating S/W
   public static String getDistance(Decimal ilat1,Decimal ilon1, Decimal ilat2, Decimal ilon2) {
        Decimal R = 3963.1; // miles
        Decimal PI = 3.1428571 ;
        Decimal RD_PI = PI.divide(180,6) ;

        Decimal dLat = (ilat2-ilat1)* RD_PI ;
        Decimal dLon = (ilon2-ilon1) * RD_PI;
        Decimal lat1 = ilat1 * RD_PI;
        Decimal lat2 = ilat2 * RD_PI;

        Decimal a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
        Decimal c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        Decimal d = R * c;
       
        return d.format() ;
   }
  
  
   static User currentUser=[Select Profile.Name from User where Id=:Userinfo.getUserId()];
   static String[] extensions=Lookup.getTarget('Attachment','Type','Excluded',false).toUpperCase().split(',');
  
   public static boolean IsFileTypeAllowed(string filename){
        if(filename==null){
            throw new CustomException('File Name must be specified');
        }
        for(String x:extensions){
            if (filename!=null && filename.toUpperCase().endsWith('.'+x) && currentUser.Profile.Name!='GE Integration User'){
                return false;
            }
        }
        return true;
   }
  
    public static boolean IsBlank(string s){
        return s==null || s=='';  
    }
   
   
    public static string UpsertResultToString(Database.UpsertResult result){
        return UpsertResultsToString(new Database.UpsertResult[]{result});
    }
   
    public static string UpsertResultsToString(Database.UpsertResult[] results){
        string s='ID\tIs Success\tIs Created\tErrors\n';
        for(Database.UpsertResult result:results){
            s+=result.getId()+'\t'+result.isSuccess()+'\t'+result.isCreated()+'\t'+DBErrorsToString(result.getErrors())+'\n';
        }
        return s;
    }
  
    public static string DBErrorsToString(Database.Error[] errors){
        string s='';
        for(Database.Error e:Errors){
            s+='['+e.getStatusCode()+']'+e.getMessage()+';';
        }
        return s;  
    }  
    /*
    *   Purpose: test whether the value matches with regx expression
    */
    public static boolean CheckRestriction(string regx,string value){
        String v=value;
        if(value==null){
            v='';
        }
        return Pattern.matches(regx, v);
    }

    public static String EncryptId(String ObjectId){
        String privateKey=Lookup.getTarget('AccessGE', 'UpdateContact', 'PrivateKey', true);
        String b64 = EncodingUtil.base64Encode(Crypto.encrypt('AES128',Blob.valueOf(privateKey),Blob.valueOf(privateKey),Blob.valueOf(objectId)));
        return EncodingUtil.urlEncode(b64,'UTF-8');
    }
   
     public static String EncryptIdB64(String ObjectId){
        String privateKey=Lookup.getTarget('AccessGE', 'UpdateContact', 'PrivateKey', true);
        String b64 = EncodingUtil.base64Encode(Crypto.encrypt('AES128',Blob.valueOf(privateKey),Blob.valueOf(privateKey),Blob.valueOf(objectId)));
        return b64;
    }
   
    public static String decryptId(String encryptedvalue){
        String intermediateValue = EncodingUtil.urlDecode(encryptedvalue,'UTF-8') ;
        Blob base64decode=EncodingUtil.base64Decode(intermediateValue);
        String privateKey=Lookup.getTarget('AccessGE', 'UpdateContact', 'PrivateKey', true);
        return Crypto.decrypt('AES128',Blob.valueOf(privateKey),Blob.valueOf(privateKey),base64decode).toString();       
    }
Rst123Rst123
=======Contd . CLASS  part-2 ========================


// Currency Code changes for LAEF Mexico
    //Block Start
    public static Map<String,Double> getRecentCurrencyRate(){
          
        List<CurrencyType> currencyList=new List<CurrencyType>();
        //Audit Cleanup: We only consider the active currencies. We can add this 'where' clause WLOG.
        currencyList=[Select c.IsoCode, c.ConversionRate From CurrencyType c where c.isActive=true];
        Map<String,Double> currencyMap=new Map<string,Double>();
        for(CurrencyType currencyVar : currencyList) {
            currencyMap.put(currencyVar.IsoCode,currencyVar.ConversionRate);
        }

        return currencyMap;
    }

    public static Decimal convertCurrency(String sourceCurrency, String targetCurrency,
                                        Map<String,Double> currencyMap, Decimal valueToConvert){
      
        if(currencyMap == null){
            currencyMap=getRecentCurrencyRate();
        }

        //Convert to USD
       Decimal valueUSD = valueToConvert;
       if(!'USD'.equalsIgnoreCase(sourceCurrency)){
            Double exchangeRateUSD = currencyMap.get(sourceCurrency);
            valueUSD = valueToConvert/exchangeRateUSD;
       }
      
        //Convert to Target
        Decimal value = valueUSD;
        if(!'USD'.equalsIgnoreCase(targetCurrency)){
            Double exchangeRateTarget = currencyMap.get(targetCurrency);
            value = valueUSD*exchangeRateTarget;
        }
      
        return value;
    }
    //Case #: 00014738:CF Currency Code changes for LAEF Mexico
    //Block End
  
  
    public static string getGECAStage(String SubSegment
                                , String RiskDecision
                                , String OppStageName
                                , Boolean value){
      
        Map<string,string> GECAStagevaluemap=new Map<string,string>();
        Integer counter=0;
        List<GECAStageMapping__c> GECAStagelist=null;
        Integer countermax=0;
      
        string rkey=SubSegment+':'+RiskDecision+':'+OppStageName;
        System.debug('GECAStageMapping.getGECAStage : rkey is ' + rkey);
        if(GECAStagelist==null){
            GECAStagelist=GECAStageMapping__c.getall().values();
            countermax=GECAStagelist.size();
        }
        if(GECAStagevaluemap.keyset().contains(rkey)){
            return GECAStagevaluemap.get(rkey);
        }else{
            for(;counter<countermax;++counter){
                if(GECAStagevaluemap.put(GECAStagelist[counter].Segment__c+':'+GECAStagelist[counter].Risk_Decision__c+':'+GECAStagelist[counter].SFDC_Sales_Stage__c,GECAStagelist[counter].GECA_Stage__c)==null
                    && GECAStagevaluemap.keyset().contains(rkey)){
                    system.debug('GECAStage is : '+GECAStagelist[counter].GECA_Stage__c);
                    return GECAStagelist[counter].GECA_Stage__c;
                }
            }
        }
        if(value){
            throw new CustomException('GECA Stage value for SubSegment: '+SubSegment+' RiskDecision: ' + RiskDecision + ' OppStageName: ' + OppStageName +' not found');
        }
        return '';
     }
   
    public static String[] Split(String Message,Integer Size){
        string[] out=new string[0];
        /*if(Message!=null && Message.length()>0){
            if(Message.length()>Size){
                out.add(Message.substring(0,size));
                String rest=Message.substring(size);
                out.addAll(Split(rest,size));
            }else{
                out.add(Message);
            }
        }*/
        if(Message!=null){
            integer L=Message.length();
            for(integer i=0;i<=L-1;i=i+size){
                Integer e=i+size>L?L:i+size;
                out.add(message.substring(i,e));
            }
        }
        log('Split','No of splitted strings: '+out.size());      
        return out;
    }
       
    public static Id[] SaveStringToDataStore(String ObjectId,String ObjectName, String Request){
      
      
        Integer FieldSize = Data_Store__c.Data__c.getDescribe().getLength();
        System.debug(logginglevel.info,'Field size: '+FieldSize);
        String[] parts=Split(Request,FieldSize);
        System.debug(logginglevel.info,'Number of parts: '+parts.size());
      
        Data_Store__c[] dataRows=new Data_Store__c[0];
        for(Integer i=0;i<parts.size();++i){
            dataRows.add(new Data_Store__c(Parent_Id__c=ObjectId,Parent_Object__c=ObjectName,Data__c=parts[i],Index__c=i));
        }
        insert datarows;
        Id[] ids=new Id[0];
        for(Data_Store__c ds:datarows){
            ids.add(ds.Id);
        }
        return Ids;
    }
  
  
    public static void saveMultipleLogsToDataStore(String [] ObjectIds,String ObjectName, String [] Requests){
        List<Data_Store__c> dataRows=new List<Data_Store__c>();
      
        for (Integer k=0;k < ObjectIds.size();k++){
            String ObjectId = ObjectIds[k] ;
            String Request = (String)Requests[k];
            if (Request != null && Request.length() > 0){
                Integer FieldSize = Data_Store__c.Data__c.getDescribe().getLength();
                System.debug(logginglevel.info,'Field size: '+FieldSize);
                String[] parts=Split(Request,FieldSize);
                System.debug(logginglevel.info,'Number of parts: '+parts.size());
              
                for(Integer i=0;i<parts.size();++i){
                    dataRows.add(new Data_Store__c(Parent_Id__c=ObjectId,Parent_Object__c=ObjectName,Data__c=parts[i],Index__c=i));
                }
            }
        if (dataRows.size() > 0)
            upsert datarows;
        }
    }
  
  
    public Static String getStringFromDataStore(String ObjectId){
        String msg='';
        for(Data_Store__c ds:[SELECT Data__c FROM Data_Store__c where Parent_Id__c=:ObjectId Order By Index__c asc]){
            if(ds.Data__c!=null){
                msg+=ds.Data__c;
            }
        }
        return msg;
    }
  
    // sorts the value of option list
    public static List<SelectOption> SortOptionList(SelectOption[] ListToSort)
    {
        if(ListToSort == null || ListToSort.size() <= 1)
            return ListToSort;
          
        List<SelectOption> Less = new List<SelectOption>();
        List<SelectOption> Greater = new List<SelectOption>();
        integer pivot = ListToSort.size() / 2;
        
        // save the pivot and remove it from the list
        SelectOption pivotValue = ListToSort[pivot];
        ListToSort.remove(pivot);
      
        for(SelectOption x : ListToSort)
        {
            if(x.getLabel() <= pivotValue.getLabel())
                Less.add(x);
            else if(x.getLabel() > pivotValue.getLabel()) Greater.add(x); 
        }
        List<SelectOption> returnList = new List<SelectOption> ();
        returnList.addAll(SortOptionList(Less));
        returnList.add(pivotValue);
        returnList.addAll(SortOptionList(Greater));
        return returnList;
    } 

    //Email Validation function
    //Added during AccessGE 2.0 implementation
    public static Boolean validateEmail(String emailAddress){
      
        if(isBlank(emailAddress)){
            return false;
        }
        //The (tweaked) version of RFC 2822 regex for email address validation
        String emailRegex = '(?:[a-zA-Z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&\'*+/=?^_`{|}~-]+)*|"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*")@(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-zA-Z0-9-]*[a-zA-Z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])';
        //String emailRegex = '([a-zA-Z0-9_\\-\\.]+)@((\\[a-z]{1,3}\\.[a-z]{1,3}\\.[a-z]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})';
        Pattern emailPattern = Pattern.compile(emailRegex);

        Matcher emailMatcher = emailPattern.matcher(emailAddress);
        return emailMatcher.matches();
    }
  
    //Validation Alpha Numeric function
    //Added during AccessGE 2.0 implementation
    public static Boolean validateAlphaNumeric(String alphaNumeric){
      
        if(isBlank(alphaNumeric)){
            return false;
        }
        String emailRegex = '^[a-zA-Z0-9]([a-zA-Z0-9. -]*)';
        Pattern emailPattern = Pattern.compile(emailRegex);

        Matcher emailMatcher = emailPattern.matcher(alphaNumeric);
        return emailMatcher.matches();
    }
Rst123Rst123
=======Contd . CLASS  part-3 ========================

//Convert DateTime to Date
    //Added during AccessGE 2.0 implementation
    public static Date dateTimeToDate(DateTime dt){
      
        if(dt == null)
            return null;
        return Date.newInstance(dt.year(),dt.month(),dt.day());
    }

    //Get a list of picklist values from an existing object field.
    //Added during AccessGE 2.0 implementation
    public static List<SelectOption> getPicklistValues(SObject obj, String fld){

        List<SelectOption> options = new List<SelectOption>();
        // Get the object type of the SObject.
        Schema.sObjectType objType = obj.getSObjectType();
        // Describe the SObject using its object type.
        Schema.DescribeSObjectResult objDescribe = objType.getDescribe();     
        // Get a map of fields for the SObject
        Map<String,Schema.sObjectField> fieldMap = objDescribe.fields.getMap();
        // Get the list of picklist values for this field.
        List<Schema.PicklistEntry> values = fieldMap.get(fld).getDescribe().getPickListValues();
        // Add these values to the selectoption list.
        for (Schema.PicklistEntry a : values){
           
            options.add(new SelectOption(a.getLabel(), a.getValue()));
        }
        return options;
   }

  
    //Function to return the day of the date
    public static String DayofDate(String DateType){
        String Dayofweek = '';
        if(DateType == 'ActivityDate'){
            Datetime dt = DateTime.newInstance(System.Today()+5, Time.newInstance(0, 0, 0, 0));
            Dayofweek=dt.format('EEEE');
        }
      
        if(DateType == 'ReminderDateTime'){
            Datetime dt = DateTime.newInstance(System.Today()+10, Time.newInstance(0, 0, 0, 0));
            Dayofweek=dt.format('EEEE');
        }
      
        return Dayofweek;
    }
  
    // Method to Truncate

    public static String truncate(String value, Integer charaters){
        if(value!=null && value.length()>charaters){
            value = value.trim();
            value = value.substring(0,charaters);
        }
        return value;
    }   
  
    //Start of changes for  Truncate Pricing fields when Negative 
    public static Decimal truncate(Decimal value, Integer digits){
      
        if(value!= null && digits!=null && String.valueOf(value).length()>digits){
            value = value.stripTrailingZeros();
        }
        /*
        if(value!= null && String.valueOf(value).length()>digits){
            Integer scale = value.scale();
            Integer newscale = scale;
            Integer precision = value.precision();
            if(value<0 && digits>2 && scale>0){
                newscale = digits-precision+scale-2;
            } else if(digits>1){
                newscale = digits-precision+scale-1;
            }
            value = value.setScale(newscale);
        }*/
      
        if(value!= null && digits!=null){
        String svalue= String.valueOf(value);
            if(svalue.length()>digits)
            {
            //String sd1= String.valueOf(d1);
            List<String> svalueparts= svalue.split('\\.');
              if(svalueparts[0].length()>=digits)
              {
                 value = value.round();
              }
              else{
                    Integer i=svalueparts[0].length();
                    Integer newscale= digits-i-1;
                    value = value.setScale(newscale);
                  }
           }
        }
        return value;
    
    }
  
    private static String printLimits(Integer actualCount, Integer limitCount, String limitname){
        double govLimit = 0.8 ;
        String log = '' ;

        if (limitCount == 0)
            return '' ;
          
        double callLimit = double.valueOf(actualCount)/double.valueOf(limitCount) ;
        log = limitname + ': ' + callLimit * 100 + ' % ( '+ actualCount + ' of ' + limitCount +'  ) used \n' ;
       
        if (callLimit > govLimit){
            log += 'WARNING - LIMIT BREACH !!!!!  \n' ;
        }

        return log ;
      
    }
  
     //End of changes for Truncate Pricing fields when Negative
    // End of Methods to Truncate Number Case - 24513
  
    public static String checkLimits(String mainLog){
        String log = '' ;
        log += '\n\n**** RESOURCE USAGE ****\n ' ;
        log += '------------------------------------------------------------- \n ' ;
      
        log += printLimits(Limits.getScriptStatements(),Limits.getLimitScriptStatements(),'Script Statements') ;
        log += printLimits(Limits.getHeapSize(),Limits.getLimitHeapSize(),'Heap Size Limit') ;
        log += printLimits(Limits.getQueries(),Limits.getLimitQueries(),'SOQL Query Limit') ;
        log += printLimits(Limits.getQueryRows(),Limits.getLimitQueryRows(),'SOQL Query Rows Returned') ;
        log += printLimits(Limits.getSoslQueries(),Limits.getLimitSoslQueries(),'SOSL Query Limit') ;
        log += printLimits(Limits.getAggregateQueries(),Limits.getLimitAggregateQueries(),'Aggregate Queries') ;
        log += printLimits(Limits.getCallouts(),Limits.getLimitCallouts(),'Callouts') ;
        log += printLimits(Limits.getCpuTime(),Limits.getLimitScriptStatements(),'CPU Time') ;
        log += printLimits(Limits.getDMLRows(),Limits.getLimitDMLRows(),'DML Rows Count') ;
        log += printLimits(Limits.getDMLStatements(),Limits.getLimitDMLStatements(),'DML Statements') ;
        log += printLimits(Limits.getFutureCalls(),Limits.getLimitFutureCalls(),'Future Calls') ;
      
        log += '------------------------------------------------------------- \n' ;
      
        if (mainLog != null)
            mainLog += log ;          

        debuglog += log ;
        System.debug(log) ;
      
        return mainLog ;  
    }
  
    //This Method returns the recordtype list of objects
    public static Map<Id,String> GetRecordType(String ObjName){
        Map<Id,String> RTName = new Map<Id,String>();
        Schema.SObjectType targetType = Schema.getGlobalDescribe().get(ObjName);
        SObject obj = targetType.newSObject();
        Schema.DescribeSObjectResult d = obj.getSObjectType().getDescribe();
        map<String,Schema.RecordTypeInfo> rtypename = d.getRecordTypeInfosByName();
        for(Schema.RecordTypeInfo s: rtypename.values()){
            RTName.put(s.getRecordTypeId(),s.getName());
        }
        return RTName;
     }
   
     //This Method checks the trigger if active and returns boolean value
     public static boolean CheckTriggerIsActive(String TriggerName){
        Boolean isActive = true;
         if(!IsBlank(TriggerName)
          && TriggerActiveController__c.getInstance(TriggerName)!=null
           && TriggerActiveController__c.getInstance(TriggerName).IsActive__c!=null){
             isActive = TriggerActiveController__c.getInstance(TriggerName).IsActive__c;
         }
         return isActive;
     }
   
      // HFS Project Change
      /**
      *This method reformats the date to yyyy-mm-dd format.
      **/
     public static String dateformat(Date dt){
        String strDate;
        String mon;
        String day1;
        if(dt == null)
            return null;
          
        if(dt.month()<=9) mon='0'+dt.month();
        else
            mon=String.valueof(dt.month());       
        if(dt.day()<=9) day1='0'+dt.day();
        else
            day1=String.valueof(dt.day());        
        strDate=dt.year()+'-'+mon+'-'+day1;             
        return strDate;
    }
}