public List<MaterialRevision> addDependencyRevisionModification(
     List<MaterialRevision> materialRevisions,
     DependencyMaterial dependencyMaterial,
     Pipeline... upstreams) {
   String stageName = CaseInsensitiveString.str(dependencyMaterial.getStageName());
   String label = upstreams[0].getLabel();
   List<Modification> modifications = new ArrayList<Modification>();
   for (Pipeline upstream : upstreams) {
     modifications.add(
         new Modification(
             new Date(),
             DependencyMaterialRevision.create(
                     CaseInsensitiveString.str(dependencyMaterial.getPipelineName()),
                     upstream.getCounter(),
                     label,
                     stageName,
                     upstream.findStage(stageName).getCounter())
                 .getRevision(),
             label,
             upstream.getId()));
   }
   MaterialRevision depRev =
       addRevisionsWithModifications(
           dependencyMaterial, modifications.toArray(new Modification[0]));
   materialRevisions.add(depRev);
   return Arrays.asList(depRev);
 }
  @Test
  public void
      shouldCancelAScheduledJobInCaseThePipelineIsRemovedFromTheConfig_SpecificallyAPipelineRenameToADifferentCaseAndStageNameToADifferentName()
          throws Exception {
    Material hgMaterial = new HgMaterial("url", "folder");
    String[] hgRevs = new String[] {"h1"};
    u.checkinInOrder(hgMaterial, hgRevs);

    ScheduleTestUtil.AddedPipeline p1 =
        u.saveConfigWith("PIPELINE_WHICH_WILL_EVENTUALLY_CHANGE_CASE", u.m(hgMaterial));

    u.scheduleWith(p1, hgRevs);
    ScheduleTestUtil.AddedPipeline renamedPipeline =
        u.renamePipelineAndFirstStage(
            p1,
            "pipeline_which_will_eventually_change_case",
            "NEW_RANDOM_STAGE_NAME" + UUID.randomUUID());

    Pipeline p1_2 = u.scheduleWith(renamedPipeline, hgRevs);
    CruiseConfig cruiseConfig = configHelper.load();
    buildAssignmentService.onTimer(); // To Reload Job Plans
    buildAssignmentService.onConfigChange(cruiseConfig);

    Stages allStages = stageDao.findAllStagesFor(p1_2.getName(), p1_2.getCounter());
    assertThat(
        allStages.byName(CaseInsensitiveString.str(p1.config.first().name())).getState(),
        is(StageState.Cancelled));
  }
  @Test
  public void shouldGetAPresenterWithLabelAndRelevantBuildPlansAndPipelineNameAndId()
      throws Exception {
    StageJsonPresentationModel presenter =
        new StageJsonPresentationModel(pipeline, stage, null, new Agents());
    Map json = presenter.toJson();

    new JsonTester(json)
        .shouldContain(
            "{ 'pipelineName' : 'pipeline',"
                + "  'stageName' : 'stage',"
                + "  'builds' : ["
                + "    { 'name' : 'job-that-will-fail' },"
                + "    { 'name' : 'job-that-will-pass' },"
                + "    { 'name' : 'scheduledBuild' }"
                + "  ],"
                + " 'current_label' : '"
                + pipeline.getLabel()
                + "', "
                + " 'pipelineCounter' : '"
                + pipeline.getCounter()
                + "', "
                + " 'pipelineCounterOrLabel' : '"
                + pipeline.getIdentifier().instanceIdentifier()
                + "', "
                + " 'id' : '1' "
                + "}");
    assertFalse(
        "JSON shouldn't contain last_successful_label",
        json.toString().contains("last_successful_label"));
  }
  @Test
  public void shouldSetAServerHealthMessageWhenMaterialForPipelineWithBuildCauseIsNotFound()
      throws IllegalArtifactLocationException, IOException {
    PipelineConfig pipelineConfig =
        PipelineConfigMother.pipelineConfig(
            "last",
            new StageConfig(
                new CaseInsensitiveString("stage"), new JobConfigs(new JobConfig("job-one"))));
    pipelineConfig.materialConfigs().clear();
    SvnMaterialConfig onDirOne =
        MaterialConfigsMother.svnMaterialConfig(
            "google.com", "dirOne", "loser", "boozer", false, "**/*.html");
    final P4MaterialConfig onDirTwo =
        MaterialConfigsMother.p4MaterialConfig(
            "host:987654321", "zoozer", "secret", "through-the-window", true);
    onDirTwo.setConfigAttributes(Collections.singletonMap(ScmMaterialConfig.FOLDER, "dirTwo"));
    pipelineConfig.addMaterialConfig(onDirOne);
    pipelineConfig.addMaterialConfig(onDirTwo);

    configHelper.addPipeline(pipelineConfig);

    Pipeline building = PipelineMother.building(pipelineConfig);
    final Pipeline pipeline = dbHelper.savePipelineWithMaterials(building);

    CruiseConfig cruiseConfig = configHelper.currentConfig();
    PipelineConfig cfg = cruiseConfig.pipelineConfigByName(new CaseInsensitiveString("last"));
    cfg.removeMaterialConfig(cfg.materialConfigs().get(1));
    configHelper.writeConfigFile(cruiseConfig);

    assertThat(
        serverHealthService.filterByScope(HealthStateScope.forPipeline("last")).size(), is(0));

    final long jobId = pipeline.getStages().get(0).getJobInstances().get(0).getId();

    Date currentTime = new Date(System.currentTimeMillis() - 1);
    Pipeline loadedPipeline =
        (Pipeline)
            transactionTemplate.execute(
                new TransactionCallback() {
                  public Object doInTransaction(TransactionStatus status) {
                    Pipeline loadedPipeline = null;
                    try {
                      loadedPipeline = loader.pipelineWithPasswordAwareBuildCauseByBuildId(jobId);
                      fail(
                          "should not have loaded pipeline with build-cause as one of the necessary materials was not found");
                    } catch (Exception e) {
                      assertThat(e, is(instanceOf(StaleMaterialsOnBuildCause.class)));
                      assertThat(
                          e.getMessage(),
                          is(
                              "Cannot load job 'last/"
                                  + pipeline.getCounter()
                                  + "/stage/1/job-one' because material "
                                  + onDirTwo
                                  + " was not found in config."));
                    }
                    return loadedPipeline;
                  }
                });

    assertThat(loadedPipeline, is(nullValue()));

    JobInstance reloadedJobInstance = jobInstanceService.buildById(jobId);
    assertThat(reloadedJobInstance.getState(), is(JobState.Completed));
    assertThat(reloadedJobInstance.getResult(), is(JobResult.Failed));

    assertThat(
        serverHealthService
            .filterByScope(HealthStateScope.forJob("last", "stage", "job-one"))
            .size(),
        is(1));
    ServerHealthState error =
        serverHealthService
            .filterByScope(HealthStateScope.forJob("last", "stage", "job-one"))
            .get(0);
    assertThat(
        error,
        is(
            ServerHealthState.error(
                "Cannot load job 'last/"
                    + pipeline.getCounter()
                    + "/stage/1/job-one' because material "
                    + onDirTwo
                    + " was not found in config.",
                "Job for pipeline 'last/"
                    + pipeline.getCounter()
                    + "/stage/1/job-one' has been failed as one or more material configurations were either changed or removed.",
                HealthStateType.general(HealthStateScope.forJob("last", "stage", "job-one")))));
    DateTime expiryTime = (DateTime) ReflectionUtil.getField(error, "expiryTime");
    assertThat(expiryTime.toDate().after(currentTime), is(true));
    assertThat(
        expiryTime.toDate().before(new Date(System.currentTimeMillis() + 5 * 60 * 1000 + 1)),
        is(true));

    String logText =
        FileUtil.readToEnd(consoleService.findConsoleArtifact(reloadedJobInstance.getIdentifier()));
    assertThat(
        logText,
        containsString(
            "Cannot load job 'last/"
                + pipeline.getCounter()
                + "/stage/1/job-one' because material "
                + onDirTwo
                + " was not found in config."));
    assertThat(
        logText,
        containsString(
            "Job for pipeline 'last/"
                + pipeline.getCounter()
                + "/stage/1/job-one' has been failed as one or more material configurations were either changed or removed."));
  }