Thursday, 15 November 2018

Nov_15th

*************************

/*
    Name               : AutomatedTestSetup_Controller
    Test class         : AutomatedTestSetup_Controller_Test
    Description        : For Automated Test class execution process(SP-684-Automate Test Classes execution in Salesforce Orgs)
    Created By         : Krishna yerru
    Created Date       : 23-Oct-2018

********************************************************************************************************************************
    Change Version   Name              Date                    Task/Case#                 Description
********************************************************************************************************************************

********************************************************************************************************************************     
*/


public with sharing class AutomatedTestSetup_Controller {

    public boolean hasScheduledJobs { get; set; }
    public boolean hasAbort { get; set; }
    public boolean hasemailpending { get; set; }
    public boolean isRunning { get; set; }
    public boolean isEmailing { get; set; } 
    public AutomatedTestSetup_Controller ATS { get; set; }
    public String DtValue {get; set; }
    public boolean showMessage {get;set;}
    public String showdatetime{get;set;}
    public String Staticstics{get;set;}
    public Decimal Percentage{get;set;}
    public String shddatetime {get;set;}
    public String ATRdetails {get;set;}
    public String PastATRdetails {get;set;}
    public List<CronTrigger> SchdjobsAdhoc{get;set;} 
    public List<CronTrigger> Schdjobs{get;set;}
    public String Jobstatus  {get;set;}
    public Automated_Test_Run__c AtrRecord  {get; set;}
    public Boolean isChecked { get; set; }
    public Boolean isCheckedRec { get; set; }
    public Boolean isAdhocChecked { get; set; }
    public Boolean isHomeChecked { get; set; }
    public Boolean reccurenceMsg;
    public Boolean AdhocMsg;
    //recurrence related
    public boolean hasRecScheduledJobs { get; set; }    
     id ATERecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Execution').getRecordTypeId();
     id ATEmailRecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Email Notification').getRecordTypeId();
     //MultipleAdhocJobs
    public string SelectedAdhocJobId { get; set; }

    public PageReference doInsert() {
        AdhocMsg=false;
       List<Automated_Test_Run__c> ATSrecrdsinsert=New List<Automated_Test_Run__c>();
        String ADrandomnumberis=generateRandomNumber();
        String ADScheduleNameis='AutoTestRunnerAdhoc_'+AtrRecord.Query__c +'_'+ADrandomnumberis;
        AtrRecord.Query__c=AtrRecord.Query__c;
        AtrRecord.Excluded_Classes__c=AtrRecord.Excluded_Classes__c;
        AtrRecord.Exclude_Managed_Packages__c=AtrRecord.Exclude_Managed_Packages__c;
        AtrRecord.Schedule__c=AtrRecord.Schedule__c;
        AtrRecord.Schedule_Name__c= ADScheduleNameis;
      
        AtrRecord.RecordTypeId=ATERecordTypeId;
        ATSrecrdsinsert.add(AtrRecord);
      
        Automated_Test_Run__c ATEemail = new Automated_Test_Run__c();
        ATEemail.Query__c=AtrRecord.Query__c;
        ATEemail.Emails__c=AtrRecord.Emails__c;
        ATEemail.Email_on_Pass__c=AtrRecord.Email_on_Pass__c;
        ATEemail.Schedule__c=AtrRecord.Schedule__c;
        ATEemail.Schedule_Name__c= ADScheduleNameis;
        ATEemail.RecordTypeId=ATEmailRecordTypeId;
        ATSrecrdsinsert.add(ATEemail);
        Savepoint sp = Database.setSavepoint();
        try{ 
            System.debug('AtrRecord.Schedule__c is***'+AtrRecord.Schedule__c);
            System.debug('AtrRecord.Schedule__c is***'+datetime.now());
            if(AtrRecord.Schedule__c>=datetime.now()){
                    scheduleJobs(AtrRecord.Schedule__c,ADScheduleNameis);
                    if(showMessage==false){
                        upsert ATSrecrdsinsert;               
                    }   
                }   else{
                    AdhocMsg=true;
                    ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.INFO,'Schedule Date Time Must be Greater than current time');
                    ApexPages.addMessage(myMsg);
                }           
        }
        catch(exception ex){
            Database.rollback(sp);          
        }
        
        PageReference pageRef;
        if(AdhocMsg==true){
            pageRef=null;
        }else if(AdhocMsg==false){
            GetATSRunDeatils();
            pageRef = new PageReference('/apex/AutomatedTestSetup');
            pageRef.setRedirect(true);
        }
      return pageRef;
       
            //return null;
    }
    public Automated_Test_Run__c getAtrRecord()
    {
        return AtrRecord;
    }
  
  
    public AutomatedTestSetup_Controller(ApexPages.StandardController controller) {       
        AtrRecord = (Automated_Test_Run__c)Controller.getRecord();
        this.ATS=ATS;      
        showMessage=false;
        ScheduledJobs();
        refreshHasScheduledJobs();     
        ShowAbortbutton();
        getPieData();
        Calculatepercentage();
        GetATSRunDeatils();
        EmailSendPending();
        //recurrence related
        System.debug('isCheckedRec value is1 '+isCheckedRec);
        //isCheckedRec=false;
        System.debug('isCheckedRec value is12is '+isCheckedRec); 
            if(isChecked==null){
             isCheckedRec = false;
             System.debug('isCheckedRec is ' +isCheckedRec);
         } 
        if(isAdhocChecked==null){
             isAdhocChecked = false;
             System.debug('isAdhocChecked is ' +isAdhocChecked);
         }   
             
        refreshHasRecrnsScheduledJobs();
    }    

    public void refreshHasScheduledJobs() {     
        integer jobCount = [SELECT count() FROM CronTrigger  where CronJobDetail.Name like '%AutoTestRunnerAdhoc%'];
        SchdjobsAdhoc=[SELECT CronJobDetail.Name,CreatedDate,TimesTriggered,NextFireTime,State FROM CronTrigger where CronJobDetail.Name like '%AutoTestRunnerAdhoc%' and State in('WAITING','ACQUIRED','EXECUTING')];
        if(SchdjobsAdhoc.size()>0){
            Jobstatus=SchdjobsAdhoc[0].State;
            if(SchdjobsAdhoc[0].NextFireTime!=null ){
            Datetime shddatetimeGSt=SchdjobsAdhoc[0].NextFireTime;
            Datetime gmt = shddatetimeGSt;
             String timeZone = UserInfo.getTimeZone().getID();
             Datetime GivenDateTime=shddatetimeGSt;// here you can user your dates e.g. createddate
              Datetime localdt=Datetime.valueOf(GivenDateTime);
              //showdatetime = string.valueOfGmt(local);
              shddatetime=localdt.format();
              }
              else if(Jobstatus!=null && Jobstatus!='') {
                  shddatetime='Test Scheduled Job Current State is '+Jobstatus;
              }
            }           
        hasScheduledJobs = jobCount !=0;         
    }
    public void GetATSRunDeatils() {
        List<String> Keywords=New List<String>();
        Keywords.clear();
        ATRdetails='';
        for(Automated_Test_Run__c atr: [select Query__c, Excluded_Classes__c,
                            Email_on_Pass__c, Exclude_Managed_Packages__c
                            from Automated_Test_Run__c
                            //where Active__c = true and RecordTypeId=:ATERecordTypeId order by createdDate DESC limit 1]){
                            where RecordTypeId=:ATERecordTypeId order by createdDate DESC limit 1]){
                        Keywords.add(atr.Query__c);                    
        }
        if(Keywords.size()>0){
            for(String kw:Keywords){
            ATRdetails+=kw;
            }
        }
    }

    public void ShowAbortbutton(){
        integer runCount = [select count() from Automated_Test_Run__c limit 1];
        List<Test_Runner_Job__c> RunningJobnm =[Select Name,Automated_Test_Run__c,CreatedDate From Test_Runner_Job__c order by CreatedDate desc limit 1];
        if(RunningJobnm.size()>0){
            integer TestexecrunCount = [select count() from ApexTestQueueItem WHERE Status IN ('Holding','Queued','Preparing','Processing') and ParentJobId=:RunningJobnm[0].Name];
            hasAbort = TestexecrunCount > 0;  
         }     
    }
  
    public void EmailSendPending(){
        List<Test_Runner_Job__c> runCountJob = [select id from Test_Runner_Job__c where Processed__c=false order by CreatedDate desc limit 1];
        hasemailpending = runCountJob.size()> 0;                 
    }

    public string getTestRunLink() {
        return '/' + Automated_Test_Run__c.SObjectType.getDescribe().getKeyPrefix();
    }
    public PageReference getHomeLink() {
        PageReference pageRef = new PageReference('/apex/AutomatedTestSetup');
                    pageRef.setRedirect(true);
                    return pageRef;
    }

    public AutomatedTestSetup_Controller() {
         Automated_Test_Run__c AtrRecord = new Automated_Test_Run__c();
         refreshHasScheduledJobs();
         ScheduledJobs();
         Calculatepercentage();
         ShowAbortbutton();
         EmailSendPending();
        System.debug('isCheckedRec value is1 '+isCheckedRec);
        //isCheckedRec=false;
        System.debug('isCheckedRec value is12is '+isCheckedRec);
        //click(); 
         if(isChecked==null){
             isCheckedRec = false;
             System.debug('isCheckedRec is ' +isCheckedRec);
         }
         if(isAdhocChecked==null){
             isAdhocChecked = false;
             System.debug('isAdhocChecked is ' +isAdhocChecked);
         }
        
    }
  
    public PageReference scheduleJobs(Datetime DtValue,String ADScheduleNameis) {
      
        System.debug('Date & Time is given***1'+DtValue);
        deleteCompletedJobs();
        Datetime gmt = DtValue;
        String timeZone = UserInfo.getTimeZone().getID();
        Datetime GivenDateTime=DtValue;// here you can user your dates e.g. createddate
         System.debug('GivenDateTime is***'+GivenDateTime);        
                Datetime local=Datetime.valueOf(GivenDateTime);
                System.debug('local is***'+local);
                Map <Integer,String> monthNumbers = new Map <Integer,String> {1=>'Jan', 2=>'Feb',3=>'Mar',4=>'Apr', 5=>'May', 6=>'Jun',7=>'Jul',8=>'Aug', 9=>'Sep', 10=>'Oct', 11=>'Nov', 12=>'Dec'};
                String TestShdmonth=monthNumbers.get(local.month());
                String strSchedule = '0 ' + local.minute() + ' ' +local.hour()+ ' ' + local.day()+ ' ' + TestShdmonth+ ' ? ' + ' ' + local.year();
                System.debug('***strSchedule***'+strSchedule);
                AutoTestRunner.setup(strSchedule,ADScheduleNameis);
                refreshHasScheduledJobs();            
                GetATSRunDeatils();
               
               
      
    return null;
    }

    public PageReference CancelJobs() {   
          //List<CronTrigger> jobsToAbort = [select id,Name from CronJobDetail where Name like 'AutoTestRunner%' and JobType = '7'];
          List<CronTrigger> jobsToAbort = [select Id from CronTrigger where CronJobDetail.JobType = '7' and CronJobDetail.Name like '%AdhocAutoTestRunner%'];
              if(jobsToAbort.size()>0){
                  for (CronTrigger job : jobsToAbort) {
                   System.abortJob(job.Id);
                   }
               }
               PageReference pageRef = new PageReference('/apex/AutomatedTestSetup');
                    pageRef.setRedirect(true);
                    return pageRef;
    }
  
    public PageReference AbortTestJobs() {  
        Test_Runner_Job__c RunningJobnm =[Select Name,Automated_Test_Run__c,CreatedDate From Test_Runner_Job__c order by CreatedDate desc limit 1];
        ApexTestQueueItem[] items = [SELECT Id FROM ApexTestQueueItem WHERE Status IN ('Holding','Queued','Preparing','Processing') and ParentJobId=:RunningJobnm.Name];
        if(items.size()>0){
                for(ApexTestQueueItem item: items) {
                    item.Status = 'Aborted';
                }
                update items;
           }
         email();
        PageReference pageRef = new PageReference('/apex/AutomatedTestSetup');
        pageRef.setRedirect(true);
        return pageRef;
    }
  
    public void deleteCompletedJobs(){
        List<CronTrigger> jobsToAbort = [select Id,State from CronTrigger where CronJobDetail.JobType = '7' and CronJobDetail.Name like '%TestRunner%' and State='DELETED'];
              for (CronTrigger job : jobsToAbort) {
               System.abortJob(job.Id);
               }     
    }

    public void email() {
        emailUnprocessedJobStatus();
        isEmailing = true;
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Confirm, 'Results processed and emailed'));
    }
  
    public static list<Messaging.SingleEmailMessage> emailUnprocessedJobStatus() {
          list<Test_Runner_Job__c> jobs = getUnprocessedJobs();     
          list<Messaging.SingleEmailMessage> messages =emailMethodStatus(jobs);    
              for (Test_Runner_Job__c job : jobs) {
                  job.Processed__c = true;
              }    
          update jobs;  
         return messages;
    }
 
   public static list<Test_Runner_Job__c> getUnprocessedJobs() {
        return [Select t.Name,
          t.Automated_Test_Run__r.Emails__c,
          t.Automated_Test_Run__r.Email_on_Pass__c,
          t.Automated_Test_Run__r.Name,
          t.Automated_Test_Run__c
          From Test_Runner_Job__c t where Processed__c = false];
   }

//Statistics part

    public Void Calculatepercentage() {
        PastATRdetails='';
        List<Test_Runner_Job__c> RunningJob =[Select Name,Automated_Test_Run__c,CreatedDate From Test_Runner_Job__c order by CreatedDate desc limit 1];
        if(RunningJob.size()>0){
                Automated_Test_Run__c PastATR=[select id,Query__c from Automated_Test_Run__c where id=:RunningJob[0].Automated_Test_Run__c order by createdDate DESC limit 1];
                PastATRdetails=PastATR.Query__c;
            integer TotalJobsis   =  [select count() FROM ApexTestQueueItem where ParentJobId=:RunningJob[0].Name];
            integer CompltedJobsis   =  [select count() FROM ApexTestQueueItem where Status IN ('Completed','Aborted') and ParentJobId=:RunningJob[0].Name];
                if((TotalJobsis>0)&& (CompltedJobsis>0)){
                Percentage=(CompltedJobsis*100)/TotalJobsis;
                System.debug('Total Jobs is'+TotalJobsis+ 'CompltedJobs' +CompltedJobsis+ 'Percentage is'+Percentage);
            }         
        }     
    }
    public List<PieWedgeData> getPieData() {
        List<PieWedgeData> data = new List<PieWedgeData>();  
        List<Test_Runner_Job__c> RunningJob =[Select Name,Automated_Test_Run__c,CreatedDate From Test_Runner_Job__c order by CreatedDate desc limit 1];
              if(RunningJob.size()>0){                 
                  integer CmpltdPass       = [select count() FROM ApexTestResult WHERE Outcome = 'Pass' and AsyncApexJobId=:RunningJob[0].Name];
                  integer Failed       = [select count() FROM ApexTestResult WHERE Outcome = 'Fail' and AsyncApexJobId=:RunningJob[0].Name];
                  integer Queuedjobs   = [select count() FROM ApexTestQueueItem where Status='Queued' and ParentJobId=:RunningJob[0].Name];
                  integer TotalJobs   =  [select count() FROM ApexTestQueueItem where ParentJobId=:RunningJob[0].Name];
                
                        if(Queuedjobs>0){
                        data.add(new PieWedgeData('In Progress'+' '+Queuedjobs, +Queuedjobs));
                        }if(CmpltdPass>0){
                        data.add(new PieWedgeData('Passed'+' '+CmpltdPass, +CmpltdPass));
                        }if(Failed>0){
                        data.add(new PieWedgeData('Fail'+' '+Failed, +Failed));
                        }
               }
        return data;
    }
    // Wrapper class
    public class PieWedgeData {
       public String name { get; set; }
       public Integer data { get; set; }
       public Integer CmpltdPass{ get; set; }
       public Integer Failed{ get; set; }
       public Integer Queuedjobs{ get; set; }
           public PieWedgeData(String name, Integer data) {
                this.name = name;
                this.data = data;
            }
    }
  
    public PageReference Refresh(){
        deleteCompletedJobs();
        Calculatepercentage();
        refreshHasScheduledJobs();
        if(Percentage==100){
                email();                  
            }else{
                hasScheduledJobs = true;
            }                     
        PageReference pageRef = new PageReference('/apex/AutomatedTestSetup');
        pageRef.setRedirect(true);
        return pageRef;
    }
    //Scheduling Job run & Email Sending from Auotestrunner class
    // Enqueue all unit test classes as spec'd by Automated_Test_Run__c record(s)
  
    public static list<ID> enqueueTests() {
       
        List<CronTrigger> CurrentShedulejob = [select Id,State,CronJobDetail.Name from CronTrigger where CronJobDetail.JobType = '7' and CronJobDetail.Name like '%AutoTestRunnerAdhoc%' limit 1];
        System.debug('Cuurent Shedule Job Name '+CurrentShedulejob[0].CronJobDetail.Name+'Cuurent Shedule Job State is'+CurrentShedulejob[0].State);
        list<Id> jobIds = new list<Id>();
  String JobNameis=CurrentShedulejob[0].CronJobDetail.Name;
        Id ATERecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Execution').getRecordTypeId();
        Id ATEmilRecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Email Notification').getRecordTypeId();
        Automated_Test_Run__c EmailRecord=[select Emails__c,Schedule_Name__c from Automated_Test_Run__c where RecordTypeId=:ATEmilRecordTypeId and Schedule_Name__c=:JobNameis  order by createdDate DESC limit 1];
        string whereExcluded = '';
        string Keywordis = '';
        string ATRIDis = '';
        for (Automated_Test_Run__c run : [select Query__c,Schedule_Name__c,Excluded_Classes__c,
            Email_on_Pass__c, Exclude_Managed_Packages__c
            from Automated_Test_Run__c where Active__c = true and RecordTypeId=:ATERecordTypeId and Schedule_Name__c=:EmailRecord.Schedule_Name__c order by createdDate DESC limit 1]) {
               ATRIDis=run.id;
                if (run.Excluded_Classes__c != null) {
                    for (string c : run.Excluded_Classes__c.split('[,\\s]+')) {
                        whereExcluded += 'and Name != \'' + c + '\'';
                    }
                }
                if (run.Exclude_Managed_Packages__c == True) {
                   whereExcluded += ' AND NameSpacePrefix = null';
                }
                if (run.Query__c != null && run.Query__c != ' ' ) {
                   Keywordis +=run.Query__c;
                }
           }
            string query = 'SELECT Id FROM ApexClass WHERE Name LIKE \'' + Keywordis+ '\' ' + whereExcluded;
            ApexClass[] testClasses = Database.query(query);
             
            if (testClasses.size() > 0) {
                ApexTestQueueItem[] queueItems = new List<ApexTestQueueItem>();
                for (ApexClass cls : testClasses) {
                    queueItems.add(new ApexTestQueueItem(ApexClassId=cls.Id));
                }
                if (!Test.isRunningTest()) {
                    DataBase.insert(queueItems,false);     
                    // Get the job ID of the first queue item returned.      
                    ApexTestQueueItem item =[SELECT ParentJobId FROM ApexTestQueueItem WHERE Id=:queueItems[0].Id LIMIT 1];                   
                    insert new Test_Runner_Job__c(Name = item.parentjobid, Automated_Test_Run__c = EmailRecord.Id);
                    jobIds.add(item.parentjobid);
                if(ATRIDis!='' && ATRIDis!=null){
                        Automated_Test_Run__c runATRrecd =[select id,Active__c from Automated_Test_Run__c where Id=:ATRIDis limit 1];
                           runATRrecd.Active__c = false;
                           update runATRrecd;
                   }
                  
                }
            }           
        return jobIds;
    }

    public static list<Messaging.SingleEmailMessage> emailMethodStatus(list<Test_Runner_Job__c> jobs) {
        set<string> jobNames = new set<string>();
        for (Test_Runner_Job__c job : jobs) {
            jobNames.add(job.Name);
        }    
        ApexTestResult[] results = [SELECT AsyncApexJobId, Outcome, ApexClass.Name, MethodName, Message, StackTrace
                                    FROM ApexTestResult
                                    WHERE AsyncApexJobId in :jobNames];
         
        return emailMethodStatus(jobs, results);
    }
     
    public static list<Messaging.SingleEmailMessage> emailMethodStatus(list<Test_Runner_Job__c> jobs, ApexTestResult[] results) {
        list<Messaging.SingleEmailMessage> messages = new list<Messaging.SingleEmailMessage>();
     
        for (Test_Runner_Job__c job : jobs) {
            system.debug('Test Runner Job: Id ' + job.Id + ' Name ' + job.Name);
            integer passed = 0;
            integer total = 0;
         
            string failTable = '<table border="1" cellpadding="5px">';
            string className = '';
             
            for (ApexTestResult atr : results) {
                system.debug('Apex Test Result: Id '  + atr.AsyncApexJobId);
                if ((string)atr.AsyncApexJobId == job.Name || (Test.isRunningTest() && jobs.size() == 1)) {
                    if (atr.Outcome == 'Pass') {
                        passed++;
                    } else {
                        if (atr.ApexClass.Name != className) {
                            className = atr.ApexClass.Name;
                            failTable += '<tr style="background: #ddd; font-weight: bold;"><td colspan="2">' + className + '</td></tr>\n';
                        }
                        failTable += '<tr><td>' + atr.MethodName + '</td><td> ' + atr.message + '</td></tr>\n';
                    }
                    total++;
                }
            }
         
            failTable += '</table>';
         
            string body = '<p>' + passed + '/' + total + ' tests passed</p>\n';
            boolean allPassed = passed == total;
         
            if (!allPassed) {
                body += '<p>Test Failures:</p>\n' + failTable;
            }
         
            if ((allPassed && job.Automated_Test_Run__r.Email_on_Pass__c) || !allPassed) {
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                mail.setToAddresses(job.Automated_Test_Run__r.Emails__c.split('[,\\s]+'));
                mail.setSubject(job.Automated_Test_Run__r.Name + ' Automated Test Results: ' + (passed < total ? 'Fail' : 'Pass'));
                mail.setHtmlBody(body);
                System.debug(mail);
                messages.add(mail);
            }
        }   

        if (!Test.isRunningTest()) {
            Messaging.sendEmail(messages);
        }
     
        return messages;
    }
   
    //Recuurence procedure Starts----
   
     public PageReference RecuureceATSinsertandSchedule(){
        
        reccurenceMsg=false;
        List<Automated_Test_Run__c> ATSrecinsert=New List<Automated_Test_Run__c>();
        deleteCompletedJobs();
        String randomnumberis=generateRandomNumber();
        String RecrnceKeyword='%Test%';
        String ScheduleNameis='AutoTestRunnerRecurrence_'+RecrnceKeyword+'_'+randomnumberis;
        AtrRecord.Query__c=RecrnceKeyword;
        AtrRecord.Excluded_Classes__c=AtrRecord.Excluded_Classes__c;
        AtrRecord.Exclude_Managed_Packages__c=AtrRecord.Exclude_Managed_Packages__c;
      
        AtrRecord.Frequency__c=AtrRecord.Frequency__c;
        AtrRecord.On_Every__c=AtrRecord.On_Every__c;
        AtrRecord.Start_Date__c=AtrRecord.Start_Date__c;
        AtrRecord.End_Date__c=AtrRecord.End_Date__c;
        AtrRecord.Schedule_Name__c= ScheduleNameis;
        AtrRecord.Preferred_Time__c=AtrRecord.Preferred_Time__c;
      
        AtrRecord.RecordTypeId=ATERecordTypeId;
        ATSrecinsert.add(AtrRecord);
      
        Automated_Test_Run__c ATEemail = new Automated_Test_Run__c();
        ATEemail.Query__c=RecrnceKeyword;
        ATEemail.Emails__c=AtrRecord.Emails__c;
        ATEemail.Email_on_Pass__c=AtrRecord.Email_on_Pass__c;
        ATEemail.Schedule_Name__c= ScheduleNameis ;
        ATEemail.RecordTypeId=ATEmailRecordTypeId;
        ATSrecinsert.add(ATEemail);
        Savepoint sp = Database.setSavepoint();
        System.debug('Inserting record is Query'+AtrRecord.Query__c +'Frequency__c is'+AtrRecord.Frequency__c+ 'On_Every__c is'+AtrRecord.On_Every__c+'Start_Date__c is'+AtrRecord.Start_Date__c+'End_Date__c is'+AtrRecord.End_Date__c +'Preferred_Time__c'+AtrRecord.Preferred_Time__c);
        Date StartDateis=AtrRecord.Start_Date__c;
        Date EndDateis=AtrRecord.End_Date__c; 
        //Validation here
        reccurenceMsg=validateDates(StartDateis,EndDateis);
        if(reccurenceMsg==false){
            Integer Startyearis=StartDateis.year();
            Integer Endyearis=EndDateis.year();
            Integer StartmonthNum =StartDateis.month();
            Integer EndmonthNum = EndDateis.month();
            Map <Integer,String> monthNumbers = new Map <Integer,String> {1=>'Jan', 2=>'Feb',3=>'Mar',4=>'Apr', 5=>'May', 6=>'Jun',7=>'Jul',8=>'Aug', 9=>'Sep', 10=>'Oct', 11=>'Nov', 12=>'Dec'};
            String StartMonth=monthNumbers.get(StartmonthNum);
            String EndMonth=monthNumbers.get(EndmonthNum);
            string gvnDateis='?';
            //String Dateis='?';
            String Shddayofmonth='?';
            String Dayofweek='?';
            string Months=StartMonth+'-'+EndMonth;
            string Years=Startyearis+'-'+Endyearis;
            try{
                if(AtrRecord.Frequency__c=='Monthly'){
                    gvnDateis=AtrRecord.On_Every__c; 
                    //Date gvnDateis=date.parse(inputDate);
                     //gvnDateis = String.valueOf(StartDateis.day());             
                    } else if(AtrRecord.Frequency__c=='Weekly'){
                    Dayofweek=AtrRecord.On_Every__c;
                    //gvnDateis = String.valueOf(StartDateis.day());               
                }
               String formatedDates=gvnDateis.replaceAll(';', ',');
               String formatedDayofweek=Dayofweek.replaceAll(';', ',');
                
                    Map<String,string> Hoursformat=new Map<String,String> {'01:00 AM'=>'1','02:00 AM'=>'2','03:00 AM'=>'3','04:00 AM'=>'4','05:00 AM'=>'5','06:00 AM'=>'6','07:00 AM'=>'7',
                    '08:00 AM'=>'8','09:00 AM'=>'9','10:00 AM'=>'10','11:00 AM'=>'11','12:00 PM'=>'12','01:00 PM'=>'13','02:00 PM'=>'14','03:00 PM'=>'15','04:00 PM'=>'16','05:00 PM'=>'17',
                    '06:00 PM'=>'18','07:00 PM'=>'19','08:00 PM'=>'20','09:00 PM'=>'21','10:00 PM'=>'22','11:00 PM'=>'23','12:00 PM'=>'0'};

                    Map <String,String> DAYformat = new Map <String,String> {'SUNDAY'=>'SUN', 'MONDAY'=>'MON','TUESDAY'=>'TUE','WEDNESDAY'=>'WED','THURSDAY'=>'THU', 'FRIDAY'=>'FRI','SATURDAY'=>'SAT'};

                    String GetHour=Hoursformat.get(AtrRecord.Preferred_Time__c);
                    System.debug('***GetHour is***'+GetHour);
                    System.debug('***formatedDates is***'+formatedDates);
                    System.debug('***Months is***'+Months);
                    System.debug('***Dayofweek is***'+Dayofweek);
                    System.debug('***yearis is***'+Years);
                   
                    //Seconds   Minutes Hours   Day Of Month    Month   Day Of Week Year
                    String strSchedule = '0 ' + '0 '+GetHour+ ' ' +formatedDates+ ' ' +Months+ ' ' +formatedDayofweek+ ' ' + Years;
                    System.debug('***strSchedule***'+strSchedule);
                   AutoTestRunnerRecurrence.setup(strSchedule,ScheduleNameis); 

                        upsert ATSrecinsert;               
                        
            }
            catch(exception ex){
                Database.rollback(sp);
                ApexPages.addMessages(ex);
                reccurenceMsg=true;
                 //ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.INFO,'Job not Schedued Please give proper data+ex');
                // ApexPages.addMessage(myMsg);
            }
        }
        PageReference pageRef;
        System.debug('reccurenceMsg is '+reccurenceMsg);
        System.debug('pageRef is '+pageRef);
        if(reccurenceMsg==true && reccurenceMsg!=false){
            pageRef=null;          
        }else if(reccurenceMsg==false){          
            pageRef = new PageReference('/apex/AutomatedTestSetupRecurrence');
                    pageRef.setRedirect(true);
                    return pageRef; 
        }
         System.debug('reccurenceMsg is 2'+reccurenceMsg);
        System.debug('pageRef is 2 '+pageRef);                        
     return pageRef;
    }
   
    public boolean validateDates(date StartDateis,date EndDateis) {
        reccurenceMsg=false;
        date today= date.today();
        if(StartDateis>=EndDateis){
            reccurenceMsg=true;                    
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.INFO,'Start Date cannot be less than End Date and also both dates not same');
            ApexPages.addMessage(myMsg);
        } else if(StartDateis < today ){
            reccurenceMsg=true;
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.INFO,'Start Date Must be Greater than Today');
            ApexPages.addMessage(myMsg);
        }else if(EndDateis < today ){
            reccurenceMsg=true;
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.INFO,'End Date Must be Greater than Today');
            ApexPages.addMessage(myMsg);
        }
        return reccurenceMsg;
    }
    public void refreshHasRecrnsScheduledJobs() {
        List<CronTrigger> recurnceSchdjobs=New  List<CronTrigger>();
        integer jobCount = [SELECT count() FROM CronTrigger  where CronJobDetail.Name like '%AutoTestRunnerRecurrence%'];
        recurnceSchdjobs=[SELECT CronJobDetail.Name,CreatedDate,NextFireTime,State FROM CronTrigger where CronJobDetail.Name like '%AutoTestRunnerRecurrence%' and State in('WAITING','ACQUIRED','EXECUTING')];
        if(recurnceSchdjobs.size()>0){
            Jobstatus=recurnceSchdjobs[0].State;
            if(recurnceSchdjobs[0].NextFireTime!=null ){
            Datetime shddatetimeGSt=recurnceSchdjobs[0].NextFireTime;
            Datetime gmt = shddatetimeGSt;
             String timeZone = UserInfo.getTimeZone().getID();
             Datetime GivenDateTime=shddatetimeGSt;// here you can user your dates e.g. createddate
              Datetime localdt=Datetime.valueOf(GivenDateTime);
              //showdatetime = string.valueOfGmt(local);
              shddatetime=localdt.format();
              }
              else if(Jobstatus!=null && Jobstatus!='') {
                  shddatetime='Test Scheduled Job Current State is '+Jobstatus;
              }
            }           
        hasRecScheduledJobs = jobCount !=0;         
    }
    public PageReference CancelRecurrenceJobs() {   
          //List<CronTrigger> jobsToAbort = [select id,Name from CronJobDetail where Name like 'AutoTestRunner%' and JobType = '7'];
          List<CronTrigger> jobsToAbort = [select Id from CronTrigger where CronJobDetail.JobType = '7' and CronJobDetail.Name like '%AutoTestRunnerRecurrence%'];
              if(jobsToAbort.size()>0){
                  for (CronTrigger job : jobsToAbort) {
                   System.abortJob(job.Id);
                   }
               }
               PageReference pageRef = new PageReference('/apex/AutomatedTestSetupRecurrence');
                    pageRef.setRedirect(true);
                    return pageRef;
    }
   
    public static list<ID> recurrenceenqueueTests() {
        list<Id> jobIds = new list<Id>();
        Id ATERecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Execution').getRecordTypeId();
        Id ATEmilRecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Email Notification').getRecordTypeId();
        Automated_Test_Run__c EmailRecord=[select Emails__c,Schedule_Name__c from Automated_Test_Run__c where RecordTypeId=:ATEmilRecordTypeId and Schedule_Name__c like '%AutoTestRunnerRecurrence%' order by createdDate DESC limit 1];
        string whereExcluded = '';
        string Keywordis = '';
        string ATRIDis = '';
        for (Automated_Test_Run__c run : [select Query__c, Excluded_Classes__c,
            Email_on_Pass__c, Exclude_Managed_Packages__c
            from Automated_Test_Run__c where Active__c = true and RecordTypeId=:ATERecordTypeId and Frequency__c!=null and Schedule_Name__c=:EmailRecord.Schedule_Name__c  order by createdDate DESC limit 1]) {
               ATRIDis=run.id;
                if (run.Excluded_Classes__c != null) {
                    for (string c : run.Excluded_Classes__c.split('[,\\s]+')) {
                        whereExcluded += 'and Name != \'' + c + '\'';
                    }
                }
                if (run.Exclude_Managed_Packages__c == True) {
                   whereExcluded += ' AND NameSpacePrefix = null';
                }
                if (run.Query__c != null && run.Query__c != ' ' ) {
                   Keywordis +=run.Query__c;
                }
           }
            string query = 'SELECT Id FROM ApexClass WHERE Name LIKE \'' + Keywordis+ '\' ' + whereExcluded;
            ApexClass[] testClasses = Database.query(query);
             
            if (testClasses.size() > 0) {
                ApexTestQueueItem[] queueItems = new List<ApexTestQueueItem>();
                for (ApexClass cls : testClasses) {
                    queueItems.add(new ApexTestQueueItem(ApexClassId=cls.Id));
                }
                if (!Test.isRunningTest()) {
                    DataBase.insert(queueItems,false);     
                    // Get the job ID of the first queue item returned.      
                    ApexTestQueueItem item =[SELECT ParentJobId FROM ApexTestQueueItem WHERE Id=:queueItems[0].Id LIMIT 1];                   
                    insert new Test_Runner_Job__c(Name = item.parentjobid, Automated_Test_Run__c = EmailRecord.Id);
                    jobIds.add(item.parentjobid);               
                }
            }           
        return jobIds;
    }
  public PageReference click(){ 
    System.debug('isChecked is ' +isChecked);
    PageReference pageRef;
         if(isChecked!=TRUE){
             isCheckedRec = true;
             System.debug('isCheckedRec is ' +isCheckedRec);
        pageRef = new PageReference('/apex/AutomatedTestSetupRecurrence');
         }
         else{
             isCheckedRec = false;
             pageRef = new PageReference('/apex/AutomatedTestSetup');
         }      
                    pageRef.setRedirect(true);
                    return pageRef;
         //return null;
     }
    
   public PageReference Adhocclick(){ 
    System.debug('isAdhocChecked is ' +isAdhocChecked);
    PageReference pageRef;
         if(isAdhocChecked!=TRUE){
             isAdhocChecked = true;
             System.debug('isAdhocChecked is ' +isAdhocChecked);
        pageRef = new PageReference('/apex/AutomatedTestSetupAdhoc');
         }
         else{
             isCheckedRec = false;
             pageRef = new PageReference('/apex/AutomatedTestSetupRecurrence');
         }      
                    pageRef.setRedirect(true);
                    return pageRef;
         //return null;
     }
      
   public static String generateRandomNumber(){       
       Decimal randomValue = 100000 * math.random();       
       String userCode = String.valueOf(randomValue);       
       userCode = userCode.substring(0,3);       
       return userCode;    
       }
      
    //multipleAdhocJobs

  public PageReference CancelAdhocJobs() {   
    System.debug('SelectedAdhocJobId is'+SelectedAdhocJobId);
     //String AbortJobID = ApexPages.CurrentPage().getParameters().get('SelectedAdhocJobId');
   
     /*if (SelectedAdhocJobId == null) {    
         //return;
      }  */
      // find the CronTrigger record within the collection
      for(CronTrigger a : Schdjobs){
           if (a.Id == SelectedAdhocJobId) {
            System.abortJob(a.Id);
            }
       }  

       PageReference pageRef = new PageReference('/apex/AutomatedTestSetup');
       pageRef.setRedirect(true);
      return pageRef;
  }
  
  public void ScheduledJobs() {        
        Schdjobs=[SELECT CronJobDetail.Name,CreatedDate,TimesTriggered,NextFireTime,State FROM CronTrigger where CronJobDetail.Name like '%AutoTestRunner%' and State in('WAITING','ACQUIRED','EXECUTING')];           
    }
  
}


**************************************************
Page:

<!--*************************************************************************            
              
    Page Name          : AutomatedTestSetup
    Description        : For Automated Test class execution process(SP-684-Automate Test Classes execution in Salesforce Orgs)
    Created By         : Krishna yerru
    Created Date       : 23-Oct-2018

********************************************************************************************************************************
    Change Version   Name              Date                    Task/Case#                 Description
********************************************************************************************************************************
    CH0001          Krishna Yerru       08-Nov-2018             SP-2793                 Enhance Automated Test Execution to allow continuous runs
********************************************************************************************************************************  
*************************************************************************/-->

<apex:page standardController="Automated_Test_Run__c" extensions="AutomatedTestSetup_Controller" Sidebar="False" id="pg" docType="html-5.0">

    <apex:form id="frm">

         <div style="text-align:center;font-size: 18px; font-weight: bold ;">
            <apex:outputText style="text-align:center; font-weight: bold ;"  value="Job Schedule - Home"></apex:outputText>
         </div>
         
        <apex:pageBlock id="ATSPB" >
        
                    <apex:pageMessages /> 
                        
                    <apex:outputpanel id="ATSTest" rendered="{!(isCheckedRec != true)}">
                               <!-- <apex:pageBlock title="Job Schedule - Test Execution" id="ThePanel2">-->
                                
                                     <apex:outputLabel value="Recurrence" style="font-weight:bold;font-size:13px;float:left;"/> 
                                        <apex:inputcheckbox value="{!isChecked}" label="checkBox">    
                                            <apex:actionSupport event="onchange" rerender="ATSTest" action="{!click}" immediate="true"/>    
                                        </apex:inputcheckbox>
                                <br/>  
                                        <apex:outputLabel value="Adhoc Job" style="font-weight:bold;font-size:13px;float:left;"/> 
                                        <apex:inputcheckbox value="{!isAdhocChecked}" label="checkBox">    
                                            <apex:actionSupport event="onchange" action="{!Adhocclick}" immediate="true"/>    
                                        </apex:inputcheckbox>
                                
                                
                                        <br/>
                                        <div align="right" draggable="false" >
                                            <apex:outputLink style="font-weight:bold;font-size:13px;float:Right;" value="{!testRunLink}">Scheduled Jobs History</apex:outputLink>
                                         </div>
                                            <br/><br/>
                                          <!--Sheduled Jobs Showing Block-Start-->
                                <apex:outputPanel >
                                       <apex:pageBlockSection title="Scheduled Jobs" id="AdhocSheduled" columns="1">      
                                            <div>
                                            <apex:pageBlockTable value="{!Schdjobs}" var="jobs">
                                               <apex:column >
                                                <apex:facet name="header">Scheduled Name</apex:facet>
                                                <apex:outputText value="{!jobs.CronJobDetail.Name}"/>
                                               </apex:column> 
                                               
                                               <apex:column >
                                                <apex:facet name="header">Current State</apex:facet>
                                                <apex:outputText value="{!jobs.State}"/>
                                               </apex:column>
                                               
                                               
                                                <apex:column >
                                               <apex:facet name="header">Next Fire Time</apex:facet>
                                                <apex:outputText value="{!jobs.NextFireTime}"/>
                                               </apex:column>
                                                <!--
                                                <apex:column >
                                               <apex:facet name="header">Next Fire Time</apex:facet>
                                                <apex:outputText value="{!jobs.NextFireTime}"/>
                                               </apex:column>

                                              
                                               <apex:column >
                                               <apex:facet name="header">Next Fire Time</apex:facet>
                                                <apex:outputText value="{0,date,MM/dd/yy}">
                                                <apex:outputText value="{0,date,dd MMM YYYY h:mm a}">
                                                <apex:param value="{!jobs.NextFireTime}" /> </apex:outputText>
                                               </apex:column>
                                               
                                                <apex:column >
                                               <apex:facet name="header">Next Fire Time</apex:facet>
                                                <apex:outputText value="{0,date,yyyy.MM.dd G 'at' HH:mm:ss z}">
                                                    <apex:param value="{!jobs.NextFireTime}" />
                                                </apex:outputText>
                                               </apex:column>
                                                --> 
                                               <apex:column >
                                               <apex:facet name="header">Cancel</apex:facet>
                                              <apex:commandLink value="Cancel" action="{!CancelAdhocJobs}" styleClass="btn" >
                                                            <apex:param value="{!jobs.id}" assignTo="{!SelectedAdhocJobId}" name="Schdjobs" />
                                                        </apex:commandLink>
                                               </apex:column>
                                               
                                             </apex:pageBlockTable>
                                             </div>     
                                       </apex:pageBlockSection>         
                                </apex:outputPanel>  
                                
                                <!--Sheduled Jobs Showing Block-end-->                              

                                        <!--Startstics Section -->
                                 
                                        <apex:pageBlockSection title="Test Class Execution Statistics" id="Piechartsec" columns="4">
                                                     <apex:pageBlockSectionItem >
                                         TestRun Name:{!PastATRdetails}<div></div>
                                         Testclass execution {!Percentage}% completed
                                          </apex:pageBlockSectionItem>
                                                <apex:pageBlockSectionItem id="ShowGraph">  
                                                    <apex:outputPanel id="Graph">
                                                            <apex:chart height="250" width="350" data="{!pieData}" id="Piechartsec2">
                                                                <apex:pieSeries dataField="data" labelField="name"/>
                                                                <apex:legend position="left"/>
                                                            </apex:chart>
                                                        </apex:outputPanel>                                                    
                                                </apex:pageBlockSectionItem>  
                                                
                                                <apex:pageBlockSectionItem id="Refresh">   
                                                    <apex:commandlink value=" Refresh " status="progress" action="{!Refresh}" styleClass="btn" reRender="Piechartsec2"/>
                                                </apex:pageBlockSectionItem>

                                                <apex:pageBlockSectionItem id="Abort">                   
                                                    <apex:commandButton value="Abort" status="progress" action="{!AbortTestJobs}" rendered="{!(hasAbort)}" onclick="return confirm('Are you sure to abort and get the current results in an email ?')" />
                                              </apex:pageBlockSectionItem>                    
                                        </apex:pageBlockSection>   
                                        
                            <!--</apex:pageBlock> -->
                       </apex:outputPanel>           
        </apex:pageBlock>   

    </apex:form>
</apex:page>
               

************************************************

<!--*************************************************************************            
              
    Page Name          : AutomatedTestSetupRecurrence
    Description        : For recuurence Automated Test class execution process(SP-2793  -Enhance Automated Test Execution to allow continuous runs)
    Created By         : Krishna yerru
    Created Date       : 8th-nov-2018

********************************************************************************************************************************
    Change Version   Name              Date                    Task/Case#                 Description
********************************************************************************************************************************

********************************************************************************************************************************  
*************************************************************************/-->

<apex:page standardController="Automated_Test_Run__c" extensions="AutomatedTestSetup_Controller" Sidebar="False" id="pg" docType="html-5.0">

        <apex:form id="frm">           
            <apex:pageBlock title="Reccurence Job Schedule - Test Execution" id="ATSPB" >            
                        <apex:outputPanel >
                                <apex:pagemessages />
                        </apex:outputPanel>      
                                                            <!--<apex:pageBlock title="Reccurence Job Schedule - Test Execution" id="ThePanelrec2">-->
                                               <apex:pageBlockSection columns="3">  

                                                            <apex:inputcheckbox style="text-align:left;font-size: 13px; font-weight: bold ;" value="{!isAdhocChecked}" label="Adhoc Job"> 
                                                                    <apex:actionSupport event="onchange" action="{!Adhocclick}" immediate="true"/>    
                                                            </apex:inputcheckbox>                                                                                                       
                                                      
                                                            <apex:outputLink style="text-align:center;font-size: 13px; font-weight: bold ;" value="{!HomeLink}">Home</apex:outputLink>

                                                            <apex:outputLink style="font-weight:bold;font-size:13px;float:Right;" value="{!testRunLink}">Scheduled Jobs History</apex:outputLink>
                                                                                             
                                                </apex:pageBlockSection>  
                   
                   
                                            <!--Automated Test Record start-->
                            <apex:outputPanel rendered="{!if(NOT(hasRecScheduledJobs),true,false)}">
                                       
                                                 <apex:pageBlockSection title="Automated Test Run" columns="2">         
                                                          <apex:pageBlockSectionItem helpText="Test class names containing this value would be considered for automated test execution Ex:Test% or %_Test (case insensitive)">
                                                                <apex:outputLabel value="Keyword"/>
                                                                <apex:inputField required="true" value="{!AtrRecord.Query__c}" html-disabled="true" label="Keyword"/>                
                                                          </apex:pageBlockSectionItem>
                                                           
                                                          <apex:pageBlockSectionItem helpText="Comma-delimited list of classes to exclude from testing">
                                                                <apex:outputLabel value="Excluded Classes"/>                   
                                                                <apex:inputField value="{!AtrRecord.Excluded_Classes__c}" label="Excluded Classes"/>      
                                                          </apex:pageBlockSectionItem>
                                                            
                                                          <apex:pageBlockSectionItem helpText="Check this box to exclude all Managed Package Unit Tests">
                                                                <apex:outputLabel value="Exclude Managed_Packages"/> 
                                                                <apex:inputField value="{!AtrRecord.Exclude_Managed_Packages__c}" label="Exclude Managed_Packages"/>                  
                                                          </apex:pageBlockSectionItem>                   
                                                 </apex:pageBlockSection>
                                                 
                                                 <apex:pageBlockSection title="Automated Test Email" columns="2">
                                                  
                                                          <apex:pageBlockSectionItem helpText="Comma-separated email addresses">
                                                               <apex:outputLabel value="Email"/>
                                                               <apex:inputField required="true" value="{!AtrRecord.Emails__c}" label="Email"/>
                                                          </apex:pageBlockSectionItem>   
                                                          
                                                          <apex:pageBlockSectionItem helpText="Send email when all tests pass">
                                                               <apex:outputLabel value="Email on Pass"/>
                                                               <apex:inputField value="{!AtrRecord.Email_on_Pass__c}" label="Email on Pass"/>
                                                          </apex:pageBlockSectionItem>                   
                                                 </apex:pageBlockSection>
                                                 
                                                 <apex:pageBlockSection title="Job Schedule " columns="1">
                                                          
                                                          
                                                          <apex:pageBlockSectionItem helpText="Frequency">
                                                              <apex:outputLabel value="Frequency"/>
                                                              <apex:inputField required="true" value="{!AtrRecord.Frequency__c}" label="Frequency"/>
                                                          </apex:pageBlockSectionItem>
                                                          
                                                          <apex:pageBlockSectionItem helpText="On Every">
                                                              <apex:outputLabel value="On Every"/>
                                                              <apex:inputField required="true" value="{!AtrRecord.On_Every__c}" label="On Every"/>                                                  
                                                          </apex:pageBlockSectionItem>
                                                          
                                                           <apex:pageBlockSectionItem helpText="Schedule Start Date">
                                                              <apex:outputLabel value="Schedule Start Date"/>
                                                              <apex:inputField required="true" value="{!AtrRecord.Start_Date__c}" label="Schedule Start Date"/>
                                                              </apex:pageBlockSectionItem>
                                                          
                                                           <apex:pageBlockSectionItem helpText="Schedule End Date">
                                                              <apex:outputLabel value="Schedule End Date"/>
                                                              <apex:inputField required="true" value="{!AtrRecord.End_Date__c}" label="Schedule End Date"/>
                                                            </apex:pageBlockSectionItem>
                                                            
                                                            
                                                            
                                                            <apex:pageBlockSectionItem helpText="Time For Schedule Job">
                                                              <apex:outputLabel value="Time For Schedule Job"/>
                                                              <apex:inputField required="true" value="{!AtrRecord.Preferred_Time__c}" label="Preferred Time"/>
                                                            </apex:pageBlockSectionItem>
                                                          
                                                           <apex:pageBlockSectionItem >
                                                                <apex:outputPanel >
                                                                    <div style="text-align: center">
                                                                         <apex:commandButton value="Save & Submit"  style="text-align:center"  action="{!RecuureceATSinsertandSchedule}" />
                                                                    </div>
                                                                </apex:outputPanel>
                                                             </apex:pageBlockSectionItem>                           
                                                  </apex:pageBlockSection>    
                                                  
                            </apex:outputPanel> 
                                    <!--Automated Test Record end-->
                            <apex:outputPanel rendered="{!IF(hasRecScheduledJobs = false , false , true)}">
                                        <apex:pageBlockSection title="Job Schedule Status" columns="1">
                                                Automated Test Run Name:%Test%_TestRun_{!shddatetime}                                                         
                                             
                                             <apex:commandLink value="Cancel" rendered="{!IF(hasRecScheduledJobs = false , false , true)}" action="{!CancelRecurrenceJobs}" styleClass="btn">
                                                </apex:commandLink>
                                            
                                        </apex:pageBlockSection>
                            </apex:outputPanel>   
                                    
               <!-- </apex:pageBlock>  -->          
           
          </apex:pageBlock>   
        </apex:form>
</apex:page>
                
******************************************

<!--*************************************************************************            
              
    Page Name          : AutomatedTestSetupAdhoc
    Description        : For Adhoc Automated Test class execution process(SP-2793   -Enhance Automated Test Execution to allow continuous runs)
    Created By         : Krishna yerru
    Created Date       : 08-Nov-2018        

********************************************************************************************************************************
    Change Version   Name              Date                    Task/Case#                 Description
********************************************************************************************************************************

********************************************************************************************************************************  
*************************************************************************/-->

<apex:page standardController="Automated_Test_Run__c" extensions="AutomatedTestSetup_Controller" Sidebar="False" id="pg" docType="html-5.0">

    <apex:form id="frm">
   
                
        <apex:pageBlock title="Adhoc Job Schedule - Test Execution" id="ATSPB" >  
                            
                    <apex:pageMessages /> 
                    
                            <apex:outputpanel id="ATSTest" rendered="{!(isCheckedRec != true)}">
                               <!-- <apex:pageBlock title="Adhoc Job Schedule - Test Execution" id="ThePanel2">-->
                                                         <apex:pageBlockSection columns="3">  
                                                                
                                                                <apex:inputcheckbox style="text-align:left;font-size: 13px; font-weight: bold ;" value="{!isChecked}" label="Recurrence"> 
                                                                        <apex:actionSupport event="onchange" rerender="ATSTest" action="{!click}" immediate="true"/>    
                                                                </apex:inputcheckbox>                                                                                                       
                                                                  
                                                                <apex:outputLink style="text-align:center;font-size: 13px; font-weight: bold ;" value="{!HomeLink}">Home</apex:outputLink>
                                                                
                                                                <apex:outputLink style="font-weight:bold;font-size:13px;float:Right;" value="{!testRunLink}">Scheduled Jobs History</apex:outputLink>
                                                                                                         
                                                        </apex:pageBlockSection>    
                                            <!--Automated Test Record-->
                                           
                                               <apex:outputPanel id="ATSFieldPanel" >
                                               
                                                         <apex:pageBlockSection title="Automated Test Run" columns="2">         
                                                                  <apex:pageBlockSectionItem helpText="Test class names containing this value would be considered for automated test execution Ex:Test% or %_Test (case insensitive)">
                                                                        <apex:outputLabel value="Keyword"/>
                                                                        <apex:inputField required="true" value="{!AtrRecord.Query__c}" label="Keyword"/>                
                                                                  </apex:pageBlockSectionItem>
                                                                   
                                                                  <apex:pageBlockSectionItem helpText="Comma-delimited list of classes to exclude from testing">
                                                                        <apex:outputLabel value="Excluded Classes"/>                   
                                                                        <apex:inputField value="{!AtrRecord.Excluded_Classes__c}" label="Excluded Classes"/>      
                                                                  </apex:pageBlockSectionItem>
                                                                    
                                                                  <apex:pageBlockSectionItem helpText="Check this box to exclude all Managed Package Unit Tests">
                                                                        <apex:outputLabel value="Exclude Managed_Packages"/> 
                                                                        <apex:inputField value="{!AtrRecord.Exclude_Managed_Packages__c}" label="Exclude Managed_Packages"/>                  
                                                                  </apex:pageBlockSectionItem>                   
                                                         </apex:pageBlockSection>
                                                         
                                                         <apex:pageBlockSection title="Automated Test Email" columns="2">
                                                          
                                                                  <apex:pageBlockSectionItem helpText="Comma-separated email addresses">
                                                                       <apex:outputLabel value="Email"/>
                                                                       <apex:inputField required="true" value="{!AtrRecord.Emails__c}" label="Email"/>
                                                                  </apex:pageBlockSectionItem>   
                                                                  
                                                                  <apex:pageBlockSectionItem helpText="Send email when all tests pass">
                                                                       <apex:outputLabel value="Email on Pass"/>
                                                                       <apex:inputField value="{!AtrRecord.Email_on_Pass__c}" label="Email on Pass"/>
                                                                  </apex:pageBlockSectionItem>                   
                                                         </apex:pageBlockSection>
                                                         
                                                         <apex:pageBlockSection title="Job Schedule " columns="1">
                                                                  <apex:pageBlockSectionItem helpText="To Schedule Testclass Execution">
                                                                      <apex:outputLabel value="Schedule Date and Time"/>
                                                                      <apex:inputField required="true" value="{!AtrRecord.Schedule__c}" label="Schedule Date and Time"/>
                                                                      
                                                                  </apex:pageBlockSectionItem>
                                                                  
                                                                   <apex:pageBlockSectionItem >
                                                                        <apex:outputPanel >
                                                                            <div style="text-align: center">
                                                                                 <apex:commandButton value="Save & Submit"  style="text-align:center"  action="{!doInsert}" />
                                                                            </div>
                                                                        </apex:outputPanel>
                                                                     </apex:pageBlockSectionItem>                           
                                                          </apex:pageBlockSection>    
                                                          
                                               </apex:outputPanel>                                                                      
                           <!-- </apex:pageBlock> -->
                       </apex:outputPanel>           
        </apex:pageBlock>   

    </apex:form>
</apex:page>
                 

****************************************

/*
    Name               : AutoTestRunner
    Test class         : AutomatedTestSetup_Controller_Test
    Description        : For Automated Test class execution process(SP-684-Automate Test Classes execution in Salesforce Orgs)
    Created By         : Krishna yerru
    Created Date       : 23-Oct-2018

********************************************************************************************************************************
    Change Version   Name              Date                    Task/Case#                 Description
********************************************************************************************************************************
 
********************************************************************************************************************************       
*/

global class AutoTestRunner implements Schedulable {
    public static void setup(String strSchedule,String ADScheduleNameis) {
        try {
            String cronexpression=strSchedule;
            system.schedule(ADScheduleNameis,cronexpression, new AutoTestRunner());
        } catch (Asyncexception ex) {
            system.debug('Job Not scheduled');
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.INFO,'Job Not scheduled Please give Proper Data'+ex);
             ApexPages.addMessage(myMsg);
        }
    }
    
   global void execute(SchedulableContext SC) {
    AutomatedTestSetup_Controller.enqueueTests();    
   }  
 }

***********************************

/*
    Name               : AutoTestRunnerRecurrence
    Test class         : AutomatedTestSetup_Controller_Test
    Description        : For Automated Test class execution process(SP-684-Automate Test Classes execution in Salesforce Orgs)
    Created By         : Krishna yerru
    Created Date       : 26-Oct-2018

********************************************************************************************************************************
    Change Version   Name              Date                    Task/Case#                 Description
********************************************************************************************************************************
 
********************************************************************************************************************************       
*/

global class AutoTestRunnerRecurrence implements Schedulable {
    
   public static void setup(String strSchedule,String ScheduleName) {
        try {
            system.debug('strSchedule is ***'+strSchedule);
            String cronexpression=strSchedule;
            system.schedule(ScheduleName,cronexpression, new AutoTestRunnerRecurrence());
        } catch (Asyncexception ex) {
            system.debug('Job Not scheduled');
            //ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.INFO,'Job not Schedued Please give proper data+ex');
            // ApexPages.addMessage(myMsg);
            ApexPages.addMessages(ex);
        }
    }
   global void execute(SchedulableContext SC) {
    AutomatedTestSetup_Controller.recurrenceenqueueTests();    
   }  
   
 }

*********************************

No comments:

Post a Comment