/*
 * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
 * under one or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership. Camunda licenses this file to you under the Apache License,
 * Version 2.0; you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.camunda.bpm.engine.test.jobexecutor;

import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.engine.impl.interceptor.Command;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.persistence.entity.JobEntity;
import org.camunda.bpm.engine.runtime.Job;
import org.camunda.bpm.engine.test.Deployment;
import org.camunda.bpm.engine.test.ProcessEngineRule;
import org.camunda.bpm.engine.test.RequiredHistoryLevel;
import org.camunda.bpm.engine.test.util.ProcessEngineTestRule;
import org.camunda.bpm.engine.test.util.ProvidedProcessEngineRule;
import org.camunda.bpm.model.bpmn.Bpmn;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.RuleChain;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

public class JobExecutorCleanupTest {

  public ProcessEngineRule engineRule = new ProvidedProcessEngineRule();
  protected ProcessEngineTestRule testRule = new ProcessEngineTestRule(engineRule);
  protected ExpectedException thrown = ExpectedException.none();

  @Rule
  public RuleChain ruleChain = RuleChain.outerRule(engineRule).around(testRule).around(thrown);

  protected RuntimeService runtimeService;
  protected HistoryService historyService;
  protected ProcessEngineConfigurationImpl configuration;

  @Before
  public void assignServices() {
    runtimeService = engineRule.getRuntimeService();
    historyService = engineRule.getHistoryService();
    configuration = engineRule.getProcessEngineConfiguration();
  }

  @After
  public void resetConfig() {
    configuration.setHistoryCleanupEnabled(true);
  }

  @Test
  @RequiredHistoryLevel(ProcessEngineConfigurationImpl.HISTORY_AUDIT)
  @Deployment(resources = {"org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml"})
  public void shouldExecuteCleanupJob() {
    // given
    testRule.deploy(Bpmn.createExecutableProcess("process")
        .camundaHistoryTimeToLive(0)
        .startEvent()
        .endEvent().done());

    runtimeService.startProcessInstanceByKey("process");

    // assume
    assertThat(historyService.createHistoricProcessInstanceQuery().count()).isOne();

    // when: schedule & execute cleanup job
    historyService.cleanUpHistoryAsync(true);
    testRule.waitForJobExecutorToProcessAllJobs(10_000L);

    // then
    assertThat(historyService.createHistoricProcessInstanceQuery().count()).isZero();
  }

  @Test
  public void shouldNotExecuteCleanupJob() {
    // given
    historyService.cleanUpHistoryAsync(true); // schedule cleanup job
    configuration.setHistoryCleanupEnabled(false);

    // then: job cannot be acquired & executed
    thrown.expect(AssertionError.class);
    thrown.expectMessage("time limit of 10000 was exceeded");

    // when: execute cleanup job
    testRule.waitForJobExecutorToProcessAllJobs();
  }

  @After
  public void resetDatabase() {
    engineRule.getProcessEngineConfiguration().getCommandExecutorTxRequired().execute(new Command<Void>() {
      public Void execute(CommandContext commandContext) {
        String handlerType = "history-cleanup";
        List<Job> jobsByHandlerType = commandContext.getJobManager()
            .findJobsByHandlerType(handlerType);

        for (Job job : jobsByHandlerType) {
          commandContext.getJobManager()
              .deleteJob((JobEntity) job);
        }

        commandContext.getHistoricJobLogManager()
            .deleteHistoricJobLogsByHandlerType(handlerType);

        commandContext.getMeterLogManager().deleteAll();

        return null;
      }
    });
  }

}

@@ -1346,65 +1346,8 @@
 le;%0A
-import org.camunda.bpm.engine.test.RequiredHistoryLevel;%0A
 impo
@@ -2595,789 +2595,8 @@
  %7D%0A%0A
-  @Test%0A  @RequiredHistoryLevel(ProcessEngineConfigurationImpl.HISTORY_AUDIT)%0A  @Deployment(resources = %7B%22org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml%22%7D)%0A  public void shouldExecuteCleanupJob() %7B%0A    // given%0A    testRule.deploy(Bpmn.createExecutableProcess(%22process%22)%0A        .camundaHistoryTimeToLive(0)%0A        .startEvent()%0A        .endEvent().done());%0A%0A    runtimeService.startProcessInstanceByKey(%22process%22);%0A%0A    // assume%0A    assertThat(historyService.createHistoricProcessInstanceQuery().count()).isOne();%0A%0A    // when: schedule & execute cleanup job%0A    historyService.cleanUpHistoryAsync(true);%0A    testRule.waitForJobExecutorToProcessAllJobs(10_000L);%0A%0A    // then%0A    assertThat(historyService.createHistoricProcessInstanceQuery().count()).isZero();%0A  %7D%0A%0A
   @T

remove test due to flakiness on oracle db